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.

UnicodeString.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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.hssf.record.common;
  16. import java.util.ArrayList;
  17. import java.util.Collections;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.Objects;
  22. import java.util.function.Supplier;
  23. import java.util.stream.Collectors;
  24. import org.apache.poi.common.Duplicatable;
  25. import org.apache.poi.common.usermodel.GenericRecord;
  26. import org.apache.poi.hssf.record.RecordInputStream;
  27. import org.apache.poi.hssf.record.cont.ContinuableRecordInput;
  28. import org.apache.poi.hssf.record.cont.ContinuableRecordOutput;
  29. import org.apache.poi.util.BitField;
  30. import org.apache.poi.util.BitFieldFactory;
  31. import org.apache.poi.util.GenericRecordUtil;
  32. import org.apache.poi.util.POILogFactory;
  33. import org.apache.poi.util.POILogger;
  34. /**
  35. * Unicode String - just standard fields that are in several records.
  36. * It is considered more desirable then repeating it in all of them.<p>
  37. * This is often called a XLUnicodeRichExtendedString in MS documentation.<p>
  38. */
  39. public class UnicodeString implements Comparable<UnicodeString>, Duplicatable, GenericRecord {
  40. private static final POILogger LOG = POILogFactory.getLogger(UnicodeString.class);
  41. private static final BitField highByte = BitFieldFactory.getInstance(0x1);
  42. // 0x2 is reserved
  43. private static final BitField extBit = BitFieldFactory.getInstance(0x4);
  44. private static final BitField richText = BitFieldFactory.getInstance(0x8);
  45. private short field_1_charCount;
  46. private byte field_2_optionflags;
  47. private String field_3_string;
  48. private List<FormatRun> field_4_format_runs;
  49. private ExtRst field_5_ext_rst;
  50. private UnicodeString(UnicodeString other) {
  51. field_1_charCount = other.field_1_charCount;
  52. field_2_optionflags = other.field_2_optionflags;
  53. field_3_string = other.field_3_string;
  54. field_4_format_runs = (other.field_4_format_runs == null) ? null :
  55. other.field_4_format_runs.stream().map(FormatRun::new).collect(Collectors.toList());
  56. field_5_ext_rst = (other.field_5_ext_rst == null) ? null : other.field_5_ext_rst.copy();
  57. }
  58. public UnicodeString(String str) {
  59. setString(str);
  60. }
  61. /**
  62. * construct a unicode string record and fill its fields, ID is ignored
  63. * @param in the RecordInputstream to read the record from
  64. */
  65. public UnicodeString(RecordInputStream in) {
  66. field_1_charCount = in.readShort();
  67. field_2_optionflags = in.readByte();
  68. int runCount = 0;
  69. int extensionLength = 0;
  70. //Read the number of rich runs if rich text.
  71. if (isRichText()) {
  72. runCount = in.readShort();
  73. }
  74. //Read the size of extended data if present.
  75. if (isExtendedText()) {
  76. extensionLength = in.readInt();
  77. }
  78. boolean isCompressed = ((field_2_optionflags & 1) == 0);
  79. int cc = getCharCount();
  80. field_3_string = (isCompressed) ? in.readCompressedUnicode(cc) : in.readUnicodeLEString(cc);
  81. if (isRichText() && (runCount > 0)) {
  82. field_4_format_runs = new ArrayList<>(runCount);
  83. for (int i=0;i<runCount;i++) {
  84. field_4_format_runs.add(new FormatRun(in));
  85. }
  86. }
  87. if (isExtendedText() && (extensionLength > 0)) {
  88. field_5_ext_rst = new ExtRst(new ContinuableRecordInput(in), extensionLength);
  89. if(field_5_ext_rst.getDataSize()+4 != extensionLength) {
  90. LOG.log(POILogger.WARN, "ExtRst was supposed to be " + extensionLength + " bytes long, but seems to actually be " + (field_5_ext_rst.getDataSize() + 4));
  91. }
  92. }
  93. }
  94. public int hashCode() {
  95. return Objects.hash(field_1_charCount, field_3_string);
  96. }
  97. /**
  98. * Our handling of equals is inconsistent with compareTo. The trouble is because we don't truely understand
  99. * rich text fields yet it's difficult to make a sound comparison.
  100. *
  101. * @param o The object to compare.
  102. * @return true if the object is actually equal.
  103. */
  104. public boolean equals(Object o)
  105. {
  106. if (!(o instanceof UnicodeString)) {
  107. return false;
  108. }
  109. UnicodeString other = (UnicodeString) o;
  110. //OK lets do this in stages to return a quickly, first check the actual string
  111. if (field_1_charCount != other.field_1_charCount
  112. || field_2_optionflags != other.field_2_optionflags
  113. || !field_3_string.equals(other.field_3_string)) {
  114. return false;
  115. }
  116. //OK string appears to be equal but now lets compare formatting runs
  117. if (field_4_format_runs == null) {
  118. // Strings are equal, and there are not formatting runs.
  119. return (other.field_4_format_runs == null);
  120. } else if (other.field_4_format_runs == null) {
  121. // Strings are equal, but one or the other has formatting runs
  122. return false;
  123. }
  124. //Strings are equal, so now compare formatting runs.
  125. int size = field_4_format_runs.size();
  126. if (size != other.field_4_format_runs.size()) {
  127. return false;
  128. }
  129. for (int i=0;i<size;i++) {
  130. FormatRun run1 = field_4_format_runs.get(i);
  131. FormatRun run2 = other.field_4_format_runs.get(i);
  132. if (!run1.equals(run2)) {
  133. return false;
  134. }
  135. }
  136. // Well the format runs are equal as well!, better check the ExtRst data
  137. if (field_5_ext_rst == null) {
  138. return (other.field_5_ext_rst == null);
  139. } else if (other.field_5_ext_rst == null) {
  140. return false;
  141. }
  142. return field_5_ext_rst.equals(other.field_5_ext_rst);
  143. }
  144. /**
  145. * get the number of characters in the string,
  146. * as an un-wrapped int
  147. *
  148. * @return number of characters
  149. */
  150. public int getCharCount() {
  151. if(field_1_charCount < 0) {
  152. return field_1_charCount + 65536;
  153. }
  154. return field_1_charCount;
  155. }
  156. /**
  157. * get the number of characters in the string,
  158. * wrapped as needed to fit within a short
  159. *
  160. * @return number of characters
  161. */
  162. public short getCharCountShort() {
  163. return field_1_charCount;
  164. }
  165. /**
  166. * set the number of characters in the string
  167. * @param cc - number of characters
  168. */
  169. public void setCharCount(short cc)
  170. {
  171. field_1_charCount = cc;
  172. }
  173. /**
  174. * get the option flags which among other things return if this is a 16-bit or
  175. * 8 bit string
  176. *
  177. * @return optionflags bitmask
  178. *
  179. */
  180. public byte getOptionFlags()
  181. {
  182. return field_2_optionflags;
  183. }
  184. /**
  185. * set the option flags which among other things return if this is a 16-bit or
  186. * 8 bit string
  187. *
  188. * @param of optionflags bitmask
  189. *
  190. */
  191. public void setOptionFlags(byte of)
  192. {
  193. field_2_optionflags = of;
  194. }
  195. /**
  196. * @return the actual string this contains as a java String object
  197. */
  198. public String getString()
  199. {
  200. return field_3_string;
  201. }
  202. /**
  203. * set the actual string this contains
  204. * @param string the text
  205. */
  206. public void setString(String string)
  207. {
  208. field_3_string = string;
  209. setCharCount((short)field_3_string.length());
  210. // scan for characters greater than 255 ... if any are
  211. // present, we have to use 16-bit encoding. Otherwise, we
  212. // can use 8-bit encoding
  213. boolean useUTF16 = false;
  214. int strlen = string.length();
  215. for ( int j = 0; j < strlen; j++ ) {
  216. if ( string.charAt( j ) > 255 ) {
  217. useUTF16 = true;
  218. break;
  219. }
  220. }
  221. if (useUTF16) {
  222. //Set the uncompressed bit
  223. field_2_optionflags = highByte.setByte(field_2_optionflags);
  224. } else {
  225. field_2_optionflags = highByte.clearByte(field_2_optionflags);
  226. }
  227. }
  228. public int getFormatRunCount() {
  229. return (field_4_format_runs == null) ? 0 : field_4_format_runs.size();
  230. }
  231. public FormatRun getFormatRun(int index) {
  232. if (field_4_format_runs == null) {
  233. return null;
  234. }
  235. if (index < 0 || index >= field_4_format_runs.size()) {
  236. return null;
  237. }
  238. return field_4_format_runs.get(index);
  239. }
  240. private int findFormatRunAt(int characterPos) {
  241. int size = field_4_format_runs.size();
  242. for (int i=0;i<size;i++) {
  243. FormatRun r = field_4_format_runs.get(i);
  244. if (r._character == characterPos) {
  245. return i;
  246. } else if (r._character > characterPos) {
  247. return -1;
  248. }
  249. }
  250. return -1;
  251. }
  252. /** Adds a font run to the formatted string.
  253. *
  254. * If a font run exists at the current charcter location, then it is
  255. * replaced with the font run to be added.
  256. */
  257. public void addFormatRun(FormatRun r) {
  258. if (field_4_format_runs == null) {
  259. field_4_format_runs = new ArrayList<>();
  260. }
  261. int index = findFormatRunAt(r._character);
  262. if (index != -1) {
  263. field_4_format_runs.remove(index);
  264. }
  265. field_4_format_runs.add(r);
  266. //Need to sort the font runs to ensure that the font runs appear in
  267. //character order
  268. Collections.sort(field_4_format_runs);
  269. //Make sure that we now say that we are a rich string
  270. field_2_optionflags = richText.setByte(field_2_optionflags);
  271. }
  272. public Iterator<FormatRun> formatIterator() {
  273. if (field_4_format_runs != null) {
  274. return field_4_format_runs.iterator();
  275. }
  276. return null;
  277. }
  278. public void removeFormatRun(FormatRun r) {
  279. field_4_format_runs.remove(r);
  280. if (field_4_format_runs.size() == 0) {
  281. field_4_format_runs = null;
  282. field_2_optionflags = richText.clearByte(field_2_optionflags);
  283. }
  284. }
  285. public void clearFormatting() {
  286. field_4_format_runs = null;
  287. field_2_optionflags = richText.clearByte(field_2_optionflags);
  288. }
  289. public ExtRst getExtendedRst() {
  290. return this.field_5_ext_rst;
  291. }
  292. void setExtendedRst(ExtRst ext_rst) {
  293. if (ext_rst != null) {
  294. field_2_optionflags = extBit.setByte(field_2_optionflags);
  295. } else {
  296. field_2_optionflags = extBit.clearByte(field_2_optionflags);
  297. }
  298. this.field_5_ext_rst = ext_rst;
  299. }
  300. /**
  301. * Swaps all use in the string of one font index
  302. * for use of a different font index.
  303. * Normally only called when fonts have been
  304. * removed / re-ordered
  305. */
  306. public void swapFontUse(short oldFontIndex, short newFontIndex) {
  307. if (field_4_format_runs != null) {
  308. for (FormatRun run : field_4_format_runs) {
  309. if(run._fontIndex == oldFontIndex) {
  310. run._fontIndex = newFontIndex;
  311. }
  312. }
  313. }
  314. }
  315. /**
  316. * unlike the real records we return the same as "getString()" rather than debug info
  317. * @see #getDebugInfo()
  318. * @return String value of the record
  319. */
  320. public String toString()
  321. {
  322. return getString();
  323. }
  324. /**
  325. * return a character representation of the fields of this record
  326. *
  327. *
  328. * @return String of output for biffviewer etc.
  329. *
  330. */
  331. public String getDebugInfo()
  332. {
  333. StringBuilder buffer = new StringBuilder();
  334. buffer.append("[UNICODESTRING]\n");
  335. buffer.append(" .charcount = ")
  336. .append(Integer.toHexString(getCharCount())).append("\n");
  337. buffer.append(" .optionflags = ")
  338. .append(Integer.toHexString(getOptionFlags())).append("\n");
  339. buffer.append(" .string = ").append(getString()).append("\n");
  340. if (field_4_format_runs != null) {
  341. for (int i = 0; i < field_4_format_runs.size();i++) {
  342. FormatRun r = field_4_format_runs.get(i);
  343. buffer.append(" .format_run").append(i).append(" = ").append(r).append("\n");
  344. }
  345. }
  346. if (field_5_ext_rst != null) {
  347. buffer.append(" .field_5_ext_rst = ").append("\n");
  348. buffer.append(field_5_ext_rst).append("\n");
  349. }
  350. buffer.append("[/UNICODESTRING]\n");
  351. return buffer.toString();
  352. }
  353. /**
  354. * Serialises out the String. There are special rules
  355. * about where we can and can't split onto
  356. * Continue records.
  357. */
  358. public void serialize(ContinuableRecordOutput out) {
  359. int numberOfRichTextRuns = 0;
  360. int extendedDataSize = 0;
  361. if (isRichText() && field_4_format_runs != null) {
  362. numberOfRichTextRuns = field_4_format_runs.size();
  363. }
  364. if (isExtendedText() && field_5_ext_rst != null) {
  365. extendedDataSize = 4 + field_5_ext_rst.getDataSize();
  366. }
  367. // Serialise the bulk of the String
  368. // The writeString handles tricky continue stuff for us
  369. out.writeString(field_3_string, numberOfRichTextRuns, extendedDataSize);
  370. if (numberOfRichTextRuns > 0) {
  371. //This will ensure that a run does not split a continue
  372. for (int i=0;i<numberOfRichTextRuns;i++) {
  373. if (out.getAvailableSpace() < 4) {
  374. out.writeContinue();
  375. }
  376. FormatRun r = field_4_format_runs.get(i);
  377. r.serialize(out);
  378. }
  379. }
  380. if (extendedDataSize > 0 && field_5_ext_rst != null) {
  381. field_5_ext_rst.serialize(out);
  382. }
  383. }
  384. public int compareTo(UnicodeString str) {
  385. int result = getString().compareTo(str.getString());
  386. //As per the equals method lets do this in stages
  387. if (result != 0) {
  388. return result;
  389. }
  390. //OK string appears to be equal but now lets compare formatting runs
  391. if (field_4_format_runs == null) {
  392. //Strings are equal, and there are no formatting runs. -> 0
  393. //Strings are equal, but one or the other has formatting runs -> 1
  394. return (str.field_4_format_runs == null) ? 0 : 1;
  395. } else if (str.field_4_format_runs == null) {
  396. //Strings are equal, but one or the other has formatting runs
  397. return -1;
  398. }
  399. //Strings are equal, so now compare formatting runs.
  400. int size = field_4_format_runs.size();
  401. if (size != str.field_4_format_runs.size()) {
  402. return size - str.field_4_format_runs.size();
  403. }
  404. for (int i=0;i<size;i++) {
  405. FormatRun run1 = field_4_format_runs.get(i);
  406. FormatRun run2 = str.field_4_format_runs.get(i);
  407. result = run1.compareTo(run2);
  408. if (result != 0) {
  409. return result;
  410. }
  411. }
  412. //Well the format runs are equal as well!, better check the ExtRst data
  413. if (field_5_ext_rst == null) {
  414. return (str.field_5_ext_rst == null) ? 0 : 1;
  415. } else if (str.field_5_ext_rst == null) {
  416. return -1;
  417. } else {
  418. return field_5_ext_rst.compareTo(str.field_5_ext_rst);
  419. }
  420. }
  421. private boolean isRichText() {
  422. return richText.isSet(getOptionFlags());
  423. }
  424. private boolean isExtendedText() {
  425. return extBit.isSet(getOptionFlags());
  426. }
  427. @Override
  428. public UnicodeString copy() {
  429. return new UnicodeString(this);
  430. }
  431. @Override
  432. public Map<String, Supplier<?>> getGenericProperties() {
  433. return GenericRecordUtil.getGenericProperties(
  434. "charCount", this::getCharCount,
  435. "optionFlags", this::getOptionFlags,
  436. "string", this::getString,
  437. "formatRuns", () -> field_4_format_runs,
  438. "extendedRst", this::getExtendedRst
  439. );
  440. }
  441. }