View Javadoc
1   package fr.ifremer.tutti.ui.swing.util;
2   
3   /*
4    * #%L
5    * Tutti :: UI
6    * %%
7    * Copyright (C) 2012 - 2014 Ifremer
8    * %%
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU General Public License as
11   * published by the Free Software Foundation, either version 3 of the 
12   * License, or (at your option) any later version.
13   * 
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Public License for more details.
18   * 
19   * You should have received a copy of the GNU General Public 
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/gpl-3.0.html>.
22   * #L%
23   */
24  
25  import fr.ifremer.tutti.persistence.entities.data.Cruise;
26  import fr.ifremer.tutti.persistence.entities.data.Cruises;
27  import fr.ifremer.tutti.ui.swing.TuttiUIContext;
28  import jaxx.runtime.JAXXObject;
29  import jaxx.runtime.JAXXUtil;
30  import jaxx.runtime.SwingUtil;
31  import org.apache.commons.io.IOUtils;
32  import org.apache.commons.lang3.BooleanUtils;
33  import org.apache.commons.logging.Log;
34  import org.apache.commons.logging.LogFactory;
35  import org.nuiton.jaxx.application.ApplicationBusinessException;
36  import org.nuiton.jaxx.application.swing.util.ApplicationUIUtil;
37  
38  import javax.swing.AbstractButton;
39  import javax.swing.Action;
40  import javax.swing.ImageIcon;
41  import javax.swing.JCheckBox;
42  import javax.swing.JComponent;
43  import javax.swing.JMenuItem;
44  import javax.swing.JRadioButton;
45  import javax.swing.JTree;
46  import javax.swing.KeyStroke;
47  import javax.swing.SwingUtilities;
48  import java.awt.Color;
49  import java.awt.Desktop;
50  import java.awt.event.KeyEvent;
51  import java.awt.event.MouseAdapter;
52  import java.awt.event.MouseEvent;
53  import java.awt.event.MouseListener;
54  import java.io.File;
55  import java.io.InputStream;
56  import java.net.MalformedURLException;
57  import java.net.URL;
58  import java.net.URLConnection;
59  
60  import static org.nuiton.i18n.I18n.t;
61  
62  /**
63   * Created: 14/06/12
64   *
65   * @author Tony Chemit - chemit@codelutin.com
66   * @since 0.1
67   */
68  public final class TuttiUIUtil extends ApplicationUIUtil {
69  
70      /** Logger. */
71      private static final Log log = LogFactory.getLog(TuttiUIUtil.class);
72  
73      private TuttiUIUtil() {
74          // never instanciate util class
75      }
76  
77      public static final MouseListener GRAB_FOCUS_ON_ENTER_LISTENER = new MouseAdapter() {
78          @Override
79          public void mouseEntered(MouseEvent e) {
80              JComponent source = (JComponent) e.getSource();
81              source.grabFocus();
82          }
83      };
84  
85      public static TuttiUIContext getApplicationContext(JAXXObject ui) {
86          return (TuttiUIContext) ApplicationUIUtil.getApplicationContext(ui);
87      }
88  
89      public static void setParentUI(JAXXObject ui, TuttiUI<?, ?> parentUI) {
90          JAXXUtil.initContext(ui, parentUI);
91          setApplicationContext(ui, parentUI.getHandler().getContext());
92      }
93  
94      public static void tryToConnectToUpdateUrl(String urlAsString,
95                                                 String badUrlFormatI18nKey,
96                                                 String notReachI18nKey,
97                                                 String notFoundI18nKey) {
98          URL url;
99          // get url
100         try {
101             url = new URL(urlAsString);
102         } catch (MalformedURLException e) {
103             if (log.isDebugEnabled()) {
104                 log.debug("Bad url syntax at " + urlAsString, e);
105             }
106             throw new ApplicationBusinessException(t(badUrlFormatI18nKey, urlAsString));
107         }
108 
109         URLConnection urlConnection;
110         // try to connect (fail if network or remote host does not exists)
111         try {
112             urlConnection = url.openConnection();
113             urlConnection.setConnectTimeout(10000);
114             urlConnection.connect();
115         } catch (Exception e) {
116             if (log.isDebugEnabled()) {
117                 log.debug("Could not connect to " + urlAsString, e);
118             }
119             throw new ApplicationBusinessException(t(notReachI18nKey, urlAsString));
120         }
121 
122         // try to open the resource (fail if resources does not exist)
123         try {
124             urlConnection.setReadTimeout(1000);
125             InputStream inputStream = null;
126             try {
127                 inputStream = urlConnection.getInputStream();
128             } finally {
129                 IOUtils.closeQuietly(inputStream);
130             }
131         } catch (Exception e) {
132             if (log.isDebugEnabled()) {
133                 log.debug("Could not found file at to " + urlAsString, e);
134             }
135             throw new ApplicationBusinessException(t(notFoundI18nKey, urlAsString));
136         }
137     }
138 
139     public static ImageIcon getCruiseIcon(Cruise cruise) {
140         String iconName = "cruise";
141         if (cruise != null) {
142 
143             if (Cruises.isDirty(cruise)) {
144                 iconName = "cruise-dirty";
145             } else if (Cruises.isReadyToSynch(cruise)) {
146                 iconName = "cruise-ready-to-sync";
147             } else if (Cruises.isSynch(cruise)) {
148                 iconName = "cruise-waiting";
149             }
150         }
151         return SwingUtil.createActionIcon(iconName);
152     }
153 
154     public static void openResource(File file) {
155 
156         Desktop desktop = getDesktopForOpen();
157 
158         try {
159 
160             desktop.open(file);
161         } catch (Exception e) {
162 
163             throw new ApplicationBusinessException(t("swing.error.cannot.open.file"));
164 
165         }
166     }
167 
168     /**
169      * Computes the brightness of a color. This can be useful to determine the text color according to the backgound.
170      * (e.g. if the backgound's brightness is over 125, the text could be written in black, otherwise in white)
171      *
172      * @param c the color
173      * @return the brightness of the color: 0 the darkest, 255 the brightest
174      */
175     public static int getColorBrightness(Color c) {
176         int red = c.getRed();
177         int green = c.getGreen();
178         int blue = c.getBlue();
179 
180         return (int) Math.sqrt(red * red * .241 +
181                                green * green * .691 +
182                                blue * blue * .068);
183     }
184 
185     public static void prepareAction(AbstractButton button, Action action, String actionName) {
186 
187         action.putValue(Action.SMALL_ICON, button.getIcon());
188         action.putValue(Action.LARGE_ICON_KEY, button.getIcon());
189         action.putValue(Action.ACTION_COMMAND_KEY, actionName);
190         action.putValue(Action.NAME, button.getText());
191         action.putValue(Action.SHORT_DESCRIPTION, button.getToolTipText());
192         action.putValue(Action.MNEMONIC_KEY, button.getMnemonic());
193 
194         button.setAction(action);
195 
196     }
197 
198     public static void initButton(TuttiUIContext context, JAXXObject ui, AbstractButton abstractButton) {
199 
200 //        super.initButton(abstractButton);
201 
202         Class actionType = (Class) abstractButton.getClientProperty("simpleAction");
203         if (actionType != null) {
204 
205             Action action = context.getActionFactory().createSimpleAction(ui, abstractButton, actionType);
206             abstractButton.setAction(action);
207 
208         }
209 
210         String actionName = abstractButton.getName();
211         Action action = abstractButton.getAction();
212         Boolean skipAction = (Boolean) abstractButton.getClientProperty("skipAction");
213 
214         if (BooleanUtils.isNotTrue(skipAction)
215             && abstractButton.isFocusable()
216             && !(abstractButton instanceof JMenuItem)
217             && !(abstractButton instanceof JCheckBox)
218             && !(abstractButton instanceof JRadioButton)) {
219 
220             if (action == null) {
221                 throw new IllegalStateException("No action defined for button: " + actionName);
222             }
223 
224             if (log.isDebugEnabled()) {
225                 log.debug("Register action: " + actionName);
226             }
227 
228             abstractButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), actionName);
229             abstractButton.getActionMap().put(actionName, action);
230 
231         }
232     }
233 
234     //FIXME move to jaxx
235     public static void collapseTree(final JTree tree) {
236         SwingUtilities.invokeLater(() -> {
237             int i = 0;
238 
239             while(i < tree.getRowCount()) {
240                 tree.collapseRow(i++);
241             }
242 
243         });
244     }
245 
246 }