Merge branch 'develop' into features/JAL-653_gffalignments
[jalview.git] / src / jalview / io / FileLoader.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.io;
22
23 import jalview.api.ComplexAlignFile;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.ColumnSelection;
26 import jalview.datamodel.PDBEntry;
27 import jalview.datamodel.SequenceI;
28 import jalview.gui.AlignFrame;
29 import jalview.gui.AlignViewport;
30 import jalview.gui.Desktop;
31 import jalview.gui.Jalview2XML;
32 import jalview.schemes.ColourSchemeI;
33 import jalview.structure.StructureSelectionManager;
34 import jalview.util.MessageManager;
35
36 import java.util.StringTokenizer;
37 import java.util.Vector;
38
39 import javax.swing.JOptionPane;
40 import javax.swing.SwingUtilities;
41
42 public class FileLoader implements Runnable
43 {
44   String file;
45
46   String protocol;
47
48   String format;
49
50   FileParse source = null; // alternative specification of where data comes
51
52   // from
53
54   AlignViewport viewport;
55
56   AlignFrame alignFrame;
57
58   long loadtime;
59
60   long memused;
61
62   boolean raiseGUI = true;
63
64   /**
65    * default constructor always raised errors in GUI dialog boxes
66    */
67   public FileLoader()
68   {
69     this(true);
70   }
71
72   /**
73    * construct a Fileloader that may raise errors non-interactively
74    * 
75    * @param raiseGUI
76    *          true if errors are to be raised as GUI dialog boxes
77    */
78   public FileLoader(boolean raiseGUI)
79   {
80     this.raiseGUI = raiseGUI;
81   }
82
83   public void LoadFile(AlignViewport viewport, String file,
84           String protocol, String format)
85   {
86     this.viewport = viewport;
87     LoadFile(file, protocol, format);
88   }
89
90   public void LoadFile(String file, String protocol, String format)
91   {
92     this.file = file;
93     this.protocol = protocol;
94     this.format = format;
95
96     final Thread loader = new Thread(this);
97
98     SwingUtilities.invokeLater(new Runnable()
99     {
100       public void run()
101       {
102         loader.start();
103       }
104     });
105   }
106
107   /**
108    * Load a (file, protocol) source of unknown type
109    * 
110    * @param file
111    * @param protocol
112    */
113   public void LoadFile(String file, String protocol)
114   {
115     LoadFile(file, protocol, null);
116   }
117
118   /**
119    * Load alignment from (file, protocol) and wait till loaded
120    * 
121    * @param file
122    * @param protocol
123    * @return alignFrame constructed from file contents
124    */
125   public AlignFrame LoadFileWaitTillLoaded(String file, String protocol)
126   {
127     return LoadFileWaitTillLoaded(file, protocol, null);
128   }
129
130   /**
131    * Load alignment from (file, protocol) of type format and wait till loaded
132    * 
133    * @param file
134    * @param protocol
135    * @param format
136    * @return alignFrame constructed from file contents
137    */
138   public AlignFrame LoadFileWaitTillLoaded(String file, String protocol,
139           String format)
140   {
141     this.file = file;
142     this.protocol = protocol;
143     this.format = format;
144     return _LoadFileWaitTillLoaded();
145   }
146
147   /**
148    * Load alignment from FileParse source of type format and wait till loaded
149    * 
150    * @param source
151    * @param format
152    * @return alignFrame constructed from file contents
153    */
154   public AlignFrame LoadFileWaitTillLoaded(FileParse source, String format)
155   {
156     this.source = source;
157
158     file = source.getInFile();
159     protocol = source.type;
160     this.format = format;
161     return _LoadFileWaitTillLoaded();
162   }
163
164   /**
165    * start thread and wait until finished, then return the alignFrame that's
166    * (hopefully) been read.
167    * 
168    * @return
169    */
170   protected AlignFrame _LoadFileWaitTillLoaded()
171   {
172     Thread loader = new Thread(this);
173     loader.start();
174
175     while (loader.isAlive())
176     {
177       try
178       {
179         Thread.sleep(500);
180       } catch (Exception ex)
181       {
182       }
183     }
184
185     return alignFrame;
186   }
187
188   public void updateRecentlyOpened()
189   {
190     Vector recent = new Vector();
191     if (protocol.equals(FormatAdapter.PASTE))
192     {
193       // do nothing if the file was pasted in as text... there is no filename to
194       // refer to it as.
195       return;
196     }
197     String type = protocol.equals(FormatAdapter.FILE) ? "RECENT_FILE"
198             : "RECENT_URL";
199
200     String historyItems = jalview.bin.Cache.getProperty(type);
201
202     StringTokenizer st;
203
204     if (historyItems != null)
205     {
206       st = new StringTokenizer(historyItems, "\t");
207
208       while (st.hasMoreTokens())
209       {
210         recent.addElement(st.nextElement().toString().trim());
211       }
212     }
213
214     if (recent.contains(file))
215     {
216       recent.remove(file);
217     }
218
219     StringBuffer newHistory = new StringBuffer(file);
220     for (int i = 0; i < recent.size() && i < 10; i++)
221     {
222       newHistory.append("\t");
223       newHistory.append(recent.elementAt(i));
224     }
225
226     jalview.bin.Cache.setProperty(type, newHistory.toString());
227
228     if (protocol.equals(FormatAdapter.FILE))
229     {
230       jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT", format);
231     }
232   }
233
234   public void run()
235   {
236     String title = protocol.equals(AppletFormatAdapter.PASTE) ? "Copied From Clipboard"
237             : file;
238     Runtime rt = Runtime.getRuntime();
239     try
240     {
241       if (Desktop.instance != null)
242       {
243         Desktop.instance.startLoading(file);
244       }
245       if (format == null)
246       {
247         // just in case the caller didn't identify the file for us
248         if (source != null)
249         {
250           format = new IdentifyFile().Identify(source, false); // identify
251           // stream and
252           // rewind rather
253           // than close
254         }
255         else
256         {
257           format = new IdentifyFile().Identify(file, protocol);
258         }
259       }
260       // TODO: cache any stream datasources as a temporary file (eg. PDBs
261       // retrieved via URL)
262       if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
263       {
264         System.gc();
265         memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
266         // memory
267         // before
268         // load
269       }
270       loadtime = -System.currentTimeMillis();
271       AlignmentI al = null;
272
273       if (format.equalsIgnoreCase("Jalview"))
274       {
275         if (source != null)
276         {
277           // Tell the user (developer?) that this is going to cause a problem
278           System.err
279                   .println("IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
280           // We read the data anyway - it might make sense.
281         }
282         alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
283       }
284       else
285       {
286         String error = AppletFormatAdapter.SUPPORTED_FORMATS;
287         if (FormatAdapter.isValidFormat(format))
288         {
289           try
290           {
291             if (source != null)
292             {
293               // read from the provided source
294               al = new FormatAdapter().readFromFile(source, format);
295             }
296             else
297             {
298
299               // open a new source and read from it
300               FormatAdapter fa = new FormatAdapter();
301               al = fa.readFile(file, protocol, format);
302               source = fa.getAlignFile(); // keep reference for later if necessary.
303             }
304           } catch (java.io.IOException ex)
305           {
306             error = ex.getMessage();
307           }
308         }
309         else
310         {
311           if (format != null && format.length() > 7)
312           {
313             // ad hoc message in format.
314             error = format + "\n" + error;
315           }
316         }
317
318         if ((al != null) && (al.getHeight() > 0))
319         {
320           // construct and register dataset sequences
321           for (SequenceI sq : al.getSequences())
322           {
323             while (sq.getDatasetSequence() != null)
324             {
325               sq = sq.getDatasetSequence();
326             }
327             if (sq.getPDBId() != null)
328             {
329               for (PDBEntry pdbe : sq.getPDBId())
330               {
331                 // register PDB entries with desktop's structure selection
332                 // manager
333                 StructureSelectionManager.getStructureSelectionManager(
334                         Desktop.instance).registerPDBEntry(pdbe);
335               }
336             }
337           }
338
339           if (viewport != null)
340           {
341             // append to existing alignment
342             viewport.addAlignment(al, title);
343           }
344           else
345           {
346             // otherwise construct the alignFrame
347
348             if (source instanceof ComplexAlignFile)
349             {
350               ColumnSelection colSel = ((ComplexAlignFile) source)
351                       .getColumnSelection();
352               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
353                       .getHiddenSequences();
354               boolean showSeqFeatures = ((ComplexAlignFile) source)
355                       .isShowSeqFeatures();
356               ColourSchemeI cs = ((ComplexAlignFile) source)
357                       .getColourScheme();
358               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
359                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
360
361               alignFrame.getViewport().setShowSequenceFeatures(
362                       showSeqFeatures);
363               alignFrame.changeColour(cs);
364             }
365             else
366             {
367               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
368                       AlignFrame.DEFAULT_HEIGHT);
369             }
370           }
371           // add metadata and update ui
372           if (!protocol.equals(AppletFormatAdapter.PASTE))
373           {
374             alignFrame.setFileName(file, format);
375           }
376
377           alignFrame.statusBar.setText(MessageManager.formatMessage(
378                   "label.successfully_loaded_file", new String[]
379                   { title }));
380
381           if (raiseGUI)
382           {
383             // add the window to the GUI
384             // note - this actually should happen regardless of raiseGUI
385             // status in Jalview 3
386             // TODO: define 'virtual desktop' for benefit of headless scripts
387             // that perform queries to find the 'current working alignment'
388             Desktop.addInternalFrame(alignFrame, title,
389                     AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
390           }
391
392           try
393           {
394             alignFrame.setMaximum(jalview.bin.Cache.getDefault(
395                     "SHOW_FULLSCREEN", false));
396           } catch (java.beans.PropertyVetoException ex)
397           {
398           }
399         }
400         else
401         {
402           if (Desktop.instance != null)
403           {
404             Desktop.instance.stopLoading();
405           }
406
407           final String errorMessage = "Couldn't load file " + title + "\n"
408                   + error;
409           // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
410           // bits ?
411           if (raiseGUI && Desktop.desktop != null)
412           {
413             javax.swing.SwingUtilities.invokeLater(new Runnable()
414             {
415               public void run()
416               {
417                 JOptionPane.showInternalMessageDialog(Desktop.desktop,
418                         errorMessage, MessageManager
419                                 .getString("label.error_loading_file"),
420                         JOptionPane.WARNING_MESSAGE);
421               }
422             });
423           }
424           else
425           {
426             System.err.println(errorMessage);
427           }
428         }
429       }
430
431       updateRecentlyOpened();
432
433     } catch (Exception er)
434     {
435       System.err.println("Exception whilst opening file '" + file);
436       er.printStackTrace();
437       if (raiseGUI)
438       {
439         javax.swing.SwingUtilities.invokeLater(new Runnable()
440         {
441           public void run()
442           {
443             javax.swing.JOptionPane.showInternalMessageDialog(
444                     Desktop.desktop, MessageManager.formatMessage(
445                             "label.problems_opening_file", new String[]
446                             { file }), MessageManager
447                             .getString("label.file_open_error"),
448                     javax.swing.JOptionPane.WARNING_MESSAGE);
449           }
450         });
451       }
452       alignFrame = null;
453     } catch (OutOfMemoryError er)
454     {
455
456       er.printStackTrace();
457       alignFrame = null;
458       if (raiseGUI)
459       {
460         javax.swing.SwingUtilities.invokeLater(new Runnable()
461         {
462           public void run()
463           {
464             javax.swing.JOptionPane
465                     .showInternalMessageDialog(
466                             Desktop.desktop,
467                             MessageManager.formatMessage("warn.out_of_memory_loading_file", new String[]{file}),
468                             MessageManager.getString("label.out_of_memory"),
469                             javax.swing.JOptionPane.WARNING_MESSAGE);
470           }
471         });
472       }
473       System.err.println("Out of memory loading file " + file + "!!");
474
475     }
476     loadtime += System.currentTimeMillis();
477     // TODO: Estimate percentage of memory used by a newly loaded alignment -
478     // warn if more memory will be needed to work with it
479     // System.gc();
480     memused = memused
481             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
482     // in free
483     // memory
484     // after
485     // load
486     if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
487     {
488       if (alignFrame != null)
489       {
490         AlignmentI al = alignFrame.getViewport().getAlignment();
491
492         System.out.println("Loaded '" + title + "' in "
493                 + (loadtime / 1000.0) + "s, took an additional "
494                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
495                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
496       }
497       else
498       {
499         // report that we didn't load anything probably due to an out of memory
500         // error
501         System.out.println("Failed to load '" + title + "' in "
502                 + (loadtime / 1000.0) + "s, took an additional "
503                 + (1.0 * memused / (1024.0 * 1024.0))
504                 + " MB (alignment is null)");
505       }
506     }
507     // remove the visual delay indicator
508     if (Desktop.instance != null)
509     {
510       Desktop.instance.stopLoading();
511     }
512
513   }
514
515   /*
516    * (non-Javadoc)
517    * 
518    * @see java.lang.Object#finalize()
519    */
520   protected void finalize() throws Throwable
521   {
522     source = null;
523     alignFrame = null;
524     viewport = null;
525     super.finalize();
526   }
527
528 }