JAL-3675 update release note for JAL-2656
[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.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);
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);
187     loader.start();
188
189     while (loader.isAlive())
190     {
191       try
192       {
193         Thread.sleep(500);
194       } catch (Exception ex)
195       {
196         System.out.println(
197                 "Exception caught while waiting for FileLoader thread");
198         ex.printStackTrace();
199       }
200     }
201
202     return alignFrame;
203   }
204
205   public void updateRecentlyOpened()
206   {
207     Vector recent = new Vector();
208     if (protocol == DataSourceType.PASTE)
209     {
210       // do nothing if the file was pasted in as text... there is no filename to
211       // refer to it as.
212       return;
213     }
214     if (file != null
215             && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
216     {
217       // ignore files loaded from the system's temporary directory
218       return;
219     }
220     String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
221             : "RECENT_URL";
222
223     String historyItems = jalview.bin.Cache.getProperty(type);
224
225     StringTokenizer st;
226
227     if (historyItems != null)
228     {
229       st = new StringTokenizer(historyItems, "\t");
230
231       while (st.hasMoreTokens())
232       {
233         recent.addElement(st.nextElement().toString().trim());
234       }
235     }
236
237     if (recent.contains(file))
238     {
239       recent.remove(file);
240     }
241
242     StringBuffer newHistory = new StringBuffer(file);
243     for (int i = 0; i < recent.size() && i < 10; i++)
244     {
245       newHistory.append("\t");
246       newHistory.append(recent.elementAt(i));
247     }
248
249     Cache.setProperty(type, newHistory.toString());
250
251     if (protocol == DataSourceType.FILE)
252     {
253       Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
254     }
255   }
256
257   @Override
258   public void run()
259   {
260     String title = protocol == DataSourceType.PASTE
261             ? "Copied From Clipboard"
262             : file;
263     Runtime rt = Runtime.getRuntime();
264     try
265     {
266       if (Desktop.instance != null)
267       {
268         Desktop.instance.startLoading(file);
269       }
270       if (format == null)
271       {
272         // just in case the caller didn't identify the file for us
273         if (source != null)
274         {
275           format = new IdentifyFile().identify(source, false);
276           // identify stream and rewind rather than close
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               al = fa.readFile(file, protocol, format);
359               source = fa.getAlignFile(); // keep reference for later if
360                                           // necessary.
361             }
362           }
363         } catch (java.io.IOException ex)
364         {
365           error = ex.getMessage();
366         }
367
368         if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
369         {
370           // construct and register dataset sequences
371           for (SequenceI sq : al.getSequences())
372           {
373             while (sq.getDatasetSequence() != null)
374             {
375               sq = sq.getDatasetSequence();
376             }
377             if (sq.getAllPDBEntries() != null)
378             {
379               for (PDBEntry pdbe : sq.getAllPDBEntries())
380               {
381                 // register PDB entries with desktop's structure selection
382                 // manager
383                 StructureSelectionManager
384                         .getStructureSelectionManager(Desktop.instance)
385                         .registerPDBEntry(pdbe);
386               }
387             }
388           }
389
390           FeatureSettingsModelI proxyColourScheme = source
391                   .getFeatureColourScheme();
392           if (viewport != null)
393           {
394             if (proxyColourScheme != null)
395             {
396               viewport.applyFeaturesStyle(proxyColourScheme);
397             }
398             // append to existing alignment
399             viewport.addAlignment(al, title);
400           }
401           else
402           {
403             // otherwise construct the alignFrame
404
405             if (source instanceof ComplexAlignFile)
406             {
407               HiddenColumns colSel = ((ComplexAlignFile) source)
408                       .getHiddenColumns();
409               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
410                       .getHiddenSequences();
411               String colourSchemeName = ((ComplexAlignFile) source)
412                       .getGlobalColourScheme();
413               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
414                       .getDisplayedFeatures();
415               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
416                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
417               alignFrame.getViewport().setFeaturesDisplayed(fd);
418               alignFrame.getViewport().setShowSequenceFeatures(
419                       ((ComplexAlignFile) source).isShowSeqFeatures());
420               ColourSchemeI cs = ColourSchemeMapper
421                       .getJalviewColourScheme(colourSchemeName, al);
422               if (cs != null)
423               {
424                 alignFrame.changeColour(cs);
425               }
426             }
427             else
428             {
429               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
430                       AlignFrame.DEFAULT_HEIGHT);
431               if (source instanceof FeaturesSourceI)
432               {
433                 alignFrame.getViewport().setShowSequenceFeatures(true);
434               }
435             }
436             // add metadata and update ui
437             if (!(protocol == DataSourceType.PASTE))
438             {
439               alignFrame.setFileName(file, format);
440             }
441             if (proxyColourScheme != null)
442             {
443               alignFrame.getViewport()
444                       .applyFeaturesStyle(proxyColourScheme);
445             }
446             alignFrame.setStatus(MessageManager.formatMessage(
447                     "label.successfully_loaded_file", new String[]
448                     { title }));
449
450             if (raiseGUI)
451             {
452               // add the window to the GUI
453               // note - this actually should happen regardless of raiseGUI
454               // status in Jalview 3
455               // TODO: define 'virtual desktop' for benefit of headless scripts
456               // that perform queries to find the 'current working alignment'
457               Desktop.addInternalFrame(alignFrame, title,
458                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
459             }
460
461             try
462             {
463               alignFrame.setMaximum(jalview.bin.Cache
464                       .getDefault("SHOW_FULLSCREEN", false));
465             } catch (java.beans.PropertyVetoException ex)
466             {
467             }
468           }
469         }
470         else
471         {
472           if (Desktop.instance != null)
473           {
474             Desktop.instance.stopLoading();
475           }
476
477           final String errorMessage = MessageManager.getString(
478                   "label.couldnt_load_file") + " " + title + "\n" + error;
479           // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
480           // bits ?
481           if (raiseGUI && Desktop.desktop != null)
482           {
483             javax.swing.SwingUtilities.invokeLater(new Runnable()
484             {
485               @Override
486               public void run()
487               {
488                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
489                         errorMessage,
490                         MessageManager
491                                 .getString("label.error_loading_file"),
492                         JvOptionPane.WARNING_MESSAGE);
493               }
494             });
495           }
496           else
497           {
498             System.err.println(errorMessage);
499           }
500         }
501       }
502
503       updateRecentlyOpened();
504
505     } catch (Exception er)
506     {
507       System.err.println("Exception whilst opening file '" + file);
508       er.printStackTrace();
509       if (raiseGUI)
510       {
511         javax.swing.SwingUtilities.invokeLater(new Runnable()
512         {
513           @Override
514           public void run()
515           {
516             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
517                     MessageManager.formatMessage(
518                             "label.problems_opening_file", new String[]
519                             { file }),
520                     MessageManager.getString("label.file_open_error"),
521                     JvOptionPane.WARNING_MESSAGE);
522           }
523         });
524       }
525       alignFrame = null;
526     } catch (OutOfMemoryError er)
527     {
528
529       er.printStackTrace();
530       alignFrame = null;
531       if (raiseGUI)
532       {
533         javax.swing.SwingUtilities.invokeLater(new Runnable()
534         {
535           @Override
536           public void run()
537           {
538             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
539                     MessageManager.formatMessage(
540                             "warn.out_of_memory_loading_file", new String[]
541                             { file }),
542                     MessageManager.getString("label.out_of_memory"),
543                     JvOptionPane.WARNING_MESSAGE);
544           }
545         });
546       }
547       System.err.println("Out of memory loading file " + file + "!!");
548
549     }
550     loadtime += System.currentTimeMillis();
551     // TODO: Estimate percentage of memory used by a newly loaded alignment -
552     // warn if more memory will be needed to work with it
553     // System.gc();
554     memused = memused
555             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
556     // in free
557     // memory
558     // after
559     // load
560     if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
561     {
562       if (alignFrame != null)
563       {
564         AlignmentI al = alignFrame.getViewport().getAlignment();
565
566         System.out.println("Loaded '" + title + "' in "
567                 + (loadtime / 1000.0) + "s, took an additional "
568                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
569                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
570       }
571       else
572       {
573         // report that we didn't load anything probably due to an out of memory
574         // error
575         System.out.println("Failed to load '" + title + "' in "
576                 + (loadtime / 1000.0) + "s, took an additional "
577                 + (1.0 * memused / (1024.0 * 1024.0))
578                 + " MB (alignment is null)");
579       }
580     }
581     // remove the visual delay indicator
582     if (Desktop.instance != null)
583     {
584       Desktop.instance.stopLoading();
585     }
586
587   }
588
589   /**
590    * This method creates the file -
591    * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
592    * file name and extension
593    * 
594    * @param fileName
595    *          the name of the temp file to be created
596    * @param extension
597    *          the extension of the temp file to be created
598    * @return
599    */
600   private static String createNamedJvTempFile(String fileName,
601           String extension) throws IOException
602   {
603     String seprator = System.getProperty("file.separator");
604     String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
605             + seprator + System.currentTimeMillis();
606     File tempStructFile = new File(
607             jvTempDir + seprator + fileName + "." + extension);
608     tempStructFile.mkdirs();
609     return tempStructFile.toString();
610   }
611
612 }