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 21KB

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