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