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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /*
  2. * Copyright (c) 2006-2011 Chris Smith, Shane Mc Cormack, Gregory Holmes
  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.util.ReturnableThread;
  29. import java.awt.FontMetrics;
  30. import java.awt.Graphics2D;
  31. import java.awt.Image;
  32. import java.awt.Rectangle;
  33. import java.awt.event.KeyEvent;
  34. import java.lang.reflect.InvocationTargetException;
  35. import javax.swing.BorderFactory;
  36. import javax.swing.JComboBox;
  37. import javax.swing.JComponent;
  38. import javax.swing.JScrollPane;
  39. import javax.swing.KeyStroke;
  40. import javax.swing.SwingUtilities;
  41. import javax.swing.UIManager;
  42. import javax.swing.UnsupportedLookAndFeelException;
  43. import javax.swing.UIManager.LookAndFeelInfo;
  44. import javax.swing.text.JTextComponent;
  45. import javax.swing.undo.UndoManager;
  46. import net.miginfocom.layout.PlatformDefaults;
  47. /**
  48. * UI constants.
  49. */
  50. public final class UIUtilities {
  51. /** Not intended to be instatiated. */
  52. private UIUtilities() {
  53. }
  54. /**
  55. * Adds an undo manager and associated key bindings to the specified text
  56. * component.
  57. *
  58. * @param component component Text component to add an undo manager to
  59. */
  60. public static void addUndoManager(final JTextComponent component) {
  61. final UndoManager undoManager = new UndoManager();
  62. // Listen for undo and redo events
  63. component.getDocument().addUndoableEditListener(
  64. new DMDircUndoableEditListener(undoManager));
  65. // Create an undo action and add it to the text component
  66. component.getActionMap().put("Undo", new UndoAction(undoManager));
  67. // Bind the undo action to ctl-Z
  68. component.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
  69. // Create a redo action and add it to the text component
  70. component.getActionMap().put("Redo", new RedoAction(undoManager));
  71. // Bind the redo action to ctl-Y
  72. component.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
  73. }
  74. /**
  75. * Initialises any settings required by this UI (this is always called
  76. * before any aspect of the UI is instansiated).
  77. *
  78. * @throws UnsupportedOperationException If unable to switch to the system
  79. * look and feel
  80. */
  81. public static void initUISettings() {
  82. try {
  83. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  84. } catch (InstantiationException ex) {
  85. throw new UnsupportedOperationException("Unable to switch to the " +
  86. "system look and feel", ex);
  87. } catch (ClassNotFoundException ex) {
  88. throw new UnsupportedOperationException("Unable to switch to the " +
  89. "system look and feel", ex);
  90. } catch (UnsupportedLookAndFeelException ex) {
  91. throw new UnsupportedOperationException("Unable to switch to the " +
  92. "system look and feel", ex);
  93. } catch (IllegalAccessException ex) {
  94. throw new UnsupportedOperationException("Unable to switch to the " +
  95. "system look and feel", ex);
  96. }
  97. UIManager.put("swing.useSystemFontSettings", true);
  98. if (getTabbedPaneOpaque()) {
  99. // If this is set on windows then .setOpaque seems to be ignored
  100. // and still used as true
  101. UIManager.put("TabbedPane.contentOpaque", false);
  102. }
  103. UIManager.put("swing.boldMetal", false);
  104. UIManager.put("InternalFrame.useTaskBar", false);
  105. UIManager.put("SplitPaneDivider.border",
  106. BorderFactory.createEmptyBorder());
  107. UIManager.put("Tree.scrollsOnExpand", true);
  108. UIManager.put("Tree.scrollsHorizontallyAndVertically", true);
  109. UIManager.put("SplitPane.border", BorderFactory.createEmptyBorder());
  110. UIManager.put("SplitPane.dividerSize", (int) PlatformDefaults.
  111. getPanelInsets(0).getValue());
  112. UIManager.put("TreeUI", TreeUI.class.getName());
  113. if (isGTKUI()) {
  114. UIManager.put("TitledBorder.titleColor", UIManager.getColor(
  115. "Label.foreground"));
  116. }
  117. PlatformDefaults.setDefaultRowAlignmentBaseline(false);
  118. }
  119. /**
  120. * Returns the class name of the look and feel from its display name.
  121. *
  122. * @param displayName Look and feel display name
  123. *
  124. * @return Look and feel class name or a zero length string
  125. */
  126. public static String getLookAndFeel(final String displayName) {
  127. if (displayName == null || displayName.isEmpty() ||
  128. "Native".equals(displayName)) {
  129. return UIManager.getSystemLookAndFeelClassName();
  130. }
  131. final StringBuilder classNameBuilder = new StringBuilder();
  132. for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
  133. if (laf.getName().equals(displayName)) {
  134. classNameBuilder.append(laf.getClassName());
  135. break;
  136. }
  137. }
  138. if (classNameBuilder.length() == 0) {
  139. classNameBuilder.append(UIManager.getSystemLookAndFeelClassName());
  140. }
  141. return classNameBuilder.toString();
  142. }
  143. /**
  144. * Invokes and waits for the specified runnable, executed on the EDT.
  145. *
  146. * @param runnable Thread to be executed
  147. */
  148. public static void invokeAndWait(final Runnable runnable) {
  149. if (SwingUtilities.isEventDispatchThread()) {
  150. runnable.run();
  151. } else {
  152. try {
  153. SwingUtilities.invokeAndWait(runnable);
  154. } catch (InterruptedException ex) {
  155. //Ignore
  156. } catch (InvocationTargetException ex) {
  157. Logger.appError(ErrorLevel.HIGH, "Unable to execute thread.", ex);
  158. }
  159. }
  160. }
  161. /**
  162. * Invokes and waits for the specified runnable, executed on the EDT.
  163. *
  164. * @param <T> The return type of the returnable thread
  165. * @param returnable Thread to be executed
  166. * @return Result from the compelted thread
  167. */
  168. public static <T> T invokeAndWait(final ReturnableThread<T> returnable) {
  169. if (SwingUtilities.isEventDispatchThread()) {
  170. returnable.run();
  171. } else {
  172. try {
  173. SwingUtilities.invokeAndWait(returnable);
  174. } catch (InterruptedException ex) {
  175. //Ignore
  176. } catch (InvocationTargetException ex) {
  177. Logger.appError(ErrorLevel.HIGH, "Unable to execute thread.", ex);
  178. }
  179. }
  180. return returnable.getObject();
  181. }
  182. /**
  183. * Queues the runnable to be executed on the EDT.
  184. *
  185. * @param runnable Runnable to be executed.
  186. */
  187. public static void invokeLater(final Runnable runnable) {
  188. if (SwingUtilities.isEventDispatchThread()) {
  189. runnable.run();
  190. } else {
  191. SwingUtilities.invokeLater(runnable);
  192. }
  193. }
  194. /**
  195. * Check if we are using the GTK look and feel.
  196. *
  197. * @return true iif the LAF is GTK
  198. */
  199. public static boolean isGTKUI() {
  200. return "com.sun.java.swing.plaf.gtk.GTKLookAndFeel".equals(UIManager
  201. .getLookAndFeel().getClass().getName());
  202. }
  203. /**
  204. * Check if we are using one of the Windows Look and Feels.
  205. *
  206. * @return True iff the current LAF is "Windows" or "Windows Classic"
  207. */
  208. public static boolean isWindowsUI() {
  209. final String uiname = UIManager.getLookAndFeel().getClass().getName();
  210. final String windows =
  211. "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
  212. final String classic =
  213. "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel";
  214. return windows.equals(uiname) || classic.equals(uiname);
  215. }
  216. /**
  217. * Get the value to pass to set Opaque on items being added to a JTabbedPane.
  218. *
  219. * @return True iff the current LAF is not Windows or OS X.
  220. * @since 0.6
  221. */
  222. public static boolean getTabbedPaneOpaque() {
  223. final String uiname = UIManager.getLookAndFeel().getClass().getName();
  224. final String windows =
  225. "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
  226. final String nimbus = "sun.swing.plaf.nimbus.NimbusLookAndFeel";
  227. return !(windows.equals(uiname) || Apple.isAppleUI() || nimbus.equals(
  228. uiname));
  229. }
  230. /**
  231. * Get the DOWN_MASK for the command/ctrl key.
  232. *
  233. * @return on OSX this returns META_DOWN_MASK, else CTRL_DOWN_MASK
  234. * @since 0.6
  235. */
  236. public static int getCtrlDownMask() {
  237. return Apple.isAppleUI() ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK;
  238. }
  239. /**
  240. * Get the MASK for the command/ctrl key.
  241. *
  242. * @return on OSX this returns META_MASK, else CTRL_MASK
  243. * @since 0.6
  244. */
  245. public static int getCtrlMask() {
  246. return Apple.isAppleUI() ? KeyEvent.META_MASK : KeyEvent.CTRL_MASK;
  247. }
  248. /**
  249. * Check if the command/ctrl key is pressed down.
  250. *
  251. * @param e The KeyEvent to check
  252. * @return on OSX this returns e.isMetaDown(), else e.isControlDown()
  253. * @since 0.6
  254. */
  255. public static boolean isCtrlDown(final KeyEvent e) {
  256. return Apple.isAppleUI() ? e.isMetaDown() : e.isControlDown();
  257. }
  258. /**
  259. * Clips a string if its longer than the specified width.
  260. *
  261. * @param component Component containing string
  262. * @param string String to check
  263. * @param avaiableWidth Available Width
  264. *
  265. * @return String (clipped if required)
  266. */
  267. public static String clipStringifNeeded(final JComponent component,
  268. final String string, final int avaiableWidth) {
  269. if ((string == null) || (string.equals(""))) {
  270. return "";
  271. }
  272. final FontMetrics fm = component.getFontMetrics(component.getFont());
  273. final int width = SwingUtilities.computeStringWidth(fm, string);
  274. if (width > avaiableWidth) {
  275. return clipString(component, string, avaiableWidth);
  276. }
  277. return string;
  278. }
  279. /**
  280. * Clips the passed string .
  281. *
  282. * @param component Component containing string
  283. * @param string String to check
  284. * @param avaiableWidth Available Width
  285. *
  286. * @return String (clipped if required)
  287. */
  288. public static String clipString(final JComponent component,
  289. final String string, final int avaiableWidth) {
  290. if ((string == null) || (string.equals(""))) {
  291. return "";
  292. }
  293. final FontMetrics fm = component.getFontMetrics(component.getFont());
  294. final String clipString = "...";
  295. int width = SwingUtilities.computeStringWidth(fm, clipString);
  296. int nChars = 0;
  297. for (int max = string.length(); nChars < max; nChars++) {
  298. width += fm.charWidth(string.charAt(nChars));
  299. if (width > avaiableWidth) {
  300. break;
  301. }
  302. }
  303. return string.substring(0, nChars) + clipString;
  304. }
  305. /**
  306. * Resets the scroll pane to 0,0.
  307. *
  308. * @param scrollPane Scrollpane to reset
  309. *
  310. * @since 0.6.3m1
  311. */
  312. public static void resetScrollPane(final JScrollPane scrollPane) {
  313. SwingUtilities.invokeLater(new Runnable() {
  314. /** {@inheritDoc} */
  315. @Override
  316. public void run() {
  317. scrollPane.getHorizontalScrollBar().setValue(0);
  318. scrollPane.getVerticalScrollBar().setValue(0);
  319. }
  320. });
  321. }
  322. /**
  323. * Paints the background, either from the config setting or the background
  324. * colour of the textpane.
  325. *
  326. * @param g Graphics object to draw onto
  327. * @param bounds
  328. * @param backgroundImage
  329. * @param backgroundOption
  330. */
  331. public static void paintBackground(final Graphics2D g,
  332. final Rectangle bounds,
  333. final Image backgroundImage,
  334. final BackgroundOption backgroundOption) {
  335. if (backgroundImage == null) {
  336. paintNoBackground(g, bounds);
  337. } else {
  338. switch (backgroundOption) {
  339. case TILED:
  340. paintTiledBackground(g, bounds, backgroundImage);
  341. break;
  342. case SCALE:
  343. paintStretchedBackground(g, bounds, backgroundImage);
  344. break;
  345. case SCALE_ASPECT_RATIO:
  346. paintStretchedAspectRatioBackground(g, bounds, backgroundImage);
  347. break;
  348. case CENTER:
  349. paintCenterBackground(g, bounds, backgroundImage);
  350. break;
  351. default:
  352. break;
  353. }
  354. }
  355. }
  356. private static void paintNoBackground(final Graphics2D g, final Rectangle bounds) {
  357. g.fill(bounds);
  358. }
  359. private static void paintStretchedBackground(final Graphics2D g,
  360. final Rectangle bounds, final Image backgroundImage) {
  361. g.drawImage(backgroundImage, 0, 0, bounds.width, bounds.height, null);
  362. }
  363. private static void paintCenterBackground(final Graphics2D g,
  364. final Rectangle bounds, final Image backgroundImage) {
  365. final int x = (bounds.width / 2) - (backgroundImage.getWidth(null) / 2);
  366. final int y = (bounds.height / 2) - (backgroundImage.getHeight(null) / 2);
  367. g.drawImage(backgroundImage, x, y, backgroundImage.getWidth(null),
  368. backgroundImage.getHeight(null), null);
  369. }
  370. private static void paintStretchedAspectRatioBackground(final Graphics2D g,
  371. final Rectangle bounds, final Image backgroundImage) {
  372. final double widthratio = bounds.width
  373. / (double) backgroundImage.getWidth(null);
  374. final double heightratio = bounds.height
  375. / (double) backgroundImage.getHeight(null);
  376. final double ratio = Math.min(widthratio, heightratio);
  377. final int width = (int) (backgroundImage.getWidth(null) * ratio);
  378. final int height = (int) (backgroundImage.getWidth(null) * ratio);
  379. final int x = (bounds.width / 2) - (width / 2);
  380. final int y = (bounds.height / 2) - (height / 2);
  381. g.drawImage(backgroundImage, x, y, width, height, null);
  382. }
  383. private static void paintTiledBackground(final Graphics2D g,
  384. final Rectangle bounds, final Image backgroundImage) {
  385. final int width = backgroundImage.getWidth(null);
  386. final int height = backgroundImage.getHeight(null);
  387. if (width <= 0 || height <= 0) {
  388. // ARG!
  389. return;
  390. }
  391. for (int x = 0; x < bounds.width; x += width) {
  392. for (int y = 0; y < bounds.height; y += height) {
  393. g.drawImage(backgroundImage, x, y, width, height, null);
  394. }
  395. }
  396. }
  397. /**
  398. * Adds a popup listener which will modify the width of the combo box
  399. * popup menu to be sized according to the preferred size of its components.
  400. *
  401. * @param combo Combo box to modify
  402. */
  403. public static void addComboBoxWidthModifier(final JComboBox combo) {
  404. combo.addPopupMenuListener(new ComboBoxWidthModifier());
  405. }
  406. }