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