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

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