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