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