Revert "JAL-2799 all tabs now get mouse listeners and Jalview switches tree view"
[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, "LoadFileThread");
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     return alignFrame;
213   }
214
215   public void updateRecentlyOpened()
216   {
217     Vector<String> recent = new Vector<>();
218     if (protocol == DataSourceType.PASTE)
219     {
220       // do nothing if the file was pasted in as text... there is no filename to
221       // refer to it as.
222       return;
223     }
224     if (file != null
225             && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
226     {
227       // ignore files loaded from the system's temporary directory
228       return;
229     }
230     String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
231             : "RECENT_URL";
232
233     String historyItems = Cache.getProperty(type);
234
235     StringTokenizer st;
236
237     if (historyItems != null)
238     {
239       st = new StringTokenizer(historyItems, "\t");
240
241       while (st.hasMoreTokens())
242       {
243         recent.addElement(st.nextToken().trim());
244       }
245     }
246
247     if (recent.contains(file))
248     {
249       recent.remove(file);
250     }
251
252     StringBuffer newHistory = new StringBuffer(file);
253     for (int i = 0; i < recent.size() && i < 10; i++)
254     {
255       newHistory.append("\t");
256       newHistory.append(recent.elementAt(i));
257     }
258
259     Cache.setProperty(type, newHistory.toString());
260
261     if (protocol == DataSourceType.FILE)
262     {
263       Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
264     }
265   }
266
267   @Override
268   public void run()
269   {
270     String title = protocol == DataSourceType.PASTE
271             ? "Copied From Clipboard"
272             : file;
273     Runtime rt = Runtime.getRuntime();
274     try
275     {
276       if (Desktop.instance != null)
277       {
278         Desktop.instance.startLoading(file);
279       }
280       if (format == null)
281       {
282         // just in case the caller didn't identify the file for us
283         if (source != null)
284         {
285           format = new IdentifyFile().identify(source, false);
286           // identify stream and rewind rather than close
287         }
288         else if (selectedFile != null)
289         {
290           format = new IdentifyFile().identify(selectedFile, protocol);
291         }
292         else
293         {
294           format = new IdentifyFile().identify(file, protocol);
295         }
296
297       }
298
299       if (format == null)
300       {
301         Desktop.instance.stopLoading();
302         System.err.println("The input file \"" + file
303                 + "\" has null or unidentifiable data content!");
304         if (!Jalview.isHeadlessMode())
305         {
306           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
307                   MessageManager.getString("label.couldnt_read_data")
308                           + " in " + file + "\n"
309                           + AppletFormatAdapter.getSupportedFormats(),
310                   MessageManager.getString("label.couldnt_read_data"),
311                   JvOptionPane.WARNING_MESSAGE);
312         }
313         return;
314       }
315       // TODO: cache any stream datasources as a temporary file (eg. PDBs
316       // retrieved via URL)
317       if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
318       {
319         System.gc();
320         memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
321         // memory
322         // before
323         // load
324       }
325       loadtime = -System.currentTimeMillis();
326       AlignmentI al = null;
327
328       if (FileFormat.Jalview.equals(format))
329       {
330         if (source != null)
331         {
332           // Tell the user (developer?) that this is going to cause a problem
333           System.err.println(
334                   "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
335           // We read the data anyway - it might make sense.
336         }
337         // BH 2018 switch to File object here instead of filename
338         alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(
339                 selectedFile == null ? file : selectedFile);
340       }
341       else
342       {
343         String error = AppletFormatAdapter.getSupportedFormats();
344         try
345         {
346           if (source != null)
347           {
348             // read from the provided source
349             al = new FormatAdapter().readFromFile(source, format);
350           }
351           else
352           {
353
354             // open a new source and read from it
355             FormatAdapter fa = new FormatAdapter();
356             boolean downloadStructureFile = format.isStructureFile()
357                     && protocol.equals(DataSourceType.URL);
358             if (downloadStructureFile)
359             {
360               String structExt = format.getExtensions().split(",")[0];
361               String urlLeafName = file.substring(
362                       file.lastIndexOf(
363                               System.getProperty("file.separator")),
364                       file.lastIndexOf("."));
365               String tempStructureFileStr = createNamedJvTempFile(
366                       urlLeafName, structExt);
367
368               // BH - switching to File object here so as to hold
369               // ._bytes array directly
370               File tempFile = new File(tempStructureFileStr);
371               UrlDownloadClient.download(file, tempFile);
372
373               al = fa.readFile(tempFile, DataSourceType.FILE, format);
374               source = fa.getAlignFile();
375             }
376             else
377             {
378               if (selectedFile == null)
379               {
380                 al = fa.readFile(file, protocol, format);
381
382               }
383               else
384               {
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                 StructureSelectionManager
413                         .getStructureSelectionManager(Desktop.instance)
414                         .registerPDBEntry(pdbe);
415               }
416             }
417           }
418
419           FeatureSettingsModelI proxyColourScheme = source
420                   .getFeatureColourScheme();
421           if (viewport != null)
422           {
423             // append to existing alignment
424             viewport.addAlignment(al, title);
425             viewport.applyFeaturesStyle(proxyColourScheme);
426           }
427           else
428           {
429             // otherwise construct the alignFrame
430
431             if (source instanceof ComplexAlignFile)
432             {
433               HiddenColumns colSel = ((ComplexAlignFile) source)
434                       .getHiddenColumns();
435               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
436                       .getHiddenSequences();
437               String colourSchemeName = ((ComplexAlignFile) source)
438                       .getGlobalColourScheme();
439               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
440                       .getDisplayedFeatures();
441               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
442                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
443               alignFrame.getViewport().setFeaturesDisplayed(fd);
444               alignFrame.getViewport().setShowSequenceFeatures(
445                       ((ComplexAlignFile) source).isShowSeqFeatures());
446               ColourSchemeI cs = ColourSchemeMapper
447                       .getJalviewColourScheme(colourSchemeName, al);
448               if (cs != null)
449               {
450                 alignFrame.changeColour(cs);
451               }
452             }
453             else
454             {
455               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
456                       AlignFrame.DEFAULT_HEIGHT);
457               if (source instanceof FeaturesSourceI)
458               {
459                 alignFrame.getViewport().setShowSequenceFeatures(true);
460               }
461             }
462             // add metadata and update ui
463             if (!(protocol == DataSourceType.PASTE))
464             {
465               alignFrame.setFileName(file, format);
466               alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
467             }
468             if (proxyColourScheme != null)
469             {
470               alignFrame.getViewport()
471                       .applyFeaturesStyle(proxyColourScheme);
472             }
473             alignFrame.setStatus(MessageManager.formatMessage(
474                     "label.successfully_loaded_file", new String[]
475                     { title }));
476
477             if (raiseGUI)
478             {
479               // add the window to the GUI
480               // note - this actually should happen regardless of raiseGUI
481               // status in Jalview 3
482               // TODO: define 'virtual desktop' for benefit of headless scripts
483               // that perform queries to find the 'current working alignment'
484               Desktop.addInternalFrame(alignFrame, title,
485                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
486             }
487
488             try
489             {
490               alignFrame.setMaximum(
491                       Cache.getDefault("SHOW_FULLSCREEN", false));
492             } catch (java.beans.PropertyVetoException ex)
493             {
494             }
495           }
496         }
497         else
498         {
499           if (Desktop.instance != null)
500           {
501             Desktop.instance.stopLoading();
502           }
503
504           final String errorMessage = MessageManager.getString(
505                   "label.couldnt_load_file") + " " + title + "\n" + error;
506           // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
507           // bits ?
508           if (raiseGUI && Desktop.desktop != null)
509           {
510             javax.swing.SwingUtilities.invokeLater(new Runnable()
511             {
512               @Override
513               public void run()
514               {
515                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
516                         errorMessage,
517                         MessageManager
518                                 .getString("label.error_loading_file"),
519                         JvOptionPane.WARNING_MESSAGE);
520               }
521             });
522           }
523           else
524           {
525             System.err.println(errorMessage);
526           }
527         }
528       }
529
530       updateRecentlyOpened();
531
532     } catch (Exception er)
533     {
534       System.err.println("Exception whilst opening file '" + file);
535       er.printStackTrace();
536       if (raiseGUI)
537       {
538         javax.swing.SwingUtilities.invokeLater(new Runnable()
539         {
540           @Override
541           public void run()
542           {
543             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
544                     MessageManager.formatMessage(
545                             "label.problems_opening_file", new String[]
546                             { file }),
547                     MessageManager.getString("label.file_open_error"),
548                     JvOptionPane.WARNING_MESSAGE);
549           }
550         });
551       }
552       alignFrame = null;
553     } catch (OutOfMemoryError er)
554     {
555
556       er.printStackTrace();
557       alignFrame = null;
558       if (raiseGUI)
559       {
560         javax.swing.SwingUtilities.invokeLater(new Runnable()
561         {
562           @Override
563           public void run()
564           {
565             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
566                     MessageManager.formatMessage(
567                             "warn.out_of_memory_loading_file", new String[]
568                             { file }),
569                     MessageManager.getString("label.out_of_memory"),
570                     JvOptionPane.WARNING_MESSAGE);
571           }
572         });
573       }
574       System.err.println("Out of memory loading file " + file + "!!");
575
576     }
577     loadtime += System.currentTimeMillis();
578     // TODO: Estimate percentage of memory used by a newly loaded alignment -
579     // warn if more memory will be needed to work with it
580     // System.gc();
581     memused = memused
582             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
583     // in free
584     // memory
585     // after
586     // load
587     if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
588     {
589       if (alignFrame != null)
590       {
591         AlignmentI al = alignFrame.getViewport().getAlignment();
592
593         System.out.println("Loaded '" + title + "' in "
594                 + (loadtime / 1000.0) + "s, took an additional "
595                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
596                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
597       }
598       else
599       {
600         // report that we didn't load anything probably due to an out of memory
601         // error
602         System.out.println("Failed to load '" + title + "' in "
603                 + (loadtime / 1000.0) + "s, took an additional "
604                 + (1.0 * memused / (1024.0 * 1024.0))
605                 + " MB (alignment is null)");
606       }
607     }
608     // remove the visual delay indicator
609     if (Desktop.instance != null)
610     {
611       Desktop.instance.stopLoading();
612     }
613
614   }
615
616   /**
617    * This method creates the file -
618    * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
619    * file name and extension
620    * 
621    * @param fileName
622    *          the name of the temp file to be created
623    * @param extension
624    *          the extension of the temp file to be created
625    * @return
626    */
627   private static String createNamedJvTempFile(String fileName,
628           String extension) throws IOException
629   {
630     String seprator = System.getProperty("file.separator");
631     String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
632             + seprator + System.currentTimeMillis();
633     File tempStructFile = new File(
634             jvTempDir + seprator + fileName + "." + extension);
635     tempStructFile.mkdirs();
636     return tempStructFile.toString();
637   }
638
639 }