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