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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. * Copyright (c) 2006-2010 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.logger.ErrorLevel;
  24. import com.dmdirc.logger.Logger;
  25. import com.dmdirc.addons.ui_swing.actions.RedoAction;
  26. import com.dmdirc.addons.ui_swing.actions.UndoAction;
  27. import com.dmdirc.addons.ui_swing.components.DMDircUndoableEditListener;
  28. import com.dmdirc.util.ReturnableThread;
  29. import java.awt.Dimension;
  30. import java.awt.FontMetrics;
  31. import java.awt.event.KeyEvent;
  32. import java.lang.reflect.InvocationTargetException;
  33. import javax.swing.BorderFactory;
  34. import javax.swing.JComponent;
  35. import javax.swing.JScrollPane;
  36. import javax.swing.KeyStroke;
  37. import javax.swing.SwingUtilities;
  38. import javax.swing.UIManager;
  39. import javax.swing.UIManager.LookAndFeelInfo;
  40. import javax.swing.UnsupportedLookAndFeelException;
  41. import javax.swing.text.JTextComponent;
  42. import javax.swing.undo.UndoManager;
  43. import net.miginfocom.layout.PlatformDefaults;
  44. /**
  45. * UI constants.
  46. */
  47. public final class UIUtilities {
  48. /** Size of a large border. */
  49. public static final int LARGE_BORDER = 10;
  50. /** Size of a small border. */
  51. public static final int SMALL_BORDER = 5;
  52. /** Standard button size. */
  53. public static final Dimension BUTTON_SIZE = new Dimension(100, 25);
  54. /** Not intended to be instatiated. */
  55. private UIUtilities() {
  56. }
  57. /**
  58. * Adds an undo manager and associated key bindings to the specified text
  59. * component.
  60. *
  61. * @param component component Text component to add an undo manager to
  62. */
  63. public static void addUndoManager(final JTextComponent component) {
  64. final UndoManager undoManager = new UndoManager();
  65. // Listen for undo and redo events
  66. component.getDocument().addUndoableEditListener(
  67. new DMDircUndoableEditListener(undoManager));
  68. // Create an undo action and add it to the text component
  69. component.getActionMap().put("Undo", new UndoAction(undoManager));
  70. // Bind the undo action to ctl-Z
  71. component.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
  72. // Create a redo action and add it to the text component
  73. component.getActionMap().put("Redo", new RedoAction(undoManager));
  74. // Bind the redo action to ctl-Y
  75. component.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
  76. }
  77. /**
  78. * Initialises any settings required by this UI (this is always called
  79. * before any aspect of the UI is instansiated).
  80. *
  81. * @throws UnsupportedOperationException If unable to switch to the system
  82. * look and feel
  83. */
  84. public static void initUISettings() {
  85. try {
  86. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  87. } catch (InstantiationException ex) {
  88. throw new UnsupportedOperationException("Unable to switch to the " +
  89. "system look and feel", ex);
  90. } catch (ClassNotFoundException ex) {
  91. throw new UnsupportedOperationException("Unable to switch to the " +
  92. "system look and feel", ex);
  93. } catch (UnsupportedLookAndFeelException ex) {
  94. throw new UnsupportedOperationException("Unable to switch to the " +
  95. "system look and feel", ex);
  96. } catch (IllegalAccessException ex) {
  97. throw new UnsupportedOperationException("Unable to switch to the " +
  98. "system look and feel", ex);
  99. }
  100. UIManager.put("swing.useSystemFontSettings", true);
  101. if (getTabbedPaneOpaque()) {
  102. // If this is set on windows then .setOpaque seems to be ignored
  103. // and still used as true
  104. UIManager.put("TabbedPane.contentOpaque", false);
  105. }
  106. UIManager.put("swing.boldMetal", false);
  107. UIManager.put("InternalFrame.useTaskBar", false);
  108. UIManager.put("SplitPaneDivider.border",
  109. BorderFactory.createEmptyBorder());
  110. UIManager.put("Tree.scrollsOnExpand", true);
  111. UIManager.put("Tree.scrollsHorizontallyAndVertically", true);
  112. UIManager.put("SplitPane.border", BorderFactory.createEmptyBorder());
  113. UIManager.put("SplitPane.dividerSize", (int) PlatformDefaults.
  114. getPanelInsets(0).getValue());
  115. UIManager.put("TreeUI", "javax.swing.plaf.metal.MetalTreeUI");
  116. PlatformDefaults.setDefaultRowAlignmentBaseline(false);
  117. }
  118. /**
  119. * Returns the class name of the look and feel from its display name.
  120. *
  121. * @param displayName Look and feel display name
  122. *
  123. * @return Look and feel class name or a zero length string
  124. */
  125. public static String getLookAndFeel(final String displayName) {
  126. if (displayName == null || displayName.isEmpty() ||
  127. "Native".equals(displayName)) {
  128. return UIManager.getSystemLookAndFeelClassName();
  129. }
  130. final StringBuilder classNameBuilder = new StringBuilder();
  131. for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
  132. if (laf.getName().equals(displayName)) {
  133. classNameBuilder.append(laf.getClassName());
  134. break;
  135. }
  136. }
  137. if (classNameBuilder.length() == 0) {
  138. classNameBuilder.append(UIManager.getSystemLookAndFeelClassName());
  139. }
  140. return classNameBuilder.toString();
  141. }
  142. /**
  143. * Invokes and waits for the specified runnable, executed on the EDT.
  144. *
  145. * @param runnable Thread to be executed
  146. */
  147. public static void invokeAndWait(final Runnable runnable) {
  148. if (SwingUtilities.isEventDispatchThread()) {
  149. runnable.run();
  150. } else {
  151. try {
  152. SwingUtilities.invokeAndWait(runnable);
  153. } catch (InterruptedException ex) {
  154. //Ignore
  155. } catch (InvocationTargetException ex) {
  156. Logger.appError(ErrorLevel.HIGH, "Unable to execute thread.", ex);
  157. }
  158. }
  159. }
  160. /**
  161. * Invokes and waits for the specified runnable, executed on the EDT.
  162. *
  163. * @param <T> The return type of the returnable thread
  164. * @param returnable Thread to be executed
  165. * @return Result from the compelted thread
  166. */
  167. public static <T> T invokeAndWait(final ReturnableThread<T> returnable) {
  168. if (SwingUtilities.isEventDispatchThread()) {
  169. returnable.run();
  170. } else {
  171. try {
  172. SwingUtilities.invokeAndWait(returnable);
  173. } catch (InterruptedException ex) {
  174. //Ignore
  175. } catch (InvocationTargetException ex) {
  176. Logger.appError(ErrorLevel.HIGH, "Unable to execute thread.", ex);
  177. }
  178. }
  179. return returnable.getObject();
  180. }
  181. /**
  182. * Queues the runnable to be executed on the EDT.
  183. *
  184. * @param runnable Runnable to be executed.
  185. */
  186. public static void invokeLater(final Runnable runnable) {
  187. if (SwingUtilities.isEventDispatchThread()) {
  188. runnable.run();
  189. } else {
  190. SwingUtilities.invokeLater(runnable);
  191. }
  192. }
  193. /**
  194. * Check if we are using one of the Windows Look and Feels
  195. *
  196. * @return True iff the current LAF is "Windows" or "Windows Classic"
  197. */
  198. public static boolean isWindowsUI() {
  199. final String uiname = UIManager.getLookAndFeel().getClass().getName();
  200. final String windows =
  201. "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
  202. final String classic =
  203. "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel";
  204. return windows.equals(uiname) || classic.equals(uiname);
  205. }
  206. /**
  207. * Get the value to pass to set Opaque on items being added to a JTabbedPane
  208. *
  209. * @return True iff the current LAF is not Windows or OS X.
  210. * @since 0.6
  211. */
  212. public static boolean getTabbedPaneOpaque() {
  213. final String uiname = UIManager.getLookAndFeel().getClass().getName();
  214. final String windows =
  215. "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
  216. final String nimbus = "sun.swing.plaf.nimbus.NimbusLookAndFeel";
  217. return !(windows.equals(uiname) || Apple.isAppleUI() || nimbus.equals(
  218. uiname));
  219. }
  220. /**
  221. * Get the DOWN_MASK for the command/ctrl key.
  222. *
  223. * @return on OSX this returns META_DOWN_MASK, else CTRL_DOWN_MASK
  224. * @since 0.6
  225. */
  226. public static int getCtrlDownMask() {
  227. return Apple.isAppleUI() ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK;
  228. }
  229. /**
  230. * Get the MASK for the command/ctrl key.
  231. *
  232. * @return on OSX this returns META_MASK, else CTRL_MASK
  233. * @since 0.6
  234. */
  235. public static int getCtrlMask() {
  236. return Apple.isAppleUI() ? KeyEvent.META_MASK : KeyEvent.CTRL_MASK;
  237. }
  238. /**
  239. * Check if the command/ctrl key is pressed down.
  240. *
  241. * @param e The KeyEvent to check
  242. * @return on OSX this returns e.isMetaDown(), else e.isControlDown()
  243. * @since 0.6
  244. */
  245. public static boolean isCtrlDown(final KeyEvent e) {
  246. return Apple.isAppleUI() ? e.isMetaDown() : e.isControlDown();
  247. }
  248. /**
  249. * Clips a string if its longer than the specified width.
  250. *
  251. * @param component Component containing string
  252. * @param string String to check
  253. * @param avaiableWidth Available Width
  254. *
  255. * @return String (clipped if required)
  256. */
  257. public static String clipStringifNeeded(final JComponent component,
  258. final String string, final int avaiableWidth) {
  259. if ((string == null) || (string.equals(""))) {
  260. return "";
  261. }
  262. final FontMetrics fm = component.getFontMetrics(component.getFont());
  263. final int width = SwingUtilities.computeStringWidth(fm, string);
  264. if (width > avaiableWidth) {
  265. return clipString(component, string, avaiableWidth);
  266. }
  267. return string;
  268. }
  269. /**
  270. * Clips the passed string .
  271. *
  272. * @param component Component containing string
  273. * @param string String to check
  274. * @param avaiableWidth Available Width
  275. *
  276. * @return String (clipped if required)
  277. */
  278. public static String clipString(final JComponent component,
  279. final String string, final int avaiableWidth) {
  280. if ((string == null) || (string.equals(""))) {
  281. return "";
  282. }
  283. final FontMetrics fm = component.getFontMetrics(component.getFont());
  284. final String clipString = "...";
  285. int width = SwingUtilities.computeStringWidth(fm, clipString);
  286. int nChars = 0;
  287. for (int max = string.length(); nChars < max; nChars++) {
  288. width += fm.charWidth(string.charAt(nChars));
  289. if (width > avaiableWidth) {
  290. break;
  291. }
  292. }
  293. return string.substring(0, nChars) + clipString;
  294. }
  295. /**
  296. * Resets the scroll pane to 0,0.
  297. *
  298. * @param scrollPane Scrollpane to reset
  299. *
  300. * @since 0.6.3m1
  301. */
  302. public static void resetScrollPane(final JScrollPane scrollPane) {
  303. SwingUtilities.invokeLater(new Runnable() {
  304. /** {@inheritDoc} */
  305. @Override
  306. public void run() {
  307. scrollPane.getHorizontalScrollBar().setValue(0);
  308. scrollPane.getVerticalScrollBar().setValue(0);
  309. }
  310. });
  311. }
  312. }