7dd8e6ccee94d6d415f649df6ebad323a73afc15
[jalview.git] / src / jalview / gui / JvSwingUtils.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.util.MessageManager;
24
25 import java.awt.BorderLayout;
26 import java.awt.Color;
27 import java.awt.Component;
28 import java.awt.Font;
29 import java.awt.GridLayout;
30 import java.awt.Rectangle;
31 import java.awt.event.ActionListener;
32 import java.awt.event.MouseAdapter;
33 import java.awt.event.MouseEvent;
34 import java.util.List;
35 import java.util.Objects;
36
37 import javax.swing.AbstractButton;
38 import javax.swing.BorderFactory;
39 import javax.swing.JButton;
40 import javax.swing.JComboBox;
41 import javax.swing.JComponent;
42 import javax.swing.JLabel;
43 import javax.swing.JMenu;
44 import javax.swing.JMenuItem;
45 import javax.swing.JPanel;
46 import javax.swing.JScrollBar;
47 import javax.swing.SwingConstants;
48 import javax.swing.border.Border;
49 import javax.swing.border.TitledBorder;
50
51 /**
52  * useful functions for building Swing GUIs
53  * 
54  * @author JimP
55  * 
56  */
57 public final class JvSwingUtils
58 {
59   public static final String HTML_PREFIX = "<html><div style=\"width:350px;white-space:pre-wrap;padding:2px;overflow-wrap:break-word;\">";
60
61
62   /**
63    * wrap a bare html safe string to around 60 characters per line using a CSS
64    * style class specifying word-wrap and break-word
65    * 
66    * @param enclose
67    *          if true, add &lt;html&gt; wrapper tags (currently false for only
68    *          two references -- both in Jws2Discoverer --
69    * @param ttext
70    * 
71    * @return
72    */
73   public static String wrapTooltip(boolean enclose, String ttext)
74   {
75     Objects.requireNonNull(ttext,
76             "Tootip text to format must not be null!");
77     ttext = ttext.trim();
78     boolean maxLengthExceeded = false;
79     boolean isHTML = ttext.startsWith("<html>");
80     if (isHTML)
81     {
82       ttext = ttext.substring(6);
83     }
84     if (ttext.endsWith("</html>"))
85     {
86       isHTML = true;
87       ttext = ttext.substring(0, ttext.length() - 7);
88     }
89     boolean hasBR = ttext.contains("<br>");
90     enclose |= isHTML || hasBR;
91     if (hasBR)
92     {
93       String[] htmllines = ttext.split("<br>");
94       for (String line : htmllines)
95       {
96         maxLengthExceeded = line.length() > 60;
97         if (maxLengthExceeded)
98         {
99           break;
100         }
101       }
102     }
103     else
104     {
105       maxLengthExceeded = ttext.length() > 60;
106     }
107
108     if (!maxLengthExceeded)
109     {
110       return enclose ? "<html>" + ttext + "</html>" : ttext;
111     }
112     // BH 2018,2019
113     return (enclose
114             ? HTML_PREFIX
115             + ttext
116                     + "</div></html>"
117             : ttext);
118
119   }
120
121   public static JButton makeButton(String label, String tooltip,
122           ActionListener action)
123   {
124     JButton button = new JButton();
125     button.setText(label);
126     // TODO: get the base font metrics for the Jalview gui from somewhere
127     button.setFont(new java.awt.Font("Verdana", Font.PLAIN, 10));
128     button.setForeground(Color.black);
129     button.setHorizontalAlignment(SwingConstants.CENTER);
130     button.setToolTipText(tooltip);
131     button.addActionListener(action);
132     return button;
133   }
134
135   /**
136    * find or add a submenu with the given title in the given menu
137    * 
138    * @param menu
139    * @param submenu
140    * @return the new or existing submenu
141    */
142   public static JMenu findOrCreateMenu(JMenu menu, String submenu)
143   {
144     JMenu submenuinstance = null;
145     for (int i = 0, iSize = menu.getMenuComponentCount(); i < iSize; i++)
146     {
147       if (menu.getMenuComponent(i) instanceof JMenu
148               && ((JMenu) menu.getMenuComponent(i)).getText()
149                       .equals(submenu))
150       {
151         submenuinstance = (JMenu) menu.getMenuComponent(i);
152       }
153     }
154     if (submenuinstance == null)
155     {
156       submenuinstance = new JMenu(submenu);
157       menu.add(submenuinstance);
158     }
159     return submenuinstance;
160
161   }
162
163   /**
164    * 
165    * @param panel
166    * @param tooltip
167    * @param label
168    * @param valBox
169    * @return the GUI element created that was added to the layout so it's
170    *         attributes can be changed.
171    */
172   public static JPanel addtoLayout(JPanel panel, String tooltip,
173           JComponent label, JComponent valBox)
174   {
175     JPanel laypanel = new JPanel(new GridLayout(1, 2));
176     JPanel labPanel = new JPanel(new BorderLayout());
177     JPanel valPanel = new JPanel();
178     labPanel.setBounds(new Rectangle(7, 7, 158, 23));
179     valPanel.setBounds(new Rectangle(172, 7, 270, 23));
180     labPanel.add(label, BorderLayout.WEST);
181     valPanel.add(valBox);
182     laypanel.add(labPanel);
183     laypanel.add(valPanel);
184     valPanel.setToolTipText(tooltip);
185     labPanel.setToolTipText(tooltip);
186     valBox.setToolTipText(tooltip);
187     panel.add(laypanel);
188     panel.validate();
189     return laypanel;
190   }
191
192   public static void mgAddtoLayout(JPanel cpanel, String tooltip,
193           JLabel jLabel, JComponent name)
194   {
195     mgAddtoLayout(cpanel, tooltip, jLabel, name, null);
196   }
197
198   public static void mgAddtoLayout(JPanel cpanel, String tooltip,
199           JLabel jLabel, JComponent name, String params)
200   {
201     cpanel.add(jLabel);
202     if (params == null)
203     {
204       cpanel.add(name);
205     }
206     else
207     {
208       cpanel.add(name, params);
209     }
210     name.setToolTipText(tooltip);
211     jLabel.setToolTipText(tooltip);
212   }
213
214   /**
215    * standard font for labels and check boxes in dialog boxes
216    * 
217    * @return
218    */
219
220   public static Font getLabelFont()
221   {
222     return getLabelFont(false, false);
223   }
224
225   public static Font getLabelFont(boolean bold, boolean italic)
226   {
227     return new java.awt.Font("Verdana",
228             (!bold && !italic) ? Font.PLAIN
229                     : (bold ? Font.BOLD : 0) + (italic ? Font.ITALIC : 0),
230             11);
231   }
232
233   /**
234    * standard font for editable text areas
235    * 
236    * @return
237    */
238   public static Font getTextAreaFont()
239   {
240     return getLabelFont(false, false);
241   }
242
243   /**
244    * clean up a swing menu. Removes any empty submenus without selection
245    * listeners.
246    * 
247    * @param webService
248    */
249   public static void cleanMenu(JMenu webService)
250   {
251     for (int i = 0; i < webService.getItemCount();)
252     {
253       JMenuItem item = webService.getItem(i);
254       if (item instanceof JMenu && ((JMenu) item).getItemCount() == 0)
255       {
256         webService.remove(i);
257       }
258       else
259       {
260         i++;
261       }
262     }
263   }
264
265   /**
266    * Returns the proportion of its range that a scrollbar's position represents,
267    * as a value between 0 and 1. For example if the whole range is from 0 to
268    * 200, then a position of 40 gives proportion = 0.2.
269    * 
270    * @see http://www.javalobby.org/java/forums/t33050.html#91885334
271    * 
272    * @param scroll
273    * @return
274    */
275   public static float getScrollBarProportion(JScrollBar scroll)
276   {
277     /*
278      * The extent (scroll handle width) deduction gives the true operating range
279      * of possible positions.
280      */
281     int possibleRange = scroll.getMaximum() - scroll.getMinimum()
282             - scroll.getModel().getExtent();
283     float valueInRange = scroll.getValue()
284             - (scroll.getModel().getExtent() / 2f);
285     float proportion = valueInRange / possibleRange;
286     return proportion;
287   }
288
289   /**
290    * Returns the scroll bar position in its range that would match the given
291    * proportion (between 0 and 1) of the whole. For example if the whole range
292    * is from 0 to 200, then a proportion of 0.25 gives position 50.
293    * 
294    * @param scrollbar
295    * @param proportion
296    * @return
297    */
298   public static int getScrollValueForProportion(JScrollBar scrollbar,
299           float proportion)
300   {
301     /*
302      * The extent (scroll handle width) deduction gives the true operating range
303      * of possible positions.
304      */
305     float fraction = proportion
306             * (scrollbar.getMaximum() - scrollbar.getMinimum()
307                     - scrollbar.getModel().getExtent())
308             + (scrollbar.getModel().getExtent() / 2f);
309     return Math.min(Math.round(fraction), scrollbar.getMaximum());
310   }
311
312   public static void jvInitComponent(AbstractButton comp, String i18nString)
313   {
314     setColorAndFont(comp);
315     if (i18nString != null && !i18nString.isEmpty())
316     {
317       comp.setText(MessageManager.getString(i18nString));
318     }
319   }
320
321   public static void jvInitComponent(JComponent comp)
322   {
323     setColorAndFont(comp);
324   }
325
326   private static void setColorAndFont(JComponent comp)
327   {
328     comp.setBackground(Color.white);
329     comp.setFont(JvSwingUtils.getLabelFont());
330   }
331
332   /**
333    * A helper method to build a drop-down choice of values, with tooltips for
334    * the entries
335    * 
336    * @param entries
337    * @param tooltips
338    */
339   public static JComboBox<String> buildComboWithTooltips(
340           List<String> entries, List<String> tooltips)
341   {
342     JComboBox<String> combo = new JComboBox<>();
343     final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
344     combo.setRenderer(renderer);
345     for (String attName : entries)
346     {
347       combo.addItem(attName);
348     }
349     renderer.setTooltips(tooltips);
350     final MouseAdapter mouseListener = new MouseAdapter()
351     {
352       @Override
353       public void mouseEntered(MouseEvent e)
354       {
355         int j = combo.getSelectedIndex();
356         if (j > -1)
357         {
358           combo.setToolTipText(tooltips.get(j));
359         }
360       }
361       @Override
362       public void mouseExited(MouseEvent e)
363       {
364         combo.setToolTipText(null);
365       }
366     };
367     for (Component c : combo.getComponents())
368     {
369       c.addMouseListener(mouseListener);
370     }
371     return combo;
372   }
373
374   /**
375    * Adds a titled border to the component in the default font and position (top
376    * left), optionally witht italic text
377    * 
378    * @param comp
379    * @param title
380    * @param italic
381    */
382   public static TitledBorder createTitledBorder(JComponent comp,
383           String title, boolean italic)
384   {
385     Font font = comp.getFont();
386     if (italic)
387     {
388       font = new Font(font.getName(), Font.ITALIC, font.getSize());
389     }
390     Border border = BorderFactory.createTitledBorder("");
391     TitledBorder titledBorder = BorderFactory.createTitledBorder(border,
392             title, TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION,
393             font);
394     comp.setBorder(titledBorder);
395
396     return titledBorder;
397   }
398
399 }