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

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