1 /*
   2  * Copyright (c) 2014, 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 package javafx.scene.control;
  26 
  27 import java.lang.ref.WeakReference;
  28 import java.util.ArrayList;
  29 import java.util.Arrays;
  30 import java.util.List;
  31 import java.util.Optional;
  32 
  33 import com.sun.javafx.scene.control.skin.AccordionSkin;
  34 import com.sun.javafx.scene.control.skin.resources.ControlResources;
  35 import javafx.beans.InvalidationListener;
  36 import javafx.beans.NamedArg;
  37 import javafx.beans.property.ObjectProperty;
  38 import javafx.beans.property.SimpleObjectProperty;
  39 import javafx.collections.ListChangeListener;
  40 import javafx.collections.ObservableList;
  41 import javafx.scene.Node;
  42 import javafx.scene.image.Image;
  43 import javafx.scene.image.ImageView;
  44 
  45 /**
  46  * The Alert class subclasses the {@link Dialog} class, and provides support for a number
  47  * of pre-built dialog types that can be easily shown to users to prompt for a
  48  * response. Therefore, for many users, the Alert class is the most suited class
  49  * for their needs (as opposed to using {@link Dialog} directly). Alternatively,
  50  * users who want to prompt a user for text input or to make a choice from a list 
  51  * of options would be better served by using {@link TextInputDialog} and
  52  * {@link ChoiceDialog}, respectively.
  53  * 
  54  * <p>When creating an Alert instance, users must pass in an {@link AlertType}
  55  * enumeration value. It is by passing in this value that the Alert instance will
  56  * configure itself appropriately (by setting default values for many of the 
  57  * {@link Dialog} properties, including {@link #titleProperty() title},
  58  * {@link #headerTextProperty() header}, and {@link #graphicProperty() graphic},
  59  * as well as the default {@link #getButtonTypes() buttons} that are expected in
  60  * a dialog of the given type.
  61  * 
  62  * <p>To instantiate (but not yet show) an Alert, simply use code such as the following:
  63  * {@code Alert alert = new Alert(AlertType.CONFIRMATION, "Are you sure you want to format your system?");}
  64  * 
  65  * <p>Once an Alert is instantiated, we must show it. More often than not, alerts
  66  * (and dialogs in general) are shown in a modal and blocking fashion. 'Modal'
  67  * means that the dialog prevents user interaction with the owning application
  68  * whilst it is showing, and 'blocking' means that code execution stops at the 
  69  * point in which the dialog is shown. This means that you can show a dialog,
  70  * await the user response, and then continue running the code that directly
  71  * follows the show call, giving developers the ability to immediately deal with
  72  * the user input from the dialog (if relevant). 
  73  * 
  74  * <p>JavaFX dialogs are modal by default (you can change this via the 
  75  * {@link #initModality(javafx.stage.Modality)} API). To specify whether you want
  76  * blocking or non-blocking dialogs, developers simply choose to call
  77  * {@link #showAndWait()} or {@link #show()} (respectively). By default most 
  78  * developers should choose to use {@link #showAndWait()}, given the ease of 
  79  * coding in these situations. Shown below is three code snippets, showing three
  80  * equally valid ways of showing the Alert dialog that was specified above:
  81  * 
  82  * <p><strong>Option 1: The 'traditional' approach</strong>
  83  * <pre>{@code Optional<ButtonType> result = alert.showAndWait();
  84  * if (result.isPresent() && result.get() == ButtonType.OK) {
  85  *     formatSystem();
  86  * }}</pre>
  87  * 
  88  * <p><strong>Option 2: The traditional + Optional approach</strong>
  89  * <pre>{@code alert.showAndWait().ifPresent(response -> {
  90  *     if (response == ButtonType.OK) {
  91  *         formatSystem();
  92  *     }
  93  * });}</pre>
  94  *
  95  * <p><strong>Option 3: The fully lambda approach</strong>
  96  * <pre>{@code alert.showAndWait()
  97  *      .filter(response -> response == ButtonType.OK)
  98  *      .ifPresent(response -> formatSystem());
  99  * }</pre>
 100  * 
 101  * <p>There is no better or worse option of the three listed above, so developers
 102  * are encouraged to work to their own style preferences. The purpose of showing
 103  * the above is to help introduce developers to the {@link Optional} API, which
 104  * is new in Java 8 and may be foreign to many developers.
 105  * 
 106  * @see Dialog
 107  * @see AlertType
 108  * @see TextInputDialog
 109  * @see ChoiceDialog
 110  * @since JavaFX 8u40
 111  */
 112 public class Alert extends Dialog<ButtonType> {
 113     
 114     /**************************************************************************
 115      * 
 116      * Static enums
 117      * 
 118      **************************************************************************/
 119     
 120     /**
 121      * An enumeration containing the available, pre-built alert types that 
 122      * the {@link Alert} class can use to pre-populate various properties.
 123      *
 124      * @since JavaFX 8u40
 125      */
 126     public static enum AlertType {
 127         /**
 128          * The NONE alert type has the effect of not setting any default properties
 129          * in the Alert.
 130          */
 131         NONE,
 132         
 133         /**
 134          * The INFORMATION alert type configures the Alert dialog to appear in a
 135          * way that suggests the content of the dialog is informing the user of
 136          * a piece of information. This includes an 'information' image, an 
 137          * appropriate title and header, and just an OK button for the user to 
 138          * click on to dismiss the dialog.
 139          */
 140         INFORMATION,
 141         
 142         /**
 143          * The WARNING alert type configures the Alert dialog to appear in a
 144          * way that suggests the content of the dialog is warning the user about
 145          * some fact or action. This includes a 'warning' image, an 
 146          * appropriate title and header, and just an OK button for the user to 
 147          * click on to dismiss the dialog.
 148          */
 149         WARNING,
 150         
 151         /**
 152          * The CONFIRMATION alert type configures the Alert dialog to appear in a
 153          * way that suggests the content of the dialog is seeking confirmation from
 154          * the user. This includes a 'confirmation' image, an 
 155          * appropriate title and header, and both OK and Cancel buttons for the 
 156          * user to click on to dismiss the dialog.
 157          */
 158         CONFIRMATION,
 159         
 160         /**
 161          * The ERROR alert type configures the Alert dialog to appear in a
 162          * way that suggests that something has gone wrong. This includes an 
 163          * 'error' image, an appropriate title and header, and just an OK button 
 164          * for the user to click on to dismiss the dialog.
 165          */
 166         ERROR
 167     }
 168 
 169     
 170     
 171     /**************************************************************************
 172      * 
 173      * Fields
 174      * 
 175      **************************************************************************/
 176     
 177     private WeakReference<DialogPane> dialogPaneRef;
 178     
 179     private boolean installingDefaults = false;
 180     private boolean hasCustomButtons = false;
 181     private boolean hasCustomTitle = false;
 182     private boolean hasCustomHeaderText = false;
 183     
 184     private final InvalidationListener headerTextListener = o -> {
 185         if (!installingDefaults) hasCustomHeaderText = true; 
 186     };
 187     
 188     private final InvalidationListener titleListener = o -> { 
 189         if (!installingDefaults) hasCustomTitle = true; 
 190     };
 191     
 192     private final ListChangeListener<ButtonType> buttonsListener = change -> {
 193         if (!installingDefaults) hasCustomButtons = true; 
 194     };
 195     
 196 
 197 
 198     /**************************************************************************
 199      * 
 200      * Constructors
 201      * 
 202      **************************************************************************/
 203 
 204     /**
 205      * Creates an alert with the given AlertType (refer to the {@link AlertType}
 206      * documentation for clarification over which one is most appropriate). 
 207      * 
 208      * <p>By passing in an AlertType, default values for the 
 209      * {@link #titleProperty() title}, {@link #headerTextProperty() headerText},
 210      * and {@link #graphicProperty() graphic} properties are set, as well as the 
 211      * relevant {@link #getButtonTypes() buttons} being installed. Once the Alert 
 212      * is instantiated, developers are able to modify the values of the alert as 
 213      * desired.
 214      * 
 215      * <p>It is important to note that the one property that does not have a 
 216      * default value set, and which therefore the developer must set, is the 
 217      * {@link #contentTextProperty() content text} property (or alternatively,
 218      * the developer may call {@code alert.getDialogPane().setContent(Node)} if
 219      * they want a more complex alert). If the contentText (or content) properties
 220      * are not set, there is no useful information presented to end users.
 221      */
 222     public Alert(@NamedArg("alertType") AlertType alertType) {
 223         this(alertType, "");
 224     }
 225     
 226     /**
 227      * Creates an alert with the given contentText, ButtonTypes, and AlertType 
 228      * (refer to the {@link AlertType} documentation for clarification over which
 229      * one is most appropriate). 
 230      * 
 231      * <p>By passing in a variable number of ButtonType arguments, the developer
 232      * is directly overriding the default buttons that will be displayed in the
 233      * dialog, replacing the pre-defined buttons with whatever is specified in the
 234      * varargs array.
 235      * 
 236      * <p>By passing in an AlertType, default values for the 
 237      * {@link #titleProperty() title}, {@link #headerTextProperty() headerText},
 238      * and {@link #graphicProperty() graphic} properties are set. Once the Alert 
 239      * is instantiated, developers are able to modify the values of the alert as 
 240      * desired.
 241      */
 242     public Alert(@NamedArg("alertType") AlertType alertType,
 243                  @NamedArg("contentText") String contentText,
 244                  ButtonType... buttons) {
 245         super();
 246 
 247         final DialogPane dialogPane = getDialogPane();
 248         dialogPane.setContentText(contentText);
 249         getDialogPane().getStyleClass().add("alert");
 250         
 251         dialogPaneRef = new WeakReference<>(dialogPane);
 252         
 253         hasCustomButtons = buttons != null && buttons.length > 0; 
 254         if (hasCustomButtons) {
 255             for (ButtonType btnType : buttons) {
 256                 dialogPane.getButtonTypes().addAll(btnType);
 257             }
 258         }
 259         
 260         setAlertType(alertType);
 261         
 262         // listening to property changes on Dialog and DialogPane
 263         dialogPaneProperty().addListener(o -> updateListeners());
 264         titleProperty().addListener(titleListener);
 265         updateListeners();
 266     }
 267     
 268     
 269     
 270     /**************************************************************************
 271      * 
 272      * Properties
 273      * 
 274      **************************************************************************/
 275     
 276     /**
 277      * When creating an Alert instance, users must pass in an {@link AlertType}
 278      * enumeration value. It is by passing in this value that the Alert instance will
 279      * configure itself appropriately (by setting default values for many of the 
 280      * {@link Dialog} properties, including {@link #titleProperty() title},
 281      * {@link #headerTextProperty() header}, and {@link #graphicProperty() graphic},
 282      * as well as the default {@link #getButtonTypes() buttons} that are expected in
 283      * a dialog of the given type.
 284      */
 285     // --- alertType
 286     private final ObjectProperty<AlertType> alertType = new SimpleObjectProperty<AlertType>(null) {
 287         final String[] styleClasses = new String[] { "information", "warning", "error", "confirmation" };
 288 
 289         protected void invalidated() {
 290             String newTitle = "";
 291             String newHeader = "";
 292 //            Node newGraphic = null;
 293             String styleClass = "";
 294             ButtonType[] newButtons = new ButtonType[] { ButtonType.OK };
 295             switch (getAlertType()) {
 296                 case NONE: {
 297                     newButtons = new ButtonType[] { };
 298                     break;
 299                 }
 300                 case INFORMATION: {
 301                     newTitle = ControlResources.getString("Dialog.info.title");
 302                     newHeader = ControlResources.getString("Dialog.info.header");
 303                     styleClass = "information";
 304                     break;
 305                 }
 306                 case WARNING: {
 307                     newTitle = ControlResources.getString("Dialog.warning.title");
 308                     newHeader = ControlResources.getString("Dialog.warning.header");
 309                     styleClass = "warning";
 310                     break;
 311                 }
 312                 case ERROR: {
 313                     newTitle = ControlResources.getString("Dialog.error.title");
 314                     newHeader = ControlResources.getString("Dialog.error.header");
 315                     styleClass = "error";
 316                     break;
 317                 }      
 318                 case CONFIRMATION: {
 319                     newTitle = ControlResources.getString("Dialog.confirm.title");
 320                     newHeader = ControlResources.getString("Dialog.confirm.header");
 321                     styleClass = "confirmation";
 322                     newButtons = new ButtonType[] { ButtonType.OK, ButtonType.CANCEL };
 323                     break;
 324                 } 
 325             }
 326             
 327             installingDefaults = true;
 328             if (!hasCustomTitle) setTitle(newTitle);
 329             if (!hasCustomHeaderText) setHeaderText(newHeader);
 330             if (!hasCustomButtons) getButtonTypes().setAll(newButtons);
 331 
 332             // update the style class based on the alert type. We use this to
 333             // specify the default graphic to use (i.e. via CSS).
 334             DialogPane dialogPane = getDialogPane();
 335             if (dialogPane != null) {
 336                 List<String> toRemove = new ArrayList<>(Arrays.asList(styleClasses));
 337                 toRemove.remove(styleClass);
 338                 dialogPane.getStyleClass().removeAll(toRemove);
 339                 if (! dialogPane.getStyleClass().contains(styleClass)) {
 340                     dialogPane.getStyleClass().add(styleClass);
 341                 }
 342             }
 343 
 344             installingDefaults = false;
 345         }
 346     };
 347 
 348     public final AlertType getAlertType() {
 349         return alertType.get();
 350     }
 351 
 352     public final void setAlertType(AlertType alertType) {
 353         this.alertType.setValue(alertType);
 354     }
 355 
 356     public final ObjectProperty<AlertType> alertTypeProperty() {
 357         return alertType;
 358     }
 359     
 360     
 361     /**
 362      * Returns an {@link ObservableList} of all {@link ButtonType} instances that
 363      * are currently set inside this Alert instance. A ButtonType may either be one
 364      * of the pre-defined types (e.g. {@link ButtonType#OK}), or it may be a 
 365      * custom type (created via the {@link ButtonType#ButtonType(String)} or
 366      * {@link ButtonType#ButtonType(String, javafx.scene.control.ButtonBar.ButtonData)}
 367      * constructors.
 368      * 
 369      * <p>Readers should refer to the {@link ButtonType} class documentation for more details,
 370      * but at a high level, each ButtonType instance is converted to
 371      * a Node (although most commonly a {@link Button}) via the (overridable) 
 372      * {@link DialogPane#createButton(ButtonType)} method on {@link DialogPane}.
 373      */
 374     // --- buttonTypes
 375     public final ObservableList<ButtonType> getButtonTypes() {
 376         return getDialogPane().getButtonTypes();
 377     }
 378 
 379     
 380 
 381     /**************************************************************************
 382      * 
 383      * Private Implementation
 384      * 
 385      **************************************************************************/
 386     
 387     private void updateListeners() {
 388         DialogPane oldPane = dialogPaneRef.get();
 389         
 390         if (oldPane != null) {
 391             oldPane.headerTextProperty().removeListener(headerTextListener);
 392             oldPane.getButtonTypes().removeListener(buttonsListener);
 393         }
 394         
 395         // listen to changes to properties that would be changed by alertType being
 396         // changed, so that we only change values that are still at their default
 397         // value (i.e. the user hasn't changed them, so we are free to set them
 398         // to a new default value when the alertType changes).
 399         
 400         DialogPane newPane = getDialogPane();
 401         if (newPane != null) {
 402             newPane.headerTextProperty().addListener(headerTextListener);
 403             newPane.getButtonTypes().addListener(buttonsListener);
 404         }
 405         
 406         dialogPaneRef = new WeakReference<DialogPane>(newPane);
 407     }    
 408 }