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