Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/print/PSPathGraphics.java
38829 views
/*1* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.print;2627import java.awt.Color;28import java.awt.Font;29import java.awt.Graphics;30import java.awt.Graphics2D;31import java.awt.Image;32import java.awt.Shape;33import java.awt.Transparency;3435import java.awt.font.FontRenderContext;36import java.awt.font.TextLayout;3738import java.awt.geom.AffineTransform;39import java.awt.geom.Area;40import java.awt.geom.PathIterator;41import java.awt.geom.Point2D;42import java.awt.geom.Rectangle2D;43import java.awt.geom.Line2D;4445import java.awt.image.BufferedImage;46import sun.awt.image.ByteComponentRaster;4748import java.awt.print.PageFormat;49import java.awt.print.Printable;50import java.awt.print.PrinterException;51import java.awt.print.PrinterJob;5253/**54* This class converts paths into PostScript55* by breaking all graphics into fills and56* clips of paths.57*/5859class PSPathGraphics extends PathGraphics {6061/**62* For a drawing application the initial user space63* resolution is 72dpi.64*/65private static final int DEFAULT_USER_RES = 72;6667PSPathGraphics(Graphics2D graphics, PrinterJob printerJob,68Printable painter, PageFormat pageFormat, int pageIndex,69boolean canRedraw) {70super(graphics, printerJob, painter, pageFormat, pageIndex, canRedraw);71}7273/**74* Creates a new <code>Graphics</code> object that is75* a copy of this <code>Graphics</code> object.76* @return a new graphics context that is a copy of77* this graphics context.78* @since JDK1.079*/80public Graphics create() {8182return new PSPathGraphics((Graphics2D) getDelegate().create(),83getPrinterJob(),84getPrintable(),85getPageFormat(),86getPageIndex(),87canDoRedraws());88}899091/**92* Override the inherited implementation of fill93* so that we can generate PostScript in user space94* rather than device space.95*/96public void fill(Shape s, Color color) {97deviceFill(s.getPathIterator(new AffineTransform()), color);98}99100/**101* Draws the text given by the specified string, using this102* graphics context's current font and color. The baseline of the103* first character is at position (<i>x</i>, <i>y</i>) in this104* graphics context's coordinate system.105* @param str the string to be drawn.106* @param x the <i>x</i> coordinate.107* @param y the <i>y</i> coordinate.108* @see java.awt.Graphics#drawBytes109* @see java.awt.Graphics#drawChars110* @since JDK1.0111*/112public void drawString(String str, int x, int y) {113drawString(str, (float) x, (float) y);114}115116/**117* Renders the text specified by the specified <code>String</code>,118* using the current <code>Font</code> and <code>Paint</code> attributes119* in the <code>Graphics2D</code> context.120* The baseline of the first character is at position121* (<i>x</i>, <i>y</i>) in the User Space.122* The rendering attributes applied include the <code>Clip</code>,123* <code>Transform</code>, <code>Paint</code>, <code>Font</code> and124* <code>Composite</code> attributes. For characters in script systems125* such as Hebrew and Arabic, the glyphs can be rendered from right to126* left, in which case the coordinate supplied is the location of the127* leftmost character on the baseline.128* @param s the <code>String</code> to be rendered129* @param x, y the coordinates where the <code>String</code>130* should be rendered131* @see #setPaint132* @see java.awt.Graphics#setColor133* @see java.awt.Graphics#setFont134* @see #setTransform135* @see #setComposite136* @see #setClip137*/138public void drawString(String str, float x, float y) {139drawString(str, x, y, getFont(), getFontRenderContext(), 0f);140}141142143protected boolean canDrawStringToWidth() {144return true;145}146147protected int platformFontCount(Font font, String str) {148PSPrinterJob psPrinterJob = (PSPrinterJob) getPrinterJob();149return psPrinterJob.platformFontCount(font, str);150}151152protected void drawString(String str, float x, float y,153Font font, FontRenderContext frc, float w) {154if (str.length() == 0) {155return;156}157158/* If the Font has layout attributes we need to delegate to TextLayout.159* TextLayout renders text as GlyphVectors. We try to print those160* using printer fonts - ie using Postscript text operators so161* we may be reinvoked. In that case the "!printingGlyphVector" test162* prevents us recursing and instead sends us into the body of the163* method where we can safely ignore layout attributes as those164* are already handled by TextLayout.165*/166if (font.hasLayoutAttributes() && !printingGlyphVector) {167TextLayout layout = new TextLayout(str, font, frc);168layout.draw(this, x, y);169return;170}171172Font oldFont = getFont();173if (!oldFont.equals(font)) {174setFont(font);175} else {176oldFont = null;177}178179boolean drawnWithPS = false;180181float translateX = 0f, translateY = 0f;182boolean fontisTransformed = getFont().isTransformed();183184if (fontisTransformed) {185AffineTransform fontTx = getFont().getTransform();186int transformType = fontTx.getType();187/* TYPE_TRANSLATION is a flag bit but we can do "==" here188* because we want to detect when its just that bit set and189*190*/191if (transformType == AffineTransform.TYPE_TRANSLATION) {192translateX = (float)(fontTx.getTranslateX());193translateY = (float)(fontTx.getTranslateY());194if (Math.abs(translateX) < 0.00001) translateX = 0f;195if (Math.abs(translateY) < 0.00001) translateY = 0f;196fontisTransformed = false;197}198}199200boolean directToPS = !fontisTransformed;201202if (!PSPrinterJob.shapeTextProp && directToPS) {203204PSPrinterJob psPrinterJob = (PSPrinterJob) getPrinterJob();205if (psPrinterJob.setFont(getFont())) {206207/* Set the text color.208* We should not be in this shape printing path209* if the application is drawing with non-solid210* colors. We should be in the raster path. Because211* we are here in the shape path, the cast of the212* paint to a Color should be fine.213*/214try {215psPrinterJob.setColor((Color)getPaint());216} catch (ClassCastException e) {217if (oldFont != null) {218setFont(oldFont);219}220throw new IllegalArgumentException(221"Expected a Color instance");222}223224psPrinterJob.setTransform(getTransform());225psPrinterJob.setClip(getClip());226227drawnWithPS = psPrinterJob.textOut(this, str,228x+translateX, y+translateY,229font, frc, w);230}231}232233/* The text could not be converted directly to PS text234* calls so decompose the text into a shape.235*/236if (drawnWithPS == false) {237if (oldFont != null) {238setFont(oldFont);239oldFont = null;240}241super.drawString(str, x, y, font, frc, w);242}243244if (oldFont != null) {245setFont(oldFont);246}247}248249/**250* The various <code>drawImage()</code> methods for251* <code>WPathGraphics</code> are all decomposed252* into an invocation of <code>drawImageToPlatform</code>.253* The portion of the passed in image defined by254* <code>srcX, srcY, srcWidth, and srcHeight</code>255* is transformed by the supplied AffineTransform and256* drawn using PS to the printer context.257*258* @param img The image to be drawn.259* This method does nothing if <code>img</code> is null.260* @param xform Used to transform the image before drawing.261* This can be null.262* @param bgcolor This color is drawn where the image has transparent263* pixels. If this parameter is null then the264* pixels already in the destination should show265* through.266* @param srcX With srcY this defines the upper-left corner267* of the portion of the image to be drawn.268*269* @param srcY With srcX this defines the upper-left corner270* of the portion of the image to be drawn.271* @param srcWidth The width of the portion of the image to272* be drawn.273* @param srcHeight The height of the portion of the image to274* be drawn.275* @param handlingTransparency if being recursively called to276* print opaque region of transparent image277*/278protected boolean drawImageToPlatform(Image image, AffineTransform xform,279Color bgcolor,280int srcX, int srcY,281int srcWidth, int srcHeight,282boolean handlingTransparency) {283284BufferedImage img = getBufferedImage(image);285if (img == null) {286return true;287}288289PSPrinterJob psPrinterJob = (PSPrinterJob) getPrinterJob();290291/* The full transform to be applied to the image is the292* caller's transform concatenated on to the transform293* from user space to device space. If the caller didn't294* supply a transform then we just act as if they passed295* in the identify transform.296*/297AffineTransform fullTransform = getTransform();298if (xform == null) {299xform = new AffineTransform();300}301fullTransform.concatenate(xform);302303/* Split the full transform into a pair of304* transforms. The first transform holds effects305* such as rotation and shearing. The second transform306* is setup to hold only the scaling effects.307* These transforms are created such that a point,308* p, in user space, when transformed by 'fullTransform'309* lands in the same place as when it is transformed310* by 'rotTransform' and then 'scaleTransform'.311*312* The entire image transformation is not in Java in order313* to minimize the amount of memory needed in the VM. By314* dividing the transform in two, we rotate and shear315* the source image in its own space and only go to316* the, usually, larger, device space when we ask317* PostScript to perform the final scaling.318*/319double[] fullMatrix = new double[6];320fullTransform.getMatrix(fullMatrix);321322/* Calculate the amount of scaling in the x323* and y directions. This scaling is computed by324* transforming a unit vector along each axis325* and computing the resulting magnitude.326* The computed values 'scaleX' and 'scaleY'327* represent the amount of scaling PS will be asked328* to perform.329* Clamp this to the device scale for better quality printing.330*/331Point2D.Float unitVectorX = new Point2D.Float(1, 0);332Point2D.Float unitVectorY = new Point2D.Float(0, 1);333fullTransform.deltaTransform(unitVectorX, unitVectorX);334fullTransform.deltaTransform(unitVectorY, unitVectorY);335336Point2D.Float origin = new Point2D.Float(0, 0);337double scaleX = unitVectorX.distance(origin);338double scaleY = unitVectorY.distance(origin);339340double devResX = psPrinterJob.getXRes();341double devResY = psPrinterJob.getYRes();342double devScaleX = devResX / DEFAULT_USER_RES;343double devScaleY = devResY / DEFAULT_USER_RES;344345/* check if rotated or sheared */346int transformType = fullTransform.getType();347boolean clampScale = ((transformType &348(AffineTransform.TYPE_GENERAL_ROTATION |349AffineTransform.TYPE_GENERAL_TRANSFORM)) != 0);350if (clampScale) {351if (scaleX > devScaleX) scaleX = devScaleX;352if (scaleY > devScaleY) scaleY = devScaleY;353}354355/* We do not need to draw anything if either scaling356* factor is zero.357*/358if (scaleX != 0 && scaleY != 0) {359360/* Here's the transformation we will do with Java2D,361*/362AffineTransform rotTransform = new AffineTransform(363fullMatrix[0] / scaleX, //m00364fullMatrix[1] / scaleY, //m10365fullMatrix[2] / scaleX, //m01366fullMatrix[3] / scaleY, //m11367fullMatrix[4] / scaleX, //m02368fullMatrix[5] / scaleY); //m12369370/* The scale transform is not used directly: we instead371* directly multiply by scaleX and scaleY.372*373* Conceptually here is what the scaleTransform is:374*375* AffineTransform scaleTransform = new AffineTransform(376* scaleX, //m00377* 0, //m10378* 0, //m01379* scaleY, //m11380* 0, //m02381* 0); //m12382*/383384/* Convert the image source's rectangle into the rotated385* and sheared space. Once there, we calculate a rectangle386* that encloses the resulting shape. It is this rectangle387* which defines the size of the BufferedImage we need to388* create to hold the transformed image.389*/390Rectangle2D.Float srcRect = new Rectangle2D.Float(srcX, srcY,391srcWidth,392srcHeight);393394Shape rotShape = rotTransform.createTransformedShape(srcRect);395Rectangle2D rotBounds = rotShape.getBounds2D();396397/* add a fudge factor as some fp precision problems have398* been observed which caused pixels to be rounded down and399* out of the image.400*/401rotBounds.setRect(rotBounds.getX(), rotBounds.getY(),402rotBounds.getWidth()+0.001,403rotBounds.getHeight()+0.001);404405int boundsWidth = (int) rotBounds.getWidth();406int boundsHeight = (int) rotBounds.getHeight();407408if (boundsWidth > 0 && boundsHeight > 0) {409410411/* If the image has transparent or semi-transparent412* pixels then we'll have the application re-render413* the portion of the page covered by the image.414* This will be done in a later call to print using the415* saved graphics state.416* However several special cases can be handled otherwise:417* - bitmask transparency with a solid background colour418* - images which have transparency color models but no419* transparent pixels420* - images with bitmask transparency and an IndexColorModel421* (the common transparent GIF case) can be handled by422* rendering just the opaque pixels.423*/424boolean drawOpaque = true;425if (!handlingTransparency && hasTransparentPixels(img)) {426drawOpaque = false;427if (isBitmaskTransparency(img)) {428if (bgcolor == null) {429if (drawBitmaskImage(img, xform, bgcolor,430srcX, srcY,431srcWidth, srcHeight)) {432// image drawn, just return.433return true;434}435} else if (bgcolor.getTransparency()436== Transparency.OPAQUE) {437drawOpaque = true;438}439}440if (!canDoRedraws()) {441drawOpaque = true;442}443} else {444// if there's no transparent pixels there's no need445// for a background colour. This can avoid edge artifacts446// in rotation cases.447bgcolor = null;448}449// if src region extends beyond the image, the "opaque" path450// may blit b/g colour (including white) where it shoudn't.451if ((srcX+srcWidth > img.getWidth(null) ||452srcY+srcHeight > img.getHeight(null))453&& canDoRedraws()) {454drawOpaque = false;455}456if (drawOpaque == false) {457458fullTransform.getMatrix(fullMatrix);459AffineTransform tx =460new AffineTransform(461fullMatrix[0] / devScaleX, //m00462fullMatrix[1] / devScaleY, //m10463fullMatrix[2] / devScaleX, //m01464fullMatrix[3] / devScaleY, //m11465fullMatrix[4] / devScaleX, //m02466fullMatrix[5] / devScaleY); //m12467468Rectangle2D.Float rect =469new Rectangle2D.Float(srcX, srcY, srcWidth, srcHeight);470471Shape shape = fullTransform.createTransformedShape(rect);472// Region isn't user space because its potentially473// been rotated for landscape.474Rectangle2D region = shape.getBounds2D();475476region.setRect(region.getX(), region.getY(),477region.getWidth()+0.001,478region.getHeight()+0.001);479480// Try to limit the amount of memory used to 8Mb, so481// if at device resolution this exceeds a certain482// image size then scale down the region to fit in483// that memory, but never to less than 72 dpi.484485int w = (int)region.getWidth();486int h = (int)region.getHeight();487int nbytes = w * h * 3;488int maxBytes = 8 * 1024 * 1024;489double origDpi = (devResX < devResY) ? devResX : devResY;490int dpi = (int)origDpi;491double scaleFactor = 1;492493double maxSFX = w/(double)boundsWidth;494double maxSFY = h/(double)boundsHeight;495double maxSF = (maxSFX > maxSFY) ? maxSFY : maxSFX;496int minDpi = (int)(dpi/maxSF);497if (minDpi < DEFAULT_USER_RES) minDpi = DEFAULT_USER_RES;498499while (nbytes > maxBytes && dpi > minDpi) {500scaleFactor *= 2;501dpi /= 2;502nbytes /= 4;503}504if (dpi < minDpi) {505scaleFactor = (origDpi / minDpi);506}507508region.setRect(region.getX()/scaleFactor,509region.getY()/scaleFactor,510region.getWidth()/scaleFactor,511region.getHeight()/scaleFactor);512513/*514* We need to have the clip as part of the saved state,515* either directly, or all the components that are516* needed to reconstitute it (image source area,517* image transform and current graphics transform).518* The clip is described in user space, so we need to519* save the current graphics transform anyway so just520* save these two.521*/522psPrinterJob.saveState(getTransform(), getClip(),523region, scaleFactor, scaleFactor);524return true;525526/* The image can be rendered directly by PS so we527* copy it into a BufferedImage (this takes care of528* ColorSpace and BufferedImageOp issues) and then529* send that to PS.530*/531} else {532533/* Create a buffered image big enough to hold the portion534* of the source image being printed.535*/536BufferedImage deepImage = new BufferedImage(537(int) rotBounds.getWidth(),538(int) rotBounds.getHeight(),539BufferedImage.TYPE_3BYTE_BGR);540541/* Setup a Graphics2D on to the BufferedImage so that the542* source image when copied, lands within the image buffer.543*/544Graphics2D imageGraphics = deepImage.createGraphics();545imageGraphics.clipRect(0, 0,546deepImage.getWidth(),547deepImage.getHeight());548549imageGraphics.translate(-rotBounds.getX(),550-rotBounds.getY());551imageGraphics.transform(rotTransform);552553/* Fill the BufferedImage either with the caller supplied554* color, 'bgColor' or, if null, with white.555*/556if (bgcolor == null) {557bgcolor = Color.white;558}559560/* REMIND: no need to use scaling here. */561imageGraphics.drawImage(img,562srcX, srcY,563srcX + srcWidth, srcY + srcHeight,564srcX, srcY,565srcX + srcWidth, srcY + srcHeight,566bgcolor, null);567568/* In PSPrinterJob images are printed in device space569* and therefore we need to set a device space clip.570* FIX: this is an overly tight coupling of these571* two classes.572* The temporary clip set needs to be an intersection573* with the previous user clip.574* REMIND: two xfms may lose accuracy in clip path.575*/576Shape holdClip = getClip();577Shape oldClip =578getTransform().createTransformedShape(holdClip);579AffineTransform sat = AffineTransform.getScaleInstance(580scaleX, scaleY);581Shape imgClip = sat.createTransformedShape(rotShape);582Area imgArea = new Area(imgClip);583Area oldArea = new Area(oldClip);584imgArea.intersect(oldArea);585psPrinterJob.setClip(imgArea);586587/* Scale the bounding rectangle by the scale transform.588* Because the scaling transform has only x and y589* scaling components it is equivalent to multiply590* the x components of the bounding rectangle by591* the x scaling factor and to multiply the y components592* by the y scaling factor.593*/594Rectangle2D.Float scaledBounds595= new Rectangle2D.Float(596(float) (rotBounds.getX() * scaleX),597(float) (rotBounds.getY() * scaleY),598(float) (rotBounds.getWidth() * scaleX),599(float) (rotBounds.getHeight() * scaleY));600601602/* Pull the raster data from the buffered image603* and pass it along to PS.604*/605ByteComponentRaster tile =606(ByteComponentRaster)deepImage.getRaster();607608psPrinterJob.drawImageBGR(tile.getDataStorage(),609scaledBounds.x, scaledBounds.y,610(float)Math.rint(scaledBounds.width+0.5),611(float)Math.rint(scaledBounds.height+0.5),6120f, 0f,613deepImage.getWidth(), deepImage.getHeight(),614deepImage.getWidth(), deepImage.getHeight());615616/* Reset the device clip to match user clip */617psPrinterJob.setClip(618getTransform().createTransformedShape(holdClip));619620621imageGraphics.dispose();622}623624}625}626627return true;628}629630/** Redraw a rectanglular area using a proxy graphics631* To do this we need to know the rectangular area to redraw and632* the transform & clip in effect at the time of the original drawImage633*634*/635636public void redrawRegion(Rectangle2D region, double scaleX, double scaleY,637Shape savedClip, AffineTransform savedTransform)638639throws PrinterException {640641PSPrinterJob psPrinterJob = (PSPrinterJob)getPrinterJob();642Printable painter = getPrintable();643PageFormat pageFormat = getPageFormat();644int pageIndex = getPageIndex();645646/* Create a buffered image big enough to hold the portion647* of the source image being printed.648*/649BufferedImage deepImage = new BufferedImage(650(int) region.getWidth(),651(int) region.getHeight(),652BufferedImage.TYPE_3BYTE_BGR);653654/* Get a graphics for the application to render into.655* We initialize the buffer to white in order to656* match the paper and then we shift the BufferedImage657* so that it covers the area on the page where the658* caller's Image will be drawn.659*/660Graphics2D g = deepImage.createGraphics();661ProxyGraphics2D proxy = new ProxyGraphics2D(g, psPrinterJob);662proxy.setColor(Color.white);663proxy.fillRect(0, 0, deepImage.getWidth(), deepImage.getHeight());664proxy.clipRect(0, 0, deepImage.getWidth(), deepImage.getHeight());665666proxy.translate(-region.getX(), -region.getY());667668/* Calculate the resolution of the source image.669*/670float sourceResX = (float)(psPrinterJob.getXRes() / scaleX);671float sourceResY = (float)(psPrinterJob.getYRes() / scaleY);672673/* The application expects to see user space at 72 dpi.674* so change user space from image source resolution to675* 72 dpi.676*/677proxy.scale(sourceResX / DEFAULT_USER_RES,678sourceResY / DEFAULT_USER_RES);679proxy.translate(680-psPrinterJob.getPhysicalPrintableX(pageFormat.getPaper())681/ psPrinterJob.getXRes() * DEFAULT_USER_RES,682-psPrinterJob.getPhysicalPrintableY(pageFormat.getPaper())683/ psPrinterJob.getYRes() * DEFAULT_USER_RES);684/* NB User space now has to be at 72 dpi for this calc to be correct */685proxy.transform(new AffineTransform(getPageFormat().getMatrix()));686687proxy.setPaint(Color.black);688689painter.print(proxy, pageFormat, pageIndex);690691g.dispose();692693/* In PSPrinterJob images are printed in device space694* and therefore we need to set a device space clip.695*/696psPrinterJob.setClip(savedTransform.createTransformedShape(savedClip));697698699/* Scale the bounding rectangle by the scale transform.700* Because the scaling transform has only x and y701* scaling components it is equivalent to multiply702* the x components of the bounding rectangle by703* the x scaling factor and to multiply the y components704* by the y scaling factor.705*/706Rectangle2D.Float scaledBounds707= new Rectangle2D.Float(708(float) (region.getX() * scaleX),709(float) (region.getY() * scaleY),710(float) (region.getWidth() * scaleX),711(float) (region.getHeight() * scaleY));712713714/* Pull the raster data from the buffered image715* and pass it along to PS.716*/717ByteComponentRaster tile = (ByteComponentRaster)deepImage.getRaster();718719psPrinterJob.drawImageBGR(tile.getDataStorage(),720scaledBounds.x, scaledBounds.y,721scaledBounds.width,722scaledBounds.height,7230f, 0f,724deepImage.getWidth(), deepImage.getHeight(),725deepImage.getWidth(), deepImage.getHeight());726727728}729730731/*732* Fill the path defined by <code>pathIter</code>733* with the specified color.734* The path is provided in current user space.735*/736protected void deviceFill(PathIterator pathIter, Color color) {737738PSPrinterJob psPrinterJob = (PSPrinterJob) getPrinterJob();739psPrinterJob.deviceFill(pathIter, color, getTransform(), getClip());740}741742/*743* Draw the bounding rectangle using path by calling draw()744* function and passing a rectangle shape.745*/746protected void deviceFrameRect(int x, int y, int width, int height,747Color color) {748749draw(new Rectangle2D.Float(x, y, width, height));750}751752/*753* Draw a line using path by calling draw() function and passing754* a line shape.755*/756protected void deviceDrawLine(int xBegin, int yBegin,757int xEnd, int yEnd, Color color) {758759draw(new Line2D.Float(xBegin, yBegin, xEnd, yEnd));760}761762/*763* Fill the rectangle with the specified color by calling fill().764*/765protected void deviceFillRect(int x, int y, int width, int height,766Color color) {767fill(new Rectangle2D.Float(x, y, width, height));768}769770771/*772* This method should not be invoked by PSPathGraphics.773* FIX: Rework PathGraphics so that this method is774* not an abstract method there.775*/776protected void deviceClip(PathIterator pathIter) {777}778779}780781782