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

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