Merge branch 'develop' into features/JAL-2909_bamImport2_11
[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.BamFileOptionsChooser;
36 import jalview.gui.Desktop;
37 import jalview.gui.Jalview2XML;
38 import jalview.gui.JvOptionPane;
39 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
40 import jalview.schemes.ColourSchemeI;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.util.MessageManager;
43 import jalview.ws.utils.UrlDownloadClient;
44
45 import java.io.File;
46 import java.io.IOException;
47 import java.util.StringTokenizer;
48 import java.util.Vector;
49
50 import javax.swing.SwingUtilities;
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   /**
76    * default constructor always raised errors in GUI dialog boxes
77    */
78   public FileLoader()
79   {
80     this(true);
81   }
82
83   /**
84    * construct a Fileloader that may raise errors non-interactively
85    * 
86    * @param raiseGUI
87    *          true if errors are to be raised as GUI dialog boxes
88    */
89   public FileLoader(boolean raiseGUI)
90   {
91     this.raiseGUI = raiseGUI;
92   }
93
94   public void LoadFile(AlignViewport viewport, String file,
95           DataSourceType protocol, FileFormatI format)
96   {
97     this.viewport = viewport;
98     LoadFile(file, protocol, format);
99   }
100
101   public void LoadFile(String file, DataSourceType protocol,
102           FileFormatI format)
103   {
104     this.file = file;
105     this.protocol = protocol;
106     this.format = format;
107
108     final Thread loader = new Thread(this);
109
110     SwingUtilities.invokeLater(new Runnable()
111     {
112       @Override
113       public void run()
114       {
115         loader.start();
116       }
117     });
118   }
119
120   /**
121    * Load a (file, protocol) source of unknown type
122    * 
123    * @param file
124    * @param protocol
125    */
126   public void LoadFile(String file, DataSourceType protocol)
127   {
128     LoadFile(file, protocol, null);
129   }
130
131   /**
132    * Load alignment from (file, protocol) and wait till loaded
133    * 
134    * @param file
135    * @param sourceType
136    * @return alignFrame constructed from file contents
137    */
138   public AlignFrame LoadFileWaitTillLoaded(String file,
139           DataSourceType sourceType)
140   {
141     return LoadFileWaitTillLoaded(file, sourceType, null);
142   }
143
144   /**
145    * Load alignment from (file, protocol) of type format and wait till loaded
146    * 
147    * @param file
148    * @param sourceType
149    * @param format
150    * @return alignFrame constructed from file contents
151    */
152   public AlignFrame LoadFileWaitTillLoaded(String file,
153           DataSourceType sourceType, FileFormatI format)
154   {
155     this.file = file;
156     this.protocol = sourceType;
157     this.format = format;
158     return _LoadFileWaitTillLoaded();
159   }
160
161   /**
162    * Load alignment from FileParse source of type format and wait till loaded
163    * 
164    * @param source
165    * @param format
166    * @return alignFrame constructed from file contents
167    */
168   public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
169           FileFormatI format)
170   {
171     this.source = source;
172
173     file = source.getInFile();
174     protocol = source.getDataSourceType();
175     this.format = format;
176     return _LoadFileWaitTillLoaded();
177   }
178
179   /**
180    * start thread and wait until finished, then return the alignFrame that's
181    * (hopefully) been read.
182    * 
183    * @return
184    */
185   protected AlignFrame _LoadFileWaitTillLoaded()
186   {
187     Thread loader = new Thread(this);
188     loader.start();
189
190     while (loader.isAlive())
191     {
192       try
193       {
194         Thread.sleep(500);
195       } catch (Exception ex)
196       {
197       }
198     }
199
200     return alignFrame;
201   }
202
203   public void updateRecentlyOpened()
204   {
205     Vector recent = new Vector();
206     if (protocol == DataSourceType.PASTE)
207     {
208       // do nothing if the file was pasted in as text... there is no filename to
209       // refer to it as.
210       return;
211     }
212     if (file != null
213             && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
214     {
215       // ignore files loaded from the system's temporary directory
216       return;
217     }
218     String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
219             : "RECENT_URL";
220
221     String historyItems = jalview.bin.Cache.getProperty(type);
222
223     StringTokenizer st;
224
225     if (historyItems != null)
226     {
227       st = new StringTokenizer(historyItems, "\t");
228
229       while (st.hasMoreTokens())
230       {
231         recent.addElement(st.nextElement().toString().trim());
232       }
233     }
234
235     if (recent.contains(file))
236     {
237       recent.remove(file);
238     }
239
240     StringBuffer newHistory = new StringBuffer(file);
241     for (int i = 0; i < recent.size() && i < 10; i++)
242     {
243       newHistory.append("\t");
244       newHistory.append(recent.elementAt(i));
245     }
246
247     Cache.setProperty(type, newHistory.toString());
248
249     if (protocol == DataSourceType.FILE)
250     {
251       Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
252     }
253   }
254
255   @Override
256   public void run()
257   {
258     String title = protocol == DataSourceType.PASTE
259             ? "Copied From Clipboard"
260             : file;
261     Runtime rt = Runtime.getRuntime();
262     try
263     {
264       if (Desktop.instance != null)
265       {
266         Desktop.instance.startLoading(file);
267       }
268       if (format == null)
269       {
270         // just in case the caller didn't identify the file for us
271         if (source != null)
272         {
273           format = new IdentifyFile().identify(source, false);
274           // identify stream and rewind rather than close
275         }
276         else
277         {
278           format = new IdentifyFile().identify(file, protocol);
279         }
280
281       }
282
283       if (format == null)
284       {
285         Desktop.instance.stopLoading();
286         System.err.println("The input file \"" + file
287                 + "\" has null or unidentifiable data content!");
288         if (!Jalview.isHeadlessMode())
289         {
290           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
291                   MessageManager.getString("label.couldnt_read_data")
292                           + " in " + file + "\n"
293                           + AppletFormatAdapter.getSupportedFormats(),
294                   MessageManager.getString("label.couldnt_read_data"),
295                   JvOptionPane.WARNING_MESSAGE);
296         }
297         return;
298       }
299       // TODO: cache any stream datasources as a temporary file (eg. PDBs
300       // retrieved via URL)
301       if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
302       {
303         System.gc();
304         memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
305         // memory
306         // before
307         // load
308       }
309       loadtime = -System.currentTimeMillis();
310       AlignmentI al = null;
311
312       if (FileFormat.Bam.equals(format))
313       {
314         FormatAdapter fa = new FormatAdapter();
315         if (source == null)
316         {
317           fa.prepareFileReader(file, protocol, format);
318           source = fa.getAlignFile();
319         }
320         if (!((BamFile) source).parseSuffix())
321         {
322           // configure a window
323           BamFileOptionsChooser bamoptions = new BamFileOptionsChooser(
324                   source);
325           // ask the user which bit of the bam they want to load
326           int confirm = JvOptionPane.showConfirmDialog(null, bamoptions,
327                   MessageManager.getString("label.bam_file_options"),
328                   JvOptionPane.OK_CANCEL_OPTION,
329                   JvOptionPane.PLAIN_MESSAGE);
330
331           if (confirm == JvOptionPane.CANCEL_OPTION
332                   || confirm == JvOptionPane.CLOSED_OPTION)
333           {
334             Desktop.instance.stopLoading();
335             return;
336           }
337           else
338           {
339             bamoptions.update(source);
340             if (file.indexOf("#") == -1)
341             {
342               file = file + "#" + ((BamFile) source).suffix;
343             }
344           }
345         }
346         al = fa.readFile(file, protocol, format);
347       }
348
349       if (FileFormat.Jalview.equals(format))
350       {
351         if (source != null)
352         {
353           // Tell the user (developer?) that this is going to cause a problem
354           System.err.println(
355                   "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
356           // We read the data anyway - it might make sense.
357         }
358         alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
359       }
360       else
361       {
362         String error = AppletFormatAdapter.getSupportedFormats();
363         try
364         {
365           if (al == null)
366           {
367             if (source != null)
368             {
369               // read from the provided source
370               al = new FormatAdapter().readFromFile(source, format);
371             }
372             else
373             {
374
375               // open a new source and read from it
376               FormatAdapter fa = new FormatAdapter();
377               boolean downloadStructureFile = format.isStructureFile()
378                       && protocol.equals(DataSourceType.URL);
379               if (downloadStructureFile)
380               {
381                 String structExt = format.getExtensions().split(",")[0];
382                 String urlLeafName = file.substring(
383                         file.lastIndexOf(
384                                 System.getProperty("file.separator")),
385                         file.lastIndexOf("."));
386                 String tempStructureFileStr = createNamedJvTempFile(
387                         urlLeafName, structExt);
388                 UrlDownloadClient.download(file, tempStructureFileStr);
389                 al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
390                         format);
391                 source = fa.getAlignFile();
392               }
393               else
394               {
395                 al = fa.readFile(file, protocol, format);
396                 source = fa.getAlignFile(); // keep reference for later if
397                                             // necessary.
398               }
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                 StructureSelectionManager
422                         .getStructureSelectionManager(Desktop.instance)
423                         .registerPDBEntry(pdbe);
424               }
425             }
426           }
427
428           FeatureSettingsModelI proxyColourScheme = source
429                   .getFeatureColourScheme();
430           if (viewport != null)
431           {
432             if (proxyColourScheme != null)
433             {
434               viewport.applyFeaturesStyle(proxyColourScheme);
435             }
436             // append to existing alignment
437             viewport.addAlignment(al, title);
438           }
439           else
440           {
441             // otherwise construct the alignFrame
442
443             if (source instanceof ComplexAlignFile)
444             {
445               HiddenColumns colSel = ((ComplexAlignFile) source)
446                       .getHiddenColumns();
447               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
448                       .getHiddenSequences();
449               String colourSchemeName = ((ComplexAlignFile) source)
450                       .getGlobalColourScheme();
451               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
452                       .getDisplayedFeatures();
453               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
454                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
455               alignFrame.getViewport().setFeaturesDisplayed(fd);
456               alignFrame.getViewport().setShowSequenceFeatures(
457                       ((ComplexAlignFile) source).isShowSeqFeatures());
458               ColourSchemeI cs = ColourSchemeMapper
459                       .getJalviewColourScheme(colourSchemeName, al);
460               if (cs != null)
461               {
462                 alignFrame.changeColour(cs);
463               }
464             }
465             else
466             {
467               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
468                       AlignFrame.DEFAULT_HEIGHT);
469               if (source instanceof FeaturesSourceI)
470               {
471                 alignFrame.getViewport().setShowSequenceFeatures(true);
472               }
473             }
474             // add metadata and update ui
475             if (!(protocol == DataSourceType.PASTE))
476             {
477               alignFrame.setFileName(file, format);
478             }
479             if (proxyColourScheme != null)
480             {
481               alignFrame.getViewport()
482                       .applyFeaturesStyle(proxyColourScheme);
483             }
484             alignFrame.statusBar.setText(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.instance != null)
511           {
512             Desktop.instance.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.desktop != null)
520           {
521             javax.swing.SwingUtilities.invokeLater(new Runnable()
522             {
523               @Override
524               public void run()
525               {
526                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
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.desktop,
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.desktop,
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.desktop != null && Desktop.desktop.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.instance != null)
621     {
622       Desktop.instance.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 }