You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UIUtilities.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. /*
  2. * Copyright (c) 2006-2015 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.addons.ui_swing;
  23. import com.dmdirc.addons.ui_swing.components.DMDircUndoableEditListener;
  24. import com.dmdirc.addons.ui_swing.components.RunnableLoggingSwingWorker;
  25. import com.dmdirc.addons.ui_swing.components.RunnableSwingWorker;
  26. import com.dmdirc.addons.ui_swing.components.SupplierLoggingSwingWorker;
  27. import com.dmdirc.util.colours.Colour;
  28. import java.awt.Color;
  29. import java.awt.Font;
  30. import java.awt.FontMetrics;
  31. import java.awt.Graphics2D;
  32. import java.awt.Image;
  33. import java.awt.Rectangle;
  34. import java.awt.Shape;
  35. import java.awt.event.InputEvent;
  36. import java.awt.event.KeyEvent;
  37. import java.lang.reflect.InvocationTargetException;
  38. import java.util.concurrent.Callable;
  39. import java.util.concurrent.FutureTask;
  40. import java.util.function.Consumer;
  41. import java.util.function.Supplier;
  42. import javax.swing.BorderFactory;
  43. import javax.swing.JComboBox;
  44. import javax.swing.JComponent;
  45. import javax.swing.JScrollPane;
  46. import javax.swing.KeyStroke;
  47. import javax.swing.SwingUtilities;
  48. import javax.swing.UIDefaults;
  49. import javax.swing.UIManager;
  50. import javax.swing.UIManager.LookAndFeelInfo;
  51. import javax.swing.UnsupportedLookAndFeelException;
  52. import javax.swing.plaf.FontUIResource;
  53. import javax.swing.text.JTextComponent;
  54. import javax.swing.undo.UndoManager;
  55. import net.miginfocom.layout.PlatformDefaults;
  56. /**
  57. * UI constants.
  58. */
  59. @SuppressWarnings("PMD.UnusedImports")
  60. public final class UIUtilities {
  61. /**
  62. * GTK LAF class name.
  63. */
  64. private static final String GTKUI = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
  65. /**
  66. * Nimbus LAF class name.
  67. */
  68. private static final String NIMBUSUI = "sun.swing.plaf.nimbus.NimbusLookAndFeel";
  69. /**
  70. * Windows LAF class name.
  71. */
  72. private static final String WINDOWSUI = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
  73. /**
  74. * Windows classic LAF class name.
  75. */
  76. private static final String WINDOWSCLASSICUI
  77. = "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel";
  78. /** Not intended to be instantiated. */
  79. private UIUtilities() {
  80. }
  81. /**
  82. * Adds an undo manager and associated key bindings to the specified text component.
  83. *
  84. * @param component The text component to add an undo manager to
  85. */
  86. public static void addUndoManager(final JTextComponent component) {
  87. final UndoManager undoManager = new UndoManager();
  88. // Listen for undo and redo events
  89. component.getDocument().addUndoableEditListener(
  90. new DMDircUndoableEditListener(undoManager));
  91. // Create an undo action and add it to the text component
  92. component.getActionMap().put("Undo", new UndoAction(undoManager));
  93. // Bind the undo action to ctl-Z
  94. component.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
  95. // Create a redo action and add it to the text component
  96. component.getActionMap().put("Redo", new RedoAction(undoManager));
  97. // Bind the redo action to ctl-Y
  98. component.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
  99. }
  100. /**
  101. * Initialises any settings required by this UI (this is always called before any aspect of the
  102. * UI is instantiated).
  103. *
  104. * @throws UnsupportedOperationException If unable to switch to the system look and feel
  105. */
  106. public static void initUISettings() {
  107. try {
  108. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  109. } catch (InstantiationException | ClassNotFoundException |
  110. UnsupportedLookAndFeelException | IllegalAccessException ex) {
  111. throw new UnsupportedOperationException("Unable to switch to the "
  112. + "system look and feel", ex);
  113. }
  114. UIManager.put("swing.useSystemFontSettings", true);
  115. if (getTabbedPaneOpaque()) {
  116. // If this is set on windows then .setOpaque seems to be ignored
  117. // and still used as true
  118. UIManager.put("TabbedPane.contentOpaque", false);
  119. }
  120. UIManager.put("swing.boldMetal", false);
  121. UIManager.put("InternalFrame.useTaskBar", false);
  122. UIManager.put("SplitPaneDivider.border",
  123. BorderFactory.createEmptyBorder());
  124. UIManager.put("Tree.scrollsOnExpand", true);
  125. UIManager.put("Tree.scrollsHorizontallyAndVertically", true);
  126. UIManager.put("SplitPane.border", BorderFactory.createEmptyBorder());
  127. UIManager.put("SplitPane.dividerSize", (int) PlatformDefaults.
  128. getPanelInsets(0).getValue());
  129. UIManager.put("TreeUI", TreeUI.class.getName());
  130. UIManager.put("TextField.background", new Color(255, 255, 255));
  131. PlatformDefaults.setDefaultRowAlignmentBaseline(false);
  132. }
  133. /**
  134. * Sets the font of all components in the current look and feel to the specified font, using the
  135. * style and size from the original font.
  136. *
  137. * @param font New font
  138. */
  139. public static void setUIFont(final Font font) {
  140. for(Object key : UIManager.getDefaults().keySet()) {
  141. final Object value = UIManager.get(key);
  142. if (value instanceof FontUIResource) {
  143. final FontUIResource orig = (FontUIResource) value;
  144. UIManager.put(key, new UIDefaults.ProxyLazyValue(
  145. "javax.swing.plaf.FontUIResource", new Object[]{
  146. font.getFontName(), orig.getStyle(), orig.getSize()
  147. }));
  148. }
  149. }
  150. }
  151. /**
  152. * Returns the class name of the look and feel from its display name.
  153. *
  154. * @param displayName Look and feel display name
  155. *
  156. * @return Look and feel class name or a zero length string
  157. */
  158. public static String getLookAndFeel(final String displayName) {
  159. if (displayName == null || displayName.isEmpty() || "Native".equals(displayName)) {
  160. return UIManager.getSystemLookAndFeelClassName();
  161. }
  162. final StringBuilder classNameBuilder = new StringBuilder();
  163. for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
  164. if (laf.getName().equals(displayName)) {
  165. classNameBuilder.append(laf.getClassName());
  166. break;
  167. }
  168. }
  169. if (classNameBuilder.length() == 0) {
  170. classNameBuilder.append(UIManager.getSystemLookAndFeelClassName());
  171. }
  172. return classNameBuilder.toString();
  173. }
  174. /**
  175. * Invokes and waits for the specified runnable, executed on the EDT.
  176. *
  177. * @param runnable Thread to be executed
  178. */
  179. public static void invokeAndWait(final Runnable runnable) {
  180. if (SwingUtilities.isEventDispatchThread()) {
  181. runnable.run();
  182. } else {
  183. try {
  184. SwingUtilities.invokeAndWait(runnable);
  185. } catch (InterruptedException ex) {
  186. //Ignore
  187. } catch (InvocationTargetException ex) {
  188. throw new RuntimeException(ex); // NOPMD
  189. }
  190. }
  191. }
  192. /**
  193. * Invokes and waits for the specified callable, executed on the EDT.
  194. *
  195. * @param <T> The return type of the returnable thread
  196. * @param returnable Thread to be executed
  197. *
  198. * @return Result from the completed thread or null if an exception occurred
  199. */
  200. public static <T> T invokeAndWait(final Callable<T> returnable) {
  201. try {
  202. if (SwingUtilities.isEventDispatchThread()) {
  203. return returnable.call();
  204. } else {
  205. final FutureTask<T> task = new FutureTask<>(returnable);
  206. SwingUtilities.invokeAndWait(task);
  207. return task.get();
  208. }
  209. } catch (Exception ex) {
  210. throw new RuntimeException(ex); // NOPMD
  211. }
  212. }
  213. /**
  214. * Queues the runnable to be executed on the EDT.
  215. *
  216. * @param runnable Runnable to be executed.
  217. */
  218. public static void invokeLater(final Runnable runnable) {
  219. if (SwingUtilities.isEventDispatchThread()) {
  220. runnable.run();
  221. } else {
  222. SwingUtilities.invokeLater(runnable);
  223. }
  224. }
  225. /**
  226. * Invokes something off the EDT, ignoring any exceptions that occur.
  227. *
  228. * @param runnable Runnable to execute off the EDT
  229. */
  230. public static void invokeOffEDTNoLogging(final Runnable runnable) {
  231. new RunnableSwingWorker<>(runnable).execute();
  232. }
  233. /**
  234. * Invokes something off the EDT, logging any exceptions that occur.
  235. *
  236. * @param runnable Runnable to execute off the EDT
  237. */
  238. public static void invokeOffEDT(final Runnable runnable) {
  239. new RunnableLoggingSwingWorker<Void, Void>(runnable).execute();
  240. }
  241. /**
  242. * Invokes something off the EDT, handling the result when its finished on the EDT, logging
  243. * any exceptions that occur.
  244. *
  245. * @param runnable Runnable to execute off the EDT
  246. * @param consumer Consumer to finalise the runnable on the EDT
  247. *
  248. * @param <T> Type the consumer takes
  249. */
  250. public static <T> void invokeOffEDT(final Runnable runnable, final Consumer<T> consumer) {
  251. new RunnableLoggingSwingWorker<>(runnable, consumer).execute();
  252. }
  253. /**
  254. * Invokes something off the EDT, handling the result when its finished on the EDT, logging
  255. * any exceptions that occur.
  256. *
  257. * @param runnable Runnable to execute off the EDT
  258. * @param consumer Consumer to finalise the runnable on the EDT
  259. *
  260. * @param <T> Type the consumer takes
  261. */
  262. public static <T> void invokeOffEDT(final Supplier<T> runnable, final Consumer<T> consumer) {
  263. new SupplierLoggingSwingWorker<>(runnable, consumer).execute();
  264. }
  265. /**
  266. * Check if we are using the GTK look and feel.
  267. *
  268. * @return true iif the LAF is GTK
  269. */
  270. public static boolean isGTKUI() {
  271. return GTKUI.equals(UIManager.getLookAndFeel().getClass().getName());
  272. }
  273. /**
  274. * Check if we are using the Nimbus look and feel.
  275. *
  276. * @return true iif the LAF is Nimbus
  277. */
  278. public static boolean isNimbusUI() {
  279. return NIMBUSUI.equals(UIManager.getLookAndFeel().getClass().getName());
  280. }
  281. /**
  282. * Check if we are using the new Windows Look and Feel.
  283. *
  284. * @return true iif the current LAF is Windows
  285. */
  286. public static boolean isWindowsNewUI() {
  287. return WINDOWSUI.equals(
  288. UIManager.getLookAndFeel().getClass().getName());
  289. }
  290. /**
  291. * Check if we are using the new Windows Classic Look and Feel.
  292. *
  293. * @return true iif the current LAF is Windows Classic
  294. */
  295. public static boolean isWindowsClassicUI() {
  296. return WINDOWSCLASSICUI.equals(UIManager.getLookAndFeel().getClass().getName());
  297. }
  298. /**
  299. * Check if we are using one of the Windows Look and Feels.
  300. *
  301. * @return True iff the current LAF is "Windows" or "Windows Classic"
  302. */
  303. public static boolean isWindowsUI() {
  304. return isWindowsNewUI() || isWindowsClassicUI();
  305. }
  306. /**
  307. * Get the value to pass to set Opaque on items being added to a JTabbedPane. Currently they
  308. * need to be transparent on Windows (non classic), Apple, Nimbus and GTK.
  309. *
  310. * @return True if tabbed panes should be opaque
  311. *
  312. * @since 0.6
  313. */
  314. public static boolean getTabbedPaneOpaque() {
  315. return !(isWindowsNewUI() || Apple.isAppleUI() || isNimbusUI() || isGTKUI());
  316. }
  317. /**
  318. * Get the DOWN_MASK for the command/ctrl key.
  319. *
  320. * @return on OSX this returns META_DOWN_MASK, else CTRL_DOWN_MASK
  321. *
  322. * @since 0.6
  323. */
  324. public static int getCtrlDownMask() {
  325. return Apple.isAppleUI() ? InputEvent.META_DOWN_MASK : InputEvent.CTRL_DOWN_MASK;
  326. }
  327. /**
  328. * Get the MASK for the command/ctrl key.
  329. *
  330. * @return on OSX this returns META_MASK, else CTRL_MASK
  331. *
  332. * @since 0.6
  333. */
  334. public static int getCtrlMask() {
  335. return Apple.isAppleUI() ? InputEvent.META_MASK : InputEvent.CTRL_MASK;
  336. }
  337. /**
  338. * Check if the command/ctrl key is pressed down.
  339. *
  340. * @param e The KeyEvent to check
  341. *
  342. * @return on OSX this returns e.isMetaDown(), else e.isControlDown()
  343. *
  344. * @since 0.6
  345. */
  346. public static boolean isCtrlDown(final KeyEvent e) {
  347. return Apple.isAppleUI() ? e.isMetaDown() : e.isControlDown();
  348. }
  349. /**
  350. * Clips a string if its longer than the specified width.
  351. *
  352. * @param component Component containing string
  353. * @param string String to check
  354. * @param avaiableWidth Available Width
  355. *
  356. * @return String (clipped if required)
  357. */
  358. public static String clipStringifNeeded(final JComponent component,
  359. final String string, final int avaiableWidth) {
  360. if (string == null || string.isEmpty()) {
  361. return "";
  362. }
  363. final FontMetrics fm = component.getFontMetrics(component.getFont());
  364. final int width = SwingUtilities.computeStringWidth(fm, string);
  365. if (width > avaiableWidth) {
  366. return clipString(component, string, avaiableWidth);
  367. }
  368. return string;
  369. }
  370. /**
  371. * Clips the passed string .
  372. *
  373. * @param component Component containing string
  374. * @param string String to check
  375. * @param avaiableWidth Available Width
  376. *
  377. * @return String (clipped if required)
  378. */
  379. public static String clipString(final JComponent component,
  380. final String string, final int avaiableWidth) {
  381. if (string == null || string.isEmpty()) {
  382. return "";
  383. }
  384. final FontMetrics fm = component.getFontMetrics(component.getFont());
  385. final String clipString = "...";
  386. int width = SwingUtilities.computeStringWidth(fm, clipString);
  387. int nChars = 0;
  388. for (final int max = string.length(); nChars < max; nChars++) {
  389. width += fm.charWidth(string.charAt(nChars));
  390. if (width > avaiableWidth) {
  391. break;
  392. }
  393. }
  394. return string.substring(0, nChars) + clipString;
  395. }
  396. /**
  397. * Resets the scroll pane to 0,0.
  398. *
  399. * @param scrollPane Scrollpane to reset
  400. *
  401. * @since 0.6.3m1
  402. */
  403. public static void resetScrollPane(final JScrollPane scrollPane) {
  404. SwingUtilities.invokeLater(() -> {
  405. scrollPane.getHorizontalScrollBar().setValue(0);
  406. scrollPane.getVerticalScrollBar().setValue(0);
  407. });
  408. }
  409. /**
  410. * Paints the background, either from the config setting or the background colour of the
  411. * textpane.
  412. *
  413. * @param g Graphics object to draw onto
  414. * @param bounds Bounds to paint within
  415. * @param backgroundImage background image
  416. * @param backgroundOption How to draw the background
  417. */
  418. public static void paintBackground(final Graphics2D g,
  419. final Rectangle bounds,
  420. final Image backgroundImage,
  421. final BackgroundOption backgroundOption) {
  422. if (backgroundImage == null) {
  423. paintNoBackground(g, bounds);
  424. } else {
  425. switch (backgroundOption) {
  426. case TILED:
  427. paintTiledBackground(g, bounds, backgroundImage);
  428. break;
  429. case SCALE:
  430. paintStretchedBackground(g, bounds, backgroundImage);
  431. break;
  432. case SCALE_ASPECT_RATIO:
  433. paintStretchedAspectRatioBackground(g, bounds, backgroundImage);
  434. break;
  435. case CENTER:
  436. paintCenterBackground(g, bounds, backgroundImage);
  437. break;
  438. default:
  439. break;
  440. }
  441. }
  442. }
  443. private static void paintNoBackground(final Graphics2D g, final Shape bounds) {
  444. g.fill(bounds);
  445. }
  446. private static void paintStretchedBackground(final Graphics2D g,
  447. final Rectangle bounds, final Image backgroundImage) {
  448. g.drawImage(backgroundImage, 0, 0, bounds.width, bounds.height, null);
  449. }
  450. private static void paintCenterBackground(final Graphics2D g,
  451. final Rectangle bounds, final Image backgroundImage) {
  452. final int x = bounds.width / 2 - backgroundImage.getWidth(null) / 2;
  453. final int y = bounds.height / 2 - backgroundImage.getHeight(null) / 2;
  454. g.drawImage(backgroundImage, x, y, backgroundImage.getWidth(null),
  455. backgroundImage.getHeight(null), null);
  456. }
  457. private static void paintStretchedAspectRatioBackground(final Graphics2D g,
  458. final Rectangle bounds, final Image backgroundImage) {
  459. final double widthratio = bounds.width
  460. / (double) backgroundImage.getWidth(null);
  461. final double heightratio = bounds.height
  462. / (double) backgroundImage.getHeight(null);
  463. final double ratio = Math.min(widthratio, heightratio);
  464. final int width = (int) (backgroundImage.getWidth(null) * ratio);
  465. final int height = (int) (backgroundImage.getWidth(null) * ratio);
  466. final int x = bounds.width / 2 - width / 2;
  467. final int y = bounds.height / 2 - height / 2;
  468. g.drawImage(backgroundImage, x, y, width, height, null);
  469. }
  470. private static void paintTiledBackground(final Graphics2D g,
  471. final Rectangle bounds, final Image backgroundImage) {
  472. final int width = backgroundImage.getWidth(null);
  473. final int height = backgroundImage.getHeight(null);
  474. if (width <= 0 || height <= 0) {
  475. // ARG!
  476. return;
  477. }
  478. for (int x = 0; x < bounds.width; x += width) {
  479. for (int y = 0; y < bounds.height; y += height) {
  480. g.drawImage(backgroundImage, x, y, width, height, null);
  481. }
  482. }
  483. }
  484. /**
  485. * Adds a popup listener which will modify the width of the combo box popup menu to be sized
  486. * according to the preferred size of its components.
  487. *
  488. * @param combo Combo box to modify
  489. */
  490. public static void addComboBoxWidthModifier(final JComboBox<?> combo) {
  491. combo.addPopupMenuListener(new ComboBoxWidthModifier());
  492. }
  493. /**
  494. * Converts a DMDirc {@link Colour} into an AWT-specific {@link Color} by copying the values of
  495. * the red, green and blue channels.
  496. *
  497. * @param colour The colour to be converted
  498. *
  499. * @return A corresponding AWT colour
  500. */
  501. public static Color convertColour(final Colour colour) {
  502. return new Color(colour.getRed(), colour.getGreen(), colour.getBlue());
  503. }
  504. /**
  505. * Converts the given colour into a hexadecimal string.
  506. *
  507. * @param colour The colour to be converted
  508. *
  509. * @return A corresponding 6 character hex string
  510. */
  511. public static String getHex(final Color colour) {
  512. return getHex(colour.getRed()) + getHex(colour.getGreen())
  513. + getHex(colour.getBlue());
  514. }
  515. /**
  516. * Converts the specified integer (in the range 0-255) into a hex string.
  517. *
  518. * @param value The integer to convert
  519. *
  520. * @return A 2 char hex string representing the specified integer
  521. */
  522. private static String getHex(final int value) {
  523. final String hex = Integer.toHexString(value);
  524. return (hex.length() < 2 ? "0" : "") + hex;
  525. }
  526. }