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.

HwmfGraphics.java 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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.draw;
  16. import java.awt.BasicStroke;
  17. import java.awt.Color;
  18. import java.awt.Graphics2D;
  19. import java.awt.GraphicsConfiguration;
  20. import java.awt.Paint;
  21. import java.awt.Rectangle;
  22. import java.awt.Shape;
  23. import java.awt.TexturePaint;
  24. import java.awt.font.FontRenderContext;
  25. import java.awt.font.TextAttribute;
  26. import java.awt.font.TextLayout;
  27. import java.awt.geom.AffineTransform;
  28. import java.awt.geom.Area;
  29. import java.awt.geom.Dimension2D;
  30. import java.awt.geom.NoninvertibleTransformException;
  31. import java.awt.geom.Point2D;
  32. import java.awt.geom.Rectangle2D;
  33. import java.awt.image.BufferedImage;
  34. import java.nio.charset.Charset;
  35. import java.text.AttributedString;
  36. import java.util.BitSet;
  37. import java.util.LinkedList;
  38. import java.util.List;
  39. import java.util.NoSuchElementException;
  40. import java.util.TreeMap;
  41. import org.apache.commons.codec.Charsets;
  42. import org.apache.poi.common.usermodel.fonts.FontCharset;
  43. import org.apache.poi.common.usermodel.fonts.FontInfo;
  44. import org.apache.poi.hwmf.record.HwmfBrushStyle;
  45. import org.apache.poi.hwmf.record.HwmfFont;
  46. import org.apache.poi.hwmf.record.HwmfHatchStyle;
  47. import org.apache.poi.hwmf.record.HwmfMapMode;
  48. import org.apache.poi.hwmf.record.HwmfMisc.WmfSetBkMode.HwmfBkMode;
  49. import org.apache.poi.hwmf.record.HwmfObjectTableEntry;
  50. import org.apache.poi.hwmf.record.HwmfPenStyle;
  51. import org.apache.poi.hwmf.record.HwmfPenStyle.HwmfLineDash;
  52. import org.apache.poi.hwmf.record.HwmfRegionMode;
  53. import org.apache.poi.hwmf.record.HwmfText;
  54. import org.apache.poi.hwmf.record.HwmfText.WmfExtTextOutOptions;
  55. import org.apache.poi.sl.draw.DrawFactory;
  56. import org.apache.poi.sl.draw.DrawFontManager;
  57. import org.apache.poi.sl.draw.DrawFontManagerDefault;
  58. import org.apache.poi.util.LocaleUtil;
  59. public class HwmfGraphics {
  60. public enum FillDrawStyle {
  61. NONE, FILL, DRAW, FILL_DRAW
  62. }
  63. protected final List<HwmfDrawProperties> propStack = new LinkedList<>();
  64. protected HwmfDrawProperties prop;
  65. protected final Graphics2D graphicsCtx;
  66. protected final BitSet objectIndexes = new BitSet();
  67. protected final TreeMap<Integer,HwmfObjectTableEntry> objectTable = new TreeMap<>();
  68. protected final AffineTransform initialAT = new AffineTransform();
  69. private static final Charset DEFAULT_CHARSET = LocaleUtil.CHARSET_1252;
  70. /** Bounding box from the placeable header */
  71. private final Rectangle2D bbox;
  72. /**
  73. * Initialize a graphics context for wmf rendering
  74. *
  75. * @param graphicsCtx the graphics context to delegate drawing calls
  76. * @param bbox the bounding box of the wmf (taken from the placeable header)
  77. */
  78. public HwmfGraphics(Graphics2D graphicsCtx, Rectangle2D bbox) {
  79. this.graphicsCtx = graphicsCtx;
  80. this.bbox = (Rectangle2D)bbox.clone();
  81. this.initialAT.setTransform(graphicsCtx.getTransform());
  82. }
  83. public HwmfDrawProperties getProperties() {
  84. if (prop == null) {
  85. prop = newProperties(null);
  86. }
  87. return prop;
  88. }
  89. protected HwmfDrawProperties newProperties(HwmfDrawProperties oldProps) {
  90. return (oldProps == null) ? new HwmfDrawProperties() : new HwmfDrawProperties(oldProps);
  91. }
  92. public void draw(Shape shape) {
  93. HwmfPenStyle ps = getProperties().getPenStyle();
  94. if (ps == null) {
  95. return;
  96. }
  97. HwmfLineDash lineDash = ps.getLineDash();
  98. if (lineDash == HwmfLineDash.NULL) {
  99. // line is not drawn
  100. return;
  101. }
  102. BasicStroke stroke = getStroke();
  103. // first draw a solid background line (depending on bkmode)
  104. // only makes sense if the line is not solid
  105. if (getProperties().getBkMode() == HwmfBkMode.OPAQUE && (lineDash != HwmfLineDash.SOLID && lineDash != HwmfLineDash.INSIDEFRAME)) {
  106. graphicsCtx.setStroke(new BasicStroke(stroke.getLineWidth()));
  107. graphicsCtx.setColor(getProperties().getBackgroundColor().getColor());
  108. graphicsCtx.draw(shape);
  109. }
  110. // then draw the (dashed) line
  111. graphicsCtx.setStroke(stroke);
  112. graphicsCtx.setColor(getProperties().getPenColor().getColor());
  113. graphicsCtx.draw(shape);
  114. }
  115. public void fill(Shape shape) {
  116. HwmfDrawProperties prop = getProperties();
  117. if (prop.getBrushStyle() != HwmfBrushStyle.BS_NULL) {
  118. if (prop.getBkMode() == HwmfBkMode.OPAQUE) {
  119. graphicsCtx.setPaint(prop.getBackgroundColor().getColor());
  120. graphicsCtx.fill(shape);
  121. }
  122. graphicsCtx.setPaint(getFill());
  123. graphicsCtx.fill(shape);
  124. }
  125. // draw(shape);
  126. }
  127. protected BasicStroke getStroke() {
  128. // TODO: fix line width calculation
  129. float width = (float)getProperties().getPenWidth();
  130. if (width == 0) {
  131. width = 1;
  132. }
  133. HwmfPenStyle ps = getProperties().getPenStyle();
  134. int cap = ps.getLineCap().awtFlag;
  135. int join = ps.getLineJoin().awtFlag;
  136. float miterLimit = (float)getProperties().getPenMiterLimit();
  137. float dashes[] = ps.getLineDashes();
  138. boolean dashAlt = ps.isAlternateDash();
  139. // This value is not an integer index into the dash pattern array.
  140. // Instead, it is a floating-point value that specifies a linear distance.
  141. float dashStart = (dashAlt && dashes != null && dashes.length > 1) ? dashes[0] : 0;
  142. return new BasicStroke(width, cap, join, miterLimit, dashes, dashStart);
  143. }
  144. protected Paint getFill() {
  145. switch (getProperties().getBrushStyle()) {
  146. default:
  147. case BS_INDEXED:
  148. case BS_PATTERN8X8:
  149. case BS_DIBPATTERN8X8:
  150. case BS_MONOPATTERN:
  151. case BS_NULL: return null;
  152. case BS_PATTERN:
  153. case BS_DIBPATTERN:
  154. case BS_DIBPATTERNPT: return getPatternPaint();
  155. case BS_SOLID: return getSolidFill();
  156. case BS_HATCHED: return getHatchedFill();
  157. }
  158. }
  159. protected Paint getSolidFill() {
  160. return getProperties().getBrushColor().getColor();
  161. }
  162. protected Paint getHatchedFill() {
  163. int dim = 7, mid = 3;
  164. BufferedImage bi = new BufferedImage(dim, dim, BufferedImage.TYPE_4BYTE_ABGR);
  165. Graphics2D g = bi.createGraphics();
  166. Color c = (getProperties().getBkMode() == HwmfBkMode.TRANSPARENT)
  167. ? new Color(0, true)
  168. : getProperties().getBackgroundColor().getColor();
  169. g.setColor(c);
  170. g.fillRect(0, 0, dim, dim);
  171. g.setColor(getProperties().getBrushColor().getColor());
  172. HwmfHatchStyle h = getProperties().getBrushHatch();
  173. if (h == HwmfHatchStyle.HS_HORIZONTAL || h == HwmfHatchStyle.HS_CROSS) {
  174. g.drawLine(0, mid, dim, mid);
  175. }
  176. if (h == HwmfHatchStyle.HS_VERTICAL || h == HwmfHatchStyle.HS_CROSS) {
  177. g.drawLine(mid, 0, mid, dim);
  178. }
  179. if (h == HwmfHatchStyle.HS_FDIAGONAL || h == HwmfHatchStyle.HS_DIAGCROSS) {
  180. g.drawLine(0, 0, dim, dim);
  181. }
  182. if (h == HwmfHatchStyle.HS_BDIAGONAL || h == HwmfHatchStyle.HS_DIAGCROSS) {
  183. g.drawLine(0, dim, dim, 0);
  184. }
  185. // TODO: handle new HS_* enumeration values
  186. g.dispose();
  187. return new TexturePaint(bi, new Rectangle(0,0,dim,dim));
  188. }
  189. protected Paint getPatternPaint() {
  190. BufferedImage bi = getProperties().getBrushBitmap();
  191. return (bi == null) ? null
  192. : new TexturePaint(bi, new Rectangle(0,0,bi.getWidth(),bi.getHeight()));
  193. }
  194. /**
  195. * Adds an record of type {@link HwmfObjectTableEntry} to the object table.
  196. *
  197. * Every object is assigned the lowest available index-that is, the smallest
  198. * numerical value-in the WMF Object Table. This binding happens at object creation,
  199. * not when the object is used.
  200. * Moreover, each object table index uniquely refers to an object.
  201. * Indexes in the WMF Object Table always start at 0.
  202. *
  203. * @param entry
  204. */
  205. public void addObjectTableEntry(HwmfObjectTableEntry entry) {
  206. int objIdx = objectIndexes.nextClearBit(0);
  207. objectIndexes.set(objIdx);
  208. objectTable.put(objIdx, entry);
  209. }
  210. /**
  211. * Applies the object table entry
  212. *
  213. * @param index the index of the object table entry (0-based)
  214. *
  215. * @throws IndexOutOfBoundsException if the index is out of range
  216. * @throws NoSuchElementException if the entry was deleted before
  217. */
  218. public void applyObjectTableEntry(int index) {
  219. HwmfObjectTableEntry ote = objectTable.get(index);
  220. if (ote == null) {
  221. throw new NoSuchElementException("WMF reference exception - object table entry on index "+index+" was deleted before.");
  222. }
  223. ote.applyObject(this);
  224. }
  225. /**
  226. * Unsets (deletes) the object table entry for further usage
  227. *
  228. * When a META_DELETEOBJECT record (section 2.3.4.7) is received that specifies this
  229. * object's particular index, the object's resources are released, the binding to its
  230. * WMF Object Table index is ended, and the index value is returned to the pool of
  231. * available indexes. The index will be reused, if needed, by a subsequent object
  232. * created by another Object Record Type record.
  233. *
  234. * @param index the index (0-based)
  235. *
  236. * @throws IndexOutOfBoundsException if the index is out of range
  237. */
  238. public void unsetObjectTableEntry(int index) {
  239. if (index < 0) {
  240. throw new IndexOutOfBoundsException("Invalid index: "+index);
  241. }
  242. // sometime emfs remove object table entries before they set them
  243. // so ignore requests, if the table entry doesn't exist
  244. objectTable.remove(index);
  245. objectIndexes.clear(index);
  246. }
  247. /**
  248. * Saves the current properties to the stack
  249. */
  250. public void saveProperties() {
  251. final HwmfDrawProperties p = getProperties();
  252. assert(p != null);
  253. p.setTransform(graphicsCtx.getTransform());
  254. p.setClip(graphicsCtx.getClip());
  255. propStack.add(p);
  256. prop = newProperties(p);
  257. }
  258. /**
  259. * Restores the properties from the stack
  260. *
  261. * @param index if the index is positive, the n-th element from the start is activated.
  262. * If the index is negative, the n-th previous element relative to the current properties element is activated.
  263. */
  264. public void restoreProperties(int index) {
  265. if (index == 0) {
  266. return;
  267. }
  268. int stackIndex = index;
  269. if (stackIndex < 0) {
  270. int curIdx = propStack.indexOf(getProperties());
  271. if (curIdx == -1) {
  272. // the current element is not pushed to the stacked, i.e. it's the last
  273. curIdx = propStack.size();
  274. }
  275. stackIndex = curIdx + index;
  276. }
  277. if (stackIndex == -1) {
  278. // roll to last when curIdx == 0
  279. stackIndex = propStack.size()-1;
  280. }
  281. // The playback device context is restored by popping state information off a stack that was created by
  282. // prior SAVEDC records
  283. // ... so because being a stack, we will remove all entries having a greater index than the stackIndex
  284. for (int i=propStack.size()-1; i>=stackIndex; i--) {
  285. prop = propStack.remove(i);
  286. }
  287. graphicsCtx.setTransform(prop.getTransform());
  288. graphicsCtx.setClip(prop.getClip());
  289. }
  290. /**
  291. * After setting various window and viewport related properties,
  292. * the underlying graphics context needs to be adapted.
  293. * This methods gathers and sets the corresponding graphics transformations.
  294. */
  295. public void updateWindowMapMode() {
  296. Rectangle2D win = getProperties().getWindow();
  297. Rectangle2D view = getProperties().getViewport();
  298. HwmfMapMode mapMode = getProperties().getMapMode();
  299. graphicsCtx.setTransform(initialAT);
  300. switch (mapMode) {
  301. default:
  302. case MM_ANISOTROPIC:
  303. // scale window bounds to output bounds
  304. if (view != null) {
  305. graphicsCtx.translate(view.getCenterX(), view.getCenterY());
  306. graphicsCtx.scale(view.getWidth() / win.getWidth(), view.getHeight() / win.getHeight());
  307. graphicsCtx.translate(-win.getCenterX(), -win.getCenterY());
  308. }
  309. break;
  310. case MM_ISOTROPIC:
  311. // TODO: to be validated ...
  312. // like anisotropic, but use x-axis as reference
  313. graphicsCtx.scale(bbox.getWidth()/win.getWidth(), bbox.getWidth()/win.getWidth());
  314. graphicsCtx.translate(-win.getX(), -win.getY());
  315. break;
  316. case MM_LOMETRIC:
  317. case MM_HIMETRIC:
  318. case MM_LOENGLISH:
  319. case MM_HIENGLISH:
  320. case MM_TWIPS: {
  321. // TODO: to be validated ...
  322. GraphicsConfiguration gc = graphicsCtx.getDeviceConfiguration();
  323. graphicsCtx.transform(gc.getNormalizingTransform());
  324. graphicsCtx.scale(1./mapMode.scale, -1./mapMode.scale);
  325. graphicsCtx.translate(-win.getX(), -win.getY());
  326. break;
  327. }
  328. case MM_TEXT:
  329. // TODO: to be validated ...
  330. break;
  331. }
  332. }
  333. public void drawString(byte[] text, int length, Point2D reference) {
  334. drawString(text, length, reference, null, null, null, null, false);
  335. }
  336. public void drawString(byte[] text, int length, Point2D reference, Dimension2D scale, Rectangle2D clip, WmfExtTextOutOptions opts, List<Integer> dx, boolean isUnicode) {
  337. final HwmfDrawProperties prop = getProperties();
  338. final AffineTransform at = graphicsCtx.getTransform();
  339. try {
  340. at.createInverse();
  341. } catch (NoninvertibleTransformException e) {
  342. return;
  343. }
  344. HwmfFont font = prop.getFont();
  345. if (font == null || text == null || text.length == 0) {
  346. return;
  347. }
  348. double fontH = getFontHeight(font);
  349. // TODO: another approx. ...
  350. double fontW = fontH/1.8;
  351. Charset charset;
  352. if (isUnicode) {
  353. charset = Charsets.UTF_16LE;
  354. } else {
  355. charset = font.getCharset().getCharset();
  356. if (charset == null) {
  357. charset = DEFAULT_CHARSET;
  358. }
  359. }
  360. String textString = new String(text, charset).substring(0,length).trim();
  361. if (textString.isEmpty()) {
  362. return;
  363. }
  364. DrawFontManager fontHandler = DrawFactory.getInstance(graphicsCtx).getFontManager(graphicsCtx);
  365. FontInfo fontInfo = fontHandler.getMappedFont(graphicsCtx, font);
  366. if (fontInfo.getCharset() == FontCharset.SYMBOL) {
  367. textString = DrawFontManagerDefault.mapSymbolChars(textString);
  368. }
  369. AttributedString as = new AttributedString(textString);
  370. addAttributes(as, font, fontInfo.getTypeface());
  371. // disabled for the time being, as the results aren't promising
  372. /*
  373. if (dx != null && !dx.isEmpty()) {
  374. //for multi-byte encodings (e.g. Shift_JIS), the byte length
  375. //might not equal the string length().
  376. //The x information is stored in dx[], an array parallel to the
  377. //byte array text[]. dx[] stores the x info in the
  378. //first byte of a multibyte character, but dx[] stores 0
  379. //for the other bytes in that character.
  380. //We need to map this information to the String offsets
  381. //dx[0] = 13 text[0] = -125
  382. //dx[1] = 0 text[1] = 118
  383. //dx[2] = 14 text[2] = -125
  384. //dx[3] = 0 text[3] = -115
  385. // needs to be remapped as:
  386. //dxNormed[0] = 13 textString.get(0) = U+30D7
  387. //dxNormed[1] = 14 textString.get(1) = U+30ED
  388. final int cps = textString.codePointCount(0, textString.length());
  389. final int unicodeSteps = Math.max(dx.size()/cps, 1);
  390. int dxPosition = 0, lastDxPosition = 0;
  391. int beginIndex = 0;
  392. while (beginIndex < textString.length() && dxPosition < dx.size()) {
  393. int endIndex = textString.offsetByCodePoints(beginIndex, 1);
  394. if (beginIndex > 0) {
  395. // Tracking works as a prefix/advance space on characters whereas
  396. // dx[...] is the complete width of the current char
  397. // therefore we need to add the additional/suffix width to the next char
  398. as.addAttribute(TextAttribute.TRACKING, (float)((dx.get(lastDxPosition) - fontW) / fontH), beginIndex, endIndex);
  399. }
  400. lastDxPosition = dxPosition;
  401. dxPosition += (isUnicode) ? unicodeSteps : (endIndex-beginIndex);
  402. beginIndex = endIndex;
  403. }
  404. }
  405. */
  406. double angle = Math.toRadians(-font.getEscapement()/10.);
  407. final HwmfText.HwmfTextAlignment align = prop.getTextAlignLatin();
  408. final HwmfText.HwmfTextVerticalAlignment valign = prop.getTextVAlignLatin();
  409. final FontRenderContext frc = graphicsCtx.getFontRenderContext();
  410. final TextLayout layout = new TextLayout(as.getIterator(), frc);
  411. final Rectangle2D pixelBounds = layout.getBounds();
  412. AffineTransform tx = new AffineTransform();
  413. switch (align) {
  414. default:
  415. case LEFT:
  416. break;
  417. case CENTER:
  418. tx.translate(-pixelBounds.getWidth() / 2., 0);
  419. break;
  420. case RIGHT:
  421. tx.translate(-pixelBounds.getWidth(), 0);
  422. break;
  423. }
  424. // TODO: check min/max orientation
  425. switch (valign) {
  426. case TOP:
  427. tx.translate(0, layout.getAscent());
  428. default:
  429. case BASELINE:
  430. break;
  431. case BOTTOM:
  432. tx.translate(0, -(pixelBounds.getHeight()-layout.getDescent()));
  433. break;
  434. }
  435. tx.rotate(angle);
  436. Point2D src = new Point2D.Double();
  437. Point2D dst = new Point2D.Double();
  438. tx.transform(src, dst);
  439. final Shape clipShape = graphicsCtx.getClip();
  440. try {
  441. if (clip != null) {
  442. graphicsCtx.translate(-clip.getCenterX(), -clip.getCenterY());
  443. graphicsCtx.rotate(angle);
  444. graphicsCtx.translate(clip.getCenterX(), clip.getCenterY());
  445. if (prop.getBkMode() == HwmfBkMode.OPAQUE && opts.isOpaque()) {
  446. graphicsCtx.setPaint(prop.getBackgroundColor().getColor());
  447. graphicsCtx.fill(clip);
  448. }
  449. if (opts.isClipped()) {
  450. graphicsCtx.setClip(clip);
  451. }
  452. graphicsCtx.setTransform(at);
  453. }
  454. graphicsCtx.translate(reference.getX(), reference.getY());
  455. graphicsCtx.rotate(angle);
  456. if (scale != null) {
  457. graphicsCtx.scale(scale.getWidth() < 0 ? -1 : 1, scale.getHeight() < 0 ? -1 : 1);
  458. }
  459. graphicsCtx.translate(dst.getX(), dst.getY());
  460. graphicsCtx.setColor(prop.getTextColor().getColor());
  461. graphicsCtx.drawString(as.getIterator(), 0, 0);
  462. } finally {
  463. graphicsCtx.setTransform(at);
  464. graphicsCtx.setClip(clipShape);
  465. }
  466. }
  467. private void addAttributes(AttributedString as, HwmfFont font, String typeface) {
  468. as.addAttribute(TextAttribute.FAMILY, typeface);
  469. as.addAttribute(TextAttribute.SIZE, getFontHeight(font));
  470. if (font.isStrikeOut()) {
  471. as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
  472. }
  473. if (font.isUnderline()) {
  474. as.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
  475. }
  476. if (font.isItalic()) {
  477. as.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
  478. }
  479. as.addAttribute(TextAttribute.WEIGHT, font.getWeight());
  480. }
  481. private double getFontHeight(HwmfFont font) {
  482. // see HwmfFont#height for details
  483. double fontHeight = font.getHeight();
  484. if (fontHeight == 0) {
  485. return 12;
  486. } else if (fontHeight < 0) {
  487. return -fontHeight;
  488. } else {
  489. // TODO: fix font height calculation
  490. // the height is given as font size + ascent + descent
  491. // as an approximation we reduce the height by a static factor
  492. return fontHeight*3/4;
  493. }
  494. }
  495. public void drawImage(BufferedImage img, Rectangle2D srcBounds, Rectangle2D dstBounds) {
  496. HwmfDrawProperties prop = getProperties();
  497. // handle raster op
  498. // currently the raster op as described in https://docs.microsoft.com/en-us/windows/desktop/gdi/ternary-raster-operations
  499. // are not supported, as we would need to extract the destination image area from the underlying buffered image
  500. // and therefore would make it mandatory that the graphics context must be from a buffered image
  501. // furthermore I doubt the purpose of bitwise image operations on non-black/white images
  502. switch (prop.getRasterOp()) {
  503. case D:
  504. // keep destination, i.e. do nothing
  505. break;
  506. case PATCOPY:
  507. graphicsCtx.setPaint(getFill());
  508. graphicsCtx.fill(dstBounds);
  509. break;
  510. case BLACKNESS:
  511. graphicsCtx.setPaint(Color.BLACK);
  512. graphicsCtx.fill(dstBounds);
  513. break;
  514. case WHITENESS:
  515. graphicsCtx.setPaint(Color.WHITE);
  516. graphicsCtx.fill(dstBounds);
  517. break;
  518. default:
  519. case SRCCOPY:
  520. final Shape clip = graphicsCtx.getClip();
  521. // add clipping in case of a source subimage, i.e. a clipped source image
  522. // some dstBounds are horizontal or vertical flipped, so we need to normalize the images
  523. Rectangle2D normalized = new Rectangle2D.Double(
  524. dstBounds.getWidth() >= 0 ? dstBounds.getMinX() : dstBounds.getMaxX(),
  525. dstBounds.getHeight() >= 0 ? dstBounds.getMinY() : dstBounds.getMaxY(),
  526. Math.abs(dstBounds.getWidth()),
  527. Math.abs(dstBounds.getHeight()));
  528. graphicsCtx.clip(normalized);
  529. final AffineTransform at = graphicsCtx.getTransform();
  530. final Rectangle2D imgBounds = new Rectangle2D.Double(0,0,img.getWidth(),img.getHeight());
  531. final boolean isImgBounds = (srcBounds.equals(new Rectangle2D.Double()));
  532. final Rectangle2D srcBounds2 = isImgBounds ? imgBounds : srcBounds;
  533. // TODO: apply emf transform
  534. graphicsCtx.translate(dstBounds.getX(), dstBounds.getY());
  535. graphicsCtx.scale(dstBounds.getWidth()/srcBounds2.getWidth(), dstBounds.getHeight()/srcBounds2.getHeight());
  536. graphicsCtx.translate(-srcBounds2.getX(), -srcBounds2.getY());
  537. graphicsCtx.drawImage(img, 0, 0, prop.getBackgroundColor().getColor(), null);
  538. graphicsCtx.setTransform(at);
  539. graphicsCtx.setClip(clip);
  540. break;
  541. }
  542. }
  543. /**
  544. * @return the initial AffineTransform, when this graphics context was created
  545. */
  546. public AffineTransform getInitTransform() {
  547. return new AffineTransform(initialAT);
  548. }
  549. /**
  550. * @return the current AffineTransform
  551. */
  552. public AffineTransform getTransform() {
  553. return new AffineTransform(graphicsCtx.getTransform());
  554. }
  555. /**
  556. * Set the current AffineTransform
  557. * @param tx the current AffineTransform
  558. */
  559. public void setTransform(AffineTransform tx) {
  560. graphicsCtx.setTransform(tx);
  561. }
  562. private static int clipCnt = 0;
  563. public void setClip(Shape clip, HwmfRegionMode regionMode, boolean useInitialAT) {
  564. final AffineTransform at = graphicsCtx.getTransform();
  565. if (useInitialAT) {
  566. graphicsCtx.setTransform(initialAT);
  567. }
  568. final Shape oldClip = graphicsCtx.getClip();
  569. final boolean isEmpty = clip.getBounds2D().isEmpty();
  570. switch (regionMode) {
  571. case RGN_AND:
  572. if (!isEmpty) {
  573. graphicsCtx.clip(clip);
  574. }
  575. break;
  576. case RGN_OR:
  577. if (!isEmpty) {
  578. if (oldClip == null) {
  579. graphicsCtx.setClip(clip);
  580. } else {
  581. Area area = new Area(oldClip);
  582. area.add(new Area(clip));
  583. graphicsCtx.setClip(area);
  584. }
  585. }
  586. break;
  587. case RGN_XOR:
  588. if (!isEmpty) {
  589. if (oldClip == null) {
  590. graphicsCtx.setClip(clip);
  591. } else {
  592. Area area = new Area(oldClip);
  593. area.exclusiveOr(new Area(clip));
  594. graphicsCtx.setClip(area);
  595. }
  596. }
  597. break;
  598. case RGN_DIFF:
  599. if (!isEmpty) {
  600. if (oldClip != null) {
  601. Area area = new Area(oldClip);
  602. area.subtract(new Area(clip));
  603. graphicsCtx.setClip(area);
  604. }
  605. }
  606. break;
  607. case RGN_COPY: {
  608. graphicsCtx.setClip(isEmpty ? null : clip);
  609. break;
  610. }
  611. }
  612. if (useInitialAT) {
  613. graphicsCtx.setTransform(at);
  614. }
  615. }
  616. }