1 /*
   2  * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javax.swing.plaf.synth;
  27 
  28 import java.awt.*;
  29 import java.awt.geom.AffineTransform;
  30 import javax.swing.*;
  31 import javax.swing.plaf.*;
  32 import javax.swing.plaf.basic.BasicProgressBarUI;
  33 import java.beans.PropertyChangeListener;
  34 import java.beans.PropertyChangeEvent;
  35 import sun.swing.SwingUtilities2;
  36 
  37 /**
  38  * Provides the Synth L&F UI delegate for
  39  * {@link javax.swing.JProgressBar}.
  40  *
  41  * @author Joshua Outwater
  42  * @since 1.7
  43  */
  44 public class SynthProgressBarUI extends BasicProgressBarUI
  45                                 implements SynthUI, PropertyChangeListener {
  46     private SynthStyle style;
  47     private int progressPadding;
  48     private boolean rotateText; // added for Nimbus LAF
  49     private boolean paintOutsideClip;
  50     private boolean tileWhenIndeterminate; //whether to tile indeterminate painting
  51     private int tileWidth; //the width of each tile
  52 
  53     /**
  54      * Creates a new UI object for the given component.
  55      *
  56      * @param x component to create UI object for
  57      * @return the UI object
  58      */
  59     public static ComponentUI createUI(JComponent x) {
  60         return new SynthProgressBarUI();
  61     }
  62 
  63     /**
  64      * {@inheritDoc}
  65      */
  66     @Override
  67     protected void installListeners() {
  68         super.installListeners();
  69         progressBar.addPropertyChangeListener(this);
  70     }
  71 
  72     /**
  73      * {@inheritDoc}
  74      */
  75     @Override
  76     protected void uninstallListeners() {
  77         super.uninstallListeners();
  78         progressBar.removePropertyChangeListener(this);
  79     }
  80 
  81     /**
  82      * {@inheritDoc}
  83      */
  84     @Override
  85     protected void installDefaults() {
  86         updateStyle(progressBar);
  87     }
  88 
  89     private void updateStyle(JProgressBar c) {
  90         SynthContext context = getContext(c, ENABLED);
  91         SynthStyle oldStyle = style;
  92         style = SynthLookAndFeel.updateStyle(context, this);
  93         setCellLength(style.getInt(context, "ProgressBar.cellLength", 1));
  94         setCellSpacing(style.getInt(context, "ProgressBar.cellSpacing", 0));
  95         progressPadding = style.getInt(context,
  96                 "ProgressBar.progressPadding", 0);
  97         paintOutsideClip = style.getBoolean(context,
  98                 "ProgressBar.paintOutsideClip", false);
  99         rotateText = style.getBoolean(context,
 100                 "ProgressBar.rotateText", false);
 101         tileWhenIndeterminate = style.getBoolean(context, "ProgressBar.tileWhenIndeterminate", false);
 102         tileWidth = style.getInt(context, "ProgressBar.tileWidth", 15);
 103         // handle scaling for sizeVarients for special case components. The
 104         // key "JComponent.sizeVariant" scales for large/small/mini
 105         // components are based on Apples LAF
 106         String scaleKey = (String)progressBar.getClientProperty(
 107                 "JComponent.sizeVariant");
 108         if (scaleKey != null){
 109             if ("large".equals(scaleKey)){
 110                 tileWidth *= 1.15;
 111             } else if ("small".equals(scaleKey)){
 112                 tileWidth *= 0.857;
 113             } else if ("mini".equals(scaleKey)){
 114                 tileWidth *= 0.784;
 115             }
 116         }
 117         context.dispose();
 118     }
 119 
 120     /**
 121      * {@inheritDoc}
 122      */
 123     @Override
 124     protected void uninstallDefaults() {
 125         SynthContext context = getContext(progressBar, ENABLED);
 126 
 127         style.uninstallDefaults(context);
 128         context.dispose();
 129         style = null;
 130     }
 131 
 132     /**
 133      * {@inheritDoc}
 134      */
 135     @Override
 136     public SynthContext getContext(JComponent c) {
 137         return getContext(c, getComponentState(c));
 138     }
 139 
 140     private SynthContext getContext(JComponent c, int state) {
 141         return SynthContext.getContext(c, style, state);
 142     }
 143 
 144     private int getComponentState(JComponent c) {
 145         return SynthLookAndFeel.getComponentState(c);
 146     }
 147 
 148     /**
 149      * {@inheritDoc}
 150      */
 151     @Override
 152     public int getBaseline(JComponent c, int width, int height) {
 153         super.getBaseline(c, width, height);
 154         if (progressBar.isStringPainted() &&
 155                 progressBar.getOrientation() == JProgressBar.HORIZONTAL) {
 156             SynthContext context = getContext(c);
 157             Font font = context.getStyle().getFont(context);
 158             FontMetrics metrics = progressBar.getFontMetrics(font);
 159             context.dispose();
 160             return (height - metrics.getAscent() - metrics.getDescent()) / 2 +
 161                     metrics.getAscent();
 162         }
 163         return -1;
 164     }
 165 
 166     /**
 167      * {@inheritDoc}
 168      */
 169     @Override
 170     protected Rectangle getBox(Rectangle r) {
 171         if (tileWhenIndeterminate) {
 172             return SwingUtilities.calculateInnerArea(progressBar, r);
 173         } else {
 174             return super.getBox(r);
 175         }
 176     }
 177 
 178     /**
 179      * {@inheritDoc}
 180      */
 181     @Override
 182     protected void setAnimationIndex(int newValue) {
 183         if (paintOutsideClip) {
 184             if (getAnimationIndex() == newValue) {
 185                 return;
 186             }
 187             super.setAnimationIndex(newValue);
 188             progressBar.repaint();
 189         } else {
 190             super.setAnimationIndex(newValue);
 191         }
 192     }
 193 
 194     /**
 195      * Notifies this UI delegate to repaint the specified component.
 196      * This method paints the component background, then calls
 197      * the {@link #paint(SynthContext,Graphics)} method.
 198      *
 199      * <p>In general, this method does not need to be overridden by subclasses.
 200      * All Look and Feel rendering code should reside in the {@code paint} method.
 201      *
 202      * @param g the {@code Graphics} object used for painting
 203      * @param c the component being painted
 204      * @see #paint(SynthContext,Graphics)
 205      */
 206     @Override
 207     public void update(Graphics g, JComponent c) {
 208         SynthContext context = getContext(c);
 209 
 210         SynthLookAndFeel.update(context, g);
 211         context.getPainter().paintProgressBarBackground(context,
 212                           g, 0, 0, c.getWidth(), c.getHeight(),
 213                           progressBar.getOrientation());
 214         paint(context, g);
 215         context.dispose();
 216     }
 217 
 218     /**
 219      * Paints the specified component according to the Look and Feel.
 220      * <p>This method is not used by Synth Look and Feel.
 221      * Painting is handled by the {@link #paint(SynthContext,Graphics)} method.
 222      *
 223      * @param g the {@code Graphics} object used for painting
 224      * @param c the component being painted
 225      * @see #paint(SynthContext,Graphics)
 226      */
 227     @Override
 228     public void paint(Graphics g, JComponent c) {
 229         SynthContext context = getContext(c);
 230 
 231         paint(context, g);
 232         context.dispose();
 233     }
 234 
 235     /**
 236      * Paints the specified component.
 237      *
 238      * @param context context for the component being painted
 239      * @param g the {@code Graphics} object used for painting
 240      * @see #update(Graphics,JComponent)
 241      */
 242     protected void paint(SynthContext context, Graphics g) {
 243         JProgressBar pBar = (JProgressBar)context.getComponent();
 244         int x = 0, y = 0, width = 0, height = 0;
 245         if (!pBar.isIndeterminate()) {
 246             Insets pBarInsets = pBar.getInsets();
 247             double percentComplete = pBar.getPercentComplete();
 248             if (percentComplete != 0.0) {
 249                 if (pBar.getOrientation() == JProgressBar.HORIZONTAL) {
 250                     x = pBarInsets.left + progressPadding;
 251                     y = pBarInsets.top + progressPadding;
 252                     width = (int)(percentComplete * (pBar.getWidth()
 253                             - (pBarInsets.left + progressPadding
 254                              + pBarInsets.right + progressPadding)));
 255                     height = pBar.getHeight()
 256                             - (pBarInsets.top + progressPadding
 257                              + pBarInsets.bottom + progressPadding);
 258 
 259                     if (!SynthLookAndFeel.isLeftToRight(pBar)) {
 260                         x = pBar.getWidth() - pBarInsets.right - width
 261                                 - progressPadding;
 262                     }
 263                 } else {  // JProgressBar.VERTICAL
 264                     x = pBarInsets.left + progressPadding;
 265                     width = pBar.getWidth()
 266                             - (pBarInsets.left + progressPadding
 267                             + pBarInsets.right + progressPadding);
 268                     height = (int)(percentComplete * (pBar.getHeight()
 269                             - (pBarInsets.top + progressPadding
 270                              + pBarInsets.bottom + progressPadding)));
 271                     y = pBar.getHeight() - pBarInsets.bottom - height
 272                             - progressPadding;
 273 
 274                     // When the progress bar is vertical we always paint
 275                     // from bottom to top, not matter what the component
 276                     // orientation is.
 277                 }
 278             }
 279         } else {
 280             boxRect = getBox(boxRect);
 281             x = boxRect.x + progressPadding;
 282             y = boxRect.y + progressPadding;
 283             width = boxRect.width - progressPadding - progressPadding;
 284             height = boxRect.height - progressPadding - progressPadding;
 285         }
 286 
 287         //if tiling and indeterminate, then paint the progress bar foreground a
 288         //bit wider than it should be. Shift as needed to ensure that there is
 289         //an animated effect
 290         if (tileWhenIndeterminate && pBar.isIndeterminate()) {
 291             double percentComplete = (double)getAnimationIndex() / (double)getFrameCount();
 292             int offset = (int)(percentComplete * tileWidth);
 293             Shape clip = g.getClip();
 294             g.clipRect(x, y, width, height);
 295             if (pBar.getOrientation() == JProgressBar.HORIZONTAL) {
 296                 //paint each tile horizontally
 297                 for (int i=x-tileWidth+offset; i<=width; i+=tileWidth) {
 298                     context.getPainter().paintProgressBarForeground(
 299                             context, g, i, y, tileWidth, height, pBar.getOrientation());
 300                 }
 301             } else { //JProgressBar.VERTICAL
 302                 //paint each tile vertically
 303                 for (int i=y-offset; i<height+tileWidth; i+=tileWidth) {
 304                     context.getPainter().paintProgressBarForeground(
 305                             context, g, x, i, width, tileWidth, pBar.getOrientation());
 306                 }
 307             }
 308             g.setClip(clip);
 309         } else {
 310             context.getPainter().paintProgressBarForeground(context, g,
 311                     x, y, width, height, pBar.getOrientation());
 312         }
 313 
 314         if (pBar.isStringPainted()) {
 315             paintText(context, g, pBar.getString());
 316         }
 317     }
 318 
 319     /**
 320      * Paints the component's text.
 321      *
 322      * @param context context for the component being painted
 323      * @param g {@code Graphics} object used for painting
 324      * @param title the text to paint
 325      */
 326     protected void paintText(SynthContext context, Graphics g, String title) {
 327         if (progressBar.isStringPainted()) {
 328             SynthStyle style = context.getStyle();
 329             Font font = style.getFont(context);
 330             FontMetrics fm = SwingUtilities2.getFontMetrics(
 331                     progressBar, g, font);
 332             int strLength = style.getGraphicsUtils(context).
 333                 computeStringWidth(context, font, fm, title);
 334             Rectangle bounds = progressBar.getBounds();
 335 
 336             if (rotateText &&
 337                     progressBar.getOrientation() == JProgressBar.VERTICAL){
 338                 Graphics2D g2 = (Graphics2D)g;
 339                 // Calculate the position for the text.
 340                 Point textPos;
 341                 AffineTransform rotation;
 342                 if (progressBar.getComponentOrientation().isLeftToRight()){
 343                     rotation = AffineTransform.getRotateInstance(-Math.PI/2);
 344                     textPos = new Point(
 345                         (bounds.width+fm.getAscent()-fm.getDescent())/2,
 346                            (bounds.height+strLength)/2);
 347                 } else {
 348                     rotation = AffineTransform.getRotateInstance(Math.PI/2);
 349                     textPos = new Point(
 350                         (bounds.width-fm.getAscent()+fm.getDescent())/2,
 351                            (bounds.height-strLength)/2);
 352                 }
 353 
 354                 // Progress bar isn't wide enough for the font.  Don't paint it.
 355                 if (textPos.x < 0) {
 356                     return;
 357                 }
 358 
 359                 // Paint the text.
 360                 font = font.deriveFont(rotation);
 361                 g2.setFont(font);
 362                 g2.setColor(style.getColor(context, ColorType.TEXT_FOREGROUND));
 363                 style.getGraphicsUtils(context).paintText(context, g, title,
 364                                                      textPos.x, textPos.y, -1);
 365             } else {
 366                 // Calculate the bounds for the text.
 367                 Rectangle textRect = new Rectangle(
 368                     (bounds.width / 2) - (strLength / 2),
 369                     (bounds.height -
 370                         (fm.getAscent() + fm.getDescent())) / 2,
 371                     0, 0);
 372 
 373                 // Progress bar isn't tall enough for the font.  Don't paint it.
 374                 if (textRect.y < 0) {
 375                     return;
 376                 }
 377 
 378                 // Paint the text.
 379                 g.setColor(style.getColor(context, ColorType.TEXT_FOREGROUND));
 380                 g.setFont(font);
 381                 style.getGraphicsUtils(context).paintText(context, g, title,
 382                                                      textRect.x, textRect.y, -1);
 383             }
 384         }
 385     }
 386 
 387     /**
 388      * {@inheritDoc}
 389      */
 390     @Override
 391     public void paintBorder(SynthContext context, Graphics g, int x,
 392                             int y, int w, int h) {
 393         context.getPainter().paintProgressBarBorder(context, g, x, y, w, h,
 394                                                     progressBar.getOrientation());
 395     }
 396 
 397     /**
 398      * {@inheritDoc}
 399      */
 400     @Override
 401     public void propertyChange(PropertyChangeEvent e) {
 402         if (SynthLookAndFeel.shouldUpdateStyle(e) ||
 403                 "indeterminate".equals(e.getPropertyName())) {
 404             updateStyle((JProgressBar)e.getSource());
 405         }
 406     }
 407 
 408     /**
 409      * {@inheritDoc}
 410      */
 411     @Override
 412     public Dimension getPreferredSize(JComponent c) {
 413         Dimension size = null;
 414         Insets border = progressBar.getInsets();
 415         FontMetrics fontSizer = progressBar.getFontMetrics(progressBar.getFont());
 416         String progString = progressBar.getString();
 417         int stringHeight = fontSizer.getHeight() + fontSizer.getDescent();
 418 
 419         if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) {
 420             size = new Dimension(getPreferredInnerHorizontal());
 421             if (progressBar.isStringPainted()) {
 422                 // adjust the height if necessary to make room for the string
 423                 if (stringHeight > size.height) {
 424                     size.height = stringHeight;
 425                 }
 426 
 427                 // adjust the width if necessary to make room for the string
 428                 int stringWidth = SwingUtilities2.stringWidth(
 429                                        progressBar, fontSizer, progString);
 430                 if (stringWidth > size.width) {
 431                     size.width = stringWidth;
 432                 }
 433             }
 434         } else {
 435             size = new Dimension(getPreferredInnerVertical());
 436             if (progressBar.isStringPainted()) {
 437                 // make sure the width is big enough for the string
 438                 if (stringHeight > size.width) {
 439                     size.width = stringHeight;
 440                 }
 441 
 442                 // make sure the height is big enough for the string
 443                 int stringWidth = SwingUtilities2.stringWidth(
 444                                        progressBar, fontSizer, progString);
 445                 if (stringWidth > size.height) {
 446                     size.height = stringWidth;
 447                 }
 448             }
 449         }
 450 
 451         // handle scaling for sizeVarients for special case components. The
 452         // key "JComponent.sizeVariant" scales for large/small/mini
 453         // components are based on Apples LAF
 454         String scaleKey = (String)progressBar.getClientProperty(
 455                 "JComponent.sizeVariant");
 456         if (scaleKey != null){
 457             if ("large".equals(scaleKey)){
 458                 size.width *= 1.15f;
 459                 size.height *= 1.15f;
 460             } else if ("small".equals(scaleKey)){
 461                 size.width *= 0.90f;
 462                 size.height *= 0.90f;
 463             } else if ("mini".equals(scaleKey)){
 464                 size.width *= 0.784f;
 465                 size.height *= 0.784f;
 466             }
 467         }
 468 
 469         size.width += border.left + border.right;
 470         size.height += border.top + border.bottom;
 471 
 472         return size;
 473     }
 474 }