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