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