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