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.

HwmfPicture.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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.hwmf.usermodel;
  16. import java.awt.Graphics2D;
  17. import java.awt.Shape;
  18. import java.awt.geom.AffineTransform;
  19. import java.awt.geom.Dimension2D;
  20. import java.awt.geom.Rectangle2D;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.nio.charset.Charset;
  24. import java.util.ArrayList;
  25. import java.util.Collections;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Objects;
  30. import java.util.Spliterator;
  31. import java.util.function.Supplier;
  32. import org.apache.logging.log4j.LogManager;
  33. import org.apache.logging.log4j.Logger;
  34. import org.apache.poi.common.usermodel.GenericRecord;
  35. import org.apache.poi.hwmf.draw.HwmfDrawProperties;
  36. import org.apache.poi.hwmf.draw.HwmfGraphics;
  37. import org.apache.poi.hwmf.draw.HwmfGraphicsState;
  38. import org.apache.poi.hwmf.record.HwmfHeader;
  39. import org.apache.poi.hwmf.record.HwmfPlaceableHeader;
  40. import org.apache.poi.hwmf.record.HwmfRecord;
  41. import org.apache.poi.hwmf.record.HwmfRecordType;
  42. import org.apache.poi.hwmf.record.HwmfWindowing.WmfSetWindowExt;
  43. import org.apache.poi.hwmf.record.HwmfWindowing.WmfSetWindowOrg;
  44. import org.apache.poi.util.Dimension2DDouble;
  45. import org.apache.poi.util.IOUtils;
  46. import org.apache.poi.util.LittleEndianInputStream;
  47. import org.apache.poi.util.LocaleUtil;
  48. import org.apache.poi.util.RecordFormatException;
  49. import org.apache.poi.util.Units;
  50. public class HwmfPicture implements Iterable<HwmfRecord>, GenericRecord {
  51. /** Max. record length - processing longer records will throw an exception */
  52. public static final int DEFAULT_MAX_RECORD_LENGTH = 50_000_000;
  53. public static int MAX_RECORD_LENGTH = DEFAULT_MAX_RECORD_LENGTH;
  54. private static final Logger LOG = LogManager.getLogger(HwmfPicture.class);
  55. final List<HwmfRecord> records = new ArrayList<>();
  56. final HwmfPlaceableHeader placeableHeader;
  57. final HwmfHeader header;
  58. /** The default charset */
  59. private Charset defaultCharset = LocaleUtil.CHARSET_1252;
  60. /**
  61. * @param length the max record length allowed for HwmfPicture
  62. */
  63. public static void setMaxRecordLength(int length) {
  64. MAX_RECORD_LENGTH = length;
  65. }
  66. /**
  67. * @return the max record length allowed for HwmfPicture
  68. */
  69. public static int getMaxRecordLength() {
  70. return MAX_RECORD_LENGTH;
  71. }
  72. /**
  73. * @param inputStream
  74. * @throws IOException
  75. * @throws RuntimeException a number of runtime exceptions can be thrown, especially if there are problems with the
  76. * input format
  77. */
  78. public HwmfPicture(InputStream inputStream) throws IOException {
  79. try (LittleEndianInputStream leis = new LittleEndianInputStream(inputStream)) {
  80. placeableHeader = HwmfPlaceableHeader.readHeader(leis);
  81. header = new HwmfHeader(leis);
  82. for (;;) {
  83. long recordSize;
  84. int recordFunction;
  85. try {
  86. // recordSize in DWORDs
  87. long recordSizeLong = leis.readUInt()*2;
  88. if (recordSizeLong > Integer.MAX_VALUE) {
  89. throw new RecordFormatException("record size can't be > "+Integer.MAX_VALUE);
  90. } else if (recordSizeLong < 0L) {
  91. throw new RecordFormatException("record size can't be < 0");
  92. }
  93. recordSize = (int)recordSizeLong;
  94. recordFunction = leis.readShort();
  95. } catch (Exception e) {
  96. LOG.atError().log("unexpected eof - wmf file was truncated");
  97. break;
  98. }
  99. // 4 bytes (recordSize) + 2 bytes (recordFunction)
  100. int consumedSize = 6;
  101. HwmfRecordType wrt = HwmfRecordType.getById(recordFunction);
  102. if (wrt == null) {
  103. throw new IOException("unexpected record type: "+recordFunction);
  104. }
  105. if (wrt == HwmfRecordType.eof) {
  106. break;
  107. }
  108. if (wrt.constructor == null) {
  109. throw new IOException("unsupported record type: "+recordFunction);
  110. }
  111. final HwmfRecord wr = wrt.constructor.get();
  112. records.add(wr);
  113. consumedSize += wr.init(leis, recordSize, recordFunction);
  114. int remainingSize = (int)(recordSize - consumedSize);
  115. if (remainingSize < 0) {
  116. throw new RecordFormatException("read too many bytes. record size: "+recordSize + "; comsumed size: "+consumedSize);
  117. } else if(remainingSize > 0) {
  118. long skipped = IOUtils.skipFully(leis, remainingSize);
  119. if (skipped != (long)remainingSize) {
  120. throw new RecordFormatException("Tried to skip "+remainingSize + " but skipped: "+skipped);
  121. }
  122. }
  123. if (wr instanceof HwmfCharsetAware) {
  124. ((HwmfCharsetAware)wr).setCharsetProvider(this::getDefaultCharset);
  125. }
  126. }
  127. }
  128. }
  129. public List<HwmfRecord> getRecords() {
  130. return Collections.unmodifiableList(records);
  131. }
  132. public void draw(Graphics2D ctx) {
  133. Dimension2D dim = getSize();
  134. int width = Units.pointsToPixel(dim.getWidth());
  135. // keep aspect ratio for height
  136. int height = Units.pointsToPixel(dim.getHeight());
  137. Rectangle2D bounds = new Rectangle2D.Double(0,0,width,height);
  138. draw(ctx, bounds);
  139. }
  140. public void draw(Graphics2D ctx, Rectangle2D graphicsBounds) {
  141. HwmfGraphicsState state = new HwmfGraphicsState();
  142. state.backup(ctx);
  143. try {
  144. Rectangle2D wmfBounds = getBounds();
  145. Rectangle2D innerBounds = getInnnerBounds();
  146. if (innerBounds == null) {
  147. innerBounds = wmfBounds;
  148. }
  149. // scale output bounds to image bounds
  150. ctx.translate(graphicsBounds.getCenterX(), graphicsBounds.getCenterY());
  151. ctx.scale(graphicsBounds.getWidth()/innerBounds.getWidth(), graphicsBounds.getHeight()/innerBounds.getHeight());
  152. ctx.translate(-innerBounds.getCenterX(), -innerBounds.getCenterY());
  153. HwmfGraphics g = new HwmfGraphics(ctx, innerBounds);
  154. HwmfDrawProperties prop = g.getProperties();
  155. prop.setViewportOrg(innerBounds.getX(), innerBounds.getY());
  156. prop.setViewportExt(innerBounds.getWidth(), innerBounds.getHeight());
  157. int idx = 0;
  158. for (HwmfRecord r : records) {
  159. prop = g.getProperties();
  160. Shape propClip = prop.getClip();
  161. Shape ctxClip = ctx.getClip();
  162. if (!Objects.equals(propClip, ctxClip)) {
  163. int a = 5;
  164. }
  165. r.draw(g);
  166. idx++;
  167. }
  168. } finally {
  169. state.restore(ctx);
  170. }
  171. }
  172. /**
  173. * Returns the bounding box in device-independent units. Usually this is taken from the placeable header.
  174. *
  175. * @return the bounding box
  176. *
  177. * @throws RuntimeException if neither WmfSetWindowOrg/Ext nor the placeableHeader are set
  178. */
  179. public Rectangle2D getBounds() {
  180. if (placeableHeader != null) {
  181. return placeableHeader.getBounds();
  182. }
  183. Rectangle2D inner = getInnnerBounds();
  184. if (inner != null) {
  185. return inner;
  186. }
  187. throw new RuntimeException("invalid wmf file - window records are incomplete.");
  188. }
  189. /**
  190. * Returns the bounding box in device-independent units taken from the WmfSetWindowOrg/Ext records
  191. *
  192. * @return the bounding box or null, if the WmfSetWindowOrg/Ext records aren't set
  193. */
  194. public Rectangle2D getInnnerBounds() {
  195. WmfSetWindowOrg wOrg = null;
  196. WmfSetWindowExt wExt = null;
  197. for (HwmfRecord r : getRecords()) {
  198. if (r instanceof WmfSetWindowOrg) {
  199. wOrg = (WmfSetWindowOrg)r;
  200. } else if (r instanceof WmfSetWindowExt) {
  201. wExt = (WmfSetWindowExt)r;
  202. }
  203. if (wOrg != null && wExt != null) {
  204. return new Rectangle2D.Double(wOrg.getX(), wOrg.getY(), wExt.getSize().getWidth(), wExt.getSize().getHeight());
  205. }
  206. }
  207. return null;
  208. }
  209. public HwmfPlaceableHeader getPlaceableHeader() {
  210. return placeableHeader;
  211. }
  212. public HwmfHeader getHeader() {
  213. return header;
  214. }
  215. /**
  216. * Return the image bound in points
  217. *
  218. * @return the image bound in points
  219. */
  220. public Rectangle2D getBoundsInPoints() {
  221. double inch = (placeableHeader == null) ? 1440 : placeableHeader.getUnitsPerInch();
  222. Rectangle2D bounds = getBounds();
  223. //coefficient to translate from WMF dpi to 72dpi
  224. double coeff = Units.POINT_DPI/inch;
  225. return AffineTransform.getScaleInstance(coeff, coeff).createTransformedShape(bounds).getBounds2D();
  226. }
  227. /**
  228. * Return the image size in points
  229. *
  230. * @return the image size in points
  231. */
  232. public Dimension2D getSize() {
  233. Rectangle2D bounds = getBoundsInPoints();
  234. return new Dimension2DDouble(bounds.getWidth(), bounds.getHeight());
  235. }
  236. public Iterable<HwmfEmbedded> getEmbeddings() {
  237. return () -> new HwmfEmbeddedIterator(HwmfPicture.this);
  238. }
  239. @Override
  240. public Iterator<HwmfRecord> iterator() {
  241. return getRecords().iterator();
  242. }
  243. @Override
  244. public Spliterator<HwmfRecord> spliterator() {
  245. return getRecords().spliterator();
  246. }
  247. @Override
  248. public Map<String, Supplier<?>> getGenericProperties() {
  249. return null;
  250. }
  251. @Override
  252. public List<? extends GenericRecord> getGenericChildren() {
  253. return getRecords();
  254. }
  255. public void setDefaultCharset(Charset defaultCharset) {
  256. this.defaultCharset = defaultCharset;
  257. }
  258. public Charset getDefaultCharset() {
  259. return defaultCharset;
  260. }
  261. }