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