001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.Component; 007import java.awt.Dimension; 008import java.awt.GridBagConstraints; 009import java.awt.GridBagLayout; 010import java.awt.Insets; 011import java.awt.Toolkit; 012import java.awt.event.ActionEvent; 013import java.util.ArrayList; 014import java.util.Arrays; 015import java.util.Collections; 016import java.util.List; 017 018import javax.swing.AbstractAction; 019import javax.swing.Action; 020import javax.swing.Icon; 021import javax.swing.JButton; 022import javax.swing.JComponent; 023import javax.swing.JDialog; 024import javax.swing.JLabel; 025import javax.swing.JOptionPane; 026import javax.swing.JPanel; 027import javax.swing.JScrollBar; 028import javax.swing.JScrollPane; 029import javax.swing.KeyStroke; 030import javax.swing.UIManager; 031 032import org.openstreetmap.josm.Main; 033import org.openstreetmap.josm.gui.help.HelpBrowser; 034import org.openstreetmap.josm.gui.help.HelpUtil; 035import org.openstreetmap.josm.gui.util.GuiHelper; 036import org.openstreetmap.josm.gui.widgets.JMultilineLabel; 037import org.openstreetmap.josm.io.OnlineResource; 038import org.openstreetmap.josm.tools.GBC; 039import org.openstreetmap.josm.tools.ImageProvider; 040import org.openstreetmap.josm.tools.Utils; 041import org.openstreetmap.josm.tools.WindowGeometry; 042 043/** 044 * General configurable dialog window. 045 * 046 * If dialog is modal, you can use {@link #getValue()} to retrieve the 047 * button index. Note that the user can close the dialog 048 * by other means. This is usually equivalent to cancel action. 049 * 050 * For non-modal dialogs, {@link #buttonAction(int, ActionEvent)} can be overridden. 051 * 052 * There are various options, see below. 053 * 054 * Note: The button indices are counted from 1 and upwards. 055 * So for {@link #getValue()}, {@link #setDefaultButton(int)} and 056 * {@link #setCancelButton} the first button has index 1. 057 * 058 * Simple example: 059 * <pre> 060 * ExtendedDialog ed = new ExtendedDialog( 061 * Main.parent, tr("Dialog Title"), 062 * new String[] {tr("Ok"), tr("Cancel")}); 063 * ed.setButtonIcons(new String[] {"ok", "cancel"}); // optional 064 * ed.setIcon(JOptionPane.WARNING_MESSAGE); // optional 065 * ed.setContent(tr("Really proceed? Interesting things may happen...")); 066 * ed.showDialog(); 067 * if (ed.getValue() == 1) { // user clicked first button "Ok" 068 * // proceed... 069 * } 070 * </pre> 071 */ 072public class ExtendedDialog extends JDialog { 073 private final boolean disposeOnClose; 074 private int result = 0; 075 public static final int DialogClosedOtherwise = 0; 076 private boolean toggleable = false; 077 private String rememberSizePref = ""; 078 private WindowGeometry defaultWindowGeometry = null; 079 private String togglePref = ""; 080 private int toggleValue = -1; 081 private ConditionalOptionPaneUtil.MessagePanel togglePanel; 082 private Component parent; 083 private Component content; 084 private final String[] bTexts; 085 private String[] bToolTipTexts; 086 private Icon[] bIcons; 087 private List<Integer> cancelButtonIdx = Collections.emptyList(); 088 private int defaultButtonIdx = 1; 089 protected JButton defaultButton = null; 090 private Icon icon; 091 private boolean modal; 092 private boolean focusOnDefaultButton = false; 093 094 /** true, if the dialog should include a help button */ 095 private boolean showHelpButton; 096 /** the help topic */ 097 private String helpTopic; 098 099 /** 100 * set to true if the content of the extended dialog should 101 * be placed in a {@link JScrollPane} 102 */ 103 private boolean placeContentInScrollPane; 104 105 // For easy access when inherited 106 protected Insets contentInsets = new Insets(10,5,0,5); 107 protected List<JButton> buttons = new ArrayList<>(); 108 109 /** 110 * This method sets up the most basic options for the dialog. Add more 111 * advanced features with dedicated methods. 112 * Possible features: 113 * <ul> 114 * <li><code>setButtonIcons</code></li> 115 * <li><code>setContent</code></li> 116 * <li><code>toggleEnable</code></li> 117 * <li><code>toggleDisable</code></li> 118 * <li><code>setToggleCheckboxText</code></li> 119 * <li><code>setRememberWindowGeometry</code></li> 120 * </ul> 121 * 122 * When done, call <code>showDialog</code> to display it. You can receive 123 * the user's choice using <code>getValue</code>. Have a look at this function 124 * for possible return values. 125 * 126 * @param parent The parent element that will be used for position and maximum size 127 * @param title The text that will be shown in the window titlebar 128 * @param buttonTexts String Array of the text that will appear on the buttons. The first button is the default one. 129 */ 130 public ExtendedDialog(Component parent, String title, String[] buttonTexts) { 131 this(parent, title, buttonTexts, true, true); 132 } 133 134 /** 135 * Same as above but lets you define if the dialog should be modal. 136 * @param parent The parent element that will be used for position and maximum size 137 * @param title The text that will be shown in the window titlebar 138 * @param buttonTexts String Array of the text that will appear on the buttons. The first button is the default one. 139 * @param modal Set it to {@code true} if you want the dialog to be modal 140 */ 141 public ExtendedDialog(Component parent, String title, String[] buttonTexts, boolean modal) { 142 this(parent, title, buttonTexts, modal, true); 143 } 144 145 public ExtendedDialog(Component parent, String title, String[] buttonTexts, boolean modal, boolean disposeOnClose) { 146 super(JOptionPane.getFrameForComponent(parent), title, modal ? ModalityType.DOCUMENT_MODAL : ModalityType.MODELESS); 147 this.parent = parent; 148 this.modal = modal; 149 bTexts = Utils.copyArray(buttonTexts); 150 if (disposeOnClose) { 151 setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 152 } 153 this.disposeOnClose = disposeOnClose; 154 } 155 156 /** 157 * Allows decorating the buttons with icons. 158 * @param buttonIcons The button icons 159 * @return {@code this} 160 */ 161 public ExtendedDialog setButtonIcons(Icon[] buttonIcons) { 162 this.bIcons = Utils.copyArray(buttonIcons); 163 return this; 164 } 165 166 /** 167 * Convenience method to provide image names instead of images. 168 * @param buttonIcons The button icon names 169 * @return {@code this} 170 */ 171 public ExtendedDialog setButtonIcons(String[] buttonIcons) { 172 bIcons = new Icon[buttonIcons.length]; 173 for (int i=0; i<buttonIcons.length; ++i) { 174 bIcons[i] = ImageProvider.get(buttonIcons[i]); 175 } 176 return this; 177 } 178 179 /** 180 * Allows decorating the buttons with tooltips. Expects a String array with 181 * translated tooltip texts. 182 * 183 * @param toolTipTexts the tool tip texts. Ignored, if null. 184 * @return {@code this} 185 */ 186 public ExtendedDialog setToolTipTexts(String[] toolTipTexts) { 187 this.bToolTipTexts = Utils.copyArray(toolTipTexts); 188 return this; 189 } 190 191 /** 192 * Sets the content that will be displayed in the message dialog. 193 * 194 * Note that depending on your other settings more UI elements may appear. 195 * The content is played on top of the other elements though. 196 * 197 * @param content Any element that can be displayed in the message dialog 198 * @return {@code this} 199 */ 200 public ExtendedDialog setContent(Component content) { 201 return setContent(content, true); 202 } 203 204 /** 205 * Sets the content that will be displayed in the message dialog. 206 * 207 * Note that depending on your other settings more UI elements may appear. 208 * The content is played on top of the other elements though. 209 * 210 * @param content Any element that can be displayed in the message dialog 211 * @param placeContentInScrollPane if true, places the content in a JScrollPane 212 * @return {@code this} 213 */ 214 public ExtendedDialog setContent(Component content, boolean placeContentInScrollPane) { 215 this.content = content; 216 this.placeContentInScrollPane = placeContentInScrollPane; 217 return this; 218 } 219 220 /** 221 * Sets the message that will be displayed. The String will be automatically 222 * wrapped if it is too long. 223 * 224 * Note that depending on your other settings more UI elements may appear. 225 * The content is played on top of the other elements though. 226 * 227 * @param message The text that should be shown to the user 228 * @return {@code this} 229 */ 230 public ExtendedDialog setContent(String message) { 231 return setContent(string2label(message), false); 232 } 233 234 /** 235 * Decorate the dialog with an icon that is shown on the left part of 236 * the window area. (Similar to how it is done in {@link JOptionPane}) 237 * @param icon The icon to display 238 * @return {@code this} 239 */ 240 public ExtendedDialog setIcon(Icon icon) { 241 this.icon = icon; 242 return this; 243 } 244 245 /** 246 * Convenience method to allow values that would be accepted by {@link JOptionPane} as messageType. 247 * @param messageType The {@link JOptionPane} messageType 248 * @return {@code this} 249 */ 250 public ExtendedDialog setIcon(int messageType) { 251 switch (messageType) { 252 case JOptionPane.ERROR_MESSAGE: 253 return setIcon(UIManager.getIcon("OptionPane.errorIcon")); 254 case JOptionPane.INFORMATION_MESSAGE: 255 return setIcon(UIManager.getIcon("OptionPane.informationIcon")); 256 case JOptionPane.WARNING_MESSAGE: 257 return setIcon(UIManager.getIcon("OptionPane.warningIcon")); 258 case JOptionPane.QUESTION_MESSAGE: 259 return setIcon(UIManager.getIcon("OptionPane.questionIcon")); 260 case JOptionPane.PLAIN_MESSAGE: 261 return setIcon(null); 262 default: 263 throw new IllegalArgumentException("Unknown message type!"); 264 } 265 } 266 267 /** 268 * Show the dialog to the user. Call this after you have set all options 269 * for the dialog. You can retrieve the result using {@link #getValue()}. 270 * @return {@code this} 271 */ 272 public ExtendedDialog showDialog() { 273 // Check if the user has set the dialog to not be shown again 274 if (toggleCheckState()) { 275 result = toggleValue; 276 return this; 277 } 278 279 setupDialog(); 280 if (defaultButton != null) { 281 getRootPane().setDefaultButton(defaultButton); 282 } 283 // Don't focus the "do not show this again" check box, but the default button. 284 if (toggleable || focusOnDefaultButton) { 285 requestFocusToDefaultButton(); 286 } 287 setVisible(true); 288 toggleSaveState(); 289 return this; 290 } 291 292 /** 293 * Retrieve the user choice after the dialog has been closed. 294 * 295 * @return <ul> <li>The selected button. The count starts with 1.</li> 296 * <li>A return value of {@link #DialogClosedOtherwise} means the dialog has been closed otherwise.</li> 297 * </ul> 298 */ 299 public int getValue() { 300 return result; 301 } 302 303 private boolean setupDone = false; 304 305 /** 306 * This is called by {@link #showDialog()}. 307 * Only invoke from outside if you need to modify the contentPane 308 */ 309 public void setupDialog() { 310 if (setupDone) 311 return; 312 setupDone = true; 313 314 setupEscListener(); 315 316 JButton button; 317 JPanel buttonsPanel = new JPanel(new GridBagLayout()); 318 319 for (int i=0; i < bTexts.length; i++) { 320 final int final_i = i; 321 Action action = new AbstractAction(bTexts[i]) { 322 @Override public void actionPerformed(ActionEvent evt) { 323 buttonAction(final_i, evt); 324 } 325 }; 326 327 button = new JButton(action); 328 if (i == defaultButtonIdx-1) { 329 defaultButton = button; 330 } 331 if(bIcons != null && bIcons[i] != null) { 332 button.setIcon(bIcons[i]); 333 } 334 if (bToolTipTexts != null && i < bToolTipTexts.length && bToolTipTexts[i] != null) { 335 button.setToolTipText(bToolTipTexts[i]); 336 } 337 338 buttonsPanel.add(button, GBC.std().insets(2,2,2,2)); 339 buttons.add(button); 340 } 341 if (showHelpButton) { 342 buttonsPanel.add(new JButton(new HelpAction()), GBC.std().insets(2,2,2,2)); 343 HelpUtil.setHelpContext(getRootPane(),helpTopic); 344 } 345 346 JPanel cp = new JPanel(new GridBagLayout()); 347 348 GridBagConstraints gc = new GridBagConstraints(); 349 gc.gridx = 0; 350 int y = 0; 351 gc.gridy = y++; 352 gc.weightx = 0.0; 353 gc.weighty = 0.0; 354 355 if (icon != null) { 356 JLabel iconLbl = new JLabel(icon); 357 gc.insets = new Insets(10,10,10,10); 358 gc.anchor = GridBagConstraints.NORTH; 359 gc.weighty = 1.0; 360 cp.add(iconLbl, gc); 361 gc.anchor = GridBagConstraints.CENTER; 362 gc.gridx = 1; 363 } 364 365 gc.fill = GridBagConstraints.BOTH; 366 gc.insets = contentInsets; 367 gc.weightx = 1.0; 368 gc.weighty = 1.0; 369 cp.add(content, gc); 370 371 gc.fill = GridBagConstraints.NONE; 372 gc.gridwidth = GridBagConstraints.REMAINDER; 373 gc.weightx = 0.0; 374 gc.weighty = 0.0; 375 376 if (toggleable) { 377 togglePanel = new ConditionalOptionPaneUtil.MessagePanel(null, ConditionalOptionPaneUtil.isInBulkOperation(togglePref)); 378 gc.gridx = icon != null ? 1 : 0; 379 gc.gridy = y++; 380 gc.anchor = GridBagConstraints.LINE_START; 381 gc.insets = new Insets(5,contentInsets.left,5,contentInsets.right); 382 cp.add(togglePanel, gc); 383 } 384 385 gc.gridy = y++; 386 gc.anchor = GridBagConstraints.CENTER; 387 gc.insets = new Insets(5,5,5,5); 388 cp.add(buttonsPanel, gc); 389 if (placeContentInScrollPane) { 390 JScrollPane pane = new JScrollPane(cp); 391 pane.setBorder(null); 392 setContentPane(pane); 393 } else { 394 setContentPane(cp); 395 } 396 pack(); 397 398 // Try to make it not larger than the parent window or at least not larger than 2/3 of the screen 399 Dimension d = getSize(); 400 Dimension x = findMaxDialogSize(); 401 402 boolean limitedInWidth = d.width > x.width; 403 boolean limitedInHeight = d.height > x.height; 404 405 if(x.width > 0 && d.width > x.width) { 406 d.width = x.width; 407 } 408 if(x.height > 0 && d.height > x.height) { 409 d.height = x.height; 410 } 411 412 // We have a vertical scrollbar and enough space to prevent a horizontal one 413 if(!limitedInWidth && limitedInHeight) { 414 d.width += new JScrollBar().getPreferredSize().width; 415 } 416 417 setSize(d); 418 setLocationRelativeTo(parent); 419 } 420 421 /** 422 * This gets performed whenever a button is clicked or activated 423 * @param buttonIndex the button index (first index is 0) 424 * @param evt the button event 425 */ 426 protected void buttonAction(int buttonIndex, ActionEvent evt) { 427 result = buttonIndex+1; 428 setVisible(false); 429 } 430 431 /** 432 * Tries to find a good value of how large the dialog should be 433 * @return Dimension Size of the parent Component or 2/3 of screen size if not available 434 */ 435 protected Dimension findMaxDialogSize() { 436 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 437 Dimension x = new Dimension(screenSize.width*2/3, screenSize.height*2/3); 438 if (parent != null) { 439 x = JOptionPane.getFrameForComponent(parent).getSize(); 440 } 441 return x; 442 } 443 444 /** 445 * Makes the dialog listen to ESC keypressed 446 */ 447 private void setupEscListener() { 448 Action actionListener = new AbstractAction() { 449 @Override public void actionPerformed(ActionEvent actionEvent) { 450 // 0 means that the dialog has been closed otherwise. 451 // We need to set it to zero again, in case the dialog has been re-used 452 // and the result differs from its default value 453 result = ExtendedDialog.DialogClosedOtherwise; 454 setVisible(false); 455 } 456 }; 457 458 getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) 459 .put(KeyStroke.getKeyStroke("ESCAPE"), "ESCAPE"); 460 getRootPane().getActionMap().put("ESCAPE", actionListener); 461 } 462 463 protected final void rememberWindowGeometry(WindowGeometry geometry) { 464 if (geometry != null) { 465 geometry.remember(rememberSizePref); 466 } 467 } 468 469 protected final WindowGeometry initWindowGeometry() { 470 return new WindowGeometry(rememberSizePref, defaultWindowGeometry); 471 } 472 473 /** 474 * Override setVisible to be able to save the window geometry if required 475 */ 476 @Override 477 public void setVisible(boolean visible) { 478 if (visible) { 479 repaint(); 480 } 481 482 // Ensure all required variables are available 483 if(rememberSizePref.length() != 0 && defaultWindowGeometry != null) { 484 if(visible) { 485 initWindowGeometry().applySafe(this); 486 } else if (isShowing()) { // should fix #6438, #6981, #8295 487 rememberWindowGeometry(new WindowGeometry(this)); 488 } 489 } 490 super.setVisible(visible); 491 492 if (!visible && disposeOnClose) { 493 dispose(); 494 } 495 } 496 497 /** 498 * Call this if you want the dialog to remember the geometry (size and position) set by the user. 499 * Set the pref to <code>null</code> or to an empty string to disable again. 500 * By default, it's disabled. 501 * 502 * Note: If you want to set the width of this dialog directly use the usual 503 * setSize, setPreferredSize, setMaxSize, setMinSize 504 * 505 * @param pref The preference to save the dimension to 506 * @param wg The default window geometry that should be used if no 507 * existing preference is found (only takes effect if 508 * <code>pref</code> is not null or empty 509 * @return {@code this} 510 */ 511 public ExtendedDialog setRememberWindowGeometry(String pref, WindowGeometry wg) { 512 rememberSizePref = pref == null ? "" : pref; 513 defaultWindowGeometry = wg; 514 return this; 515 } 516 517 /** 518 * Calling this will offer the user a "Do not show again" checkbox for the 519 * dialog. Default is to not offer the choice; the dialog will be shown 520 * every time. 521 * Currently, this is not supported for non-modal dialogs. 522 * @param togglePref The preference to save the checkbox state to 523 * @return {@code this} 524 */ 525 public ExtendedDialog toggleEnable(String togglePref) { 526 if (!modal) { 527 throw new IllegalArgumentException(); 528 } 529 this.toggleable = true; 530 this.togglePref = togglePref; 531 return this; 532 } 533 534 /** 535 * Call this if you "accidentally" called toggleEnable. This doesn't need 536 * to be called for every dialog, as it's the default anyway. 537 * @return {@code this} 538 */ 539 public ExtendedDialog toggleDisable() { 540 this.toggleable = false; 541 return this; 542 } 543 544 /** 545 * Sets the button that will react to ENTER. 546 * @param defaultButtonIdx The button index (starts to 1) 547 * @return {@code this} 548 */ 549 public ExtendedDialog setDefaultButton(int defaultButtonIdx) { 550 this.defaultButtonIdx = defaultButtonIdx; 551 return this; 552 } 553 554 /** 555 * Used in combination with toggle: 556 * If the user presses 'cancel' the toggle settings are ignored and not saved to the pref 557 * @param cancelButtonIdx index of the button that stands for cancel, accepts multiple values 558 * @return {@code this} 559 */ 560 public ExtendedDialog setCancelButton(Integer... cancelButtonIdx) { 561 this.cancelButtonIdx = Arrays.<Integer>asList(cancelButtonIdx); 562 return this; 563 } 564 565 /** 566 * Makes default button request initial focus or not. 567 * @param focus {@code true} to make default button request initial focus 568 * @since 7407 569 */ 570 public void setFocusOnDefaultButton(boolean focus) { 571 focusOnDefaultButton = focus; 572 } 573 574 private void requestFocusToDefaultButton() { 575 if (defaultButton != null) { 576 GuiHelper.runInEDT(new Runnable() { 577 @Override 578 public void run() { 579 defaultButton.requestFocusInWindow(); 580 } 581 }); 582 } 583 } 584 585 /** 586 * This function returns true if the dialog has been set to "do not show again" 587 * @return true if dialog should not be shown again 588 */ 589 public final boolean toggleCheckState() { 590 toggleable = togglePref != null && !togglePref.isEmpty(); 591 toggleValue = ConditionalOptionPaneUtil.getDialogReturnValue(togglePref); 592 return toggleable && toggleValue != -1; 593 } 594 595 /** 596 * This function checks the state of the "Do not show again" checkbox and 597 * writes the corresponding pref. 598 */ 599 private void toggleSaveState() { 600 if (!toggleable || 601 togglePanel == null || 602 cancelButtonIdx.contains(result) || 603 result == ExtendedDialog.DialogClosedOtherwise) 604 return; 605 togglePanel.getNotShowAgain().store(togglePref, result); 606 } 607 608 /** 609 * Convenience function that converts a given string into a JMultilineLabel 610 * @param msg 611 * @return JMultilineLabel 612 */ 613 private static JMultilineLabel string2label(String msg) { 614 JMultilineLabel lbl = new JMultilineLabel(msg); 615 // Make it not wider than 1/2 of the screen 616 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 617 lbl.setMaxWidth(screenSize.width/2); 618 return lbl; 619 } 620 621 /** 622 * Configures how this dialog support for context sensitive help. 623 * <ul> 624 * <li>if helpTopic is null, the dialog doesn't provide context sensitive help</li> 625 * <li>if helpTopic != null, the dialog redirect user to the help page for this helpTopic when 626 * the user clicks F1 in the dialog</li> 627 * <li>if showHelpButton is true, the dialog displays "Help" button (rightmost button in 628 * the button row)</li> 629 * </ul> 630 * 631 * @param helpTopic the help topic 632 * @param showHelpButton true, if the dialog displays a help button 633 * @return {@code this} 634 */ 635 public ExtendedDialog configureContextsensitiveHelp(String helpTopic, boolean showHelpButton) { 636 this.helpTopic = helpTopic; 637 this.showHelpButton = showHelpButton; 638 return this; 639 } 640 641 class HelpAction extends AbstractAction { 642 public HelpAction() { 643 putValue(SHORT_DESCRIPTION, tr("Show help information")); 644 putValue(NAME, tr("Help")); 645 putValue(SMALL_ICON, ImageProvider.get("help")); 646 setEnabled(!Main.isOffline(OnlineResource.JOSM_WEBSITE)); 647 } 648 649 @Override 650 public void actionPerformed(ActionEvent e) { 651 HelpBrowser.setUrlForHelpTopic(helpTopic); 652 } 653 } 654}