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