Skip to content

Commit

Permalink
Oobranch e : add backend (#7790)
Browse files Browse the repository at this point in the history
* step0 : start model/openoffice, logic/openoffice/style

* correction: import order

* add general utilities

* add UNO utilities, move CreationException, NoDocumentException

* Xlint:unchecked model/openoffice/util

* add ootext

* add rangesort

* add compareStartsUnsafe, compareStartsThenEndsUnsafe

* add Tuple3

* add ootext

* add rangesort

* delNamesArray size correction

* rangeSort update

* cleanup

* style additions

* add backend

* checkstyle on tests

* add missing message

* add backend

* apply  oobranch-D-update.patch

* apply  oobranch-E-update.patch

* deleted    src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java

* use StringUtil.isNullOrEmpty

* no natural sort for ComparableMark

* in response to review

#7788 (review)

- more use of StringUtil.isNullOrEmpty
- private final XTextRangeCompare cmp;
- List<V> partition = partitions.computeIfAbsent(partitionKey, _key -> new ArrayList<>());
- visualSort does not throw WrappedTargetException, NoDocumentException
- set renamed to comparableMarks

* use {@code }, PMD suggestions

* update logic/style from improve-reversibility-rebased-03

* update model/style from improve-reversibility-rebased-03

* replaced single-character names in OOBibStyle.java (in changed part)

* some longer names in OOBibStyleGetCitationMarker.java

* drop normalizePageInfos, use 'preferred' and 'fallback' in getAuthorLastSeparatorInTextWithFallBack

* checkstyle

* use putIfAbsent

* use "{}" with LOGGER

* use Objects.hash and Objects.equals in CitationLookupResult

* simplified CitedKey.getBibEntry

* more use of "{}" in LOGGER

* more use of "{}" in LOGGER

* Citation.lookup: use streams

* Citation.lookup: Optional::get before findFirst

* putIfAbsent returns null for new entry

* What is 52 in Backend52

* apply 2021-08-20-a/oobranch-E-update.patch

Brings oobranch-E up to
89b0968 @ origin/improve-reversibility-rebased-03 Merge remote-tracking branch 'upstream/main' into improve-reversibility-rebased-03

* putIfAbsent returns null for new entry

* What is 52 in Backend52

* using orElseThrow

* using StringBuilder

* refMarkName renamed to markName

* import StringBuilder is not needed

* orElseThrow correction (now without message)

* update

* orElseThrow correction

* renamed cg to group

* drop message not understandable by end user

* reorganized reference mark name generation

In Backend52:
- use a single expression
- expand comment
- rename refMarkName to markName

Collectors.joining(",") moved to Codec52.getUniqueMarkName

* renamed nCitations to numberOfCitations and totalCitations

* format

* insert dummy case JabRef60: branch

* indent case-label in model/style

* indent case-label in logic/backend

* indent case-label in model/ootext

* rname cgPageInfos tro pageInfos

* renamed cgPageInfo to singlePageInfo

* replace Collectors.toSet() with new HashSet<>()

* use method reference

* drop two comments

* use String.join

* remove nr/nrm prefixes from NamedRange and NamedRangeManager methods

* align dots
  • Loading branch information
antalk2 authored Aug 21, 2021
1 parent 09c0f59 commit 644e48d
Show file tree
Hide file tree
Showing 15 changed files with 1,437 additions and 174 deletions.
447 changes: 447 additions & 0 deletions src/main/java/org/jabref/logic/openoffice/backend/Backend52.java

Large diffs are not rendered by default.

137 changes: 137 additions & 0 deletions src/main/java/org/jabref/logic/openoffice/backend/Codec52.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package org.jabref.logic.openoffice.backend;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.jabref.model.openoffice.style.CitationType;

/**
* 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.
*/
class Codec52 {
private static final String BIB_CITATION = "JR_cite";
private static final Pattern CITE_PATTERN =
// Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)");
// 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.
*/
public static class ParsedMarkName {
/** "", "0", "1" ... */
public final String i;
/** in-text-citation type */
public final CitationType citationType;
/** Citation keys embedded in the reference mark. */
public final List<String> citationKeys;

ParsedMarkName(String i, CitationType citationType, List<String> citationKeys) {
Objects.requireNonNull(i);
Objects.requireNonNull(citationKeys);
this.i = i;
this.citationType = citationType;
this.citationKeys = citationKeys;
}
}

/**
* Integer representation was written into the document in JabRef52, keep it for compatibility.
*/
private static CitationType citationTypeFromInt(int i) {
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) {
return switch (i) {
case AUTHORYEAR_PAR -> 1;
case AUTHORYEAR_INTEXT -> 2;
case INVISIBLE_CIT -> 3;
default -> throw new IllegalArgumentException("Invalid CitationType");
};
}

/**
* 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 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 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<String> usedNames,
List<String> citationKeys,
CitationType citationType) {

String citationKeysPart = String.join(",", citationKeys);

int i = 0;
int citTypeCode = citationTypeToInt(citationType);
String name = BIB_CITATION + '_' + citTypeCode + '_' + citationKeysPart;
while (usedNames.contains(name)) {
name = BIB_CITATION + i + '_' + citTypeCode + '_' + citationKeysPart;
i++;
}
return name;
}

/**
* Parse a JabRef (reference) mark name.
*
* @return Optional.empty() on failure.
*
*/
public static Optional<ParsedMarkName> parseMarkName(String refMarkName) {

Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName);
if (!citeMatcher.find()) {
return Optional.empty();
}

List<String> keys = Arrays.asList(citeMatcher.group(3).split(","));
String i = citeMatcher.group(1);
int citTypeCode = Integer.parseInt(citeMatcher.group(2));
CitationType citationType = citationTypeFromInt(citTypeCode);
return (Optional.of(new Codec52.ParsedMarkName(i, citationType, keys)));
}

/**
* @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<String> filterIsJabRefReferenceMarkName(List<String> names) {
return (names.stream()
.filter(Codec52::isJabRefReferenceMarkName)
.collect(Collectors.toList()));
}
}
81 changes: 81 additions & 0 deletions src/main/java/org/jabref/logic/openoffice/backend/GetContext.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package org.jabref.logic.openoffice.backend;

import com.sun.star.text.XTextCursor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Utility methods for processing OO Writer documents.
*/
public class GetContext {

private static final Logger LOGGER = LoggerFactory.getLogger(GetContext.class);

private GetContext() {
// Just to hide the public constructor
}

/**
* Get the text belonging to cursor with up to
* charBefore and charAfter characters of context.
*
* The actual context may be smaller than requested.
*
* @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.
*
*/
public static String getCursorStringWithContext(XTextCursor cursor,
int charBefore,
int charAfter,
boolean htmlMarkup) {

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)
+ "<b>" + citPart + "</b>"
+ result.substring(lengthWithBefore));
}
return result.trim();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package org.jabref.logic.openoffice.backend;

import java.util.List;
import java.util.Optional;

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;
import com.sun.star.text.XTextDocument;

public class NamedRangeManagerReferenceMark implements NamedRangeManager {

@Override
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<String> getUsedNames(XTextDocument doc)
throws
NoDocumentException {
return UnoReferenceMark.getListOfNames(doc);
}

@Override
public Optional<NamedRange> getNamedRangeFromDocument(XTextDocument doc, String refMarkName)
throws
NoDocumentException,
WrappedTargetException {
return (NamedRangeReferenceMark
.getFromDocument(doc, refMarkName)
.map(x -> x));
}
}

Loading

0 comments on commit 644e48d

Please sign in to comment.