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