JAL-2826 added action performed for hiding collapsed sequences
[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.ext.archaeopteryx.AptxInit;
34 import jalview.gui.AlignFrame;
35 import jalview.gui.AlignViewport;
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, "LoadFile");
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, "LoadFileWithWaiting");
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   // add support for recently opened Aptx trees
204   public void updateRecentlyOpened()
205   {
206     Vector recent = new Vector();
207     if (protocol == DataSourceType.PASTE)
208     {
209       // do nothing if the file was pasted in as text... there is no filename to
210       // refer to it as.
211       return;
212     }
213     if (file != null
214             && file.indexOf(System.getProperty("java.io.tmpdir")) > -1)
215     {
216       // ignore files loaded from the system's temporary directory
217       return;
218     }
219     String type = protocol == DataSourceType.FILE ? "RECENT_FILE"
220             : "RECENT_URL";
221
222     String historyItems = jalview.bin.Cache.getProperty(type);
223
224     StringTokenizer st;
225
226     if (historyItems != null)
227     {
228       st = new StringTokenizer(historyItems, "\t");
229
230       while (st.hasMoreTokens())
231       {
232         recent.addElement(st.nextElement().toString().trim());
233       }
234     }
235
236     if (recent.contains(file))
237     {
238       recent.remove(file);
239     }
240
241     StringBuffer newHistory = new StringBuffer(file);
242     for (int i = 0; i < recent.size() && i < 10; i++)
243     {
244       newHistory.append("\t");
245       newHistory.append(recent.elementAt(i));
246     }
247
248     Cache.setProperty(type, newHistory.toString());
249
250     if (protocol == DataSourceType.FILE)
251     {
252       Cache.setProperty("DEFAULT_FILE_FORMAT", format.getName());
253     }
254   }
255
256   @Override
257   public void run()
258   {
259     String title = protocol == DataSourceType.PASTE
260             ? "Copied From Clipboard"
261             : file;
262     Runtime rt = Runtime.getRuntime();
263     try
264     {
265       if (Desktop.instance != null)
266       {
267         Desktop.instance.startLoading(file);
268       }
269       if (format == null)
270       {
271         // just in case the caller didn't identify the file for us
272         if (source != null)
273         {
274           format = new IdentifyFile().identify(source, false);
275           // identify stream and rewind rather than close
276         }
277         else
278         {
279           format = new IdentifyFile().identify(file, protocol);
280         }
281
282       }
283
284       if (format == null)
285       {
286         Desktop.instance.stopLoading();
287         System.err.println("The input file \"" + file
288                 + "\" has null or unidentifiable data content!");
289         if (!Jalview.isHeadlessMode())
290         {
291           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
292                   MessageManager.getString("label.couldnt_read_data")
293                           + " in " + file + "\n"
294                           + AppletFormatAdapter.getSupportedFormats(),
295                   MessageManager.getString("label.couldnt_read_data"),
296                   JvOptionPane.WARNING_MESSAGE);
297         }
298         return;
299       }
300       // TODO: cache any stream datasources as a temporary file (eg. PDBs
301       // retrieved via URL)
302       if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
303       {
304         System.gc();
305         memused = (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // free
306         // memory
307         // before
308         // load
309       }
310       loadtime = -System.currentTimeMillis();
311       AlignmentI al = null;
312
313       if (FileFormat.Jalview.equals(format))
314       {
315         if (source != null)
316         {
317           // Tell the user (developer?) that this is going to cause a problem
318           System.err.println(
319                   "IMPLEMENTATION ERROR: Cannot read consecutive Jalview XML projects from a stream.");
320           // We read the data anyway - it might make sense.
321         }
322         alignFrame = new Jalview2XML(raiseGUI).loadJalviewAlign(file);
323       }
324       else
325       {
326         String error = AppletFormatAdapter.getSupportedFormats();
327         try
328         {
329           if (source != null)
330           {
331             // read from the provided source
332             al = new FormatAdapter().readFromFile(source, format);
333           }
334           else
335           {
336
337             // open a new source and read from it
338             FormatAdapter fa = new FormatAdapter();
339             boolean downloadStructureFile = format.isStructureFile()
340                     && protocol.equals(DataSourceType.URL);
341             if (downloadStructureFile)
342             {
343               String structExt = format.getExtensions().split(",")[0];
344               String urlLeafName = file.substring(
345                       file.lastIndexOf(
346                               System.getProperty("file.separator")),
347                       file.lastIndexOf("."));
348               String tempStructureFileStr = createNamedJvTempFile(
349                       urlLeafName, structExt);
350               UrlDownloadClient.download(file, tempStructureFileStr);
351               al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
352                       format);
353               source = fa.getAlignFile();
354             }
355             else
356             {
357               al = fa.readFile(file, protocol, format);
358               source = fa.getAlignFile(); // keep reference for later if
359                                           // necessary.
360             }
361           }
362         } catch (java.io.IOException ex)
363         {
364           error = ex.getMessage();
365         }
366
367         if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
368         {
369           // construct and register dataset sequences
370           for (SequenceI sq : al.getSequences())
371           {
372             while (sq.getDatasetSequence() != null)
373             {
374               sq = sq.getDatasetSequence();
375             }
376             if (sq.getAllPDBEntries() != null)
377             {
378               for (PDBEntry pdbe : sq.getAllPDBEntries())
379               {
380                 // register PDB entries with desktop's structure selection
381                 // manager
382                 StructureSelectionManager
383                         .getStructureSelectionManager(Desktop.instance)
384                         .registerPDBEntry(pdbe);
385               }
386             }
387           }
388
389           FeatureSettingsModelI proxyColourScheme = source
390                   .getFeatureColourScheme();
391           if (viewport != null)
392           {
393             if (proxyColourScheme != null)
394             {
395               viewport.applyFeaturesStyle(proxyColourScheme);
396             }
397             // append to existing alignment
398             viewport.addAlignment(al, title);
399           }
400           else
401           {
402             // otherwise construct the alignFrame
403
404             if (source instanceof ComplexAlignFile)
405             {
406               HiddenColumns colSel = ((ComplexAlignFile) source)
407                       .getHiddenColumns();
408               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
409                       .getHiddenSequences();
410               String colourSchemeName = ((ComplexAlignFile) source)
411                       .getGlobalColourScheme();
412               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
413                       .getDisplayedFeatures();
414               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
415                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
416               alignFrame.getViewport().setFeaturesDisplayed(fd);
417               alignFrame.getViewport().setShowSequenceFeatures(
418                       ((ComplexAlignFile) source).isShowSeqFeatures());
419               ColourSchemeI cs = ColourSchemeMapper
420                       .getJalviewColourScheme(colourSchemeName, al);
421               if (cs != null)
422               {
423                 alignFrame.changeColour(cs);
424               }
425             }
426             else
427             {
428               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
429                       AlignFrame.DEFAULT_HEIGHT);
430               if (source instanceof FeaturesSourceI)
431               {
432                 alignFrame.getViewport().setShowSequenceFeatures(true);
433               }
434             }
435             // add metadata and update ui
436             if (!(protocol == DataSourceType.PASTE))
437             {
438               alignFrame.setFileName(file, format);
439             }
440             if (proxyColourScheme != null)
441             {
442               alignFrame.getViewport()
443                       .applyFeaturesStyle(proxyColourScheme);
444             }
445             if (format.isTreeFile())
446             {
447               // make generic instead of Aptx specific?
448               AptxInit.createInstancesFromFile(file,
449                       alignFrame.getViewport());
450
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
468             try
469             {
470               alignFrame.setMaximum(jalview.bin.Cache
471                       .getDefault("SHOW_FULLSCREEN", false));
472             } catch (java.beans.PropertyVetoException ex)
473             {
474             }
475           }
476         }
477         else
478         {
479           if (Desktop.instance != null)
480           {
481             Desktop.instance.stopLoading();
482           }
483
484           final String errorMessage = MessageManager.getString(
485                   "label.couldnt_load_file") + " " + title + "\n" + error;
486           // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
487           // bits ?
488           if (raiseGUI && Desktop.desktop != null)
489           {
490             javax.swing.SwingUtilities.invokeLater(new Runnable()
491             {
492               @Override
493               public void run()
494               {
495                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
496                         errorMessage,
497                         MessageManager
498                                 .getString("label.error_loading_file"),
499                         JvOptionPane.WARNING_MESSAGE);
500               }
501             });
502           }
503           else
504           {
505             System.err.println(errorMessage);
506           }
507         }
508       }
509
510       updateRecentlyOpened();
511
512     } catch (Exception er)
513     {
514       System.err.println("Exception whilst opening file '" + file);
515       er.printStackTrace();
516       if (raiseGUI)
517       {
518         javax.swing.SwingUtilities.invokeLater(new Runnable()
519         {
520           @Override
521           public void run()
522           {
523             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
524                     MessageManager.formatMessage(
525                             "label.problems_opening_file", new String[]
526                             { file }),
527                     MessageManager.getString("label.file_open_error"),
528                     JvOptionPane.WARNING_MESSAGE);
529           }
530         });
531       }
532       alignFrame = null;
533     } catch (OutOfMemoryError er)
534     {
535
536       er.printStackTrace();
537       alignFrame = null;
538       if (raiseGUI)
539       {
540         javax.swing.SwingUtilities.invokeLater(new Runnable()
541         {
542           @Override
543           public void run()
544           {
545             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
546                     MessageManager.formatMessage(
547                             "warn.out_of_memory_loading_file", new String[]
548                             { file }),
549                     MessageManager.getString("label.out_of_memory"),
550                     JvOptionPane.WARNING_MESSAGE);
551           }
552         });
553       }
554       System.err.println("Out of memory loading file " + file + "!!");
555
556     }
557     loadtime += System.currentTimeMillis();
558     // TODO: Estimate percentage of memory used by a newly loaded alignment -
559     // warn if more memory will be needed to work with it
560     // System.gc();
561     memused = memused
562             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
563     // in free
564     // memory
565     // after
566     // load
567     if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
568     {
569       if (alignFrame != null)
570       {
571         AlignmentI al = alignFrame.getViewport().getAlignment();
572
573         System.out.println("Loaded '" + title + "' in "
574                 + (loadtime / 1000.0) + "s, took an additional "
575                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
576                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
577       }
578       else
579       {
580         // report that we didn't load anything probably due to an out of memory
581         // error
582         System.out.println("Failed to load '" + title + "' in "
583                 + (loadtime / 1000.0) + "s, took an additional "
584                 + (1.0 * memused / (1024.0 * 1024.0))
585                 + " MB (alignment is null)");
586       }
587     }
588     // remove the visual delay indicator
589     if (Desktop.instance != null)
590     {
591       Desktop.instance.stopLoading();
592     }
593
594   }
595
596   /**
597    * This method creates the file -
598    * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
599    * file name and extension
600    * 
601    * @param fileName
602    *          the name of the temp file to be created
603    * @param extension
604    *          the extension of the temp file to be created
605    * @return
606    */
607   private static String createNamedJvTempFile(String fileName,
608           String extension) throws IOException
609   {
610     String seprator = System.getProperty("file.separator");
611     String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
612             + seprator + System.currentTimeMillis();
613     File tempStructFile = new File(
614             jvTempDir + seprator + fileName + "." + extension);
615     tempStructFile.mkdirs();
616     return tempStructFile.toString();
617   }
618
619 }