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

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