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