Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

UIUtilities.java 21KB

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