Merge branch 'Jalview-JS/develop' into merge_js_develop
[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 java.awt.Color;
24 import java.awt.Component;
25 import java.awt.Container;
26 import java.awt.Font;
27 import java.awt.event.ActionListener;
28 import java.awt.event.MouseAdapter;
29 import java.awt.event.MouseEvent;
30 import java.util.List;
31 import java.util.Objects;
32
33 import javax.swing.AbstractButton;
34 import javax.swing.BorderFactory;
35 import javax.swing.JButton;
36 import javax.swing.JComboBox;
37 import javax.swing.JComponent;
38 import javax.swing.JMenu;
39 import javax.swing.JMenuItem;
40 import javax.swing.JScrollBar;
41 import javax.swing.SwingConstants;
42 import javax.swing.border.Border;
43 import javax.swing.border.TitledBorder;
44
45 import jalview.util.MessageManager;
46 import jalview.util.Platform;
47
48 /**
49  * useful functions for building Swing GUIs
50  * 
51  * @author JimP
52  * 
53  */
54 public final class JvSwingUtils
55 {
56   static final String HTML_PREFIX = (Platform.isJS() ? 
57           "<html><div style=\"max-width:350px;overflow-wrap:break-word;display:inline-block\">"
58           : "<html><div style=\"width:350; text-align: justify; word-wrap: break-word;\">"
59             );
60
61   /**
62    * wrap a bare html safe string to around 60 characters per line using a CSS
63    * style class specifying word-wrap and break-word
64    * 
65    * @param enclose
66    *          if true, add &lt;html&gt; wrapper tags (currently false for only
67    *          two references -- both in Jws2Discoverer --
68    * @param ttext
69    * 
70    * @return
71    */
72   public static String wrapTooltip(boolean enclose, String ttext)
73   {
74     Objects.requireNonNull(ttext,
75             "Tootip text to format must not be null!");
76     ttext = ttext.trim().replaceAll("<br/>", "<br>");
77
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       int pt = -1, ptlast = -4;
94       while ((pt = ttext.indexOf("<br>", pt + 1)) >= 0) {
95         if (pt - ptlast - 4 > 60) {
96           maxLengthExceeded = true;
97           break;
98         }
99       }
100     }
101     else  
102     {
103       maxLengthExceeded = ttext.length() > 60;
104     }
105
106     String ret = (!enclose ? ttext : maxLengthExceeded ? HTML_PREFIX + ttext + "</div></html>" :
107       "<html>" + ttext + "</html>");
108     //System.out.println("JvSwUtil " + enclose + " " + maxLengthExceeded + " " + ret);
109     return ret;
110   }
111
112   public static JButton makeButton(String label, String tooltip,
113           ActionListener action)
114   {
115     JButton button = new JButton();
116     button.setText(label);
117     // TODO: get the base font metrics for the Jalview gui from somewhere
118     button.setFont(new java.awt.Font("Verdana", Font.PLAIN, 10));
119     button.setForeground(Color.black);
120     button.setHorizontalAlignment(SwingConstants.CENTER);
121     button.setToolTipText(tooltip);
122     button.addActionListener(action);
123     return button;
124   }
125
126   /**
127    * find or add a submenu with the given title in the given menu
128    * 
129    * @param menu
130    * @param submenu
131    * @return the new or existing submenu
132    */
133   public static JMenu findOrCreateMenu(JMenu menu, String submenu)
134   {
135     JMenu submenuinstance = null;
136     for (int i = 0, iSize = menu.getMenuComponentCount(); i < iSize; i++)
137     {
138       if (menu.getMenuComponent(i) instanceof JMenu
139               && ((JMenu) menu.getMenuComponent(i)).getText()
140                       .equals(submenu))
141       {
142         submenuinstance = (JMenu) menu.getMenuComponent(i);
143       }
144     }
145     if (submenuinstance == null)
146     {
147       submenuinstance = new JMenu(submenu);
148       menu.add(submenuinstance);
149     }
150     return submenuinstance;
151
152   }
153
154   /**
155    * A convenience method that that adds a component with label to a container,
156    * sets a tooltip on both component and label, and optionally specifies layout
157    * constraints for the added component (but not the label)
158    * 
159    * @param container
160    * @param tooltip
161    * @param label
162    * @param comp
163    * @param constraints
164    */
165   public static void addtoLayout(Container container, String tooltip,
166           JComponent label, JComponent comp, String constraints)
167   {
168     container.add(label);
169     container.add(comp, constraints);
170     comp.setToolTipText(tooltip); // this doesn't seem to show?
171     label.setToolTipText(tooltip);
172   }
173
174   /**
175    * standard font for labels and check boxes in dialog boxes
176    * 
177    * @return
178    */
179
180   public static Font getLabelFont()
181   {
182     return getLabelFont(false, false);
183   }
184
185   public static Font getLabelFont(boolean bold, boolean italic)
186   {
187     return new java.awt.Font("Verdana",
188             (!bold && !italic) ? Font.PLAIN
189                     : (bold ? Font.BOLD : 0) + (italic ? Font.ITALIC : 0),
190             11);
191   }
192
193   /**
194    * standard font for editable text areas
195    * 
196    * @return
197    */
198   public static Font getTextAreaFont()
199   {
200     return getLabelFont(false, false);
201   }
202
203   /**
204    * clean up a swing menu. Removes any empty submenus without selection
205    * listeners.
206    * 
207    * @param webService
208    */
209   public static void cleanMenu(JMenu webService)
210   {
211     for (int i = 0; i < webService.getItemCount();)
212     {
213       JMenuItem item = webService.getItem(i);
214       if (item instanceof JMenu && ((JMenu) item).getItemCount() == 0)
215       {
216         webService.remove(i);
217       }
218       else
219       {
220         i++;
221       }
222     }
223   }
224
225   /**
226    * Returns the proportion of its range that a scrollbar's position represents,
227    * as a value between 0 and 1. For example if the whole range is from 0 to
228    * 200, then a position of 40 gives proportion = 0.2.
229    * 
230    * @see http://www.javalobby.org/java/forums/t33050.html#91885334
231    * 
232    * @param scroll
233    * @return
234    */
235   public static float getScrollBarProportion(JScrollBar scroll)
236   {
237     /*
238      * The extent (scroll handle width) deduction gives the true operating range
239      * of possible positions.
240      */
241     int possibleRange = scroll.getMaximum() - scroll.getMinimum()
242             - scroll.getModel().getExtent();
243     float valueInRange = scroll.getValue()
244             - (scroll.getModel().getExtent() / 2f);
245     float proportion = valueInRange / possibleRange;
246     return proportion;
247   }
248
249   /**
250    * Returns the scroll bar position in its range that would match the given
251    * proportion (between 0 and 1) of the whole. For example if the whole range
252    * is from 0 to 200, then a proportion of 0.25 gives position 50.
253    * 
254    * @param scrollbar
255    * @param proportion
256    * @return
257    */
258   public static int getScrollValueForProportion(JScrollBar scrollbar,
259           float proportion)
260   {
261     /*
262      * The extent (scroll handle width) deduction gives the true operating range
263      * of possible positions.
264      */
265     float fraction = proportion
266             * (scrollbar.getMaximum() - scrollbar.getMinimum()
267                     - scrollbar.getModel().getExtent())
268             + (scrollbar.getModel().getExtent() / 2f);
269     return Math.min(Math.round(fraction), scrollbar.getMaximum());
270   }
271
272   public static void jvInitComponent(AbstractButton comp, String i18nString)
273   {
274     setColorAndFont(comp);
275     if (i18nString != null && !i18nString.isEmpty())
276     {
277       comp.setText(MessageManager.getString(i18nString));
278     }
279   }
280
281   public static void jvInitComponent(JComponent comp)
282   {
283     setColorAndFont(comp);
284   }
285
286   private static void setColorAndFont(JComponent comp)
287   {
288     comp.setBackground(Color.white);
289     comp.setFont(JvSwingUtils.getLabelFont());
290   }
291
292   /**
293    * A helper method to build a drop-down choice of values, with tooltips for
294    * the entries
295    * 
296    * @param entries
297    * @param tooltips
298    */
299   public static JComboBox<Object> buildComboWithTooltips(
300           List<Object> entries, List<String> tooltips)
301   {
302     JComboBox<Object> combo = new JComboBox<>();
303     final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
304     combo.setRenderer(renderer);
305     for (Object attName : entries)
306     {
307       combo.addItem(attName);
308     }
309     renderer.setTooltips(tooltips);
310     final MouseAdapter mouseListener = new MouseAdapter()
311     {
312       @Override
313       public void mouseEntered(MouseEvent e)
314       {
315         int j = combo.getSelectedIndex();
316         if (j > -1)
317         {
318           combo.setToolTipText(tooltips.get(j));
319         }
320       }
321       @Override
322       public void mouseExited(MouseEvent e)
323       {
324         combo.setToolTipText(null);
325       }
326     };
327     for (Component c : combo.getComponents())
328     {
329       c.addMouseListener(mouseListener);
330     }
331     return combo;
332   }
333
334   /**
335    * Adds a titled border to the component in the default font and position (top
336    * left), optionally with italic text
337    * 
338    * @param comp
339    * @param title
340    * @param italic
341    */
342   public static TitledBorder createTitledBorder(JComponent comp,
343           String title, boolean italic)
344   {
345     Font font = comp.getFont();
346     if (italic)
347     {
348       font = new Font(font.getName(), Font.ITALIC, font.getSize());
349     }
350     Border border = BorderFactory.createTitledBorder("");
351     TitledBorder titledBorder = BorderFactory.createTitledBorder(border,
352             title, TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION,
353             font);
354     comp.setBorder(titledBorder);
355
356     return titledBorder;
357   }
358
359 }