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

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