Path: blob/master/src/java.desktop/share/classes/sun/print/PSPathGraphics.java
41153 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} object that is75* a copy of this {@code Graphics} object.76* @return a new graphics context that is a copy of77* this graphics context.78* @since 1.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 1.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},118* using the current {@code Font} and {@code Paint} attributes119* in the {@code Graphics2D} 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},123* {@code Transform}, {@code Paint}, {@code Font} and124* {@code Composite} 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 str the {@code String} to be rendered129* @param x, y the coordinates where the {@code String}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()} methods for251* {@code WPathGraphics} are all decomposed252* into an invocation of {@code drawImageToPlatform}.253* The portion of the passed in image defined by254* {@code srcX, srcY, srcWidth, and srcHeight}255* is transformed by the supplied AffineTransform and256* drawn using PS to the printer context.257*258* @param image The image to be drawn.259* This method does nothing if {@code img} 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 (isCompositing(getComposite())) {426drawOpaque = false;427} else if (!handlingTransparency && hasTransparentPixels(img)) {428drawOpaque = false;429if (isBitmaskTransparency(img)) {430if (bgcolor == null) {431if (drawBitmaskImage(img, xform, bgcolor,432srcX, srcY,433srcWidth, srcHeight)) {434// image drawn, just return.435return true;436}437} else if (bgcolor.getTransparency()438== Transparency.OPAQUE) {439drawOpaque = true;440}441}442if (!canDoRedraws()) {443drawOpaque = true;444}445} else {446// if there's no transparent pixels there's no need447// for a background colour. This can avoid edge artifacts448// in rotation cases.449bgcolor = null;450}451// if src region extends beyond the image, the "opaque" path452// may blit b/g colour (including white) where it shoudn't.453if ((srcX+srcWidth > img.getWidth(null) ||454srcY+srcHeight > img.getHeight(null))455&& canDoRedraws()) {456drawOpaque = false;457}458if (drawOpaque == false) {459460fullTransform.getMatrix(fullMatrix);461AffineTransform tx =462new AffineTransform(463fullMatrix[0] / devScaleX, //m00464fullMatrix[1] / devScaleY, //m10465fullMatrix[2] / devScaleX, //m01466fullMatrix[3] / devScaleY, //m11467fullMatrix[4] / devScaleX, //m02468fullMatrix[5] / devScaleY); //m12469470Rectangle2D.Float rect =471new Rectangle2D.Float(srcX, srcY, srcWidth, srcHeight);472473Shape shape = fullTransform.createTransformedShape(rect);474// Region isn't user space because its potentially475// been rotated for landscape.476Rectangle2D region = shape.getBounds2D();477478region.setRect(region.getX(), region.getY(),479region.getWidth()+0.001,480region.getHeight()+0.001);481482// Try to limit the amount of memory used to 8Mb, so483// if at device resolution this exceeds a certain484// image size then scale down the region to fit in485// that memory, but never to less than 72 dpi.486487int w = (int)region.getWidth();488int h = (int)region.getHeight();489int nbytes = w * h * 3;490int maxBytes = 8 * 1024 * 1024;491double origDpi = (devResX < devResY) ? devResX : devResY;492int dpi = (int)origDpi;493double scaleFactor = 1;494495double maxSFX = w/(double)boundsWidth;496double maxSFY = h/(double)boundsHeight;497double maxSF = (maxSFX > maxSFY) ? maxSFY : maxSFX;498int minDpi = (int)(dpi/maxSF);499if (minDpi < DEFAULT_USER_RES) minDpi = DEFAULT_USER_RES;500501while (nbytes > maxBytes && dpi > minDpi) {502scaleFactor *= 2;503dpi /= 2;504nbytes /= 4;505}506if (dpi < minDpi) {507scaleFactor = (origDpi / minDpi);508}509510region.setRect(region.getX()/scaleFactor,511region.getY()/scaleFactor,512region.getWidth()/scaleFactor,513region.getHeight()/scaleFactor);514515/*516* We need to have the clip as part of the saved state,517* either directly, or all the components that are518* needed to reconstitute it (image source area,519* image transform and current graphics transform).520* The clip is described in user space, so we need to521* save the current graphics transform anyway so just522* save these two.523*/524psPrinterJob.saveState(getTransform(), getClip(),525region, scaleFactor, scaleFactor);526return true;527528/* The image can be rendered directly by PS so we529* copy it into a BufferedImage (this takes care of530* ColorSpace and BufferedImageOp issues) and then531* send that to PS.532*/533} else {534535/* Create a buffered image big enough to hold the portion536* of the source image being printed.537*/538BufferedImage deepImage = new BufferedImage(539(int) rotBounds.getWidth(),540(int) rotBounds.getHeight(),541BufferedImage.TYPE_3BYTE_BGR);542543/* Setup a Graphics2D on to the BufferedImage so that the544* source image when copied, lands within the image buffer.545*/546Graphics2D imageGraphics = deepImage.createGraphics();547imageGraphics.clipRect(0, 0,548deepImage.getWidth(),549deepImage.getHeight());550551imageGraphics.translate(-rotBounds.getX(),552-rotBounds.getY());553imageGraphics.transform(rotTransform);554555/* Fill the BufferedImage either with the caller supplied556* color, 'bgColor' or, if null, with white.557*/558if (bgcolor == null) {559bgcolor = Color.white;560}561562/* REMIND: no need to use scaling here. */563imageGraphics.drawImage(img,564srcX, srcY,565srcX + srcWidth, srcY + srcHeight,566srcX, srcY,567srcX + srcWidth, srcY + srcHeight,568bgcolor, null);569570/* In PSPrinterJob images are printed in device space571* and therefore we need to set a device space clip.572* FIX: this is an overly tight coupling of these573* two classes.574* The temporary clip set needs to be an intersection575* with the previous user clip.576* REMIND: two xfms may lose accuracy in clip path.577*/578Shape holdClip = getClip();579Shape oldClip =580getTransform().createTransformedShape(holdClip);581AffineTransform sat = AffineTransform.getScaleInstance(582scaleX, scaleY);583Shape imgClip = sat.createTransformedShape(rotShape);584Area imgArea = new Area(imgClip);585Area oldArea = new Area(oldClip);586imgArea.intersect(oldArea);587psPrinterJob.setClip(imgArea);588589/* Scale the bounding rectangle by the scale transform.590* Because the scaling transform has only x and y591* scaling components it is equivalent to multiply592* the x components of the bounding rectangle by593* the x scaling factor and to multiply the y components594* by the y scaling factor.595*/596Rectangle2D.Float scaledBounds597= new Rectangle2D.Float(598(float) (rotBounds.getX() * scaleX),599(float) (rotBounds.getY() * scaleY),600(float) (rotBounds.getWidth() * scaleX),601(float) (rotBounds.getHeight() * scaleY));602603604/* Pull the raster data from the buffered image605* and pass it along to PS.606*/607ByteComponentRaster tile =608(ByteComponentRaster)deepImage.getRaster();609610psPrinterJob.drawImageBGR(tile.getDataStorage(),611scaledBounds.x, scaledBounds.y,612(float)Math.rint(scaledBounds.width+0.5),613(float)Math.rint(scaledBounds.height+0.5),6140f, 0f,615deepImage.getWidth(), deepImage.getHeight(),616deepImage.getWidth(), deepImage.getHeight());617618/* Reset the device clip to match user clip */619psPrinterJob.setClip(620getTransform().createTransformedShape(holdClip));621622623imageGraphics.dispose();624}625626}627}628629return true;630}631632/** Redraw a rectanglular area using a proxy graphics633* To do this we need to know the rectangular area to redraw and634* the transform & clip in effect at the time of the original drawImage635*636*/637638public void redrawRegion(Rectangle2D region, double scaleX, double scaleY,639Shape savedClip, AffineTransform savedTransform)640641throws PrinterException {642643PSPrinterJob psPrinterJob = (PSPrinterJob)getPrinterJob();644Printable painter = getPrintable();645PageFormat pageFormat = getPageFormat();646int pageIndex = getPageIndex();647648/* Create a buffered image big enough to hold the portion649* of the source image being printed.650*/651BufferedImage deepImage = new BufferedImage(652(int) region.getWidth(),653(int) region.getHeight(),654BufferedImage.TYPE_3BYTE_BGR);655656/* Get a graphics for the application to render into.657* We initialize the buffer to white in order to658* match the paper and then we shift the BufferedImage659* so that it covers the area on the page where the660* caller's Image will be drawn.661*/662Graphics2D g = deepImage.createGraphics();663ProxyGraphics2D proxy = new ProxyGraphics2D(g, psPrinterJob);664proxy.setColor(Color.white);665proxy.fillRect(0, 0, deepImage.getWidth(), deepImage.getHeight());666proxy.clipRect(0, 0, deepImage.getWidth(), deepImage.getHeight());667668proxy.translate(-region.getX(), -region.getY());669670/* Calculate the resolution of the source image.671*/672float sourceResX = (float)(psPrinterJob.getXRes() / scaleX);673float sourceResY = (float)(psPrinterJob.getYRes() / scaleY);674675/* The application expects to see user space at 72 dpi.676* so change user space from image source resolution to677* 72 dpi.678*/679proxy.scale(sourceResX / DEFAULT_USER_RES,680sourceResY / DEFAULT_USER_RES);681proxy.translate(682-psPrinterJob.getPhysicalPrintableX(pageFormat.getPaper())683/ psPrinterJob.getXRes() * DEFAULT_USER_RES,684-psPrinterJob.getPhysicalPrintableY(pageFormat.getPaper())685/ psPrinterJob.getYRes() * DEFAULT_USER_RES);686/* NB User space now has to be at 72 dpi for this calc to be correct */687proxy.transform(new AffineTransform(getPageFormat().getMatrix()));688689proxy.setPaint(Color.black);690691painter.print(proxy, pageFormat, pageIndex);692693g.dispose();694695/* In PSPrinterJob images are printed in device space696* and therefore we need to set a device space clip.697*/698psPrinterJob.setClip(savedTransform.createTransformedShape(savedClip));699700701/* Scale the bounding rectangle by the scale transform.702* Because the scaling transform has only x and y703* scaling components it is equivalent to multiply704* the x components of the bounding rectangle by705* the x scaling factor and to multiply the y components706* by the y scaling factor.707*/708Rectangle2D.Float scaledBounds709= new Rectangle2D.Float(710(float) (region.getX() * scaleX),711(float) (region.getY() * scaleY),712(float) (region.getWidth() * scaleX),713(float) (region.getHeight() * scaleY));714715716/* Pull the raster data from the buffered image717* and pass it along to PS.718*/719ByteComponentRaster tile = (ByteComponentRaster)deepImage.getRaster();720721psPrinterJob.drawImageBGR(tile.getDataStorage(),722scaledBounds.x, scaledBounds.y,723scaledBounds.width,724scaledBounds.height,7250f, 0f,726deepImage.getWidth(), deepImage.getHeight(),727deepImage.getWidth(), deepImage.getHeight());728729730}731732733/*734* Fill the path defined by {@code pathIter}735* with the specified color.736* The path is provided in current user space.737*/738protected void deviceFill(PathIterator pathIter, Color color) {739740PSPrinterJob psPrinterJob = (PSPrinterJob) getPrinterJob();741psPrinterJob.deviceFill(pathIter, color, getTransform(), getClip());742}743744/*745* Draw the bounding rectangle using path by calling draw()746* function and passing a rectangle shape.747*/748protected void deviceFrameRect(int x, int y, int width, int height,749Color color) {750751draw(new Rectangle2D.Float(x, y, width, height));752}753754/*755* Draw a line using path by calling draw() function and passing756* a line shape.757*/758protected void deviceDrawLine(int xBegin, int yBegin,759int xEnd, int yEnd, Color color) {760761draw(new Line2D.Float(xBegin, yBegin, xEnd, yEnd));762}763764/*765* Fill the rectangle with the specified color by calling fill().766*/767protected void deviceFillRect(int x, int y, int width, int height,768Color color) {769fill(new Rectangle2D.Float(x, y, width, height));770}771772773/*774* This method should not be invoked by PSPathGraphics.775* FIX: Rework PathGraphics so that this method is776* not an abstract method there.777*/778protected void deviceClip(PathIterator pathIter) {779}780781}782783784