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