Example usage for java.awt Graphics setFont

List of usage examples for java.awt Graphics setFont

Introduction

In this page you can find the example usage for java.awt Graphics setFont.

Prototype

public abstract void setFont(Font font);

Source Link

Document

Sets this graphics context's font to the specified font.

Usage

From source file:org.prom5.analysis.performance.dottedchart.ui.DottedChartPanel.java

public void redrawTitle(int xPos) {
    Graphics g = this.getGraphics();
    Color fgColor = null;//from   ww w  . j  ava 2 s. c o  m
    Color bgColor = null;
    Color tmpColor = null;
    fgColor = null;
    bgColor = null;
    // calculate common coordinates
    int yTop = border;

    // initialze start color
    fgColor = colorLogDark;
    bgColor = colorLogBright;

    // calculate current top
    int currentTop = yTop;

    // paint actual log lane (only the part in the clipping range determined)
    Iterator itr = dcModel.getSortedKeySetList().iterator();
    g.setFont(new Font("Dialog", Font.BOLD, 13));
    int index = 0;
    currentTop = yTop;
    while (itr.hasNext()) {
        String dimName = (String) itr.next();
        if (dcModel.getTypeHashMap().equals(ST_INST) && !dcModel.getInstanceTypeToKeep().contains(dimName))
            continue;

        //         g.setColor(fgColor);
        g.setColor(Color.black);
        g.drawString(dimName, xPos + 5, currentTop + 20);

        index++;
        currentTop = unit2Cord(index);

        // swap colors
        tmpColor = fgColor;
        fgColor = bgColor;
        bgColor = tmpColor;
    }

}

From source file:org.processmining.analysis.performance.dottedchart.ui.DottedChartPanel.java

public void redrawTitle(int xPos) {
    Graphics g = this.getGraphics();
    Color fgColor = null;/*  w ww.j a  v  a 2s.co  m*/
    Color bgColor = null;
    Color tmpColor = null;
    fgColor = null;
    bgColor = null;
    // calculate common coordinates
    int yTop = border;

    // initialze start color
    fgColor = colorLogDark;
    bgColor = colorLogBright;

    // calculate current top
    int currentTop = yTop;

    // paint actual log lane (only the part in the clipping range
    // determined)
    Iterator itr = dcModel.getSortedKeySetList().iterator();
    g.setFont(new Font("Dialog", Font.BOLD, 13));
    int index = 0;
    currentTop = yTop;
    while (itr.hasNext()) {
        String dimName = (String) itr.next();
        if (dcModel.getTypeHashMap().equals(ST_INST) && !dcModel.getInstanceTypeToKeep().contains(dimName))
            continue;

        // g.setColor(fgColor);
        g.setColor(Color.black);
        g.drawString(dimName, xPos + 5, currentTop + 20);

        index++;
        currentTop = unit2Cord(index);

        // swap colors
        tmpColor = fgColor;
        fgColor = bgColor;
        bgColor = tmpColor;
    }

}

From source file:se.llbit.chunky.renderer.scene.Scene.java

/**
 * Update the canvas - draw the latest rendered frame
 * @param warningText//from   ww w. j  a  va  2 s  .  c  om
 */
public synchronized void updateCanvas(String warningText) {
    finalized = false;

    try {
        // flip buffers
        BufferedImage tmp = buffer;
        buffer = backBuffer;
        backBuffer = tmp;

        bufferData = ((DataBufferInt) backBuffer.getRaster().getDataBuffer()).getData();

        Graphics g = buffer.getGraphics();

        if (!warningText.isEmpty()) {
            g.setColor(java.awt.Color.red);
            int x0 = width / 2;
            int y0 = height / 2;
            g.setFont(infoFont);
            if (fontMetrics == null) {
                fontMetrics = g.getFontMetrics();
            }
            g.drawString(warningText, x0 - fontMetrics.stringWidth(warningText) / 2, y0);
        } else {

            if (renderState == RenderState.PREVIEW) {
                int x0 = width / 2;
                int y0 = height / 2;
                g.setColor(java.awt.Color.white);
                g.drawLine(x0, y0 - 4, x0, y0 + 4);
                g.drawLine(x0 - 4, y0, x0 + 4, y0);
                g.setFont(infoFont);
                Ray ray = new Ray();
                if (trace(ray) && ray.getCurrentMaterial() instanceof Block) {
                    Block block = (Block) ray.getCurrentMaterial();
                    g.drawString(String.format("target: %.2f m", ray.distance), 5, height - 18);
                    g.drawString(String.format("[0x%08X] %s (%s)", ray.getCurrentData(), block,
                            block.description(ray.getBlockData())), 5, height - 5);
                }
                Vector3d pos = camera.getPosition();
                g.drawString(String.format("(%.1f, %.1f, %.1f)", pos.x, pos.y, pos.z), 5, 11);
            }
        }

        g.dispose();
    } catch (IllegalStateException e) {
        Log.error("Unexpected exception while rendering back buffer", e);
    }
}

From source file:ded.ui.DiagramController.java

/** Check to see if the font is rendering properly.  I have had a
  * lot of trouble getting this to work on a wide range of
  * machines and JVMs.  If the font rendering does not work, just
  * alert the user to the problem but keep going. */
public void checkFontRendering() {
    // Render the glyph for 'A' in a box just large enough to
    // contain it when rendered properly.
    int width = 9;
    int height = 11;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics g = bi.createGraphics();
    ColorModel colorModel = bi.getColorModel();

    g.setColor(Color.WHITE);//from   ww  w.  j a  va2 s . co m
    g.fillRect(0, 0, width, height);

    g.setColor(Color.BLACK);
    g.setFont(this.dedWindow.diagramFont);
    g.drawString("A", 0, 10);

    // Print that glyph as a string.
    StringBuilder sb = new StringBuilder();
    for (int y = 0; y < height; y++) {
        int bits = 0;
        for (int x = 0; x < width; x++) {
            int pixel = bi.getRGB(x, y);
            int red = colorModel.getRed(pixel);
            int green = colorModel.getGreen(pixel);
            int blue = colorModel.getBlue(pixel);
            int alpha = colorModel.getAlpha(pixel);
            boolean isWhite = (red == 255 && green == 255 && blue == 255 && alpha == 255);
            boolean isBlack = (red == 0 && green == 0 && blue == 0 && alpha == 255);
            sb.append(
                    isWhite ? "_" : isBlack ? "X" : ("(" + red + "," + green + "," + blue + "," + alpha + ")"));

            bits <<= 1;
            if (!isWhite) {
                bits |= 1;
            }
        }
        sb.append(String.format("  (0x%03X)\n", bits));
    }

    // Also include some of the font metrics.
    FontMetrics fm = g.getFontMetrics();
    sb.append("fm: ascent=" + fm.getAscent() + " leading=" + fm.getLeading() + " charWidth('A')="
            + fm.charWidth('A') + " descent=" + fm.getDescent() + " height=" + fm.getHeight() + "\n");

    String actualGlyph = sb.toString();

    g.dispose();

    // The expected glyph and metrics.
    String expectedGlyph = "_________  (0x000)\n" + "____X____  (0x010)\n" + "___X_X___  (0x028)\n"
            + "___X_X___  (0x028)\n" + "__X___X__  (0x044)\n" + "__X___X__  (0x044)\n" + "__XXXXX__  (0x07C)\n"
            + "_X_____X_  (0x082)\n" + "_X_____X_  (0x082)\n" + "_X_____X_  (0x082)\n" + "_________  (0x000)\n"
            + "fm: ascent=10 leading=1 charWidth('A')=9 descent=3 height=14\n";

    if (!expectedGlyph.equals(actualGlyph)) {
        // Currently, this is known to happen when using OpenJDK 6
        // and 7, with 6 being close to right and 7 being very bad.
        // I also have reports of it happening on certain Mac OS/X
        // systems, but I haven't been able to determine what the
        // important factor there is.
        String warningMessage = "There is a problem with the font rendering.  The glyph "
                + "for the letter 'A' should look like:\n" + expectedGlyph + "but it renders as:\n"
                + actualGlyph + "\n" + "This probably means there is a bug in the TrueType "
                + "font library.  You might try a different Java version.  "
                + "(I'm working on how to solve this permanently.)";
        System.err.println(warningMessage);
        this.log(warningMessage);
        SwingUtil.errorMessageBox(null /*component*/, warningMessage);
    }
}

From source file:com.projity.contrib.calendar.JXXMonthView.java

private void drawDay(boolean colored, boolean flagged, boolean today, Graphics g, String text, int x, int y) {
    Color defaultColor = g.getColor();
    Font oldFont = getFont();/*from   w  w  w .  j  ava 2  s.  c  om*/
    if (colored) {
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(_bounds.x, _bounds.y, _bounds.width, _bounds.height);
        g.setColor(defaultColor);
    }
    if (today)
        g.setColor(Color.BLUE);
    if (flagged) {
        g.setColor(Color.RED);
        g.setFont(_derivedFont);
    }
    g.drawString(text, x, y);
    g.setColor(defaultColor);
    g.setFont(oldFont);
}

From source file:ro.nextreports.designer.ui.sqleditor.syntax.SyntaxView.java

@Override
protected int drawUnselectedText(Graphics graphics, int x, int y, int p0, int p1) {
    Font saveFont = graphics.getFont();
    Color saveColor = graphics.getColor();
    SyntaxDocument doc = (SyntaxDocument) getDocument();
    Segment segment = getLineBuffer();
    try {/*from  w w  w  . j a va 2 s .c o  m*/
        // Colour the parts
        Iterator<Token> tokens = doc.getTokens(p0, p1);
        int start = p0;
        while (tokens.hasNext()) {
            Token t = tokens.next();
            // if there is a gap between the next token start and where we
            // should be starting (spaces not returned in tokens), then draw
            // it in the default type
            if (start < t.start) {
                SyntaxStyles.getInstance().setGraphicsStyle(graphics, TokenType.DEFAULT);
                doc.getText(start, t.start - start, segment);
                x = Utilities.drawTabbedText(segment, x, y, graphics, this, start);
            }
            // t and s are the actual start and length of what we should
            // put on the screen.  assume these are the whole token....
            int l = t.length;
            int s = t.start;
            // ... unless the token starts before p0:
            if (s < p0) {
                // token is before what is requested. adgust the length and s
                l -= (p0 - s);
                s = p0;
            }
            // if token end (s + l is still the token end pos) is greater 
            // than p1, then just put up to p1
            if (s + l > p1) {
                l = p1 - s;
            }
            doc.getText(s, l, segment);
            x = SyntaxStyles.getInstance().drawText(segment, x, y, graphics, this, t);
            start = t.start + t.length;
        }
        // now for any remaining text not tokenized:
        if (start < p1) {
            SyntaxStyles.getInstance().setGraphicsStyle(graphics, TokenType.DEFAULT);
            doc.getText(start, p1 - start, segment);
            x = Utilities.drawTabbedText(segment, x, y, graphics, this, start);
        }
    } catch (BadLocationException e) {
        System.err.println("Requested: " + e.offsetRequested());
        LOG.error(e.getMessage(), e);
    } finally {
        graphics.setFont(saveFont);
        graphics.setColor(saveColor);
    }

    return x;
}

From source file:ClipDemo.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    // get damaged region
    Rectangle clipRect = g.getClipBounds();
    int clipx = clipRect.x;
    int clipy = clipRect.y;
    int clipw = clipRect.width;
    int cliph = clipRect.height;

    // fill damaged region only
    g.setColor(Color.white);/*from w  w  w.  j  a  v a2 s  .  com*/
    g.fillRect(clipx, clipy, clipw, cliph);

    if (clipx <= 240 && clipy <= 240) {
        g.setColor(Color.yellow);
        g.fillOval(0, 0, 240, 240);
        System.out.println(" yellow Oval repainted.");
    }

    if (clipx + clipw >= 160 && clipx <= 400 && clipy + cliph >= 160 && clipy <= 400) {
        g.setColor(Color.magenta);
        g.fillOval(160, 160, 240, 240);
        System.out.println(" magenta Oval repainted.");
    }

    int iconWidth = java2sLogo.getIconWidth();
    int iconHeight = java2sLogo.getIconHeight();

    if (clipx + clipw >= 280 - (iconWidth / 2) && clipx <= (280 + (iconWidth / 2))
            && clipy + cliph >= 120 - (iconHeight / 2) && clipy <= (120 + (iconHeight / 2))) {
        java2sLogo.paintIcon(this, g, 280 - (iconWidth / 2), 120 - (iconHeight / 2));
        System.out.println(" logo below blue Rect repainted.");
    }

    if (clipx + clipw >= 120 - (iconWidth / 2) && clipx <= (120 + (iconWidth / 2))
            && clipy + cliph >= 280 - (iconHeight / 2) && clipy <= (280 + (iconHeight / 2))) {
        java2sLogo.paintIcon(this, g, 120 - (iconWidth / 2), 280 - (iconHeight / 2));
        System.out.println(" logo below red Rect repainted.");
    }

    if (clipx + clipw >= 60 && clipx <= 180 && clipy + cliph >= 220 && clipy <= 340) {
        g.setColor(red);
        g.fillRect(60, 220, 120, 120);
        System.out.println(" red Rect repainted.");

    }

    if (clipx + clipw > 140 && clipx < 260 && clipy + cliph > 140 && clipy < 260) {
        g.setColor(green);
        g.fillOval(140, 140, 120, 120);
        System.out.println(" green Oval repainted.");

    }

    if (clipx + clipw > 220 && clipx < 380 && clipy + cliph > 60 && clipy < 180) {
        g.setColor(blue);
        g.fillRect(220, 60, 120, 120);
        System.out.println(" blue Rect repainted.");
    }

    g.setColor(Color.black);

    g.setFont(monoFont);
    FontMetrics fm = g.getFontMetrics();
    iconWidth = fm.stringWidth("Java Source");
    iconHeight = fm.getAscent();
    int d = fm.getDescent();
    if (clipx + clipw > 120 - (iconWidth / 2) && clipx < (120 + (iconWidth / 2))
            && clipy + cliph > (120 + (iconHeight / 4)) - iconHeight && clipy < (120 + (iconHeight / 4)) + d) {
        g.drawString("Java Source", 120 - (iconWidth / 2), 120 + (iconHeight / 4));
        System.out.println(" Java Source repainted.");
    }

    g.setFont(sanFont);
    fm = g.getFontMetrics();
    iconWidth = fm.stringWidth("and");
    iconHeight = fm.getAscent();
    d = fm.getDescent();
    if (clipx + clipw > 200 - (iconWidth / 2) && clipx < (200 + (iconWidth / 2))
            && clipy + cliph > (200 + (iconHeight / 4)) - iconHeight && clipy < (200 + (iconHeight / 4)) + d) {
        g.drawString("and", 200 - (iconWidth / 2), 200 + (iconHeight / 4));
        System.out.println(" and repainted.");
    }

    g.setFont(serifFont);
    fm = g.getFontMetrics();
    iconWidth = fm.stringWidth("Support.");
    iconHeight = fm.getAscent();
    d = fm.getDescent();

    if (clipx + clipw > 280 - (iconWidth / 2) && clipx < (280 + (iconWidth / 2))
            && clipy + cliph > (280 + (iconHeight / 4)) - iconHeight && clipy < (280 + (iconHeight / 4)) + d) {
        g.drawString("Support.", 280 - (iconWidth / 2), 280 + (iconHeight / 4));
        System.out.println(" Support. repainted.");
    }
}

From source file:ded.ui.DiagramController.java

/** The core of the paint routine, after we decide whether to interpose
  * another buffer. *//*from w w w .j  a  v  a2  s.co  m*/
private void innerPaint(Graphics g) {
    super.paint(g);

    // I do not know the proper way to get a font set automatically
    // in a Graphics object.  Calling JComponent.setFont has gotten
    // me nowhere.  Setting it myself when I first get control
    // seems to work; but note that I have to do this *after*
    // calling super.paint().
    g.setFont(this.dedWindow.diagramFont);

    // Filename label.
    if (this.diagram.drawFileName && !this.fileName.isEmpty()) {
        String name = new File(this.fileName).getName();
        FontMetrics fm = g.getFontMetrics();
        LineMetrics lm = fm.getLineMetrics(name, g);
        int x = fileNameLabelMargin;
        int y = fileNameLabelMargin + (int) lm.getAscent();
        g.drawString(name, x, y);
        y += (int) lm.getUnderlineOffset() + 1 /*...*/;
        g.drawLine(x, y, x + fm.stringWidth(name), y);
    }

    // Controllers.
    for (Controller c : this.controllers) {
        if (c.isSelected()) {
            c.paintSelectionBackground(g);
        }
        c.paint(g);
    }

    // Lasso rectangle.
    if (this.mode == Mode.DCM_RECT_LASSO) {
        Rectangle r = this.getLassoRect();
        g.drawRect(r.x, r.y, r.width, r.height);
    }

    // Current focused Component.
    if (debugFocus) {
        KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        Component fo = kfm.getFocusOwner();
        g.drawString("Focus: " + fo, 3, this.getHeight() - 22);
    }

    // Mode label.
    if (this.mode != Mode.DCM_SELECT) {
        g.drawString("Mode: " + this.mode.description, 3, this.getHeight() - 4);
    } else if (this.fpsMeasurementMode) {
        this.fpsFrameCount++;
        long current = System.currentTimeMillis();
        long millis = current - this.fpsStartMillis;
        if (millis > 1000) {
            // Update the FPS measurement with the results for this
            // interval.
            this.fpsSampleCount++;
            this.fpsMeasurement = "FPS: " + this.fpsFrameCount + " (millis=" + millis + ", samples="
                    + this.fpsSampleCount + ")";

            // Reset the counters.
            this.fpsStartMillis = current;
            this.fpsFrameCount = 0;
        }
        g.drawString(this.fpsMeasurement + " (Ctrl+G to stop)", 3, this.getHeight() - 4);
    }
}

From source file:net.pms.dlna.DLNAMediaInfo.java

public void parse(InputFile inputFile, Format ext, int type, boolean thumbOnly) {
    int i = 0;//from w  w  w.  ja va 2s .c om

    while (isParsing()) {
        if (i == 5) {
            setMediaparsed(true);
            break;
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        i++;
    }

    if (isMediaparsed()) {
        return;
    }

    if (inputFile != null) {
        if (inputFile.getFile() != null) {
            setSize(inputFile.getFile().length());
        } else {
            setSize(inputFile.getSize());
        }

        ProcessWrapperImpl pw = null;
        boolean ffmpeg_parsing = true;

        if (type == Format.AUDIO || ext instanceof AudioAsVideo) {
            ffmpeg_parsing = false;
            DLNAMediaAudio audio = new DLNAMediaAudio();

            if (inputFile.getFile() != null) {
                try {
                    AudioFile af = AudioFileIO.read(inputFile.getFile());
                    AudioHeader ah = af.getAudioHeader();

                    if (ah != null && !thumbOnly) {
                        int length = ah.getTrackLength();
                        int rate = ah.getSampleRateAsNumber();

                        if (ah.getEncodingType().toLowerCase().contains("flac 24")) {
                            audio.setBitsperSample(24);
                        }

                        audio.setSampleFrequency("" + rate);
                        setDuration((double) length);
                        setBitrate((int) ah.getBitRateAsNumber());
                        audio.getAudioProperties().setNumberOfChannels(2);

                        if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("mono")) {
                            audio.getAudioProperties().setNumberOfChannels(1);
                        } else if (ah.getChannels() != null
                                && ah.getChannels().toLowerCase().contains("stereo")) {
                            audio.getAudioProperties().setNumberOfChannels(2);
                        } else if (ah.getChannels() != null) {
                            audio.getAudioProperties().setNumberOfChannels(Integer.parseInt(ah.getChannels()));
                        }

                        audio.setCodecA(ah.getEncodingType().toLowerCase());

                        if (audio.getCodecA().contains("(windows media")) {
                            audio.setCodecA(audio.getCodecA()
                                    .substring(0, audio.getCodecA().indexOf("(windows media")).trim());
                        }
                    }

                    Tag t = af.getTag();

                    if (t != null) {
                        if (t.getArtworkList().size() > 0) {
                            setThumb(t.getArtworkList().get(0).getBinaryData());
                        } else {
                            if (configuration.getAudioThumbnailMethod() > 0) {
                                setThumb(CoverUtil.get().getThumbnailFromArtistAlbum(
                                        configuration.getAudioThumbnailMethod() == 1 ? CoverUtil.AUDIO_AMAZON
                                                : CoverUtil.AUDIO_DISCOGS,
                                        audio.getArtist(), audio.getAlbum()));
                            }
                        }

                        if (!thumbOnly) {
                            audio.setAlbum(t.getFirst(FieldKey.ALBUM));
                            audio.setArtist(t.getFirst(FieldKey.ARTIST));
                            audio.setSongname(t.getFirst(FieldKey.TITLE));
                            String y = t.getFirst(FieldKey.YEAR);

                            try {
                                if (y.length() > 4) {
                                    y = y.substring(0, 4);
                                }
                                audio.setYear(Integer.parseInt(((y != null && y.length() > 0) ? y : "0")));
                                y = t.getFirst(FieldKey.TRACK);
                                audio.setTrack(Integer.parseInt(((y != null && y.length() > 0) ? y : "1")));
                                audio.setGenre(t.getFirst(FieldKey.GENRE));
                            } catch (Throwable e) {
                                logger.debug("Error parsing unimportant metadata: " + e.getMessage());
                            }
                        }
                    }
                } catch (Throwable e) {
                    logger.debug("Error parsing audio file: {} - {}", e.getMessage(),
                            e.getCause() != null ? e.getCause().getMessage() : "");
                    ffmpeg_parsing = false;
                }

                if (audio.getSongname() == null || audio.getSongname().length() == 0) {
                    audio.setSongname(inputFile.getFile().getName());
                }

                if (!ffmpeg_parsing) {
                    getAudioTracksList().add(audio);
                }
            }
        }

        if (type == Format.IMAGE && inputFile.getFile() != null) {
            try {
                ffmpeg_parsing = false;
                ImageInfo info = Sanselan.getImageInfo(inputFile.getFile());
                setWidth(info.getWidth());
                setHeight(info.getHeight());
                setBitsPerPixel(info.getBitsPerPixel());
                String formatName = info.getFormatName();

                if (formatName.startsWith("JPEG")) {
                    setCodecV("jpg");
                    IImageMetadata meta = Sanselan.getMetadata(inputFile.getFile());

                    if (meta != null && meta instanceof JpegImageMetadata) {
                        JpegImageMetadata jpegmeta = (JpegImageMetadata) meta;
                        TiffField tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_MODEL);

                        if (tf != null) {
                            setModel(tf.getStringValue().trim());
                        }

                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_EXPOSURE_TIME);
                        if (tf != null) {
                            setExposure((int) (1000 * tf.getDoubleValue()));
                        }

                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ORIENTATION);
                        if (tf != null) {
                            setOrientation(tf.getIntValue());
                        }

                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ISO);
                        if (tf != null) {
                            // Galaxy Nexus jpg pictures may contain multiple values, take the first
                            int[] isoValues = tf.getIntArrayValue();
                            setIso(isoValues[0]);
                        }
                    }
                } else if (formatName.startsWith("PNG")) {
                    setCodecV("png");
                } else if (formatName.startsWith("GIF")) {
                    setCodecV("gif");
                } else if (formatName.startsWith("TIF")) {
                    setCodecV("tiff");
                }

                setContainer(getCodecV());
            } catch (Throwable e) {
                logger.info("Error parsing image ({}) with Sanselan, switching to FFmpeg.",
                        inputFile.getFile().getAbsolutePath());
            }
        }

        if (configuration.getImageThumbnailsEnabled() && type != Format.VIDEO && type != Format.AUDIO) {
            try {
                File thumbDir = new File(configuration.getTempFolder(), THUMBNAIL_DIRECTORY_NAME);

                logger.trace("Generating thumbnail for: {}", inputFile.getFile().getAbsolutePath());

                if (!thumbDir.exists() && !thumbDir.mkdirs()) {
                    logger.warn("Could not create thumbnail directory: {}", thumbDir.getAbsolutePath());
                } else {
                    File thumbFile = new File(thumbDir, inputFile.getFile().getName() + ".jpg");
                    String thumbFilename = thumbFile.getAbsolutePath();

                    logger.trace("Creating (temporary) thumbnail: {}", thumbFilename);

                    // Create the thumbnail image using the Thumbnailator library
                    final Builder<File> thumbnail = Thumbnails.of(inputFile.getFile());
                    thumbnail.size(320, 180);
                    thumbnail.outputFormat("jpg");
                    thumbnail.outputQuality(1.0f);

                    try {
                        thumbnail.toFile(thumbFilename);
                    } catch (IIOException e) {
                        logger.debug("Error generating thumbnail for: " + inputFile.getFile().getName());
                        logger.debug("The full error was: " + e);
                    }

                    File jpg = new File(thumbFilename);

                    if (jpg.exists()) {
                        InputStream is = new FileInputStream(jpg);
                        int sz = is.available();

                        if (sz > 0) {
                            setThumb(new byte[sz]);
                            is.read(getThumb());
                        }

                        is.close();

                        if (!jpg.delete()) {
                            jpg.deleteOnExit();
                        }
                    }
                }
            } catch (UnsupportedFormatException ufe) {
                logger.debug("Thumbnailator does not support the format of {}: {}",
                        inputFile.getFile().getAbsolutePath(), ufe.getMessage());
            } catch (Exception e) {
                logger.debug("Thumbnailator could not generate a thumbnail for: {}",
                        inputFile.getFile().getAbsolutePath(), e);
            }
        }

        if (ffmpeg_parsing) {
            if (!thumbOnly || !configuration.isUseMplayerForVideoThumbs()) {
                pw = getFFmpegThumbnail(inputFile);
            }

            String input = "-";
            boolean dvrms = false;

            if (inputFile.getFile() != null) {
                input = ProcessUtil.getShortFileNameIfWideChars(inputFile.getFile().getAbsolutePath());
                dvrms = inputFile.getFile().getAbsolutePath().toLowerCase().endsWith("dvr-ms");
            }

            if (!ffmpeg_failure && !thumbOnly) {
                if (input.equals("-")) {
                    input = "pipe:";
                }

                boolean matchs = false;
                ArrayList<String> lines = (ArrayList<String>) pw.getResults();
                int langId = 0;
                int subId = 0;
                ListIterator<String> FFmpegMetaData = lines.listIterator();

                for (String line : lines) {
                    FFmpegMetaData.next();
                    line = line.trim();
                    if (line.startsWith("Output")) {
                        matchs = false;
                    } else if (line.startsWith("Input")) {
                        if (line.indexOf(input) > -1) {
                            matchs = true;
                            setContainer(line.substring(10, line.indexOf(",", 11)).trim());
                        } else {
                            matchs = false;
                        }
                    } else if (matchs) {
                        if (line.indexOf("Duration") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                if (token.startsWith("Duration: ")) {
                                    String durationStr = token.substring(10);
                                    int l = durationStr.substring(durationStr.indexOf(".") + 1).length();
                                    if (l < 4) {
                                        durationStr = durationStr + "00".substring(0, 3 - l);
                                    }
                                    if (durationStr.indexOf("N/A") > -1) {
                                        setDuration(null);
                                    } else {
                                        setDuration(parseDurationString(durationStr));
                                    }
                                } else if (token.startsWith("bitrate: ")) {
                                    String bitr = token.substring(9);
                                    int spacepos = bitr.indexOf(" ");
                                    if (spacepos > -1) {
                                        String value = bitr.substring(0, spacepos);
                                        String unit = bitr.substring(spacepos + 1);
                                        setBitrate(Integer.parseInt(value));
                                        if (unit.equals("kb/s")) {
                                            setBitrate(1024 * getBitrate());
                                        }
                                        if (unit.equals("mb/s")) {
                                            setBitrate(1048576 * getBitrate());
                                        }
                                    }
                                }
                            }
                        } else if (line.indexOf("Audio:") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            int a = line.indexOf("(");
                            int b = line.indexOf("):", a);
                            DLNAMediaAudio audio = new DLNAMediaAudio();
                            audio.setId(langId++);
                            if (a > -1 && b > a) {
                                audio.setLang(line.substring(a + 1, b));
                            } else {
                                audio.setLang(DLNAMediaLang.UND);
                            }

                            // Get TS IDs
                            a = line.indexOf("[0x");
                            b = line.indexOf("]", a);
                            if (a > -1 && b > a + 3) {
                                String idString = line.substring(a + 3, b);
                                try {
                                    audio.setId(Integer.parseInt(idString, 16));
                                } catch (NumberFormatException nfe) {
                                    logger.debug("Error parsing Stream ID: " + idString);
                                }
                            }

                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                Integer nChannels;

                                if (token.startsWith("Stream")) {
                                    audio.setCodecA(token.substring(token.indexOf("Audio: ") + 7));
                                } else if (token.endsWith("Hz")) {
                                    audio.setSampleFrequency(token.substring(0, token.indexOf("Hz")).trim());
                                } else if ((nChannels = audioChannelLayout.get(token)) != null) {
                                    audio.getAudioProperties().setNumberOfChannels(nChannels);
                                } else if (token.matches("\\d+(?:\\s+channels?)")) { // implicitly anchored at both ends e.g. ^ ... $
                                    // setNumberOfChannels(String) parses the number out of the string
                                    audio.getAudioProperties().setNumberOfChannels(token);
                                } else if (token.equals("s32")) {
                                    audio.setBitsperSample(32);
                                } else if (token.equals("s24")) {
                                    audio.setBitsperSample(24);
                                } else if (token.equals("s16")) {
                                    audio.setBitsperSample(16);
                                }
                            }
                            int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();

                            if (FFmpegMetaDataNr > -1) {
                                line = lines.get(FFmpegMetaDataNr);
                            }

                            if (line.indexOf("Metadata:") > -1) {
                                FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                line = lines.get(FFmpegMetaDataNr);
                                while (line.indexOf("      ") == 0) {
                                    if (line.toLowerCase().indexOf("title           :") > -1) {
                                        int aa = line.indexOf(": ");
                                        int bb = line.length();
                                        if (aa > -1 && bb > aa) {
                                            audio.setFlavor(line.substring(aa + 2, bb));
                                            break;
                                        }
                                    } else {
                                        FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                        line = lines.get(FFmpegMetaDataNr);
                                    }
                                }
                            }

                            getAudioTracksList().add(audio);
                        } else if (line.indexOf("Video:") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                if (token.startsWith("Stream")) {
                                    setCodecV(token.substring(token.indexOf("Video: ") + 7));
                                } else if ((token.indexOf("tbc") > -1 || token.indexOf("tb(c)") > -1)) {
                                    // A/V sync issues with newest FFmpeg, due to the new tbr/tbn/tbc outputs
                                    // Priority to tb(c)
                                    String frameRateDoubleString = token.substring(0, token.indexOf("tb"))
                                            .trim();
                                    try {
                                        if (!frameRateDoubleString.equals(getFrameRate())) {// tbc taken into account only if different than tbr
                                            Double frameRateDouble = Double.parseDouble(frameRateDoubleString);
                                            setFrameRate(
                                                    String.format(Locale.ENGLISH, "%.2f", frameRateDouble / 2));
                                        }
                                    } catch (NumberFormatException nfe) {
                                        // Could happen if tbc is "1k" or something like that, no big deal
                                        logger.debug(
                                                "Could not parse frame rate \"" + frameRateDoubleString + "\"");
                                    }

                                } else if ((token.indexOf("tbr") > -1 || token.indexOf("tb(r)") > -1)
                                        && getFrameRate() == null) {
                                    setFrameRate(token.substring(0, token.indexOf("tb")).trim());
                                } else if ((token.indexOf("fps") > -1 || token.indexOf("fps(r)") > -1)
                                        && getFrameRate() == null) { // dvr-ms ?
                                    setFrameRate(token.substring(0, token.indexOf("fps")).trim());
                                } else if (token.indexOf("x") > -1) {
                                    String resolution = token.trim();
                                    if (resolution.indexOf(" [") > -1) {
                                        resolution = resolution.substring(0, resolution.indexOf(" ["));
                                    }
                                    try {
                                        setWidth(Integer
                                                .parseInt(resolution.substring(0, resolution.indexOf("x"))));
                                    } catch (NumberFormatException nfe) {
                                        logger.debug("Could not parse width from \""
                                                + resolution.substring(0, resolution.indexOf("x")) + "\"");
                                    }
                                    try {
                                        setHeight(Integer
                                                .parseInt(resolution.substring(resolution.indexOf("x") + 1)));
                                    } catch (NumberFormatException nfe) {
                                        logger.debug("Could not parse height from \""
                                                + resolution.substring(resolution.indexOf("x") + 1) + "\"");
                                    }
                                }
                            }
                        } else if (line.indexOf("Subtitle:") > -1 && !line.contains("tx3g")) {
                            DLNAMediaSubtitle lang = new DLNAMediaSubtitle();
                            lang.setType((line.contains("dvdsub") && Platform.isWindows() ? SubtitleType.VOBSUB
                                    : SubtitleType.UNKNOWN));
                            int a = line.indexOf("(");
                            int b = line.indexOf("):", a);
                            if (a > -1 && b > a) {
                                lang.setLang(line.substring(a + 1, b));
                            } else {
                                lang.setLang(DLNAMediaLang.UND);
                            }

                            lang.setId(subId++);
                            int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();

                            if (FFmpegMetaDataNr > -1) {
                                line = lines.get(FFmpegMetaDataNr);
                            }

                            if (line.indexOf("Metadata:") > -1) {
                                FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                line = lines.get(FFmpegMetaDataNr);

                                while (line.indexOf("      ") == 0) {
                                    if (line.toLowerCase().indexOf("title           :") > -1) {
                                        int aa = line.indexOf(": ");
                                        int bb = line.length();
                                        if (aa > -1 && bb > aa) {
                                            lang.setFlavor(line.substring(aa + 2, bb));
                                            break;
                                        }
                                    } else {
                                        FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                        line = lines.get(FFmpegMetaDataNr);
                                    }
                                }
                            }
                            getSubtitleTracksList().add(lang);
                        }
                    }
                }
            }

            if (!thumbOnly && getContainer() != null && inputFile.getFile() != null
                    && getContainer().equals("mpegts") && isH264() && getDurationInSeconds() == 0) {
                // Parse the duration
                try {
                    int length = MpegUtil.getDurationFromMpeg(inputFile.getFile());
                    if (length > 0) {
                        setDuration((double) length);
                    }
                } catch (IOException e) {
                    logger.trace("Error retrieving length: " + e.getMessage());
                }
            }

            if (configuration.isUseMplayerForVideoThumbs() && type == Format.VIDEO && !dvrms) {
                try {
                    getMplayerThumbnail(inputFile);
                    String frameName = "" + inputFile.hashCode();
                    frameName = configuration.getTempFolder() + "/mplayer_thumbs/" + frameName
                            + "00000001/00000001.jpg";
                    frameName = frameName.replace(',', '_');
                    File jpg = new File(frameName);

                    if (jpg.exists()) {
                        InputStream is = new FileInputStream(jpg);
                        int sz = is.available();

                        if (sz > 0) {
                            setThumb(new byte[sz]);
                            is.read(getThumb());
                        }

                        is.close();

                        if (!jpg.delete()) {
                            jpg.deleteOnExit();
                        }

                        // Try and retry
                        if (!jpg.getParentFile().delete() && !jpg.getParentFile().delete()) {
                            logger.debug("Failed to delete \"" + jpg.getParentFile().getAbsolutePath() + "\"");
                        }
                    }
                } catch (IOException e) {
                    logger.debug("Caught exception", e);
                }
            }

            if (type == Format.VIDEO && pw != null && getThumb() == null) {
                InputStream is;
                try {
                    is = pw.getInputStream(0);
                    int sz = is.available();
                    if (sz > 0) {
                        setThumb(new byte[sz]);
                        is.read(getThumb());
                    }
                    is.close();

                    if (sz > 0 && !net.pms.PMS.isHeadless()) {
                        BufferedImage image = ImageIO.read(new ByteArrayInputStream(getThumb()));
                        if (image != null) {
                            Graphics g = image.getGraphics();
                            g.setColor(Color.WHITE);
                            g.setFont(new Font("Arial", Font.PLAIN, 14));
                            int low = 0;
                            if (getWidth() > 0) {
                                if (getWidth() == 1920 || getWidth() == 1440) {
                                    g.drawString("1080p", 0, low += 18);
                                } else if (getWidth() == 1280) {
                                    g.drawString("720p", 0, low += 18);
                                }
                            }
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            ImageIO.write(image, "jpeg", out);
                            setThumb(out.toByteArray());
                        }
                    }
                } catch (IOException e) {
                    logger.debug("Error while decoding thumbnail: " + e.getMessage());
                }
            }
        }

        finalize(type, inputFile);
        setMediaparsed(true);
    }
}

From source file:edu.upf.bioevo.manhattanPlotter.QQPlot.java

void drawPlot() {
    int dotRadius;
    int xIncrement = (IMAGE_WIDTH - (xMargin * 2)) / (int) (maxExpectedLogValue + 1);
    int yIncrement = (IMAGE_HEIGHT - (yMargin * 2)) / (int) (maxObservedLogValue + 1);
    Graphics g = image.getGraphics();

    // Cleans image
    g.setColor(Color.WHITE);//w w w  .j ava2s. co m
    g.fillRect(0, 0, image.getWidth(), image.getHeight());

    // Draws axis lines
    g.setColor(Color.black);
    g.drawLine(xMargin, IMAGE_HEIGHT - yMargin, IMAGE_WIDTH - xMargin, IMAGE_HEIGHT - yMargin);
    g.drawLine(xMargin, IMAGE_HEIGHT - yMargin, xMargin, yMargin);

    // Draws confidence interval
    if (ic95Option) {
        g.setColor(Color.lightGray);
        for (int i = 0; i < upperCI.length - 1; i++) {
            int[] xPoints = { xMargin + (int) (orderedLog10ExpectedValues[i] * xIncrement),
                    xMargin + (int) (orderedLog10ExpectedValues[i] * xIncrement),
                    xMargin + (int) (orderedLog10ExpectedValues[i + 1] * xIncrement),
                    xMargin + (int) (orderedLog10ExpectedValues[i + 1] * xIncrement) };
            int[] yPoints = { IMAGE_HEIGHT - (yMargin + ((int) (upperCI[i] * yIncrement))),
                    IMAGE_HEIGHT - (yMargin + ((int) (lowerCI[i] * yIncrement))),
                    IMAGE_HEIGHT - (yMargin + ((int) (lowerCI[i + 1] * yIncrement))),
                    IMAGE_HEIGHT - (yMargin + ((int) (upperCI[i + 1] * yIncrement))) };

            g.fillPolygon(xPoints, yPoints, 4);
        }
    }

    // Draws dots
    dotRadius = 4;
    g.setColor(Color.black);
    for (int i = 0; i < orderedLog10ObservedValues.length; i++) {
        int xPosition = xMargin + ((int) (orderedLog10ExpectedValues[i] * xIncrement));
        int yPosition = IMAGE_HEIGHT - (yMargin + ((int) (orderedLog10ObservedValues[i] * yIncrement)));
        g.fillOval(xPosition - dotRadius, yPosition - dotRadius, dotRadius * 2, dotRadius * 2);
    }

    // --draw y axis scale
    // ----Calculates interval between labels in y axis
    int yInterval = 1;
    int verticalMaxValue = (int) maxObservedLogValue + 1;

    if (verticalMaxValue > 20) {
        yInterval = 5;
    }
    if (verticalMaxValue > 100) {
        yInterval = 50;
    }
    if (verticalMaxValue > 1000) {
        yInterval = verticalMaxValue;
    }

    g.setColor(Color.BLACK);
    for (int i = 0; i <= verticalMaxValue; i = i + yInterval) {
        int yPos = IMAGE_HEIGHT
                - (yMargin + (int) (((float) i / verticalMaxValue) * (IMAGE_HEIGHT - 2 * yMargin)));
        g.fillRect(45, yPos, 15, 3);
        g.setFont(new Font("courier", 1, 30));
        String value = String.valueOf(i);
        if (value.length() == 1) {
            value = " " + value;
        }
        g.drawString(value, 5, yPos + 10);
    }

    // --draw x axis scale
    // ----Calculates interval between labels in x axis
    int xInterval = 1;
    int horizontalMaxValue = (int) maxExpectedLogValue + 1;

    if (horizontalMaxValue > 20) {
        xInterval = 5;
    }
    if (horizontalMaxValue > 100) {
        xInterval = 50;
    }
    if (horizontalMaxValue > 1000) {
        xInterval = verticalMaxValue;
    }

    g.setColor(Color.BLACK);
    for (int i = 0; i <= horizontalMaxValue; i = i + xInterval) {
        int xPos = (xMargin + (int) (((float) i / horizontalMaxValue) * (IMAGE_WIDTH - 2 * xMargin)));
        g.fillRect(xPos, IMAGE_HEIGHT - yMargin, 3, 15);
        g.setFont(new Font("courier", 1, 30));
        String value = String.valueOf(i);
        if (value.length() == 1) {
            value = " " + value;
        }
        g.drawString(value, xPos - 15, IMAGE_HEIGHT - yMargin + 45);
    }

    // Draws identity line
    g.setColor(Color.RED);
    int endLineValue = horizontalMaxValue < verticalMaxValue ? horizontalMaxValue : verticalMaxValue;
    g.drawLine(xMargin, IMAGE_HEIGHT - yMargin, xMargin + ((int) (endLineValue * xIncrement)),
            IMAGE_HEIGHT - (yMargin + ((int) (endLineValue * yIncrement))));

    // -- title
    g.setColor(Color.blue);
    g.setFont(new Font("arial", 1, 35));
    g.drawString(label, IMAGE_WIDTH / 7, 40);
}