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