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