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