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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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.IOException;
  17. import java.io.Serializable;
  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.poi.hwpf.model.io.HWPFOutputStream;
  24. import org.apache.poi.poifs.common.POIFSConstants;
  25. import org.apache.poi.util.Internal;
  26. import org.apache.poi.util.POILogFactory;
  27. import org.apache.poi.util.POILogger;
  28. /**
  29. * The piece table for matching up character positions to bits of text. This
  30. * mostly works in bytes, but the TextPieces themselves work in characters. This
  31. * does the icky convertion.
  32. *
  33. * @author Ryan Ackley
  34. */
  35. @Internal
  36. public class TextPieceTable implements CharIndexTranslator {
  37. private static final POILogger logger = POILogFactory
  38. .getLogger(TextPieceTable.class);
  39. // int _multiple;
  40. int _cpMin;
  41. protected ArrayList<TextPiece> _textPieces = new ArrayList<TextPiece>();
  42. protected ArrayList<TextPiece> _textPiecesFCOrder = new ArrayList<TextPiece>();
  43. public TextPieceTable() {
  44. }
  45. public TextPieceTable(byte[] documentStream, byte[] tableStream,
  46. int offset, int size, int fcMin) {
  47. // get our plex of PieceDescriptors
  48. PlexOfCps pieceTable = new PlexOfCps(tableStream, offset, size,
  49. PieceDescriptor.getSizeInBytes());
  50. int length = pieceTable.length();
  51. PieceDescriptor[] pieces = new PieceDescriptor[length];
  52. // iterate through piece descriptors raw bytes and create
  53. // PieceDescriptor objects
  54. for (int x = 0; x < length; x++) {
  55. GenericPropertyNode node = pieceTable.getProperty(x);
  56. pieces[x] = new PieceDescriptor(node.getBytes(), 0);
  57. }
  58. // Figure out the cp of the earliest text piece
  59. // Note that text pieces don't have to be stored in order!
  60. _cpMin = pieces[0].getFilePosition() - fcMin;
  61. for (PieceDescriptor piece : pieces) {
  62. int start = piece.getFilePosition() - fcMin;
  63. if (start < _cpMin) {
  64. _cpMin = start;
  65. }
  66. }
  67. // using the PieceDescriptors, build our list of TextPieces.
  68. for (int x = 0; x < pieces.length; x++) {
  69. int start = pieces[x].getFilePosition();
  70. GenericPropertyNode node = pieceTable.getProperty(x);
  71. // Grab the start and end, which are in characters
  72. int nodeStartChars = node.getStart();
  73. int nodeEndChars = node.getEnd();
  74. // What's the relationship between bytes and characters?
  75. boolean unicode = pieces[x].isUnicode();
  76. int multiple = 1;
  77. if (unicode) {
  78. multiple = 2;
  79. }
  80. // Figure out the length, in bytes and chars
  81. int textSizeChars = (nodeEndChars - nodeStartChars);
  82. int textSizeBytes = textSizeChars * multiple;
  83. // Grab the data that makes up the piece
  84. byte[] buf = new byte[textSizeBytes];
  85. System.arraycopy(documentStream, start, buf, 0, textSizeBytes);
  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<TextPiece>(_textPieces);
  95. Collections.sort(_textPiecesFCOrder, new FCComparator());
  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. Collections.sort(_textPiecesFCOrder, new FCComparator());
  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. public int getByteIndex(int charPos) {
  141. int byteCount = 0;
  142. for (TextPiece tp : _textPieces) {
  143. if (charPos >= tp.getEnd()) {
  144. byteCount = tp.getPieceDescriptor().getFilePosition()
  145. + (tp.getEnd() - tp.getStart())
  146. * (tp.isUnicode() ? 2 : 1);
  147. if (charPos == tp.getEnd())
  148. break;
  149. continue;
  150. }
  151. if (charPos < tp.getEnd()) {
  152. int left = charPos - tp.getStart();
  153. byteCount = tp.getPieceDescriptor().getFilePosition() + left
  154. * (tp.isUnicode() ? 2 : 1);
  155. break;
  156. }
  157. }
  158. return byteCount;
  159. }
  160. @Deprecated
  161. public int getCharIndex(int bytePos) {
  162. return getCharIndex(bytePos, 0);
  163. }
  164. @Deprecated
  165. public int getCharIndex(int startBytePos, int startCP) {
  166. int charCount = 0;
  167. int bytePos = lookIndexForward(startBytePos);
  168. for (TextPiece tp : _textPieces) {
  169. int pieceStart = tp.getPieceDescriptor().getFilePosition();
  170. int bytesLength = tp.bytesLength();
  171. int pieceEnd = pieceStart + bytesLength;
  172. int toAdd;
  173. if (bytePos < pieceStart || bytePos > pieceEnd) {
  174. toAdd = bytesLength;
  175. } else if (bytePos > pieceStart && bytePos < pieceEnd) {
  176. toAdd = (bytePos - pieceStart);
  177. } else {
  178. toAdd = bytesLength - (pieceEnd - bytePos);
  179. }
  180. if (tp.isUnicode()) {
  181. charCount += toAdd / 2;
  182. } else {
  183. charCount += toAdd;
  184. }
  185. if (bytePos >= pieceStart && bytePos <= pieceEnd
  186. && charCount >= startCP) {
  187. break;
  188. }
  189. }
  190. return charCount;
  191. }
  192. @Override
  193. public int[][] getCharIndexRanges(int startBytePosInclusive,
  194. int endBytePosExclusive) {
  195. List<int[]> result = new LinkedList<int[]>();
  196. for (TextPiece textPiece : _textPiecesFCOrder) {
  197. final int tpStart = textPiece.getPieceDescriptor()
  198. .getFilePosition();
  199. final int tpEnd = textPiece.getPieceDescriptor().getFilePosition()
  200. + textPiece.bytesLength();
  201. if (startBytePosInclusive > tpEnd)
  202. continue;
  203. if (endBytePosExclusive <= tpStart)
  204. break;
  205. final int rangeStartBytes = Math.max(tpStart,
  206. startBytePosInclusive);
  207. final int rangeEndBytes = Math.min(tpEnd, endBytePosExclusive);
  208. final int rangeLengthBytes = rangeEndBytes - rangeStartBytes;
  209. if (rangeStartBytes > rangeEndBytes)
  210. continue;
  211. final int encodingMultiplier = getEncodingMultiplier(textPiece);
  212. final int rangeStartCp = textPiece.getStart()
  213. + (rangeStartBytes - tpStart) / encodingMultiplier;
  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 = System.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. logger.log(
  235. POILogger.WARN,
  236. "Text piece has boundaries [",
  237. Integer.valueOf(textPiece.getStart()),
  238. "; ",
  239. Integer.valueOf(textPiece.getEnd()),
  240. ") but length ",
  241. Integer.valueOf(textPiece.getEnd()
  242. - textPiece.getStart()));
  243. }
  244. docText.replace(textPiece.getStart(), textPiece.getStart()
  245. + toAppendLength, toAppend);
  246. }
  247. logger.log(POILogger.DEBUG, "Document text were rebuilded in ",
  248. Long.valueOf(System.currentTimeMillis() - start), " ms (",
  249. Integer.valueOf(docText.length()), " chars)");
  250. return docText;
  251. }
  252. public List<TextPiece> getTextPieces() {
  253. return _textPieces;
  254. }
  255. @Override
  256. public int hashCode() {
  257. return _textPieces.size();
  258. }
  259. public boolean isIndexInTable(int bytePos) {
  260. for (TextPiece tp : _textPiecesFCOrder) {
  261. int pieceStart = tp.getPieceDescriptor().getFilePosition();
  262. if (bytePos > pieceStart + tp.bytesLength()) {
  263. continue;
  264. }
  265. if (pieceStart > bytePos) {
  266. return false;
  267. }
  268. return true;
  269. }
  270. return false;
  271. }
  272. boolean isIndexInTable(int startBytePos, int endBytePos) {
  273. for (TextPiece tp : _textPiecesFCOrder) {
  274. int pieceStart = tp.getPieceDescriptor().getFilePosition();
  275. if (startBytePos >= pieceStart + tp.bytesLength()) {
  276. continue;
  277. }
  278. int left = Math.max(startBytePos, pieceStart);
  279. int right = Math.min(endBytePos, pieceStart + tp.bytesLength());
  280. if (left >= right)
  281. return false;
  282. return true;
  283. }
  284. return false;
  285. }
  286. public int lookIndexBackward(final int startBytePos) {
  287. int bytePos = startBytePos;
  288. int lastEnd = 0;
  289. for (TextPiece tp : _textPiecesFCOrder) {
  290. int pieceStart = tp.getPieceDescriptor().getFilePosition();
  291. if (bytePos > pieceStart + tp.bytesLength()) {
  292. lastEnd = pieceStart + tp.bytesLength();
  293. continue;
  294. }
  295. if (pieceStart > bytePos) {
  296. bytePos = lastEnd;
  297. }
  298. break;
  299. }
  300. return bytePos;
  301. }
  302. public int lookIndexForward(final int startBytePos) {
  303. if (_textPiecesFCOrder.isEmpty())
  304. throw new IllegalStateException("Text pieces table is empty");
  305. if (_textPiecesFCOrder.get(0).getPieceDescriptor().getFilePosition() > startBytePos)
  306. return _textPiecesFCOrder.get(0).getPieceDescriptor().getFilePosition();
  307. if (_textPiecesFCOrder.get(_textPiecesFCOrder.size() - 1)
  308. .getPieceDescriptor().getFilePosition() <= startBytePos)
  309. return startBytePos;
  310. int low = 0;
  311. int high = _textPiecesFCOrder.size() - 1;
  312. while (low <= high) {
  313. int mid = (low + high) >>> 1;
  314. final TextPiece textPiece = _textPiecesFCOrder.get(mid);
  315. int midVal = textPiece.getPieceDescriptor().getFilePosition();
  316. if (midVal < startBytePos)
  317. low = mid + 1;
  318. else if (midVal > startBytePos)
  319. high = mid - 1;
  320. else
  321. // found piece with exact start
  322. return textPiece.getPieceDescriptor().getFilePosition();
  323. }
  324. assert low == high;
  325. assert _textPiecesFCOrder.get(low).getPieceDescriptor()
  326. .getFilePosition() < startBytePos;
  327. // last line can't be current, can it?
  328. assert _textPiecesFCOrder.get(low + 1).getPieceDescriptor()
  329. .getFilePosition() > startBytePos;
  330. // shifting to next piece start
  331. return _textPiecesFCOrder.get(low + 1).getPieceDescriptor().getFilePosition();
  332. }
  333. public byte[] writeTo(HWPFOutputStream docStream) throws IOException {
  334. PlexOfCps textPlex = new PlexOfCps(PieceDescriptor.getSizeInBytes());
  335. // int fcMin = docStream.getOffset();
  336. for (TextPiece next : _textPieces) {
  337. PieceDescriptor pd = next.getPieceDescriptor();
  338. int offset = docStream.getOffset();
  339. int mod = (offset % POIFSConstants.SMALLER_BIG_BLOCK_SIZE);
  340. if (mod != 0) {
  341. mod = POIFSConstants.SMALLER_BIG_BLOCK_SIZE - mod;
  342. byte[] buf = new byte[mod];
  343. docStream.write(buf);
  344. }
  345. // set the text piece position to the current docStream offset.
  346. pd.setFilePosition(docStream.getOffset());
  347. // write the text to the docstream and save the piece descriptor to
  348. // the
  349. // plex which will be written later to the tableStream.
  350. docStream.write(next.getRawBytes());
  351. // The TextPiece is already in characters, which
  352. // makes our life much easier
  353. int nodeStart = next.getStart();
  354. int nodeEnd = next.getEnd();
  355. textPlex.addProperty(new GenericPropertyNode(nodeStart, nodeEnd,
  356. pd.toByteArray()));
  357. }
  358. return textPlex.toByteArray();
  359. }
  360. protected static class FCComparator implements Comparator<TextPiece>, Serializable {
  361. public int compare(TextPiece textPiece, TextPiece textPiece1) {
  362. if (textPiece.getPieceDescriptor().fc > textPiece1
  363. .getPieceDescriptor().fc) {
  364. return 1;
  365. } else if (textPiece.getPieceDescriptor().fc < textPiece1
  366. .getPieceDescriptor().fc) {
  367. return -1;
  368. } else {
  369. return 0;
  370. }
  371. }
  372. }
  373. }