View Javadoc

1   /*
2    *                Doelan development code
3    *
4    * This code may be freely distributed and modified under the
5    * terms of the GNU General Public Licence.  This should
6    * be distributed with the code. If you do not have a copy,
7    * see:
8    *
9    *      http://www.gnu.org/copyleft/gpl.txt
10   *
11   * Copyright (c) 2004-2005 ENS Microarray Platform
12   * Copyright for this code is held jointly by the individual
13   * authors.  These should be listed in @author doc comments.
14   *
15   * For more information on the Doelan project and its aims,
16   * or to join the Doelan mailing list, visit the home page
17   * at:
18   *
19   *      http://www.transcriptome.ens.fr/doelan
20   */
21  
22  package fr.ens.transcriptome.doelan.gui;
23  
24  import java.awt.BorderLayout;
25  import java.awt.Color;
26  import java.awt.Dimension;
27  import java.awt.Image;
28  import java.awt.Toolkit;
29  import java.awt.event.ActionEvent;
30  import java.awt.event.ActionListener;
31  import java.awt.event.KeyEvent;
32  import java.awt.image.RenderedImage;
33  import java.io.File;
34  import java.io.FileNotFoundException;
35  import java.io.FileOutputStream;
36  import java.io.FileWriter;
37  import java.io.IOException;
38  import java.io.OutputStream;
39  import java.io.PrintWriter;
40  import java.net.MalformedURLException;
41  import java.util.Iterator;
42  import java.util.Map;
43  
44  import javax.imageio.ImageIO;
45  import javax.swing.JButton;
46  import javax.swing.JEditorPane;
47  import javax.swing.JFileChooser;
48  import javax.swing.JLabel;
49  import javax.swing.JOptionPane;
50  import javax.swing.JPanel;
51  import javax.swing.JScrollPane;
52  import javax.swing.JTextField;
53  import javax.swing.filechooser.FileFilter;
54  
55  import org.apache.log4j.Logger;
56  
57  import fr.ens.transcriptome.doelan.Defaults;
58  import fr.ens.transcriptome.doelan.DoelanRegistery;
59  import fr.ens.transcriptome.nividic.om.BioAssay;
60  import fr.ens.transcriptome.nividic.om.io.BioAssayWriter;
61  import fr.ens.transcriptome.nividic.om.io.GALWriter;
62  import fr.ens.transcriptome.nividic.om.io.NividicIOException;
63  import fr.ens.transcriptome.nividic.util.SystemUtils;
64  import fr.ens.transcriptome.nividic.util.WebBrowser;
65  
66  /***
67   * Report widget.
68   * @author Laurent Jourdren
69   */
70  public class ReportTabWidget extends JPanel {
71  
72    // For log system
73    private Logger log = Logger.getLogger(ReportTabWidget.class);
74  
75    private JEditorPane editor;
76    private DoelanEditorKit kit;
77    private BioAssay galData;
78    private JButton saveReportButton = new JButton("Save report");
79    private JButton printReportButton = new JButton("Print report");
80    private JButton saveGALButton = new JButton("Save new Array List");
81    private JLabel lablelLocation = new JLabel("Location :");
82    private JLabel statusBar;
83    private JTextField locationfield = new JTextField(System
84        .getProperty("user.home"));
85    private ReportTabWidget panel = this;
86    private Map images;
87    private String browserPath = DoelanRegistery.getBrowserPath();
88    private String htmlText;
89    private String prefixImage;
90  
91    //
92    // Getters
93    //
94  
95    /***
96     * Get the editor widget.
97     * @return Returns the editor
98     */
99    private JEditorPane getEditor() {
100     return editor;
101   }
102 
103   //
104   // Setters
105   //
106 
107   /***
108    * Set the image for the HTML render.
109    * @param mapImage Map of the image to set
110    */
111   public void setImages(final Map mapImage) {
112     this.kit.setMapImages(mapImage);
113     this.images = mapImage;
114 
115   }
116 
117   /***
118    * Set the text of the report.
119    * @param text The text of the report
120    */
121   public void setText(final String text) {
122 
123     getEditor().setText(text);
124     this.htmlText = text;
125     if (text == null) {
126       this.saveReportButton.setEnabled(false);
127       this.printReportButton.setEnabled(false);
128     } else {
129       this.saveReportButton.setEnabled(true);
130       this.printReportButton.setEnabled(true);
131     }
132 
133     // Replace the filename in html
134 
135     this.prefixImage = "" + System.currentTimeMillis();
136 
137     if (this.images == null || this.htmlText == null)
138       return;
139     Iterator it = this.images.keySet().iterator();
140     while (it.hasNext()) {
141 
142       String name = (String) it.next();
143 
144       this.htmlText = this.htmlText.replaceFirst("<img src=\"" + name,
145           "<IMG SRC=\"" + this.prefixImage + "_" + name);
146     }
147 
148   }
149 
150   /***
151    * Set the new Gal file.
152    * @param gal The new gal data
153    */
154   public void setGalData(final BioAssay gal) {
155     this.galData = gal;
156     if (gal == null)
157       this.saveGALButton.setEnabled(false);
158     else
159       this.saveGALButton.setEnabled(true);
160   }
161 
162   /***
163    * Get the new Gal data.
164    * @return The new gal data
165    */
166   public BioAssay getGalData() {
167     return this.galData;
168   }
169 
170   //
171   // Other methods
172   //
173 
174   public void clear() {
175     this.galData = null;
176     this.images = null;
177     setText(null);
178   }
179 
180   private void saveImages(final String directory) {
181 
182     if (this.images == null || this.images.size() == 0 || directory == null)
183       return;
184 
185     Iterator it = this.images.keySet().iterator();
186     while (it.hasNext()) {
187 
188       String name = (String) it.next();
189       Image img = (Image) this.images.get(name);
190       if (img == null)
191         continue;
192 
193       File file = new File(directory, this.prefixImage + "_" + name);
194 
195       try {
196         ImageIO.write((RenderedImage) img, "jpeg", file);
197       } catch (IOException e) {
198         showMessage("Error while writing images files : " + e.getMessage(),
199             true);
200       }
201     }
202   }
203 
204   private void saveReport() {
205 
206     if (getEditor().getText() == null || "".equals(getEditor().getText())) {
207 
208       showMessage("Nothing to save.", true);
209       return;
210     }
211 
212     if (DoelanRegistery.isAppletMode())
213       saveReportFile(this.locationfield.getText());
214     else {
215 
216       JFileChooser jfc = new JFileChooser();
217       jfc.setCurrentDirectory(new File(DoelanRegistery
218           .getDoelanReportDirectory()));
219       jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
220 
221       FileFilter ff = new FileFilter() {
222         public boolean accept(final File f) {
223 
224           if (f.isDirectory())
225             return true;
226 
227           final String filename = f.getName().toLowerCase();
228           return filename.endsWith(".html") || filename.endsWith(".htm");
229         }
230 
231         public String getDescription() {
232           return "HTML file";
233         }
234       };
235 
236       jfc.addChoosableFileFilter(ff);
237 
238       int result = jfc.showSaveDialog(this);
239       if (result == JFileChooser.APPROVE_OPTION) {
240 
241         String filename = jfc.getSelectedFile().getAbsolutePath();
242         saveReportFile(filename);
243 
244         // jfc.getSelectedFile()
245 
246       }
247     }
248   }
249 
250   private void saveReportFile(String filename) {
251 
252     if (filename == null || "".equals(filename)) {
253       showMessage("Invalid file name.", true);
254       return;
255     }
256 
257     if (DoelanRegistery.isAppletMode()) {
258 
259       File f = new File(filename);
260       if (f.isDirectory())
261         filename = filename + File.separator + Defaults.APP_NAME.toLowerCase()
262             + ".html";
263     }
264 
265     try {
266 
267       if (filename.length() < 5)
268         filename = filename + ".html";
269       else {
270         String end = filename.substring(filename.length() - 5);
271 
272         if (!end.toLowerCase().endsWith(".html"))
273           filename = filename + ".html";
274       }
275 
276       File f = new File(filename);
277       OutputStream fos = new FileOutputStream(f);
278       fos.write(this.htmlText.getBytes("ISO-8859-1"));
279       fos.close();
280 
281       saveImages(f.getParent());
282 
283     } catch (FileNotFoundException e1) {
284       showMessage("Error while writing the file : " + e1.getMessage(), true);
285 
286     } catch (MalformedURLException e1) {
287       showMessage("Bad URL", true);
288     } catch (IOException e) {
289       showMessage("Error while writing the file : ", true);
290     }
291 
292   }
293 
294   private void saveArrayList() {
295 
296     if (getGalData() == null) {
297 
298       showMessage("Nothing to save.", true);
299       return;
300     }
301 
302     if (DoelanRegistery.isAppletMode())
303       saveReportFile(this.locationfield.getText());
304     else {
305 
306       JFileChooser jfc = new JFileChooser();
307       jfc
308           .setCurrentDirectory(new File(DoelanRegistery
309               .getDoelanDataDirectory()));
310       jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
311       jfc.addChoosableFileFilter(new FileFilter() {
312         public boolean accept(final File f) {
313 
314           if (f.isDirectory())
315             return true;
316           if (f.getName().length() < 4)
317             return false;
318           String end = f.getName().substring(f.getName().length() - 4);
319 
320           if (end.toLowerCase().endsWith(".gal"))
321             return true;
322           else
323             return false;
324         }
325 
326         public String getDescription() {
327           return "Genepix Array List";
328         }
329       });
330 
331       int result = jfc.showSaveDialog(this);
332       if (result == JFileChooser.APPROVE_OPTION) {
333 
334         String filename = jfc.getSelectedFile().getAbsolutePath();
335         saveArrayListFile(filename);
336 
337       }
338     }
339   }
340 
341   private void saveArrayListFile(String filename) {
342 
343     if (filename == null || "".equals(filename)) {
344       showMessage("Invalid file name.", true);
345       return;
346     }
347 
348     if (DoelanRegistery.isAppletMode()) {
349 
350       File f = new File(filename);
351       if (f.isDirectory())
352         filename = filename + File.separator + Defaults.APP_NAME.toLowerCase()
353             + ".gal";
354     }
355 
356     if (filename.length() < 4)
357       filename = filename + ".gal";
358     else {
359       String end = filename.substring(filename.length() - 4);
360 
361       if (!end.toLowerCase().endsWith(".gal"))
362         filename = filename + ".gal";
363     }
364 
365     // write file
366 
367     try {
368       FileOutputStream fos = new FileOutputStream(new File(filename));
369       BioAssayWriter baw = new GALWriter(fos);
370       // baw.addAllFieldsToWrite();
371       baw.write(getGalData());
372       fos.close();
373 
374     } catch (FileNotFoundException e) {
375       showMessage("File not found", true);
376     } catch (NividicIOException e) {
377       showMessage("Unable to save the file", true);
378     } catch (IOException e) {
379       showMessage("Error while saving the file", true);
380     }
381 
382   }
383 
384   private void printReport() {
385 
386     if (getEditor().getText() == null || "".equals(getEditor().getText())) {
387       showMessage("Nothing to print.", true);
388       return;
389     }
390 
391     String outputFile = null;
392 
393     try {
394 
395       File f = File.createTempFile(Defaults.APP_NAME.toLowerCase(), ".html");
396       PrintWriter out = new PrintWriter(new FileWriter(f));
397 
398       String text = this.htmlText;
399       String newText1 = text
400           .replaceFirst("//<//!//-//-// PRINT// COMMAND// HERE// //-//-//>",
401               "<script language=\"javascript\">if (window.print)  window.print();</script>");
402 
403       String newText2 = newText1.replaceFirst(
404           "//<//!//-//-// PRINT// HEADER1// HERE// //-//-//>",
405           "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n");
406       String newText3 = newText2
407           .replaceFirst(
408               "//<//!//-//-// PRINT// HEADER2// HERE// //-//-//>",
409               "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"/>\n");
410 
411       out.write(newText3);
412       out.close();
413 
414       saveImages(f.getParent());
415       outputFile = f.getAbsolutePath();
416 
417     } catch (FileNotFoundException e1) {
418       showMessage("Error while writing the file : " + e1.getMessage(), true);
419 
420     } catch (MalformedURLException e1) {
421       showMessage("Bad URL", true);
422 
423     } catch (IOException e) {
424       showMessage("Error while writing the file : ", true);
425 
426     }
427 
428     if (outputFile != null)
429       try {
430 
431         WebBrowser.launch(this.browserPath, outputFile);
432       } catch (IOException e) {
433         showMessage("Error while launching navigator : " + e.getMessage(), true);
434       }
435 
436   }
437 
438   //
439   // Constructor
440   //
441 
442   /***
443    * Public constructor.
444    */
445   public ReportTabWidget(final JLabel statusBar) {
446 
447     saveReportButton.setToolTipText("Press this button to save the report");
448     printReportButton.setToolTipText("Press this button to print the report");
449     saveGALButton
450         .setToolTipText("Press this button to save the output array list");
451 
452     if (!SystemUtils.isMacOsX()) {
453       saveReportButton.setMnemonic(KeyEvent.VK_S);
454       printReportButton.setMnemonic(KeyEvent.VK_P);
455       saveGALButton.setMnemonic(KeyEvent.VK_L);
456     }
457 
458     this.statusBar = statusBar;
459     this.editor = new JEditorPane();
460     this.editor.setContentType("text/html");
461     this.kit = new DoelanEditorKit();
462     editor.setEditorKit(this.kit);
463 
464     getEditor().setEditable(false);
465 
466     JScrollPane editorScrollPane = new JScrollPane(getEditor());
467     editorScrollPane
468         .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
469 
470     setLayout(new BorderLayout());
471 
472     add(editorScrollPane, BorderLayout.CENTER);
473 
474     JPanel buttonsPane = new JPanel();
475     add(buttonsPane, BorderLayout.SOUTH);
476 
477     if (DoelanRegistery.isAppletMode()) {
478       buttonsPane.add(lablelLocation);
479       buttonsPane.add(locationfield);
480     }
481 
482     buttonsPane.add(saveReportButton);
483     saveReportButton.addActionListener(new ActionListener() {
484       public void actionPerformed(final ActionEvent e) {
485         panel.saveReport();
486       }
487     });
488 
489     if (this.browserPath != null) {
490       buttonsPane.add(printReportButton);
491       printReportButton.addActionListener(new ActionListener() {
492         public void actionPerformed(final ActionEvent e) {
493           panel.printReport();
494         }
495       });
496     }
497 
498     buttonsPane.add(saveGALButton);
499     saveGALButton.addActionListener(new ActionListener() {
500       public void actionPerformed(final ActionEvent e) {
501 
502         saveArrayList();
503       }
504     });
505 
506     setText(null);
507     setGalData(null);
508 
509     // editorScrollPane.setPreferredSize(new Dimension(1280, 1024));
510     // editorScrollPane.setMinimumSize(new Dimension(200, 600));
511 
512   }
513 
514   /***
515    * Show a message to the user.
516    * @param message Message to show
517    * @param error true if message is an error
518    */
519   private void showMessage(final String message, final boolean error) {
520 
521     log.error("Message : " + message);
522     if (DoelanRegistery.isAppletMode()) {
523       if (error)
524         this.statusBar.setForeground(Color.RED);
525       else
526         this.statusBar.setForeground(Color.BLACK);
527       this.statusBar.setText(message);
528       Toolkit.getDefaultToolkit().beep();
529     } else
530       JOptionPane.showMessageDialog(this, message, error ? "Error" : "Message",
531           error ? JOptionPane.ERROR_MESSAGE : JOptionPane.WARNING_MESSAGE);
532   }
533 
534 }