6735a80e27b42c187aec8eaae10a3b657998ecb6
[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.File;
45 import java.io.IOException;
46 import java.util.StringTokenizer;
47 import java.util.Vector;
48
49 import javax.swing.SwingUtilities;
50
51 public class FileLoader implements Runnable
52 {
53   String file;
54
55   DataSourceType protocol;
56
57   FileFormatI format;
58
59   AlignmentFileReaderI source = null; // alternative specification of where data
60                                       // comes
61
62   // from
63
64   AlignViewport viewport;
65
66   AlignFrame alignFrame;
67
68   long loadtime;
69
70   long memused;
71
72   boolean raiseGUI = true;
73
74   /**
75    * default constructor always raised errors in GUI dialog boxes
76    */
77   public FileLoader()
78   {
79     this(true);
80   }
81
82   /**
83    * construct a Fileloader that may raise errors non-interactively
84    * 
85    * @param raiseGUI
86    *          true if errors are to be raised as GUI dialog boxes
87    */
88   public FileLoader(boolean raiseGUI)
89   {
90     this.raiseGUI = raiseGUI;
91   }
92
93   public void LoadFile(AlignViewport viewport, String file,
94           DataSourceType protocol, FileFormatI format)
95   {
96     this.viewport = viewport;
97     LoadFile(file, protocol, format);
98   }
99
100   public void LoadFile(String file, DataSourceType protocol,
101           FileFormatI format)
102   {
103     this.file = file;
104     this.protocol = protocol;
105     this.format = format;
106
107     final Thread loader = new Thread(this, "LoadFile");
108
109     SwingUtilities.invokeLater(new Runnable()
110     {
111       @Override
112       public void run()
113       {
114         loader.start();
115       }
116     });
117   }
118
119   /**
120    * Load a (file, protocol) source of unknown type
121    * 
122    * @param file
123    * @param protocol
124    */
125   public void LoadFile(String file, DataSourceType protocol)
126   {
127     LoadFile(file, protocol, null);
128   }
129
130   /**
131    * Load alignment from (file, protocol) and wait till loaded
132    * 
133    * @param file
134    * @param sourceType
135    * @return alignFrame constructed from file contents
136    */
137   public AlignFrame LoadFileWaitTillLoaded(String file,
138           DataSourceType sourceType)
139   {
140     return LoadFileWaitTillLoaded(file, sourceType, null);
141   }
142
143   /**
144    * Load alignment from (file, protocol) of type format and wait till loaded
145    * 
146    * @param file
147    * @param sourceType
148    * @param format
149    * @return alignFrame constructed from file contents
150    */
151   public AlignFrame LoadFileWaitTillLoaded(String file,
152           DataSourceType sourceType, FileFormatI format)
153   {
154     this.file = file;
155     this.protocol = sourceType;
156     this.format = format;
157     return _LoadFileWaitTillLoaded();
158   }
159
160   /**
161    * Load alignment from FileParse source of type format and wait till loaded
162    * 
163    * @param source
164    * @param format
165    * @return alignFrame constructed from file contents
166    */
167   public AlignFrame LoadFileWaitTillLoaded(AlignmentFileReaderI source,
168           FileFormatI format)
169   {
170     this.source = source;
171
172     file = source.getInFile();
173     protocol = source.getDataSourceType();
174     this.format = format;
175     return _LoadFileWaitTillLoaded();
176   }
177
178   /**
179    * start thread and wait until finished, then return the alignFrame that's
180    * (hopefully) been read.
181    * 
182    * @return
183    */
184   protected AlignFrame _LoadFileWaitTillLoaded()
185   {
186     Thread loader = new Thread(this, "LoadFileWithWaiting");
187     loader.start();
188
189     while (loader.isAlive())
190     {
191       try
192       {
193         Thread.sleep(500);
194       } catch (Exception ex)
195       {
196       }
197     }
198
199     return alignFrame;
200   }
201
202   // add support for recently opened Aptx trees
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.Jalview.equals(format))
313       {
314         if (source != null)
315         {
316           // Tell the user (developer?) that this is going to cause a problem
317           System.err.println(
318                   "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
319           // We read the data anyway - it might make sense.
320         }
321         alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
322       }
323       else
324       {
325         String error = AppletFormatAdapter.getSupportedFormats();
326         try
327         {
328           if (source != null)
329           {
330             // read from the provided source
331             al = new FormatAdapter().readFromFile(source, format);
332           }
333           else
334           {
335
336             // open a new source and read from it
337             FormatAdapter fa = new FormatAdapter();
338             boolean downloadStructureFile = format.isStructureFile()
339                     && protocol.equals(DataSourceType.URL);
340             if (downloadStructureFile)
341             {
342               String structExt = format.getExtensions().split(",")[0];
343               String urlLeafName = file.substring(
344                       file.lastIndexOf(
345                               System.getProperty("file.separator")),
346                       file.lastIndexOf("."));
347               String tempStructureFileStr = createNamedJvTempFile(
348                       urlLeafName, structExt);
349               UrlDownloadClient.download(file, tempStructureFileStr);
350               al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
351                       format);
352               source = fa.getAlignFile();
353             }
354             else
355             {
356               al = fa.readFile(file, protocol, format);
357               source = fa.getAlignFile(); // keep reference for later if
358                                           // necessary.
359             }
360           }
361         } catch (java.io.IOException ex)
362         {
363           error = ex.getMessage();
364         }
365
366         if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
367         {
368           // construct and register dataset sequences
369           for (SequenceI sq : al.getSequences())
370           {
371             while (sq.getDatasetSequence() != null)
372             {
373               sq = sq.getDatasetSequence();
374             }
375             if (sq.getAllPDBEntries() != null)
376             {
377               for (PDBEntry pdbe : sq.getAllPDBEntries())
378               {
379                 // register PDB entries with desktop's structure selection
380                 // manager
381                 StructureSelectionManager
382                         .getStructureSelectionManager(Desktop.instance)
383                         .registerPDBEntry(pdbe);
384               }
385             }
386           }
387
388           FeatureSettingsModelI proxyColourScheme = source
389                   .getFeatureColourScheme();
390           if (viewport != null)
391           {
392             if (proxyColourScheme != null)
393             {
394               viewport.applyFeaturesStyle(proxyColourScheme);
395             }
396             // append to existing alignment
397             viewport.addAlignment(al, title);
398           }
399           else
400           {
401             // otherwise construct the alignFrame
402
403             if (source instanceof ComplexAlignFile)
404             {
405               HiddenColumns colSel = ((ComplexAlignFile) source)
406                       .getHiddenColumns();
407               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
408                       .getHiddenSequences();
409               String colourSchemeName = ((ComplexAlignFile) source)
410                       .getGlobalColourScheme();
411               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
412                       .getDisplayedFeatures();
413               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
414                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
415               alignFrame.getViewport().setFeaturesDisplayed(fd);
416               alignFrame.getViewport().setShowSequenceFeatures(
417                       ((ComplexAlignFile) source).isShowSeqFeatures());
418               ColourSchemeI cs = ColourSchemeMapper
419                       .getJalviewColourScheme(colourSchemeName, al);
420               if (cs != null)
421               {
422                 alignFrame.changeColour(cs);
423               }
424             }
425             else
426             {
427               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
428                       AlignFrame.DEFAULT_HEIGHT);
429               if (source instanceof FeaturesSourceI)
430               {
431                 alignFrame.getViewport().setShowSequenceFeatures(true);
432               }
433             }
434             // add metadata and update ui
435             if (!(protocol == DataSourceType.PASTE))
436             {
437               alignFrame.setFileName(file, format);
438             }
439             if (proxyColourScheme != null)
440             {
441               alignFrame.getViewport()
442                       .applyFeaturesStyle(proxyColourScheme);
443             }
444             alignFrame.statusBar.setText(MessageManager.formatMessage(
445                     "label.successfully_loaded_file", new String[]
446                     { title }));
447
448             if (raiseGUI)
449             {
450               // add the window to the GUI
451               // note - this actually should happen regardless of raiseGUI
452               // status in Jalview 3
453               // TODO: define 'virtual desktop' for benefit of headless scripts
454               // that perform queries to find the 'current working alignment'
455               Desktop.addInternalFrame(alignFrame, title,
456                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
457             }
458
459             try
460             {
461               alignFrame.setMaximum(jalview.bin.Cache
462                       .getDefault("SHOW_FULLSCREEN", false));
463             } catch (java.beans.PropertyVetoException ex)
464             {
465             }
466           }
467         }
468         else
469         {
470           if (Desktop.instance != null)
471           {
472             Desktop.instance.stopLoading();
473           }
474
475           final String errorMessage = MessageManager.getString(
476                   "label.couldnt_load_file") + " " + title + "\n" + error;
477           // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
478           // bits ?
479           if (raiseGUI && Desktop.desktop != null)
480           {
481             javax.swing.SwingUtilities.invokeLater(new Runnable()
482             {
483               @Override
484               public void run()
485               {
486                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
487                         errorMessage,
488                         MessageManager
489                                 .getString("label.error_loading_file"),
490                         JvOptionPane.WARNING_MESSAGE);
491               }
492             });
493           }
494           else
495           {
496             System.err.println(errorMessage);
497           }
498         }
499       }
500
501       updateRecentlyOpened();
502
503     } catch (Exception er)
504     {
505       System.err.println("Exception whilst opening file '" + file);
506       er.printStackTrace();
507       if (raiseGUI)
508       {
509         javax.swing.SwingUtilities.invokeLater(new Runnable()
510         {
511           @Override
512           public void run()
513           {
514             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
515                     MessageManager.formatMessage(
516                             "label.problems_opening_file", new String[]
517                             { file }),
518                     MessageManager.getString("label.file_open_error"),
519                     JvOptionPane.WARNING_MESSAGE);
520           }
521         });
522       }
523       alignFrame = null;
524     } catch (OutOfMemoryError er)
525     {
526
527       er.printStackTrace();
528       alignFrame = null;
529       if (raiseGUI)
530       {
531         javax.swing.SwingUtilities.invokeLater(new Runnable()
532         {
533           @Override
534           public void run()
535           {
536             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
537                     MessageManager.formatMessage(
538                             "warn.out_of_memory_loading_file", new String[]
539                             { file }),
540                     MessageManager.getString("label.out_of_memory"),
541                     JvOptionPane.WARNING_MESSAGE);
542           }
543         });
544       }
545       System.err.println("Out of memory loading file " + file + "!!");
546
547     }
548     loadtime += System.currentTimeMillis();
549     // TODO: Estimate percentage of memory used by a newly loaded alignment -
550     // warn if more memory will be needed to work with it
551     // System.gc();
552     memused = memused
553             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
554     // in free
555     // memory
556     // after
557     // load
558     if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
559     {
560       if (alignFrame != null)
561       {
562         AlignmentI al = alignFrame.getViewport().getAlignment();
563
564         System.out.println("Loaded '" + title + "' in "
565                 + (loadtime / 1000.0) + "s, took an additional "
566                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
567                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
568       }
569       else
570       {
571         // report that we didn't load anything probably due to an out of memory
572         // error
573         System.out.println("Failed to load '" + title + "' in "
574                 + (loadtime / 1000.0) + "s, took an additional "
575                 + (1.0 * memused / (1024.0 * 1024.0))
576                 + " MB (alignment is null)");
577       }
578     }
579     // remove the visual delay indicator
580     if (Desktop.instance != null)
581     {
582       Desktop.instance.stopLoading();
583     }
584
585   }
586
587   /**
588    * This method creates the file -
589    * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
590    * file name and extension
591    * 
592    * @param fileName
593    *          the name of the temp file to be created
594    * @param extension
595    *          the extension of the temp file to be created
596    * @return
597    */
598   private static String createNamedJvTempFile(String fileName,
599           String extension) throws IOException
600   {
601     String seprator = System.getProperty("file.separator");
602     String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
603             + seprator + System.currentTimeMillis();
604     File tempStructFile = new File(
605             jvTempDir + seprator + fileName + "." + extension);
606     tempStructFile.mkdirs();
607     return tempStructFile.toString();
608   }
609
610 }