Merge branch 'feature/JAL-1713_overviewInProject' into bug/JAL-3785autoOverviewTitle
[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       this.selectedFile = (File) file;
101       file = selectedFile.getPath();
102     }
103     LoadFile(file.toString(), protocol, format);
104   }
105
106   public void LoadFile(String file, DataSourceType protocol,
107           FileFormatI format)
108   {
109     this.file = file;
110     this.protocol = protocol;
111     this.format = format;
112
113     final Thread loader = new Thread(this);
114
115     SwingUtilities.invokeLater(new Runnable()
116     {
117       @Override
118       public void run()
119       {
120         loader.start();
121       }
122     });
123   }
124
125   /**
126    * Load a (file, protocol) source of unknown type
127    * 
128    * @param file
129    * @param protocol
130    */
131   public void LoadFile(String file, DataSourceType protocol)
132   {
133     LoadFile(file, protocol, null);
134   }
135
136   /**
137    * Load alignment from (file, protocol) and wait till loaded
138    * 
139    * @param file
140    * @param sourceType
141    * @return alignFrame constructed from file contents
142    */
143   public AlignFrame LoadFileWaitTillLoaded(String file,
144           DataSourceType sourceType)
145   {
146     return LoadFileWaitTillLoaded(file, sourceType, null);
147   }
148
149   /**
150    * Load alignment from (file, protocol) of type format and wait till loaded
151    * 
152    * @param file
153    * @param sourceType
154    * @param format
155    * @return alignFrame constructed from file contents
156    */
157   public AlignFrame LoadFileWaitTillLoaded(String file,
158           DataSourceType sourceType, FileFormatI format)
159   {
160     this.file = file;
161     this.protocol = sourceType;
162     this.format = format;
163     return _LoadFileWaitTillLoaded();
164   }
165
166   /**
167    * Load alignment from (file, protocol) of type format and wait till loaded
168    * 
169    * @param file
170    * @param sourceType
171    * @param format
172    * @return alignFrame constructed from file contents
173    */
174   public AlignFrame LoadFileWaitTillLoaded(File file,
175           DataSourceType sourceType, FileFormatI format)
176   {
177     this.selectedFile = file;
178     this.file = file.getPath();
179     this.protocol = sourceType;
180     this.format = format;
181     return _LoadFileWaitTillLoaded();
182   }
183
184   /**
185    * Load alignment from FileParse source of type format and wait till loaded
186    * 
187    * @param source
188    * @param format
189    * @return alignFrame constructed from file contents
190    */
191   public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
192           FileFormatI format)
193   {
194     this.source = source;
195
196     file = source.getInFile();
197     protocol = source.getDataSourceType();
198     this.format = format;
199     return _LoadFileWaitTillLoaded();
200   }
201
202   /**
203    * runs the 'run' method (in this thread), then return the alignFrame that's
204    * (hopefully) been read
205    * 
206    * @return
207    */
208   protected AlignFrame _LoadFileWaitTillLoaded()
209   {
210     this.run();
211
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           format = new IdentifyFile().identify(selectedFile, protocol);
290         }
291         else
292         {
293           format = new IdentifyFile().identify(file, protocol);
294         }
295
296       }
297
298       if (format == null)
299       {
300         Desktop.instance.stopLoading();
301         System.err.println("The input file \"" + file
302                 + "\" has null or unidentifiable data content!");
303         if (!Jalview.isHeadlessMode())
304         {
305           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
306                   MessageManager.getString("label.couldnt_read_data")
307                           + " in " + file + "\n"
308                           + AppletFormatAdapter.getSupportedFormats(),
309                   MessageManager.getString("label.couldnt_read_data"),
310                   JvOptionPane.WARNING_MESSAGE);
311         }
312         return;
313       }
314       // TODO: cache any stream datasources as a temporary file (eg. PDBs
315       // retrieved via URL)
316       if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
317       {
318         System.gc();
319         memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
320         // memory
321         // before
322         // load
323       }
324       loadtime = -System.currentTimeMillis();
325       AlignmentI al = null;
326
327       if (FileFormat.Jalview.equals(format))
328       {
329         if (source != null)
330         {
331           // Tell the user (developer?) that this is going to cause a problem
332           System.err.println(
333                   "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
334           // We read the data anyway - it might make sense.
335         }
336         // BH 2018 switch to File object here instead of filename
337         alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(selectedFile == null ? file : selectedFile);
338       }
339       else
340       {
341         String error = AppletFormatAdapter.getSupportedFormats();
342         try
343         {
344           if (source != null)
345           {
346             // read from the provided source
347             al = new FormatAdapter().readFromFile(source, format);
348           }
349           else
350           {
351
352             // open a new source and read from it
353             FormatAdapter fa = new FormatAdapter();
354             boolean downloadStructureFile = format.isStructureFile()
355                     && protocol.equals(DataSourceType.URL);
356             if (downloadStructureFile)
357             {
358               String structExt = format.getExtensions().split(",")[0];
359               String urlLeafName = file.substring(
360                       file.lastIndexOf(
361                               System.getProperty("file.separator")),
362                       file.lastIndexOf("."));
363               String tempStructureFileStr = createNamedJvTempFile(
364                       urlLeafName, structExt);
365               
366               // BH - switching to File object here so as to hold
367               // ._bytes array directly
368               File tempFile = new File(tempStructureFileStr);
369               UrlDownloadClient.download(file, tempFile);
370               
371               al = fa.readFile(tempFile, DataSourceType.FILE,
372                       format);
373               source = fa.getAlignFile();
374             }
375             else
376             {
377               if (selectedFile == null) {
378                 al = fa.readFile(file, protocol, format);
379                 
380               } else {
381                 al = fa.readFile(selectedFile, protocol, format);
382                              }
383               source = fa.getAlignFile(); // keep reference for later if
384               
385                                           // necessary.
386             }
387           }
388         } catch (java.io.IOException ex)
389         {
390           error = ex.getMessage();
391         }
392
393         if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
394         {
395           // construct and register dataset sequences
396           for (SequenceI sq : al.getSequences())
397           {
398             while (sq.getDatasetSequence() != null)
399             {
400               sq = sq.getDatasetSequence();
401             }
402             if (sq.getAllPDBEntries() != null)
403             {
404               for (PDBEntry pdbe : sq.getAllPDBEntries())
405               {
406                 // register PDB entries with desktop's structure selection
407                 // manager
408                 StructureSelectionManager
409                         .getStructureSelectionManager(Desktop.instance)
410                         .registerPDBEntry(pdbe);
411               }
412             }
413           }
414
415           FeatureSettingsModelI proxyColourScheme = source
416                   .getFeatureColourScheme();
417           if (viewport != null)
418           {
419             // append to existing alignment
420             viewport.addAlignment(al, title);
421             viewport.applyFeaturesStyle(proxyColourScheme);
422           }
423           else
424           {
425             // otherwise construct the alignFrame
426
427             if (source instanceof ComplexAlignFile)
428             {
429               HiddenColumns colSel = ((ComplexAlignFile) source)
430                       .getHiddenColumns();
431               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
432                       .getHiddenSequences();
433               String colourSchemeName = ((ComplexAlignFile) source)
434                       .getGlobalColourScheme();
435               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
436                       .getDisplayedFeatures();
437               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
438                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
439               alignFrame.getViewport().setFeaturesDisplayed(fd);
440               alignFrame.getViewport().setShowSequenceFeatures(
441                       ((ComplexAlignFile) source).isShowSeqFeatures());
442               ColourSchemeI cs = ColourSchemeMapper
443                       .getJalviewColourScheme(colourSchemeName, al);
444               if (cs != null)
445               {
446                 alignFrame.changeColour(cs);
447               }
448             }
449             else
450             {
451               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
452                       AlignFrame.DEFAULT_HEIGHT);
453               if (source instanceof FeaturesSourceI)
454               {
455                 alignFrame.getViewport().setShowSequenceFeatures(true);
456               }
457             }
458             // add metadata and update ui
459             if (!(protocol == DataSourceType.PASTE))
460             {
461               alignFrame.setFileName(file, format);
462               alignFrame.setFileObject(selectedFile); // BH 2018 SwingJS
463             }
464             if (proxyColourScheme != null)
465             {
466               alignFrame.getViewport()
467                       .applyFeaturesStyle(proxyColourScheme);
468             }
469             alignFrame.setStatus(MessageManager.formatMessage(
470                     "label.successfully_loaded_file", new String[]
471                     { title }));
472
473             if (raiseGUI)
474             {
475               // add the window to the GUI
476               // note - this actually should happen regardless of raiseGUI
477               // status in Jalview 3
478               // TODO: define 'virtual desktop' for benefit of headless scripts
479               // that perform queries to find the 'current working alignment'
480               Desktop.addInternalFrame(alignFrame, title,
481                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
482
483               /*
484                * for an Overview automatically opened with alignment,
485                * set its title now alignFrame title has been set
486                */
487               alignFrame.alignPanel.setOverviewTitle(alignFrame);
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.instance != null)
502           {
503             Desktop.instance.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.desktop != null)
511           {
512             javax.swing.SwingUtilities.invokeLater(new Runnable()
513             {
514               @Override
515               public void run()
516               {
517                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
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.desktop,
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.desktop,
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.desktop != null && Desktop.desktop.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.instance != null)
612     {
613       Desktop.instance.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 }