Example usage for java.awt RenderingHints VALUE_TEXT_ANTIALIAS_ON

List of usage examples for java.awt RenderingHints VALUE_TEXT_ANTIALIAS_ON

Introduction

In this page you can find the example usage for java.awt RenderingHints VALUE_TEXT_ANTIALIAS_ON.

Prototype

Object VALUE_TEXT_ANTIALIAS_ON

To view the source code for java.awt RenderingHints VALUE_TEXT_ANTIALIAS_ON.

Click Source Link

Document

Text antialiasing hint value -- text rendering is done with some form of antialiasing.

Usage

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.graphics.internal.LogicalPageDrawable.java

/**
 * Renders the glyphs stored in the text node.
 *
 * @param renderableText/* w  w w . j  a  va2 s .c om*/
 *          the text node that should be rendered.
 * @param contentX2
 */
protected void drawText(final RenderableText renderableText, final long contentX2) {
    if (renderableText.getLength() == 0) {
        // This text is empty.
        return;
    }

    final long posX = renderableText.getX();
    final long posY = renderableText.getY();

    final Graphics2D g2;
    if (getTextSpec() == null) {
        g2 = (Graphics2D) getGraphics().create();
        final StyleSheet layoutContext = renderableText.getStyleSheet();
        configureGraphics(layoutContext, g2);
        g2.setStroke(LogicalPageDrawable.DEFAULT_STROKE);

        if (RenderUtility.isFontSmooth(layoutContext, metaData)) {
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        } else {
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
        }
    } else {
        g2 = getTextSpec().getGraphics();
    }

    // This shifting is necessary to make sure that all text is rendered like in the previous versions.
    // In the earlier versions, we did not really obey to the baselines of the text, we just hoped and prayed.
    // Therefore, all text was printed at the bottom of the text elements. With the introduction of the full
    // font metrics setting, this situation got a little bit better, for the price that text-elements became
    // nearly unpredictable ..
    //
    // The code below may be weird, but at least it is predictable weird.

    final FontMetrics fm = g2.getFontMetrics();
    final Rectangle2D rect = fm.getMaxCharBounds(g2);
    final long awtBaseLine = StrictGeomUtility.toInternalValue(-rect.getY());

    final GlyphList gs = renderableText.getGlyphs();
    if (metaData.isFeatureSupported(OutputProcessorFeature.FAST_FONTRENDERING)
            && isNormalTextSpacing(renderableText)) {
        final int maxLength = renderableText.computeMaximumTextSize(contentX2);
        final String text = gs.getText(renderableText.getOffset(), maxLength, codePointBuffer);
        final float y = (float) StrictGeomUtility.toExternalValue(posY + awtBaseLine);
        g2.drawString(text, (float) StrictGeomUtility.toExternalValue(posX), y);
    } else {
        final ExtendedBaselineInfo baselineInfo = renderableText.getBaselineInfo();
        final int maxPos = renderableText.getOffset() + renderableText.computeMaximumTextSize(contentX2);
        long runningPos = posX;
        final long baseline = baselineInfo.getBaseline(baselineInfo.getDominantBaseline());
        final long baselineDelta = awtBaseLine - baseline;
        final float y = (float) (StrictGeomUtility.toExternalValue(posY + awtBaseLine + baselineDelta));
        for (int i = renderableText.getOffset(); i < maxPos; i++) {
            final Glyph g = gs.getGlyph(i);
            g2.drawString(gs.getGlyphAsString(i, codePointBuffer),
                    (float) StrictGeomUtility.toExternalValue(runningPos), y);
            runningPos += RenderableText.convert(g.getWidth()) + g.getSpacing().getMinimum();
        }
    }
    g2.dispose();
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

/**
 * @see Graphics2D#getFontRenderContext()
 *///from w ww.  j  a  v  a  2 s  .  c  o  m
@Override
public FontRenderContext getFontRenderContext() {
    final boolean antialias = RenderingHints.VALUE_TEXT_ANTIALIAS_ON
            .equals(getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING));
    final boolean fractions = RenderingHints.VALUE_FRACTIONALMETRICS_ON
            .equals(getRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS));
    return new FontRenderContext(new AffineTransform(), antialias, fractions);
}

From source file:org.polymap.core.data.feature.FeatureRenderProcessor2.java

protected Image getMap(final Set<ILayer> layers, int width, int height, final ReferencedEnvelope bbox) {
    //        Logger wfsLog = Logging.getLogger( "org.geotools.data.wfs.protocol.http" );
    //        wfsLog.setLevel( Level.FINEST );

    // mapContext
    MapContext mapContext = mapContextRef.get(new Supplier<MapContext>() {
        public MapContext get() {
            log.debug("Creating new MapContext... ");
            // sort z-priority
            TreeMap<String, ILayer> sortedLayers = new TreeMap();
            for (ILayer layer : layers) {
                String uniqueOrderKey = String.valueOf(layer.getOrderKey()) + layer.id();
                sortedLayers.put(uniqueOrderKey, layer);
            }/*from w ww . j a v a 2s .c  o  m*/
            // add to mapContext
            MapContext result = new DefaultMapContext(bbox.getCoordinateReferenceSystem());
            for (ILayer layer : sortedLayers.values()) {
                try {
                    FeatureSource fs = PipelineFeatureSource.forLayer(layer, false);
                    log.debug("        FeatureSource: " + fs);
                    log.debug("            fs.getName(): " + fs.getName());

                    Style style = layer.getStyle().resolve(Style.class, null);
                    if (style == null) {
                        log.warn("            fs.getName(): " + fs.getName());
                        style = new DefaultStyles().findStyle(fs);
                    }
                    result.addLayer(fs, style);

                    // watch layer for style changes
                    LayerStyleListener listener = new LayerStyleListener(mapContextRef);
                    if (watchedLayers.putIfAbsent(layer, listener) == null) {
                        layer.addPropertyChangeListener(listener);
                    }
                } catch (IOException e) {
                    log.warn(e);
                    // FIXME set layer status and statusMessage
                } catch (PipelineIncubationException e) {
                    log.warn("No pipeline.", e);
                }
            }
            log.debug("created: " + result);
            return result;
        }
    });
    log.debug("using: " + mapContext);

    // render
    //        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    //        GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
    //        VolatileImage result = gc.createCompatibleVolatileImage( width, height, Transparency.TRANSLUCENT );

    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    result.setAccelerationPriority(1);

    final Graphics2D g = result.createGraphics();
    //        log.info( "IMAGE: accelerated=" + result.getCapabilities( g.getDeviceConfiguration() ).isAccelerated() );

    try {
        final StreamingRenderer renderer = new StreamingRenderer();

        // rendering hints
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_SPEED);
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON));

        renderer.setJava2DHints(hints);
        //            g.setRenderingHints( hints );

        // error handler
        renderer.addRenderListener(new RenderListener() {
            int featureCount = 0;

            @Override
            public void featureRenderer(SimpleFeature feature) {
                //                  if (++featureCount == 100) {
                //                      log.info( "Switch off antialiasing!" );
                //                      RenderingHints off = new RenderingHints(
                //                              RenderingHints.KEY_ANTIALIASING,
                //                              RenderingHints.VALUE_ANTIALIAS_OFF );
                //                      renderer.setJava2DHints( off );
                //                      g.setRenderingHints( off );
                //                  }
            }

            @Override
            public void errorOccurred(Exception e) {
                log.error("Renderer error: ", e);
                drawErrorMsg(g, "Fehler bei der Darstellung.", e);
            }
        });

        // render params
        Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", Boolean.TRUE);
        renderer.setRendererHints(rendererParams);

        renderer.setContext(mapContext);
        Rectangle paintArea = new Rectangle(width, height);
        renderer.paint(g, paintArea, bbox);
        return result;
    } catch (Throwable e) {
        log.error("Renderer error: ", e);
        drawErrorMsg(g, null, e);
        return result;
    } finally {
        if (g != null) {
            g.dispose();
        }
    }
}

From source file:org.polymap.core.data.image.RasterRenderProcessor.java

protected Image getMap(Set<ILayer> layers, int width, int height, ReferencedEnvelope bbox) {
    // mapContext
    synchronized (this) {
        // check style objects
        boolean needsNewContext = false;

        // create mapContext
        if (mapContext == null || needsNewContext) {
            // sort z-priority
            TreeMap<String, ILayer> sortedLayers = new TreeMap();
            for (ILayer layer : layers) {
                String uniqueOrderKey = String.valueOf(layer.getOrderKey()) + layer.id();
                sortedLayers.put(uniqueOrderKey, layer);
            }//from  w  w  w  .  j  av a2  s .  c o m
            // add to mapContext
            mapContext = new DefaultMapContext(bbox.getCoordinateReferenceSystem());
            for (ILayer layer : sortedLayers.values()) {
                try {
                    IGeoResource res = layer.getGeoResource();
                    if (res == null) {
                        throw new IllegalStateException("Unable to find geo resource of layer: " + layer);
                    }
                    AbstractRasterService service = (AbstractRasterService) res.service(null);
                    log.debug("    service: " + service);

                    log.debug("    CRS: " + layer.getCRS());
                    AbstractGridCoverage2DReader reader = service.getReader(layer.getCRS(), null);

                    Style style = createRGBStyle(reader);
                    if (style == null) {
                        log.warn("Error creating RGB style, trying greyscale...");
                        style = createGreyscaleStyle(1);
                    }
                    mapContext.addLayer(reader, style);
                    styles.put(layer, style);
                } catch (IOException e) {
                    log.warn(e);
                    // FIXME set layer status and statusMessage
                }
            }
        } else {
        }
    }

    // render
    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
    final Graphics2D g = result.createGraphics();
    try {
        StreamingRenderer renderer = new StreamingRenderer();

        // error handler
        renderer.addRenderListener(new RenderListener() {
            public void featureRenderer(SimpleFeature feature) {
            }

            public void errorOccurred(Exception e) {
                log.error("Renderer error: ", e);
                drawErrorMsg(g, "Fehler bei der Darstellung.", e);
            }
        });

        // rendering hints
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON));

        renderer.setJava2DHints(hints);
        //            g.setRenderingHints( hints );

        // render params
        Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", Boolean.TRUE);
        renderer.setRendererHints(rendererParams);

        renderer.setContext(mapContext);
        Rectangle paintArea = new Rectangle(width, height);
        renderer.paint(g, paintArea, bbox);
        return result;
    } catch (Throwable e) {
        log.error("Renderer error: ", e);
        drawErrorMsg(g, null, e);
        return result;
    } finally {
        if (g != null) {
            g.dispose();
        }
    }
}

From source file:org.polymap.service.geoserver.spring.PipelineMapProducer.java

public void writeTo(final OutputStream out) throws ServiceException, IOException {
    Timer timer = new Timer();

    // single layer? -> request ENCODED_IMAGE
    if (mapContext.getLayerCount() == 1) {
        MapLayer mapLayer = mapContext.getLayers()[0];
        ILayer layer = loader.findLayer(mapLayer);
        try {/*from ww  w  .j a  va2s  .co  m*/
            Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.ENCODED_IMAGE);

            ProcessorRequest request = prepareProcessorRequest();
            pipeline.process(request, new ResponseHandler() {
                public void handle(ProcessorResponse pipeResponse) throws Exception {

                    HttpServletResponse response = GeoServerWms.response.get();
                    if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) {
                        log.info("Response: 304!");
                        response.setStatus(304);
                    } else {
                        long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified();
                        // allow caches and browser clients to cache for 1h
                        //response.setHeader( "Cache-Control", "public,max-age=3600" );
                        if (lastModified > 0) {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Last-Modified", lastModified);
                        } else {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Expires", 0);
                        }

                        byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk();
                        int len = ((EncodedImageResponse) pipeResponse).getChunkSize();
                        out.write(chunk, 0, len);
                    }
                }
            });
            log.debug("    flushing response stream. (" + timer.elapsedTime() + "ms)");
            out.flush();
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    // multiple layers -> render into one image
    else {
        List<Job> jobs = new ArrayList();
        final Map<MapLayer, Image> images = new HashMap();

        // run jobs for all layers
        for (final MapLayer mapLayer : mapContext.getLayers()) {
            final ILayer layer = loader.findLayer(mapLayer);
            // job
            UIJob job = new UIJob(getClass().getSimpleName() + ": " + layer.getLabel()) {
                protected void runWithException(IProgressMonitor monitor) throws Exception {
                    try {
                        // XXX this excludes Cache304 (which support EncodedImageResponse only)
                        Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.IMAGE);

                        GetMapRequest targetRequest = prepareProcessorRequest();
                        pipeline.process(targetRequest, new ResponseHandler() {
                            public void handle(ProcessorResponse pipeResponse) throws Exception {
                                Image layerImage = ((ImageResponse) pipeResponse).getImage();
                                images.put(mapLayer, layerImage);
                            }
                        });
                    } catch (Exception e) {
                        // XXX put a special image in the map
                        log.warn("", e);
                        images.put(mapLayer, null);
                        throw e;
                    }
                }
            };
            job.schedule();
            jobs.add(job);
        }

        // join jobs
        for (Job job : jobs) {
            try {
                job.join();
            } catch (InterruptedException e) {
                // XXX put a special image in the map
                log.warn("", e);
            }
        }

        // put images together (MapContext order)
        Graphics2D g = null;
        try {
            // result image
            BufferedImage result = ImageUtils.createImage(mapContext.getMapWidth(), mapContext.getMapHeight(),
                    null, true);
            g = result.createGraphics();

            // rendering hints
            RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
            hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
            g.setRenderingHints(hints);

            for (MapLayer mapLayer : mapContext.getLayers()) {
                Image layerImage = images.get(mapLayer);

                // load image data
                //                  new javax.swing.ImageIcon( image ).getImage();

                ILayer layer = loader.findLayer(mapLayer);
                int rule = AlphaComposite.SRC_OVER;
                float alpha = ((float) layer.getOpacity()) / 100;

                g.setComposite(AlphaComposite.getInstance(rule, alpha));
                g.drawImage(layerImage, 0, 0, null);
            }
            encodeImage(result, out);
        } finally {
            if (g != null) {
                g.dispose();
            }
        }
    }
}

From source file:org.springframework.cloud.stream.app.image.recognition.processor.ImageRecognitionOutputMessageBuilder.java

/**
 * Augment the input image by adding the recognized classes.
 *
 * @param imageBytes input image as byte array
 * @param result computed recognition labels
 * @return the image augmented with recognized labels.
 *///from  w  ww  .  j a  v  a2  s.  co  m
private byte[] drawLabels(byte[] imageBytes, Object result) {
    try {
        if (result != null) {
            BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageBytes));

            Graphics2D g = originalImage.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            FontMetrics fm = g.getFontMetrics();

            Tuple resultTuple = new JsonStringToTupleConverter().convert(result.toString());
            ArrayList<Tuple> labels = (ArrayList) resultTuple.getValues().get(0);

            int x = 1;
            int y = 1;
            for (Tuple l : labels) {

                String labelName = l.getFieldNames().get(0);
                int probability = (int) (100 * l.getFloat(0));
                String title = labelName + ": " + probability + "%";

                Rectangle2D rect = fm.getStringBounds(title, g);

                g.setColor(bgColor);
                g.fillRect(x, y, (int) rect.getWidth() + 6, (int) rect.getHeight());

                g.setColor(textColor);
                g.drawString(title, x + 3, (int) (y + rect.getHeight() - 3));
                y = (int) (y + rect.getHeight() + 1);
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(originalImage, IMAGE_FORMAT, baos);
            baos.flush();
            imageBytes = baos.toByteArray();
            baos.close();
        }
    } catch (IOException e) {
        logger.error("Failed to draw labels in the input image", e);
    }

    return imageBytes;
}

From source file:org.springframework.cloud.stream.app.pose.estimation.processor.PoseEstimateOutputMessageBuilder.java

private byte[] drawPoses(byte[] imageBytes, List<Body> bodies) throws IOException {

    if (bodies != null) {

        BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageBytes));

        Graphics2D g = originalImage.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Stroke stroke = g.getStroke();
        g.setStroke(new BasicStroke(this.poseProperties.getDrawLineWidth()));

        for (Body body : bodies) {
            for (Limb limb : body.getLimbs()) {

                Color limbColor = findLimbColor(body, limb);

                Part from = limb.getFromPart();
                Part to = limb.getToPart();

                if (limb.getLimbType() != Model.LimbType.limb17
                        && limb.getLimbType() != Model.LimbType.limb18) {
                    g.setColor(limbColor);
                    g.draw(new Line2D.Double(from.getNormalizedX(), from.getNormalizedY(), to.getNormalizedX(),
                            to.getNormalizedY()));
                }//ww w. j  av  a  2  s .  co m

                g.setStroke(new BasicStroke(1));
                drawPartOval(from, this.poseProperties.getDrawPartRadius(), g);
                drawPartOval(to, this.poseProperties.getDrawPartRadius(), g);
                g.setStroke(new BasicStroke(this.poseProperties.getDrawLineWidth()));
            }
        }

        g.setStroke(stroke);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(originalImage, IMAGE_FORMAT, baos);
        baos.flush();
        imageBytes = baos.toByteArray();
        baos.close();
        g.dispose();
    }

    return imageBytes;
}

From source file:org.squidy.designer.shape.VisualShape.java

@Override
protected final void paint(PPaintContext paintContext) {
    super.paint(paintContext);

    Graphics2D g = paintContext.getGraphics();

    // Set default font.
    g.setFont(internalFont);/*from  w  w w . j  a v  a  2s .c om*/

    //      if (!renderingHintsSet) {
    if (isRenderPrimitive()) {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
        g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
        g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    } else {
        // Use anti aliasing -> May slow down performance.
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    }
    //         renderingHintsSet = true;
    //      }

    // Paint the shapes visual representation.
    paintShape(paintContext);

    // Allows visual debugging if enabled.
    if (DebugConstants.ENABLED) {
        paintDebug(paintContext);
    }
}

From source file:org.tinymediamanager.TinyMediaManager.java

/**
 * The main method./*from   w  ww.ja  v  a 2 s .c  om*/
 * 
 * @param args
 *          the arguments
 */
public static void main(String[] args) {
    // simple parse command line
    if (args != null && args.length > 0) {
        LOGGER.debug("TMM started with: " + Arrays.toString(args));
        TinyMediaManagerCMD.parseParams(args);
        System.setProperty("java.awt.headless", "true");
    } else {
        // no cmd params found, but if we are headless - display syntax
        String head = System.getProperty("java.awt.headless");
        if (head != null && head.equals("true")) {
            LOGGER.info("TMM started 'headless', and without params -> displaying syntax ");
            TinyMediaManagerCMD.printSyntax();
            System.exit(0);
        }
    }

    // check if we have write permissions to this folder
    try {
        RandomAccessFile f = new RandomAccessFile("access.test", "rw");
        f.close();
        Files.deleteIfExists(Paths.get("access.test"));
    } catch (Exception e2) {
        String msg = "Cannot write to TMM directory, have no rights - exiting.";
        if (!GraphicsEnvironment.isHeadless()) {
            JOptionPane.showMessageDialog(null, msg);
        } else {
            System.out.println(msg);
        }
        System.exit(1);
    }

    // HACK for Java 7 and JavaFX not being in boot classpath
    // In Java 8 and on, this is installed inside jre/lib/ext
    // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8003171 and references
    // so we check if it is already existent in "new" directory, and if not, load it via reflection ;o)
    String dir = new File(LaunchUtil.getJVMPath()).getParentFile().getParent(); // bin, one deeper
    File jfx = new File(dir, "lib/ext/jfxrt.jar");
    if (!jfx.exists()) {
        // java 7
        jfx = new File(dir, "lib/jfxrt.jar");
        if (jfx.exists()) {
            try {
                TmmOsUtils.addPath(jfx.getAbsolutePath());
            } catch (Exception e) {
                LOGGER.debug("failed to load JavaFX - using old styles...");
            }
        }
    }

    if (Globals.isDebug()) {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader) cl).getURLs();
        LOGGER.info("=== DEBUG CLASS LOADING =============================");
        for (URL url : urls) {
            LOGGER.info(url.getFile());
        }
    }

    LOGGER.info("=====================================================");
    LOGGER.info("=== tinyMediaManager (c) 2012-2016 Manuel Laggner ===");
    LOGGER.info("=====================================================");
    LOGGER.info("tmm.version      : " + ReleaseInfo.getRealVersion());

    if (Globals.isDonator()) {
        LOGGER.info("tmm.supporter    : THANKS FOR DONATING - ALL FEATURES UNLOCKED :)");
    }

    LOGGER.info("os.name          : " + System.getProperty("os.name"));
    LOGGER.info("os.version       : " + System.getProperty("os.version"));
    LOGGER.info("os.arch          : " + System.getProperty("os.arch"));
    LOGGER.trace("network.id       : " + License.getMac());
    LOGGER.info("java.version     : " + System.getProperty("java.version"));

    if (Globals.isRunningJavaWebStart()) {
        LOGGER.info("java.webstart    : true");
    }
    if (Globals.isRunningWebSwing()) {
        LOGGER.info("java.webswing    : true");
    }

    // START character encoding debug
    debugCharacterEncoding("default encoding : ");
    System.setProperty("file.encoding", "UTF-8");
    System.setProperty("sun.jnu.encoding", "UTF-8");
    Field charset;
    try {
        // we cannot (re)set the properties while running inside JVM
        // so we trick it to reread it by setting them to null ;)
        charset = Charset.class.getDeclaredField("defaultCharset");
        charset.setAccessible(true);
        charset.set(null, null);
    } catch (Exception e) {
        LOGGER.warn("Error resetting to UTF-8", e);
    }
    debugCharacterEncoding("set encoding to  : ");
    // END character encoding debug

    // set GUI default language
    Locale.setDefault(Utils.getLocaleFromLanguage(Globals.settings.getLanguage()));
    LOGGER.info("System language  : " + System.getProperty("user.language") + "_"
            + System.getProperty("user.country"));
    LOGGER.info(
            "GUI language     : " + Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry());
    LOGGER.info("Scraper language : " + MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage());
    LOGGER.info("TV Scraper lang  : " + TvShowModuleManager.SETTINGS.getScraperLanguage());

    // start EDT
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            boolean newVersion = !Globals.settings.isCurrentVersion(); // same snapshots/svn considered as "new", for upgrades
            try {
                Thread.setDefaultUncaughtExceptionHandler(new Log4jBackstop());
                if (!GraphicsEnvironment.isHeadless()) {
                    Thread.currentThread().setName("main");
                } else {
                    Thread.currentThread().setName("headless");
                    LOGGER.debug("starting without GUI...");
                }
                Toolkit tk = Toolkit.getDefaultToolkit();
                tk.addAWTEventListener(TmmWindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK);
                if (!GraphicsEnvironment.isHeadless()) {
                    setLookAndFeel();
                }
                doStartupTasks();

                // suppress logging messages from betterbeansbinding
                org.jdesktop.beansbinding.util.logging.Logger.getLogger(ELProperty.class.getName())
                        .setLevel(Level.SEVERE);

                // init ui logger
                TmmUILogCollector.init();

                LOGGER.info("=====================================================");
                // init splash
                SplashScreen splash = null;
                if (!GraphicsEnvironment.isHeadless()) {
                    splash = SplashScreen.getSplashScreen();
                }
                Graphics2D g2 = null;
                if (splash != null) {
                    g2 = splash.createGraphics();
                    if (g2 != null) {
                        Font font = new Font("Dialog", Font.PLAIN, 14);
                        g2.setFont(font);
                    } else {
                        LOGGER.debug("got no graphics from splash");
                    }
                } else {
                    LOGGER.debug("no splash found");
                }

                if (g2 != null) {
                    updateProgress(g2, "starting tinyMediaManager", 0);
                    splash.update();
                }
                LOGGER.info("starting tinyMediaManager");

                // upgrade check
                String oldVersion = Globals.settings.getVersion();
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading to new version", 10);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksBeforeDatabaseLoading(oldVersion); // do the upgrade tasks for the old version
                    Globals.settings.setCurrentVersion();
                    Globals.settings.saveSettings();
                }

                // proxy settings
                if (Globals.settings.useProxy()) {
                    LOGGER.info("setting proxy");
                    Globals.settings.setProxy();
                }

                // MediaInfo /////////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading MediaInfo libs", 20);
                    splash.update();
                }
                MediaInfoUtils.loadMediaInfo();

                // load modules //////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading movie module", 30);
                    splash.update();
                }
                TmmModuleManager.getInstance().startUp();
                TmmModuleManager.getInstance().registerModule(MovieModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(MovieModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading TV show module", 40);
                    splash.update();
                }

                TmmModuleManager.getInstance().registerModule(TvShowModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(TvShowModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading plugins", 50);
                    splash.update();
                }

                // just instantiate static - will block (takes a few secs)
                PluginManager.getInstance();
                if (ReleaseInfo.isSvnBuild()) {
                    PluginManager.loadClasspathPlugins();
                }

                // do upgrade tasks after database loading
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading database to new version", 70);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksAfterDatabaseLoading(oldVersion);
                }

                // launch application ////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading ui", 80);
                    splash.update();
                }
                if (!GraphicsEnvironment.isHeadless()) {
                    MainWindow window = new MainWindow("tinyMediaManager / " + ReleaseInfo.getRealVersion());

                    // finished ////////////////////////////////////////////////////
                    if (g2 != null) {
                        updateProgress(g2, "finished starting :)", 100);
                        splash.update();
                    }

                    // write a random number to file, to identify this instance (for
                    // updater, tracking, whatsoever)
                    Utils.trackEvent("startup");

                    TmmWindowSaver.getInstance().loadSettings(window);
                    window.setVisible(true);

                    // wizard for new user
                    if (Globals.settings.newConfig) {
                        Globals.settings.writeDefaultSettings(); // now all plugins are resolved - write again defaults!
                        TinyMediaManagerWizard wizard = new TinyMediaManagerWizard();
                        wizard.setVisible(true);
                    }

                    // show changelog
                    if (newVersion && !ReleaseInfo.getVersion().equals(oldVersion)) {
                        // special case nightly/svn: if same snapshot version, do not display changelog
                        Utils.trackEvent("updated");
                        showChangelog();
                    }
                } else {
                    TinyMediaManagerCMD.startCommandLineTasks();
                    // wait for other tmm threads (artwork download et all)
                    while (TmmTaskManager.getInstance().poolRunning()) {
                        Thread.sleep(2000);
                    }

                    LOGGER.info("bye bye");
                    // MainWindows.shutdown()
                    try {
                        // send shutdown signal
                        TmmTaskManager.getInstance().shutdown();
                        // save unsaved settings
                        Globals.settings.saveSettings();
                        // hard kill
                        TmmTaskManager.getInstance().shutdownNow();
                        // close database connection
                        TmmModuleManager.getInstance().shutDown();
                    } catch (Exception ex) {
                        LOGGER.warn(ex.getMessage());
                    }
                    System.exit(0);
                }
            } catch (IllegalStateException e) {
                LOGGER.error("IllegalStateException", e);
                if (!GraphicsEnvironment.isHeadless() && e.getMessage().contains("file is locked")) {
                    // MessageDialog.showExceptionWindow(e);
                    ResourceBundle bundle = ResourceBundle.getBundle("messages", new UTF8Control()); //$NON-NLS-1$
                    MessageDialog dialog = new MessageDialog(MainWindow.getActiveInstance(),
                            bundle.getString("tmm.problemdetected")); //$NON-NLS-1$
                    dialog.setImage(IconManager.ERROR);
                    dialog.setText(bundle.getString("tmm.nostart"));//$NON-NLS-1$
                    dialog.setDescription(bundle.getString("tmm.nostart.instancerunning"));//$NON-NLS-1$
                    dialog.setResizable(true);
                    dialog.pack();
                    dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                    dialog.setVisible(true);
                }
                System.exit(1);
            } catch (Exception e) {
                LOGGER.error("Exception while start of tmm", e);
                if (!GraphicsEnvironment.isHeadless()) {
                    MessageDialog.showExceptionWindow(e);
                }
                System.exit(1);
            }
        }

        /**
         * Update progress on splash screen.
         * 
         * @param text
         *          the text
         */
        private void updateProgress(Graphics2D g2, String text, int progress) {
            Object oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            g2.setComposite(AlphaComposite.Clear);
            g2.fillRect(20, 200, 480, 305);
            g2.setPaintMode();

            g2.setColor(new Color(51, 153, 255));
            g2.fillRect(22, 272, 452 * progress / 100, 21);

            g2.setColor(Color.black);
            g2.drawString(text + "...", 23, 310);
            int l = g2.getFontMetrics().stringWidth(ReleaseInfo.getRealVersion()); // bound right
            g2.drawString(ReleaseInfo.getRealVersion(), 480 - l, 325);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue);
            LOGGER.debug("Startup (" + progress + "%) " + text);
        }

        /**
         * Sets the look and feel.
         * 
         * @throws Exception
         *           the exception
         */
        private void setLookAndFeel() throws Exception {
            // get font settings
            String fontFamily = Globals.settings.getFontFamily();
            try {
                // sanity check
                fontFamily = Font.decode(fontFamily).getFamily();
            } catch (Exception e) {
                fontFamily = "Dialog";
            }

            int fontSize = Globals.settings.getFontSize();
            if (fontSize < 12) {
                fontSize = 12;
            }

            String fontString = fontFamily + " " + fontSize;

            // Get the native look and feel class name
            // String laf = UIManager.getSystemLookAndFeelClassName();
            Properties props = new Properties();
            props.setProperty("controlTextFont", fontString);
            props.setProperty("systemTextFont", fontString);
            props.setProperty("userTextFont", fontString);
            props.setProperty("menuTextFont", fontString);
            // props.setProperty("windowTitleFont", "Dialog bold 20");

            fontSize = Math.round((float) (fontSize * 0.833));
            fontString = fontFamily + " " + fontSize;

            props.setProperty("subTextFont", fontString);
            props.setProperty("backgroundColor", "237 237 237");
            props.setProperty("menuBackgroundColor", "237 237 237");
            props.setProperty("controlBackgroundColor", "237 237 237");
            props.setProperty("menuColorLight", "237 237 237");
            props.setProperty("menuColorDark", "237 237 237");
            props.setProperty("toolbarColorLight", "237 237 237");
            props.setProperty("toolbarColorDark", "237 237 237");
            props.setProperty("tooltipBackgroundColor", "255 255 255");
            props.put("windowDecoration", "system");
            props.put("logoString", "");

            // Get the look and feel class name
            com.jtattoo.plaf.luna.LunaLookAndFeel.setTheme(props);
            String laf = "com.jtattoo.plaf.luna.LunaLookAndFeel";

            // Install the look and feel
            UIManager.setLookAndFeel(laf);
        }

        /**
         * Does some tasks at startup
         */
        private void doStartupTasks() {
            // rename downloaded files
            UpgradeTasks.renameDownloadedFiles();

            // extract templates, if GD has not already done
            Utils.extractTemplates();

            // check if a .desktop file exists
            if (Platform.isLinux()) {
                File desktop = new File(TmmOsUtils.DESKTOP_FILE);
                if (!desktop.exists()) {
                    TmmOsUtils.createDesktopFileForLinux(desktop);
                }
            }
        }

        private void showChangelog() {
            // read the changelog
            try {
                final String changelog = Utils.readFileToString(Paths.get("changelog.txt"));
                if (StringUtils.isNotBlank(changelog)) {
                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            WhatsNewDialog dialog = new WhatsNewDialog(changelog);
                            dialog.pack();
                            dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                            dialog.setModalityType(ModalityType.APPLICATION_MODAL);
                            dialog.setVisible(true);
                        }
                    });
                }
            } catch (IOException e) {
                // no file found
                LOGGER.warn(e.getMessage());
            }
        }
    });
}

From source file:org.tinymediamanager.ui.components.ImageLabel.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (scaledImage != null) {
        int originalWidth = scaledImage.getWidth(null);
        int originalHeight = scaledImage.getHeight(null);

        // calculate new height/width
        int newWidth = 0;
        int newHeight = 0;

        int offsetX = 0;
        int offsetY = 0;

        if (drawBorder && !drawFullWidth) {
            Point size = ImageCache.calculateSize(this.getWidth() - 8, this.getHeight() - 8, originalWidth,
                    originalHeight, true);

            // calculate offsets
            if (position == Position.TOP_RIGHT || position == Position.BOTTOM_RIGHT) {
                offsetX = this.getWidth() - size.x - 8;
            }/*from   w  w  w .  ja v a2  s . c o  m*/

            if (position == Position.BOTTOM_LEFT || position == Position.BOTTOM_RIGHT) {
                offsetY = this.getHeight() - size.y - 8;
            }

            if (position == Position.CENTER) {
                offsetX = (this.getWidth() - size.x - 8) / 2;
                offsetY = (this.getHeight() - size.y - 8) / 2;
            }

            newWidth = size.x;
            newHeight = size.y;

            // when the image size differs too much - reload and rescale the original image
            recreateScaledImageIfNeeded(originalWidth, originalHeight, newWidth, newHeight);

            g.setColor(Color.BLACK);
            g.drawRect(offsetX, offsetY, size.x + 7, size.y + 7);
            g.setColor(Color.WHITE);
            g.fillRect(offsetX + 1, offsetY + 1, size.x + 6, size.y + 6);
            // g.drawImage(Scaling.scale(originalImage, newWidth, newHeight), offsetX + 4, offsetY + 4, newWidth, newHeight, this);
            g.drawImage(scaledImage, offsetX + 4, offsetY + 4, newWidth, newHeight, this);
        } else {
            Point size = null;
            if (drawFullWidth) {
                size = new Point(this.getWidth(), this.getWidth() * originalHeight / originalWidth);
            } else {
                size = ImageCache.calculateSize(this.getWidth(), this.getHeight(), originalWidth,
                        originalHeight, true);
            }

            // calculate offsets
            if (position == Position.TOP_RIGHT || position == Position.BOTTOM_RIGHT) {
                offsetX = this.getWidth() - size.x;
            }

            if (position == Position.BOTTOM_LEFT || position == Position.BOTTOM_RIGHT) {
                offsetY = this.getHeight() - size.y;
            }

            if (position == Position.CENTER) {
                offsetX = (this.getWidth() - size.x) / 2;
                offsetY = (this.getHeight() - size.y) / 2;
            }

            newWidth = size.x;
            newHeight = size.y;

            // when the image size differs too much - reload and rescale the original image
            recreateScaledImageIfNeeded(originalWidth, originalHeight, newWidth, newHeight);

            // g.drawImage(Scaling.scale(originalImage, newWidth, newHeight), offsetX, offsetY, newWidth, newHeight, this);
            g.drawImage(scaledImage, offsetX, offsetY, newWidth, newHeight, this);
        }
    } else {
        // draw border and background
        if (drawBorder) {
            g.setColor(Color.BLACK);
            g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
            if (getParent().isOpaque()) {
                g.setColor(getParent().getBackground());
                g.fillRect(1, 1, this.getWidth() - 2, this.getHeight() - 2);
            }
        }

        // calculate diagonal
        int diagonalSize = (int) Math
                .sqrt(this.getWidth() * this.getWidth() + this.getHeight() * this.getHeight());

        // draw text
        String text = "";
        if (alternativeText != null) {
            text = alternativeText;
        } else {
            text = BUNDLE.getString("image.nonefound"); //$NON-NLS-1$
        }
        if (!getParent().isOpaque()) {
            text = "";
        }
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        AffineTransform orig = g2.getTransform();
        AffineTransform at = new AffineTransform(orig);
        at.translate(0, this.getHeight());
        at.rotate(this.getWidth(), -this.getHeight());
        g2.setTransform(at);
        g2.setColor(Color.BLACK);
        g2.setFont(FONT);

        FontMetrics fm = g2.getFontMetrics();
        int x = (diagonalSize - fm.stringWidth(text)) / 2;
        int y = (fm.getAscent() - fm.getDescent()) / 2;

        g2.drawString(text, x, y);
        // g2.drawLine(0, 0, diagonalSize, 0);
        at.translate(0, -this.getHeight());
        g2.setTransform(orig);
    }
}