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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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.AlphaComposite;
  17. import java.awt.BasicStroke;
  18. import java.awt.Color;
  19. import java.awt.Composite;
  20. import java.awt.Font;
  21. import java.awt.Graphics2D;
  22. import java.awt.GraphicsConfiguration;
  23. import java.awt.Insets;
  24. import java.awt.Paint;
  25. import java.awt.Rectangle;
  26. import java.awt.Shape;
  27. import java.awt.TexturePaint;
  28. import java.awt.font.FontRenderContext;
  29. import java.awt.font.GlyphVector;
  30. import java.awt.font.LineBreakMeasurer;
  31. import java.awt.font.TextAttribute;
  32. import java.awt.font.TextLayout;
  33. import java.awt.geom.AffineTransform;
  34. import java.awt.geom.Dimension2D;
  35. import java.awt.geom.NoninvertibleTransformException;
  36. import java.awt.geom.Point2D;
  37. import java.awt.geom.Rectangle2D;
  38. import java.awt.image.BufferedImage;
  39. import java.awt.image.DataBuffer;
  40. import java.awt.image.IndexColorModel;
  41. import java.nio.charset.Charset;
  42. import java.nio.charset.StandardCharsets;
  43. import java.text.AttributedString;
  44. import java.util.ArrayList;
  45. import java.util.BitSet;
  46. import java.util.HashMap;
  47. import java.util.LinkedList;
  48. import java.util.List;
  49. import java.util.Locale;
  50. import java.util.Map;
  51. import java.util.NoSuchElementException;
  52. import java.util.Objects;
  53. import java.util.TreeMap;
  54. import java.util.function.BiConsumer;
  55. import java.util.function.Supplier;
  56. import org.apache.poi.common.usermodel.fonts.FontCharset;
  57. import org.apache.poi.common.usermodel.fonts.FontInfo;
  58. import org.apache.poi.hwmf.record.HwmfBrushStyle;
  59. import org.apache.poi.hwmf.record.HwmfFont;
  60. import org.apache.poi.hwmf.record.HwmfMapMode;
  61. import org.apache.poi.hwmf.record.HwmfMisc.WmfSetBkMode.HwmfBkMode;
  62. import org.apache.poi.hwmf.record.HwmfObjectTableEntry;
  63. import org.apache.poi.hwmf.record.HwmfPenStyle;
  64. import org.apache.poi.hwmf.record.HwmfPenStyle.HwmfLineDash;
  65. import org.apache.poi.hwmf.record.HwmfRegionMode;
  66. import org.apache.poi.hwmf.record.HwmfText.WmfExtTextOutOptions;
  67. import org.apache.poi.hwmf.usermodel.HwmfCharsetAware;
  68. import org.apache.poi.sl.draw.BitmapImageRenderer;
  69. import org.apache.poi.sl.draw.DrawFactory;
  70. import org.apache.poi.sl.draw.DrawFontManager;
  71. import org.apache.poi.sl.draw.DrawPictureShape;
  72. import org.apache.poi.sl.draw.ImageRenderer;
  73. import org.apache.poi.util.Internal;
  74. import org.apache.poi.util.LocaleUtil;
  75. public class HwmfGraphics implements HwmfCharsetAware {
  76. public enum FillDrawStyle {
  77. NONE(FillDrawStyle::fillNone),
  78. FILL(HwmfGraphics::fill),
  79. DRAW(HwmfGraphics::draw),
  80. FILL_DRAW(FillDrawStyle::fillDraw);
  81. public final BiConsumer<HwmfGraphics,Shape> handler;
  82. FillDrawStyle(BiConsumer<HwmfGraphics,Shape> handler) {
  83. this.handler = handler;
  84. }
  85. private static void fillNone(HwmfGraphics g, Shape s) {
  86. }
  87. private static void fillDraw(HwmfGraphics g, Shape s) {
  88. g.fill(s);
  89. g.draw(s);
  90. }
  91. }
  92. private static final Float[] WEIGHT_MAP = {
  93. 900f, TextAttribute.WEIGHT_ULTRABOLD,
  94. 800f, TextAttribute.WEIGHT_EXTRABOLD,
  95. 750f, TextAttribute.WEIGHT_HEAVY,
  96. 700f, TextAttribute.WEIGHT_BOLD,
  97. 600f, TextAttribute.WEIGHT_DEMIBOLD,
  98. 500f, TextAttribute.WEIGHT_MEDIUM,
  99. 450f, TextAttribute.WEIGHT_SEMIBOLD,
  100. 400f, TextAttribute.WEIGHT_REGULAR,
  101. 300f, TextAttribute.WEIGHT_DEMILIGHT,
  102. 200f, TextAttribute.WEIGHT_LIGHT,
  103. 1f, TextAttribute.WEIGHT_EXTRA_LIGHT
  104. };
  105. private static class DxLayout {
  106. double dx;
  107. // Spacing at default tracking value of 0
  108. double pos0;
  109. // Spacing at second tracking value
  110. double pos1;
  111. int beginIndex;
  112. int endIndex;
  113. }
  114. private final List<HwmfDrawProperties> propStack = new LinkedList<>();
  115. protected HwmfDrawProperties prop;
  116. protected final Graphics2D graphicsCtx;
  117. protected final BitSet objectIndexes = new BitSet();
  118. protected final TreeMap<Integer,HwmfObjectTableEntry> objectTable = new TreeMap<>();
  119. private final AffineTransform initialAT = new AffineTransform();
  120. /** Bounding box from the placeable header */
  121. private final Rectangle2D bbox;
  122. private Supplier<Charset> charsetProvider = () -> LocaleUtil.CHARSET_1252;
  123. /**
  124. * Initialize a graphics context for wmf rendering
  125. *
  126. * @param graphicsCtx the graphics context to delegate drawing calls
  127. * @param bbox the bounding box of the wmf (taken from the placeable header)
  128. */
  129. public HwmfGraphics(Graphics2D graphicsCtx, Rectangle2D bbox) {
  130. this.graphicsCtx = graphicsCtx;
  131. this.bbox = (Rectangle2D)bbox.clone();
  132. this.initialAT.setTransform(graphicsCtx.getTransform());
  133. }
  134. public HwmfDrawProperties getProperties() {
  135. if (prop == null) {
  136. prop = newProperties(null);
  137. }
  138. return prop;
  139. }
  140. protected HwmfDrawProperties newProperties(HwmfDrawProperties oldProps) {
  141. return (oldProps == null) ? new HwmfDrawProperties() : new HwmfDrawProperties(oldProps);
  142. }
  143. public void draw(Shape shape) {
  144. HwmfPenStyle ps = getProperties().getPenStyle();
  145. if (ps == null) {
  146. return;
  147. }
  148. HwmfLineDash lineDash = ps.getLineDash();
  149. if (lineDash == HwmfLineDash.NULL) {
  150. // line is not drawn
  151. return;
  152. }
  153. BasicStroke stroke = getStroke();
  154. // first draw a solid background line (depending on bkmode)
  155. // only makes sense if the line is not solid
  156. if (getProperties().getBkMode() == HwmfBkMode.OPAQUE && (lineDash != HwmfLineDash.SOLID && lineDash != HwmfLineDash.INSIDEFRAME)) {
  157. graphicsCtx.setStroke(new BasicStroke(stroke.getLineWidth()));
  158. graphicsCtx.setColor(getProperties().getBackgroundColor().getColor());
  159. graphicsCtx.draw(shape);
  160. }
  161. // then draw the (dashed) line
  162. graphicsCtx.setStroke(stroke);
  163. graphicsCtx.setColor(getProperties().getPenColor().getColor());
  164. graphicsCtx.draw(shape);
  165. }
  166. public void fill(Shape shape) {
  167. HwmfDrawProperties prop = getProperties();
  168. if (prop.getBrushStyle() != HwmfBrushStyle.BS_NULL) {
  169. Composite old = graphicsCtx.getComposite();
  170. graphicsCtx.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
  171. // if (prop.getBkMode() == HwmfBkMode.OPAQUE) {
  172. // graphicsCtx.setPaint(prop.getBackgroundColor().getColor());
  173. // graphicsCtx.fill(shape);
  174. // }
  175. graphicsCtx.setPaint(getFill());
  176. graphicsCtx.fill(shape);
  177. graphicsCtx.setComposite(old);
  178. }
  179. draw(shape);
  180. }
  181. @SuppressWarnings("MagicConstant")
  182. protected BasicStroke getStroke() {
  183. HwmfDrawProperties prop = getProperties();
  184. HwmfPenStyle ps = prop.getPenStyle();
  185. // TODO: fix line width calculation
  186. float width = (float)prop.getPenWidth();
  187. if (width == 0) {
  188. width = 1;
  189. }
  190. int cap = ps.getLineCap().awtFlag;
  191. int join = ps.getLineJoin().awtFlag;
  192. float miterLimit = (float)prop.getPenMiterLimit();
  193. float[] dashes = ps.getLineDashes();
  194. boolean dashAlt = ps.isAlternateDash();
  195. // This value is not an integer index into the dash pattern array.
  196. // Instead, it is a floating-point value that specifies a linear distance.
  197. float dashStart = (dashAlt && dashes != null && dashes.length > 1) ? dashes[0] : 0;
  198. return new BasicStroke(width, cap, join, Math.max(1,miterLimit), dashes, dashStart);
  199. }
  200. protected Paint getFill() {
  201. switch (getProperties().getBrushStyle()) {
  202. default:
  203. case BS_INDEXED:
  204. case BS_PATTERN8X8:
  205. case BS_DIBPATTERN8X8:
  206. case BS_MONOPATTERN:
  207. case BS_NULL: return null;
  208. case BS_PATTERN:
  209. case BS_DIBPATTERN:
  210. case BS_DIBPATTERNPT: return getPatternPaint();
  211. case BS_SOLID: return getSolidFill();
  212. case BS_HATCHED: return getHatchedFill();
  213. case BS_LINEAR_GRADIENT: return getLinearGradient();
  214. }
  215. }
  216. protected Paint getLinearGradient() {
  217. return null;
  218. }
  219. protected Paint getSolidFill() {
  220. return getProperties().getBrushColor().getColor();
  221. }
  222. protected Paint getHatchedFill() {
  223. HwmfDrawProperties prop = getProperties();
  224. BufferedImage pattern = getPatternFromLong(
  225. prop.getBrushHatch().getPattern(),
  226. prop.getBackgroundColor().getColor(),
  227. prop.getBrushColor().getColor(),
  228. prop.getBkMode() == HwmfBkMode.TRANSPARENT
  229. );
  230. return new TexturePaint(pattern, new Rectangle(0,0,8,8));
  231. }
  232. public static BufferedImage getPatternFromLong(long patternLng, Color background, Color foreground, boolean hasAlpha) {
  233. final int[] cmap = {background.getRGB(), foreground.getRGB()};
  234. final IndexColorModel icm = new IndexColorModel(1, 2, cmap, 0, hasAlpha, hasAlpha ? 0 : -1, DataBuffer.TYPE_BYTE);
  235. final BufferedImage pattern = new BufferedImage(8, 8, BufferedImage.TYPE_BYTE_INDEXED, icm);
  236. byte[] pt = new byte[64];
  237. for (int i=0; i<pt.length; i++) {
  238. pt[i] = (byte)((patternLng >>> i) & 1);
  239. }
  240. pattern.getRaster().setDataElements(0, 0, 8, 8, pt);
  241. return pattern;
  242. }
  243. protected Paint getPatternPaint() {
  244. HwmfDrawProperties prop = getProperties();
  245. ImageRenderer bb = prop.getBrushBitmap();
  246. if (bb == null) {
  247. return null;
  248. }
  249. Dimension2D dim = bb.getDimension();
  250. Rectangle2D rect = new Rectangle2D.Double(0, 0, dim.getWidth(), dim.getHeight());
  251. rect = prop.getBrushTransform().createTransformedShape(rect).getBounds2D();
  252. return new TexturePaint(bb.getImage(), rect);
  253. }
  254. /**
  255. * Adds an record of type {@link HwmfObjectTableEntry} to the object table.
  256. *
  257. * Every object is assigned the lowest available index-that is, the smallest
  258. * numerical value-in the WMF Object Table. This binding happens at object creation,
  259. * not when the object is used.
  260. * Moreover, each object table index uniquely refers to an object.
  261. * Indexes in the WMF Object Table always start at 0.
  262. *
  263. * @param entry the object table entry
  264. */
  265. public void addObjectTableEntry(HwmfObjectTableEntry entry) {
  266. int objIdx = objectIndexes.nextClearBit(0);
  267. objectIndexes.set(objIdx);
  268. objectTable.put(objIdx, entry);
  269. }
  270. /**
  271. * Applies the object table entry
  272. *
  273. * @param index the index of the object table entry (0-based)
  274. *
  275. * @throws IndexOutOfBoundsException if the index is out of range
  276. * @throws NoSuchElementException if the entry was deleted before
  277. */
  278. public void applyObjectTableEntry(int index) {
  279. HwmfObjectTableEntry ote = objectTable.get(index);
  280. if (ote == null) {
  281. throw new NoSuchElementException("WMF reference exception - object table entry on index "+index+" was deleted before.");
  282. }
  283. ote.applyObject(this);
  284. }
  285. /**
  286. * Unsets (deletes) the object table entry for further usage
  287. *
  288. * When a META_DELETEOBJECT record (section 2.3.4.7) is received that specifies this
  289. * object's particular index, the object's resources are released, the binding to its
  290. * WMF Object Table index is ended, and the index value is returned to the pool of
  291. * available indexes. The index will be reused, if needed, by a subsequent object
  292. * created by another Object Record Type record.
  293. *
  294. * @param index the index (0-based)
  295. *
  296. * @throws IndexOutOfBoundsException if the index is out of range
  297. */
  298. public void unsetObjectTableEntry(int index) {
  299. if (index < 0) {
  300. throw new IndexOutOfBoundsException("Invalid index: "+index);
  301. }
  302. // sometime emfs remove object table entries before they set them
  303. // so ignore requests, if the table entry doesn't exist
  304. objectTable.remove(index);
  305. objectIndexes.clear(index);
  306. }
  307. /**
  308. * Saves the current properties to the stack
  309. */
  310. public void saveProperties() {
  311. final HwmfDrawProperties p = getProperties();
  312. assert(p != null);
  313. p.setTransform(graphicsCtx.getTransform());
  314. p.setClip(graphicsCtx.getClip());
  315. propStack.add(p);
  316. prop = newProperties(p);
  317. }
  318. /**
  319. * Restores the properties from the stack
  320. *
  321. * @param index if the index is positive, the n-th element from the start is activated.
  322. * If the index is negative, the n-th previous element relative to the current properties element is activated.
  323. */
  324. public void restoreProperties(int index) {
  325. if (index == 0) {
  326. return;
  327. }
  328. int stackIndex = index;
  329. if (stackIndex < 0) {
  330. int curIdx = propStack.indexOf(getProperties());
  331. if (curIdx == -1) {
  332. // the current element is not pushed to the stacked, i.e. it's the last
  333. curIdx = propStack.size();
  334. }
  335. stackIndex = curIdx + index;
  336. }
  337. if (stackIndex == -1) {
  338. // roll to last when curIdx == 0
  339. stackIndex = propStack.size()-1;
  340. }
  341. // The playback device context is restored by popping state information off a stack that was created by
  342. // prior SAVEDC records
  343. // ... so because being a stack, we will remove all entries having a greater index than the stackIndex
  344. for (int i=propStack.size()-1; i>=stackIndex; i--) {
  345. prop = propStack.remove(i);
  346. }
  347. graphicsCtx.setTransform(prop.getTransform());
  348. graphicsCtx.setClip(prop.getClip());
  349. }
  350. /**
  351. * After setting various window and viewport related properties,
  352. * the underlying graphics context needs to be adapted.
  353. * This methods gathers and sets the corresponding graphics transformations.
  354. */
  355. public void updateWindowMapMode() {
  356. Rectangle2D win = getProperties().getWindow();
  357. Rectangle2D view = getProperties().getViewport();
  358. HwmfMapMode mapMode = getProperties().getMapMode();
  359. graphicsCtx.setTransform(getInitTransform());
  360. switch (mapMode) {
  361. default:
  362. case MM_ANISOTROPIC:
  363. // scale window bounds to output bounds
  364. if (view != null) {
  365. graphicsCtx.translate(view.getCenterX(), view.getCenterY());
  366. graphicsCtx.scale(view.getWidth() / win.getWidth(), view.getHeight() / win.getHeight());
  367. graphicsCtx.translate(-win.getCenterX(), -win.getCenterY());
  368. }
  369. break;
  370. case MM_ISOTROPIC:
  371. // TODO: to be validated ...
  372. // like anisotropic, but use x-axis as reference
  373. graphicsCtx.translate(bbox.getCenterX(), bbox.getCenterY());
  374. graphicsCtx.scale(bbox.getWidth()/win.getWidth(), bbox.getWidth()/win.getWidth());
  375. graphicsCtx.translate(-win.getCenterX(), -win.getCenterY());
  376. break;
  377. case MM_LOMETRIC:
  378. case MM_HIMETRIC:
  379. case MM_LOENGLISH:
  380. case MM_HIENGLISH:
  381. case MM_TWIPS: {
  382. // TODO: to be validated ...
  383. GraphicsConfiguration gc = graphicsCtx.getDeviceConfiguration();
  384. graphicsCtx.transform(gc.getNormalizingTransform());
  385. graphicsCtx.scale(1./mapMode.scale, -1./mapMode.scale);
  386. graphicsCtx.translate(-win.getX(), -win.getY());
  387. break;
  388. }
  389. case MM_TEXT:
  390. // TODO: to be validated ...
  391. break;
  392. }
  393. }
  394. public void drawString(byte[] text, int length, Point2D reference) {
  395. drawString(text, length, reference, null, null, null, null, false);
  396. }
  397. public void drawString(byte[] text, int length, Point2D reference, Dimension2D scale, Rectangle2D clip, WmfExtTextOutOptions opts, List<Integer> dx, boolean isUnicode) {
  398. final HwmfDrawProperties prop = getProperties();
  399. final AffineTransform at = graphicsCtx.getTransform();
  400. try {
  401. at.createInverse();
  402. } catch (NoninvertibleTransformException e) {
  403. return;
  404. }
  405. final HwmfFont font = prop.getFont();
  406. if (font == null || text == null || text.length == 0) {
  407. return;
  408. }
  409. final Charset charset = getCharset(font, isUnicode);
  410. String textString = trimText(charset, text, length);
  411. if (textString.isEmpty()) {
  412. return;
  413. }
  414. final DrawFontManager fontHandler = DrawFactory.getInstance(graphicsCtx).getFontManager(graphicsCtx);
  415. final FontInfo fontInfo = fontHandler.getMappedFont(graphicsCtx, font);
  416. textString = fontHandler.mapFontCharset(graphicsCtx, fontInfo, textString);
  417. final AttributedString as = new AttributedString(textString);
  418. addAttributes(as::addAttribute, font, fontInfo.getTypeface());
  419. final FontRenderContext frc = graphicsCtx.getFontRenderContext();
  420. calculateDx(textString, dx, font, fontInfo, frc, as);
  421. LineBreakMeasurer lbm = new LineBreakMeasurer(as.getIterator(), frc);
  422. TextLayout textLayout = lbm.nextLayout(Integer.MAX_VALUE);
  423. final double angle = Math.toRadians(-font.getEscapement()/10.);
  424. // TODO: find out when to use asian align
  425. boolean useAsianAlign = (opts == null) &&
  426. textString.codePoints().anyMatch(Character::isIdeographic) &&
  427. charset.displayName(Locale.ROOT). startsWith("GB");
  428. final Point2D dst = getRotatedOffset(angle, frc, as, useAsianAlign);
  429. final Shape clipShape = graphicsCtx.getClip();
  430. try {
  431. updateClipping(graphicsCtx, clip, angle, opts);
  432. // TODO: Check: certain images don't use the reference of the extTextOut, but rely on a moveto issued beforehand
  433. Point2D moveTo = (reference.distance(0,0) == 0) ? prop.getLocation() : reference;
  434. graphicsCtx.translate(moveTo.getX(), moveTo.getY());
  435. graphicsCtx.rotate(angle);
  436. if (scale != null) {
  437. graphicsCtx.scale(scale.getWidth() < 0 ? -1 : 1, scale.getHeight() < 0 ? -1 : 1);
  438. }
  439. graphicsCtx.scale(at.getScaleX() < 0 ? -1 : 1, at.getScaleY() < 0 ? -1 : 1);
  440. graphicsCtx.translate(dst.getX(), dst.getY());
  441. graphicsCtx.setColor(prop.getTextColor().getColor());
  442. graphicsCtx.drawString(as.getIterator(), 0, 0);
  443. // move current location to the end of string
  444. AffineTransform atRev = new AffineTransform();
  445. atRev.translate(-dst.getX(), -dst.getY());
  446. if (scale != null) {
  447. atRev.scale(scale.getWidth() < 0 ? 1 : -1, scale.getHeight() < 0 ? 1 : -1);
  448. }
  449. atRev.rotate(-angle);
  450. Point2D deltaX = new Point2D.Double(textLayout.getBounds().getWidth(), 0);
  451. Point2D oldLoc = prop.getLocation();
  452. prop.setLocation(oldLoc.getX() + deltaX.getX(), oldLoc.getY() + deltaX.getY());
  453. } finally {
  454. graphicsCtx.setTransform(at);
  455. graphicsCtx.setClip(clipShape);
  456. }
  457. }
  458. /**
  459. * The dx array indicate the distance between origins of adjacent character cells.
  460. * For example, dx[i] logical units separate the origins of character cell i and character cell i + 1.
  461. * So dx{i] is the complete width of the current char + space to the next character
  462. *
  463. * In AWT we have the {@link TextAttribute#TRACKING} attribute, which works very similar.
  464. * As we don't know (yet) the calculation based on the font size/height, we interpolate
  465. * between the default tracking and a tracking value of 1
  466. */
  467. private void calculateDx(String textString, List<Integer> dx, HwmfFont font, FontInfo fontInfo, FontRenderContext frc, AttributedString as) {
  468. if (dx == null || dx.isEmpty()) {
  469. return;
  470. }
  471. final List<DxLayout> dxList = new ArrayList<>();
  472. Map<TextAttribute,Object> fontAtt = new HashMap<>();
  473. // Font tracking default (= 0)
  474. addAttributes(fontAtt::put, font, fontInfo.getTypeface());
  475. final GlyphVector gv0 = new Font(fontAtt).createGlyphVector(frc, textString);
  476. // Font tracking = 1
  477. fontAtt.put(TextAttribute.TRACKING, 1);
  478. final GlyphVector gv1 = new Font(fontAtt).createGlyphVector(frc, textString);
  479. int beginIndex = 0;
  480. for (int offset = 0; offset < dx.size(); offset++) {
  481. if (beginIndex >= textString.length()) {
  482. break;
  483. }
  484. DxLayout dxLayout = new DxLayout();
  485. dxLayout.dx = dx.get(offset);
  486. dxLayout.pos0 = gv0.getGlyphPosition(offset).getX();
  487. dxLayout.pos1 = gv1.getGlyphPosition(offset).getX();
  488. dxLayout.beginIndex = beginIndex;
  489. dxLayout.endIndex = textString.offsetByCodePoints(beginIndex, 1);
  490. dxList.add(dxLayout);
  491. beginIndex = dxLayout.endIndex;
  492. }
  493. // Calculate the linear (y ~= Tracking setting / x ~= character spacing / target value)
  494. // y = m * x + n
  495. // y = ((y2-y1)/(x2-x1))x + ((y1x2-y2x1)/(x2-x1))
  496. DxLayout dx0 = null;
  497. for (DxLayout dx1 : dxList) {
  498. if (dx0 != null) {
  499. // Default Tracking = 0 (y1)
  500. double y1 = 0, x1 = dx1.pos0-dx0.pos0;
  501. // Second Tracking = 1 (y2)
  502. double y2 = 1, x2 = dx1.pos1-dx0.pos1;
  503. double track = ((y2-y1)/(x2-x1))*dx0.dx + ((y1*x2-y2*x1)/(x2-x1));
  504. as.addAttribute(TextAttribute.TRACKING, (float)track, dx0.beginIndex, dx0.endIndex);
  505. }
  506. dx0 = dx1;
  507. }
  508. }
  509. private void addAttributes(BiConsumer<TextAttribute,Object> attributes, HwmfFont font, String typeface) {
  510. Map<TextAttribute,Object> att = new HashMap<>();
  511. att.put(TextAttribute.FAMILY, typeface);
  512. att.put(TextAttribute.SIZE, getFontHeight(font));
  513. if (font.isStrikeOut()) {
  514. att.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
  515. }
  516. if (font.isUnderline()) {
  517. att.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
  518. }
  519. if (font.isItalic()) {
  520. att.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
  521. }
  522. // convert font weight to awt font weight - usually a font weight of 400 is regarded as regular
  523. final int fw = font.getWeight();
  524. Float awtFW = TextAttribute.WEIGHT_REGULAR;
  525. for (int i=0; i<WEIGHT_MAP.length; i+=2) {
  526. if (fw >= WEIGHT_MAP[i]) {
  527. awtFW = WEIGHT_MAP[i+1];
  528. break;
  529. }
  530. }
  531. att.put(TextAttribute.WEIGHT, awtFW);
  532. att.put(TextAttribute.FONT, new Font(att));
  533. att.forEach(attributes);
  534. }
  535. private double getFontHeight(HwmfFont font) {
  536. // see HwmfFont#height for details
  537. double fontHeight = font.getHeight();
  538. if (fontHeight == 0) {
  539. return 12;
  540. } else if (fontHeight < 0) {
  541. return -fontHeight;
  542. } else {
  543. // TODO: fix font height calculation
  544. // the height is given as font size + ascent + descent
  545. // as an approximation we reduce the height by a static factor
  546. return fontHeight*3/4;
  547. }
  548. }
  549. private Charset getCharset(HwmfFont font, boolean isUnicode) {
  550. if (isUnicode) {
  551. return StandardCharsets.UTF_16LE;
  552. }
  553. FontCharset fc = font.getCharset();
  554. if (fc == FontCharset.DEFAULT) {
  555. return charsetProvider.get();
  556. }
  557. Charset charset = fc.getCharset();
  558. return (charset == null) ? charsetProvider.get() : charset;
  559. }
  560. @Override
  561. public void setCharsetProvider(Supplier<Charset> provider) {
  562. charsetProvider = provider;
  563. }
  564. private String trimText(Charset charset, byte[] text, int length) {
  565. int trimLen;
  566. for (trimLen=0; trimLen<text.length; trimLen+=2) {
  567. if (trimLen == text.length-1) {
  568. if (text[trimLen] != 0) {
  569. trimLen++;
  570. }
  571. break;
  572. } else if ((text[trimLen] == -1 && text[trimLen+1] == -1) ||
  573. ((text[trimLen] & 0xE0) == 0 && text[trimLen+1] == 0)) {
  574. break;
  575. }
  576. }
  577. String textString = new String(text, 0, trimLen, charset);
  578. return textString.substring(0, Math.min(textString.length(), length));
  579. }
  580. private void updateHorizontalAlign(AffineTransform tx, TextLayout layout, boolean useAsianAlign) {
  581. // TODO: using prop.getTextAlignAsian doesn't look good ...
  582. switch (prop.getTextAlignLatin()) {
  583. default:
  584. case LEFT:
  585. break;
  586. case CENTER:
  587. tx.translate(-layout.getBounds().getWidth() / 2., 0);
  588. break;
  589. case RIGHT:
  590. tx.translate(-layout.getAdvance(), 0);
  591. break;
  592. }
  593. }
  594. private void updateVerticalAlign(AffineTransform tx, TextLayout layout, boolean useAsianAlign) {
  595. // TODO: check min/max orientation
  596. switch (useAsianAlign ? prop.getTextVAlignAsian() : prop.getTextVAlignLatin()) {
  597. case TOP:
  598. tx.translate(0, layout.getAscent());
  599. break;
  600. default:
  601. case BASELINE:
  602. break;
  603. case BOTTOM:
  604. tx.translate(0, -(layout.getBounds().getHeight()-layout.getDescent()));
  605. break;
  606. }
  607. }
  608. private void updateClipping(Graphics2D graphicsCtx, Rectangle2D clip, double angle, WmfExtTextOutOptions opts) {
  609. if (clip == null || clip.getBounds2D().isEmpty()) {
  610. return;
  611. }
  612. final AffineTransform at = graphicsCtx.getTransform();
  613. graphicsCtx.translate(-clip.getCenterX(), -clip.getCenterY());
  614. graphicsCtx.rotate(angle);
  615. graphicsCtx.translate(clip.getCenterX(), clip.getCenterY());
  616. if (prop.getBkMode() == HwmfBkMode.OPAQUE && opts.isOpaque()) {
  617. graphicsCtx.setPaint(prop.getBackgroundColor().getColor());
  618. graphicsCtx.fill(clip);
  619. }
  620. if (opts.isClipped()) {
  621. graphicsCtx.setClip(clip);
  622. }
  623. graphicsCtx.setTransform(at);
  624. }
  625. private Point2D getRotatedOffset(double angle, FontRenderContext frc, AttributedString as, boolean useAsianAlign) {
  626. final TextLayout layout = new TextLayout(as.getIterator(), frc);
  627. final AffineTransform tx = new AffineTransform();
  628. updateHorizontalAlign(tx, layout, useAsianAlign);
  629. updateVerticalAlign(tx, layout, useAsianAlign);
  630. tx.rotate(angle);
  631. Point2D src = new Point2D.Double();
  632. return tx.transform(src, null);
  633. }
  634. public void drawImage(BufferedImage img, Rectangle2D srcBounds, Rectangle2D dstBounds) {
  635. drawImage(new BufferedImageRenderer(img), srcBounds, dstBounds);
  636. }
  637. public void drawImage(ImageRenderer img, Rectangle2D srcBounds, Rectangle2D dstBounds) {
  638. if (srcBounds.isEmpty()) {
  639. return;
  640. }
  641. HwmfDrawProperties prop = getProperties();
  642. // handle raster op
  643. // currently the raster op as described in https://docs.microsoft.com/en-us/windows/desktop/gdi/ternary-raster-operations
  644. // are not supported, as we would need to extract the destination image area from the underlying buffered image
  645. // and therefore would make it mandatory that the graphics context must be from a buffered image
  646. // furthermore I doubt the purpose of bitwise image operations on non-black/white images
  647. switch (prop.getRasterOp3()) {
  648. case D:
  649. // keep destination, i.e. do nothing
  650. break;
  651. case PATCOPY:
  652. graphicsCtx.setPaint(getFill());
  653. graphicsCtx.fill(dstBounds);
  654. break;
  655. case BLACKNESS:
  656. graphicsCtx.setPaint(Color.BLACK);
  657. graphicsCtx.fill(dstBounds);
  658. break;
  659. case WHITENESS:
  660. graphicsCtx.setPaint(Color.WHITE);
  661. graphicsCtx.fill(dstBounds);
  662. break;
  663. default:
  664. case SRCAND:
  665. case SRCCOPY:
  666. case SRCINVERT:
  667. if (img == null) {
  668. return;
  669. }
  670. final Shape oldClip = graphicsCtx.getClip();
  671. final AffineTransform oldTrans = graphicsCtx.getTransform();
  672. // add clipping in case of a source subimage, i.e. a clipped source image
  673. // some dstBounds are horizontal or vertical flipped, so we need to normalize the images
  674. Rectangle2D normBounds = normalizeRect(dstBounds);
  675. // graphicsCtx.clip(normBounds);
  676. if (prop.getBkMode() == HwmfBkMode.OPAQUE) {
  677. Paint oldPaint = graphicsCtx.getPaint();
  678. graphicsCtx.setPaint(prop.getBackgroundColor().getColor());
  679. graphicsCtx.fill(dstBounds);
  680. graphicsCtx.setPaint(oldPaint);
  681. }
  682. graphicsCtx.translate(normBounds.getCenterX(), normBounds.getCenterY());
  683. graphicsCtx.scale(Math.signum(dstBounds.getWidth()), Math.signum(dstBounds.getHeight()));
  684. graphicsCtx.translate(-normBounds.getCenterX(), -normBounds.getCenterY());
  685. // this is similar to drawing bitmaps with a clipping
  686. // see {@link BitmapImageRenderer#drawImage(Graphics2D,Rectangle2D,Insets)}
  687. // the difference is, that clippings are 0-based, whereas the srcBounds are absolute in the user-space
  688. // of the referenced image and can be also negative
  689. Composite old = graphicsCtx.getComposite();
  690. int newComp;
  691. switch (prop.getRasterOp3()) {
  692. default:
  693. case SRCCOPY:
  694. newComp = AlphaComposite.SRC_OVER;
  695. break;
  696. case SRCINVERT:
  697. newComp = AlphaComposite.SRC_IN;
  698. break;
  699. case SRCAND:
  700. newComp = AlphaComposite.SRC;
  701. break;
  702. }
  703. graphicsCtx.setComposite(AlphaComposite.getInstance(newComp));
  704. boolean useDeviceBounds = (img instanceof HwmfImageRenderer);
  705. img.drawImage(graphicsCtx, normBounds,
  706. getSubImageInsets(srcBounds, useDeviceBounds ? img.getNativeBounds() : img.getBounds()));
  707. graphicsCtx.setComposite(old);
  708. graphicsCtx.setTransform(oldTrans);
  709. graphicsCtx.setClip(oldClip);
  710. break;
  711. }
  712. }
  713. private static Rectangle2D normalizeRect(Rectangle2D dstBounds) {
  714. return new Rectangle2D.Double(
  715. dstBounds.getWidth() >= 0 ? dstBounds.getMinX() : dstBounds.getMaxX(),
  716. dstBounds.getHeight() >= 0 ? dstBounds.getMinY() : dstBounds.getMaxY(),
  717. Math.abs(dstBounds.getWidth()),
  718. Math.abs(dstBounds.getHeight()));
  719. }
  720. private static Insets getSubImageInsets(Rectangle2D srcBounds, Rectangle2D nativeBounds) {
  721. // Todo: check if we need to normalize srcBounds x/y, in case of flipped images
  722. // for now we assume the width/height is positive
  723. int left = (int)Math.round((srcBounds.getX()-nativeBounds.getX())/nativeBounds.getWidth()*100_000.);
  724. int top = (int)Math.round((srcBounds.getY()-nativeBounds.getY())/nativeBounds.getHeight()*100_000.);
  725. int right = (int)Math.round((nativeBounds.getMaxX()-srcBounds.getMaxX())/nativeBounds.getWidth()*100_000.);
  726. int bottom = (int)Math.round((nativeBounds.getMaxY()-srcBounds.getMaxY())/nativeBounds.getHeight()*100_000.);
  727. return new Insets(top, left, bottom, right);
  728. }
  729. /**
  730. * @return the initial AffineTransform, when this graphics context was created
  731. */
  732. public AffineTransform getInitTransform() {
  733. return new AffineTransform(initialAT);
  734. }
  735. /**
  736. * @return the current AffineTransform
  737. */
  738. public AffineTransform getTransform() {
  739. return new AffineTransform(graphicsCtx.getTransform());
  740. }
  741. /**
  742. * Set the current AffineTransform
  743. * @param tx the current AffineTransform
  744. */
  745. public void setTransform(AffineTransform tx) {
  746. graphicsCtx.setTransform(tx);
  747. }
  748. /**
  749. * Set the new clipping region
  750. *
  751. * @param clip the next clipping region to be processed
  752. * @param regionMode the mode and operation of how to apply the next clipping region
  753. * @param useInitialAT if true, the clipping is applied on the initial (world) coordinate system
  754. */
  755. public void setClip(Shape clip, HwmfRegionMode regionMode, boolean useInitialAT) {
  756. final AffineTransform at = graphicsCtx.getTransform();
  757. if (useInitialAT) {
  758. graphicsCtx.setTransform(getInitTransform());
  759. }
  760. final Shape oldClip = graphicsCtx.getClip();
  761. final Shape newClip = regionMode.applyOp(oldClip, clip);
  762. if (!Objects.equals(oldClip, newClip)) {
  763. graphicsCtx.setClip(newClip);
  764. }
  765. if (useInitialAT) {
  766. graphicsCtx.setTransform(at);
  767. }
  768. prop.setClip(graphicsCtx.getClip());
  769. }
  770. public ImageRenderer getImageRenderer(String contentType) {
  771. // TODO: refactor DrawPictureShape method to POI Common
  772. return DrawPictureShape.getImageRenderer(graphicsCtx, contentType);
  773. }
  774. @Internal
  775. static class BufferedImageRenderer extends BitmapImageRenderer {
  776. public BufferedImageRenderer(BufferedImage img) {
  777. this.img = img;
  778. }
  779. }
  780. }