You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TextPieceTable.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hwpf.model;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.IOException;
  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.Comparator;
  21. import java.util.LinkedList;
  22. import java.util.List;
  23. import org.apache.logging.log4j.LogManager;
  24. import org.apache.logging.log4j.Logger;
  25. import org.apache.poi.poifs.common.POIFSConstants;
  26. import org.apache.poi.util.IOUtils;
  27. import org.apache.poi.util.Internal;
  28. import static java.lang.System.currentTimeMillis;
  29. import static org.apache.logging.log4j.util.Unbox.box;
  30. /**
  31. * The piece table for matching up character positions to bits of text. This
  32. * mostly works in bytes, but the TextPieces themselves work in characters. This
  33. * does the icky convertion.
  34. */
  35. @Internal
  36. public class TextPieceTable implements CharIndexTranslator {
  37. private static final Logger LOG = LogManager.getLogger(TextPieceTable.class);
  38. //arbitrarily selected; may need to increase
  39. private static final int MAX_RECORD_LENGTH = 100_000_000;
  40. // int _multiple;
  41. int _cpMin;
  42. protected ArrayList<TextPiece> _textPieces = new ArrayList<>();
  43. protected ArrayList<TextPiece> _textPiecesFCOrder = new ArrayList<>();
  44. public TextPieceTable() {
  45. }
  46. public TextPieceTable(byte[] documentStream, byte[] tableStream,
  47. int offset, int size, int fcMin) {
  48. // get our plex of PieceDescriptors
  49. PlexOfCps pieceTable = new PlexOfCps(tableStream, offset, size,
  50. PieceDescriptor.getSizeInBytes());
  51. int length = pieceTable.length();
  52. PieceDescriptor[] pieces = new PieceDescriptor[length];
  53. // iterate through piece descriptors raw bytes and create
  54. // PieceDescriptor objects
  55. for (int x = 0; x < length; x++) {
  56. GenericPropertyNode node = pieceTable.getProperty(x);
  57. pieces[x] = new PieceDescriptor(node.getBytes(), 0);
  58. }
  59. // Figure out the cp of the earliest text piece
  60. // Note that text pieces don't have to be stored in order!
  61. _cpMin = pieces[0].getFilePosition() - fcMin;
  62. for (PieceDescriptor piece : pieces) {
  63. int start = piece.getFilePosition() - fcMin;
  64. if (start < _cpMin) {
  65. _cpMin = start;
  66. }
  67. }
  68. // using the PieceDescriptors, build our list of TextPieces.
  69. for (int x = 0; x < pieces.length; x++) {
  70. int start = pieces[x].getFilePosition();
  71. GenericPropertyNode node = pieceTable.getProperty(x);
  72. // Grab the start and end, which are in characters
  73. int nodeStartChars = node.getStart();
  74. int nodeEndChars = node.getEnd();
  75. // What's the relationship between bytes and characters?
  76. boolean unicode = pieces[x].isUnicode();
  77. int multiple = 1;
  78. if (unicode) {
  79. multiple = 2;
  80. }
  81. // Figure out the length, in bytes and chars
  82. int textSizeChars = (nodeEndChars - nodeStartChars);
  83. int textSizeBytes = textSizeChars * multiple;
  84. // Grab the data that makes up the piece
  85. byte[] buf = IOUtils.safelyClone(documentStream, start, textSizeBytes, MAX_RECORD_LENGTH);
  86. // And now build the piece
  87. final TextPiece newTextPiece = newTextPiece(nodeStartChars, nodeEndChars, buf,
  88. pieces[x]);
  89. _textPieces.add(newTextPiece);
  90. }
  91. // In the interest of our sanity, now sort the text pieces
  92. // into order, if they're not already
  93. Collections.sort(_textPieces);
  94. _textPiecesFCOrder = new ArrayList<>(_textPieces);
  95. _textPiecesFCOrder.sort(byFilePosition());
  96. }
  97. protected TextPiece newTextPiece(int nodeStartChars, int nodeEndChars, byte[] buf, PieceDescriptor pd) {
  98. return new TextPiece(nodeStartChars, nodeEndChars, buf, pd);
  99. }
  100. public void add(TextPiece piece) {
  101. _textPieces.add(piece);
  102. _textPiecesFCOrder.add(piece);
  103. Collections.sort(_textPieces);
  104. _textPiecesFCOrder.sort(byFilePosition());
  105. }
  106. /**
  107. * Adjust all the text piece after inserting some text into one of them
  108. *
  109. * @param listIndex The TextPiece that had characters inserted into
  110. * @param length The number of characters inserted
  111. */
  112. public int adjustForInsert(int listIndex, int length) {
  113. int size = _textPieces.size();
  114. TextPiece tp = _textPieces.get(listIndex);
  115. // Update with the new end
  116. tp.setEnd(tp.getEnd() + length);
  117. // Now change all subsequent ones
  118. for (int x = listIndex + 1; x < size; x++) {
  119. tp = _textPieces.get(x);
  120. tp.setStart(tp.getStart() + length);
  121. tp.setEnd(tp.getEnd() + length);
  122. }
  123. // All done
  124. return length;
  125. }
  126. public boolean equals(Object o) {
  127. if (!(o instanceof TextPieceTable)) return false;
  128. TextPieceTable tpt = (TextPieceTable) o;
  129. int size = tpt._textPieces.size();
  130. if (size == _textPieces.size()) {
  131. for (int x = 0; x < size; x++) {
  132. if (!tpt._textPieces.get(x).equals(_textPieces.get(x))) {
  133. return false;
  134. }
  135. }
  136. return true;
  137. }
  138. return false;
  139. }
  140. @Override
  141. public int getByteIndex(int charPos) {
  142. int byteCount = 0;
  143. for (TextPiece tp : _textPieces) {
  144. if (charPos >= tp.getEnd()) {
  145. byteCount = tp.getPieceDescriptor().getFilePosition()
  146. + (tp.getEnd() - tp.getStart())
  147. * (tp.isUnicode() ? 2 : 1);
  148. if (charPos == tp.getEnd())
  149. break;
  150. continue;
  151. }
  152. if (charPos < tp.getEnd()) {
  153. int left = charPos - tp.getStart();
  154. byteCount = tp.getPieceDescriptor().getFilePosition() + left
  155. * (tp.isUnicode() ? 2 : 1);
  156. break;
  157. }
  158. }
  159. return byteCount;
  160. }
  161. @Deprecated
  162. public int getCharIndex(int bytePos) {
  163. return getCharIndex(bytePos, 0);
  164. }
  165. @Deprecated
  166. public int getCharIndex(int startBytePos, int startCP) {
  167. int charCount = 0;
  168. int bytePos = lookIndexForward(startBytePos);
  169. for (TextPiece tp : _textPieces) {
  170. int pieceStart = tp.getPieceDescriptor().getFilePosition();
  171. int bytesLength = tp.bytesLength();
  172. int pieceEnd = pieceStart + bytesLength;
  173. int toAdd;
  174. if (bytePos < pieceStart || bytePos > pieceEnd) {
  175. toAdd = bytesLength;
  176. } else if (bytePos > pieceStart && bytePos < pieceEnd) {
  177. toAdd = (bytePos - pieceStart);
  178. } else {
  179. toAdd = bytesLength - (pieceEnd - bytePos);
  180. }
  181. if (tp.isUnicode()) {
  182. charCount += toAdd / 2;
  183. } else {
  184. charCount += toAdd;
  185. }
  186. if (bytePos >= pieceStart && bytePos <= pieceEnd
  187. && charCount >= startCP) {
  188. break;
  189. }
  190. }
  191. return charCount;
  192. }
  193. @Override
  194. public int[][] getCharIndexRanges(int startBytePosInclusive,
  195. int endBytePosExclusive) {
  196. List<int[]> result = new LinkedList<>();
  197. for (TextPiece textPiece : _textPiecesFCOrder) {
  198. final int tpStart = textPiece.getPieceDescriptor()
  199. .getFilePosition();
  200. if (endBytePosExclusive <= tpStart)
  201. break;
  202. final int tpEnd = textPiece.getPieceDescriptor().getFilePosition()
  203. + textPiece.bytesLength();
  204. if (startBytePosInclusive > tpEnd)
  205. continue;
  206. final int rangeStartBytes = Math.max(tpStart, startBytePosInclusive);
  207. final int rangeEndBytes = Math.min(tpEnd, endBytePosExclusive);
  208. if (rangeStartBytes > rangeEndBytes)
  209. continue;
  210. final int encodingMultiplier = getEncodingMultiplier(textPiece);
  211. final int rangeStartCp = textPiece.getStart()
  212. + (rangeStartBytes - tpStart) / encodingMultiplier;
  213. final int rangeLengthBytes = rangeEndBytes - rangeStartBytes;
  214. final int rangeEndCp = rangeStartCp + rangeLengthBytes
  215. / encodingMultiplier;
  216. result.add(new int[]{rangeStartCp, rangeEndCp});
  217. }
  218. return result.toArray(new int[result.size()][]);
  219. }
  220. protected int getEncodingMultiplier(TextPiece textPiece) {
  221. return textPiece.isUnicode() ? 2 : 1;
  222. }
  223. public int getCpMin() {
  224. return _cpMin;
  225. }
  226. public StringBuilder getText() {
  227. final long start = currentTimeMillis();
  228. // rebuild document paragraphs structure
  229. StringBuilder docText = new StringBuilder();
  230. for (TextPiece textPiece : _textPieces) {
  231. String toAppend = textPiece.getStringBuilder().toString();
  232. int toAppendLength = toAppend.length();
  233. if (toAppendLength != textPiece.getEnd() - textPiece.getStart()) {
  234. LOG.atWarn().log("Text piece has boundaries [{}; {}) but length {}", box(textPiece.getStart()),box(textPiece.getEnd()),box(textPiece.getEnd() - textPiece.getStart()));
  235. }
  236. docText.replace(textPiece.getStart(), textPiece.getStart()
  237. + toAppendLength, toAppend);
  238. }
  239. LOG.atDebug().log("Document text were rebuilt in {} ms ({} chars)", box(currentTimeMillis() - start),box(docText.length()));
  240. return docText;
  241. }
  242. public List<TextPiece> getTextPieces() {
  243. return _textPieces;
  244. }
  245. @Override
  246. public int hashCode() {
  247. return _textPieces.hashCode();
  248. }
  249. @Override
  250. public boolean isIndexInTable(int bytePos) {
  251. for (TextPiece tp : _textPiecesFCOrder) {
  252. int pieceStart = tp.getPieceDescriptor().getFilePosition();
  253. if (bytePos > pieceStart + tp.bytesLength()) {
  254. continue;
  255. }
  256. return pieceStart <= bytePos;
  257. }
  258. return false;
  259. }
  260. boolean isIndexInTable(int startBytePos, int endBytePos) {
  261. for (TextPiece tp : _textPiecesFCOrder) {
  262. int pieceStart = tp.getPieceDescriptor().getFilePosition();
  263. if (startBytePos >= pieceStart + tp.bytesLength()) {
  264. continue;
  265. }
  266. int left = Math.max(startBytePos, pieceStart);
  267. int right = Math.min(endBytePos, pieceStart + tp.bytesLength());
  268. return left < right;
  269. }
  270. return false;
  271. }
  272. @Override
  273. public int lookIndexBackward(final int startBytePos) {
  274. int bytePos = startBytePos;
  275. int lastEnd = 0;
  276. for (TextPiece tp : _textPiecesFCOrder) {
  277. int pieceStart = tp.getPieceDescriptor().getFilePosition();
  278. if (bytePos > pieceStart + tp.bytesLength()) {
  279. lastEnd = pieceStart + tp.bytesLength();
  280. continue;
  281. }
  282. if (pieceStart > bytePos) {
  283. bytePos = lastEnd;
  284. }
  285. break;
  286. }
  287. return bytePos;
  288. }
  289. @Override
  290. public int lookIndexForward(final int startBytePos) {
  291. if (_textPiecesFCOrder.isEmpty())
  292. throw new IllegalStateException("Text pieces table is empty");
  293. if (_textPiecesFCOrder.get(0).getPieceDescriptor().getFilePosition() > startBytePos)
  294. return _textPiecesFCOrder.get(0).getPieceDescriptor().getFilePosition();
  295. if (_textPiecesFCOrder.get(_textPiecesFCOrder.size() - 1)
  296. .getPieceDescriptor().getFilePosition() <= startBytePos)
  297. return startBytePos;
  298. int low = 0;
  299. int high = _textPiecesFCOrder.size() - 1;
  300. while (low <= high) {
  301. int mid = (low + high) >>> 1;
  302. final TextPiece textPiece = _textPiecesFCOrder.get(mid);
  303. int midVal = textPiece.getPieceDescriptor().getFilePosition();
  304. if (midVal < startBytePos)
  305. low = mid + 1;
  306. else if (midVal > startBytePos)
  307. high = mid - 1;
  308. else
  309. // found piece with exact start
  310. return textPiece.getPieceDescriptor().getFilePosition();
  311. }
  312. assert low == high;
  313. assert _textPiecesFCOrder.get(low).getPieceDescriptor()
  314. .getFilePosition() < startBytePos;
  315. // last line can't be current, can it?
  316. assert _textPiecesFCOrder.get(low + 1).getPieceDescriptor()
  317. .getFilePosition() > startBytePos;
  318. // shifting to next piece start
  319. return _textPiecesFCOrder.get(low + 1).getPieceDescriptor().getFilePosition();
  320. }
  321. public byte[] writeTo(ByteArrayOutputStream docStream) throws IOException {
  322. PlexOfCps textPlex = new PlexOfCps(PieceDescriptor.getSizeInBytes());
  323. // int fcMin = docStream.getOffset();
  324. for (TextPiece next : _textPieces) {
  325. PieceDescriptor pd = next.getPieceDescriptor();
  326. int offset = docStream.size();
  327. int mod = (offset % POIFSConstants.SMALLER_BIG_BLOCK_SIZE);
  328. if (mod != 0) {
  329. mod = POIFSConstants.SMALLER_BIG_BLOCK_SIZE - mod;
  330. byte[] buf = IOUtils.safelyAllocate(mod, MAX_RECORD_LENGTH);
  331. docStream.write(buf);
  332. }
  333. // set the text piece position to the current docStream offset.
  334. pd.setFilePosition(docStream.size());
  335. // write the text to the docstream and save the piece descriptor to
  336. // the
  337. // plex which will be written later to the tableStream.
  338. docStream.write(next.getRawBytes());
  339. // The TextPiece is already in characters, which
  340. // makes our life much easier
  341. int nodeStart = next.getStart();
  342. int nodeEnd = next.getEnd();
  343. textPlex.addProperty(new GenericPropertyNode(nodeStart, nodeEnd,
  344. pd.toByteArray()));
  345. }
  346. return textPlex.toByteArray();
  347. }
  348. static Comparator<TextPiece> byFilePosition() {
  349. return Comparator.comparing(t -> t.getPieceDescriptor().getFilePosition());
  350. }
  351. }