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.

HemfPictureTest.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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.hemf.usermodel;
  16. import static org.apache.poi.POITestCase.assertContains;
  17. import static org.junit.Assert.assertEquals;
  18. import static org.junit.Assert.assertTrue;
  19. import java.awt.geom.Point2D;
  20. import java.io.BufferedWriter;
  21. import java.io.ByteArrayInputStream;
  22. import java.io.ByteArrayOutputStream;
  23. import java.io.FileWriter;
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.nio.charset.StandardCharsets;
  27. import java.nio.file.Files;
  28. import java.nio.file.Path;
  29. import java.nio.file.Paths;
  30. import java.nio.file.StandardOpenOption;
  31. import java.util.HashSet;
  32. import java.util.List;
  33. import java.util.Set;
  34. import java.util.stream.Stream;
  35. import org.apache.poi.POIDataSamples;
  36. import org.apache.poi.hemf.record.emf.HemfComment;
  37. import org.apache.poi.hemf.record.emf.HemfComment.EmfComment;
  38. import org.apache.poi.hemf.record.emf.HemfComment.EmfCommentDataFormat;
  39. import org.apache.poi.hemf.record.emf.HemfComment.EmfCommentDataMultiformats;
  40. import org.apache.poi.hemf.record.emf.HemfHeader;
  41. import org.apache.poi.hemf.record.emf.HemfRecord;
  42. import org.apache.poi.hemf.record.emf.HemfRecordType;
  43. import org.apache.poi.hemf.record.emf.HemfText;
  44. import org.apache.poi.util.IOUtils;
  45. import org.apache.poi.util.RecordFormatException;
  46. import org.junit.Test;
  47. public class HemfPictureTest {
  48. private static final POIDataSamples ss_samples = POIDataSamples.getSpreadSheetInstance();
  49. private static final POIDataSamples sl_samples = POIDataSamples.getSlideShowInstance();
  50. /*
  51. @Test
  52. @Ignore("Only for manual tests - need to add org.tukaani:xz:1.8 for this to work")
  53. public void paint() throws IOException {
  54. byte buf[] = new byte[50_000_000];
  55. // good test samples to validate rendering:
  56. // emfs/commoncrawl2/NB/NBWN2YH5VFCLZRFDQU7PB7IDD4UKY7DN_2.emf
  57. // emfs/govdocs1/777/777525.ppt_0.emf
  58. // emfs/govdocs1/844/844795.ppt_2.emf
  59. // emfs/commoncrawl2/TO/TOYZSTNUSW5OFCFUQ6T5FBLIDLCRF3NH_0.emf
  60. final boolean writeLog = true;
  61. final boolean dumpRecords = false;
  62. final boolean savePng = true;
  63. Set<String> passed = new HashSet<>();
  64. try (BufferedWriter sucWrite = parseEmfLog(passed, "emf-success.txt");
  65. BufferedWriter parseError = parseEmfLog(passed, "emf-parse.txt");
  66. BufferedWriter renderError = parseEmfLog(passed, "emf-render.txt");
  67. SevenZFile sevenZFile = new SevenZFile(new File("tmp/render_emf.7z"))) {
  68. for (int idx=0;;idx++) {
  69. SevenZArchiveEntry entry = sevenZFile.getNextEntry();
  70. if (entry == null) break;
  71. final String etName = entry.getName();
  72. if (entry.isDirectory() || !etName.endsWith(".emf") || passed.contains(etName)) continue;
  73. System.out.println(etName);
  74. int size = sevenZFile.read(buf);
  75. HemfPicture emf = null;
  76. try {
  77. emf = new HemfPicture(new ByteArrayInputStream(buf, 0, size));
  78. // initialize parsing
  79. emf.getRecords();
  80. } catch (Exception|AssertionError e) {
  81. if (writeLog) {
  82. parseError.write(etName+" "+hashException(e)+"\n");
  83. parseError.flush();
  84. }
  85. System.out.println("parse error");
  86. // continue with the read records up to the error anyway
  87. if (emf.getRecords().isEmpty()) {
  88. continue;
  89. }
  90. }
  91. if (dumpRecords) {
  92. dumpRecords(emf);
  93. }
  94. Graphics2D g = null;
  95. try {
  96. Dimension2D dim = emf.getSize();
  97. double width = Units.pointsToPixel(dim.getWidth());
  98. // keep aspect ratio for height
  99. double height = Units.pointsToPixel(dim.getHeight());
  100. double max = Math.max(width, height);
  101. if (max > 1500.) {
  102. width *= 1500. / max;
  103. height *= 1500. / max;
  104. }
  105. width = Math.ceil(width);
  106. height = Math.ceil(height);
  107. BufferedImage bufImg = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_ARGB);
  108. g = bufImg.createGraphics();
  109. g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  110. g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
  111. g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
  112. g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
  113. g.setComposite(AlphaComposite.Clear);
  114. g.fillRect(0, 0, (int)width, (int)height);
  115. g.setComposite(AlphaComposite.Src);
  116. emf.draw(g, new Rectangle2D.Double(0, 0, width, height));
  117. final File pngName = new File("build/tmp", etName.replaceFirst(".+/", "").replace(".emf", ".png"));
  118. if (savePng) {
  119. ImageIO.write(bufImg, "PNG", pngName);
  120. }
  121. } catch (Exception|AssertionError e) {
  122. System.out.println("render error");
  123. if (writeLog) {
  124. // dumpRecords(emf.getRecords());
  125. renderError.write(etName+" "+hashException(e)+"\n");
  126. renderError.flush();
  127. }
  128. continue;
  129. } finally {
  130. if (g != null) g.dispose();
  131. }
  132. if (writeLog) {
  133. sucWrite.write(etName + "\n");
  134. sucWrite.flush();
  135. }
  136. }
  137. }
  138. } */
  139. private static int hashException(Throwable e) {
  140. StringBuilder sb = new StringBuilder();
  141. for (StackTraceElement se : e.getStackTrace()) {
  142. sb.append(se.getClassName()+":"+se.getLineNumber());
  143. }
  144. return sb.toString().hashCode();
  145. }
  146. private static void dumpRecords(HemfPicture emf) throws IOException {
  147. FileWriter fw = new FileWriter("record-list.txt");
  148. int i = 0;
  149. for (HemfRecord r : emf.getRecords()) {
  150. if (r.getEmfRecordType() != HemfRecordType.comment) {
  151. fw.write(i + " " + r.getEmfRecordType() + " " + r.toString() + "\n");
  152. }
  153. i++;
  154. }
  155. fw.close();
  156. }
  157. private static BufferedWriter parseEmfLog(Set<String> passed, String logFile) throws IOException {
  158. Path log = Paths.get(logFile);
  159. StandardOpenOption soo;
  160. if (Files.exists(log)) {
  161. soo = StandardOpenOption.APPEND;
  162. try (Stream<String> stream = Files.lines(log)) {
  163. stream.forEach((s) -> passed.add(s.split("\\s")[0]));
  164. }
  165. } else {
  166. soo = StandardOpenOption.CREATE;
  167. }
  168. return Files.newBufferedWriter(log, StandardCharsets.UTF_8, soo);
  169. }
  170. @Test
  171. public void testBasicWindows() throws Exception {
  172. try (InputStream is = ss_samples.openResourceAsStream("SimpleEMF_windows.emf")) {
  173. HemfPicture pic = new HemfPicture(is);
  174. HemfHeader header = pic.getHeader();
  175. assertEquals(27864, header.getBytes());
  176. assertEquals(31, header.getRecords());
  177. assertEquals(3, header.getHandles());
  178. assertEquals(346000, header.getMicroDimension().getWidth());
  179. assertEquals(194000, header.getMicroDimension().getHeight());
  180. List<HemfRecord> records = pic.getRecords();
  181. assertEquals(31, records.size());
  182. }
  183. }
  184. @Test
  185. public void testBasicMac() throws Exception {
  186. try (InputStream is = ss_samples.openResourceAsStream("SimpleEMF_mac.emf")) {
  187. HemfPicture pic = new HemfPicture(is);
  188. HemfHeader header = pic.getHeader();
  189. int records = 0;
  190. boolean extractedData = false;
  191. for (HemfRecord record : pic) {
  192. if (record.getEmfRecordType() == HemfRecordType.comment) {
  193. HemfComment.EmfCommentData comment = ((EmfComment) record).getCommentData();
  194. if (comment instanceof EmfCommentDataMultiformats) {
  195. for (EmfCommentDataFormat d : ((EmfCommentDataMultiformats) comment).getFormats()) {
  196. byte[] data = d.getRawData();
  197. //make sure header starts at 0
  198. assertEquals('%', data[0]);
  199. assertEquals('P', data[1]);
  200. assertEquals('D', data[2]);
  201. assertEquals('F', data[3]);
  202. //make sure byte array ends at EOF\n
  203. assertEquals('E', data[data.length - 4]);
  204. assertEquals('O', data[data.length - 3]);
  205. assertEquals('F', data[data.length - 2]);
  206. assertEquals('\n', data[data.length - 1]);
  207. extractedData = true;
  208. }
  209. }
  210. }
  211. records++;
  212. }
  213. assertTrue(extractedData);
  214. assertEquals(header.getRecords(), records);
  215. }
  216. }
  217. @Test
  218. public void testMacText() throws Exception {
  219. try (InputStream is = ss_samples.openResourceAsStream("SimpleEMF_mac.emf")) {
  220. HemfPicture pic = new HemfPicture(is);
  221. double lastY = -1;
  222. double lastX = -1;
  223. //derive this from the font information!
  224. long fudgeFactorX = 1000;
  225. StringBuilder sb = new StringBuilder();
  226. for (HemfRecord record : pic) {
  227. if (record.getEmfRecordType().equals(HemfRecordType.extTextOutW)) {
  228. HemfText.EmfExtTextOutW extTextOutW = (HemfText.EmfExtTextOutW) record;
  229. Point2D reference = extTextOutW.getReference();
  230. if (lastY > -1 && lastY != reference.getY()) {
  231. sb.append("\n");
  232. lastX = -1;
  233. }
  234. if (lastX > -1 && reference.getX() - lastX > fudgeFactorX) {
  235. sb.append(" ");
  236. }
  237. sb.append(extTextOutW.getText());
  238. lastY = reference.getY();
  239. lastX = reference.getX();
  240. }
  241. }
  242. String txt = sb.toString();
  243. assertContains(txt, "Tika http://incubator.apache.org");
  244. assertContains(txt, "Latest News\n");
  245. }
  246. }
  247. @Test
  248. public void testWindowsText() throws Exception {
  249. try (InputStream is = ss_samples.openResourceAsStream("SimpleEMF_windows.emf")) {
  250. HemfPicture pic = new HemfPicture(is);
  251. double lastY = -1;
  252. double lastX = -1;
  253. long fudgeFactorX = 1000;//derive this from the font or frame/bounds information
  254. StringBuilder sb = new StringBuilder();
  255. Set<String> expectedParts = new HashSet<>();
  256. expectedParts.add("C:\\Users\\tallison\\");
  257. expectedParts.add("testPDF.pdf");
  258. int foundExpected = 0;
  259. for (HemfRecord record : pic) {
  260. if (record.getEmfRecordType().equals(HemfRecordType.extTextOutW)) {
  261. HemfText.EmfExtTextOutW extTextOutW = (HemfText.EmfExtTextOutW) record;
  262. Point2D reference = extTextOutW.getReference();
  263. if (lastY > -1 && lastY != reference.getY()) {
  264. sb.append("\n");
  265. lastX = -1;
  266. }
  267. if (lastX > -1 && reference.getX() - lastX > fudgeFactorX) {
  268. sb.append(" ");
  269. }
  270. String txt = extTextOutW.getText();
  271. if (expectedParts.contains(txt)) {
  272. foundExpected++;
  273. }
  274. sb.append(txt);
  275. lastY = reference.getY();
  276. lastX = reference.getX();
  277. }
  278. }
  279. String txt = sb.toString();
  280. assertContains(txt, "C:\\Users\\tallison\\\n");
  281. assertContains(txt, "asf2-git-1.x\\tika-\n");
  282. assertEquals(expectedParts.size(), foundExpected);
  283. }
  284. }
  285. @Test(expected = RecordFormatException.class)
  286. public void testInfiniteLoopOnFile() throws Exception {
  287. try (InputStream is = ss_samples.openResourceAsStream("61294.emf")) {
  288. HemfPicture pic = new HemfPicture(is);
  289. for (HemfRecord record : pic) {
  290. }
  291. }
  292. }
  293. @Test(expected = RecordFormatException.class)
  294. public void testInfiniteLoopOnByteArray() throws Exception {
  295. try (InputStream is = ss_samples.openResourceAsStream("61294.emf")) {
  296. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  297. IOUtils.copy(is, bos);
  298. is.close();
  299. HemfPicture pic = new HemfPicture(new ByteArrayInputStream(bos.toByteArray()));
  300. for (HemfRecord record : pic) {
  301. }
  302. }
  303. }
  304. /*
  305. govdocs1 064213.doc-0.emf contains an example of extextouta
  306. */
  307. }