JAL-2629 fix incorrect gap insertions on HMM sequence
[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.SequenceGroup;
33 import jalview.datamodel.SequenceI;
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);
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 ? "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
276         {
277           format = new IdentifyFile().identify(file, protocol);
278         }
279
280       }
281
282       if (format == null)
283       {
284         Desktop.instance.stopLoading();
285         System.err.println("The input file \"" + file
286                 + "\" has null or unidentifiable data content!");
287         if (!Jalview.isHeadlessMode())
288         {
289           JvOptionPane.showInternalMessageDialog(
290                   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
318                   .println("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(file.lastIndexOf(System
344                       .getProperty("file.separator")), file
345                       .lastIndexOf("."));
346               String tempStructureFileStr = createNamedJvTempFile(
347                       urlLeafName, structExt);
348               UrlDownloadClient.download(file, tempStructureFileStr);
349               al = fa.readFile(tempStructureFileStr, DataSourceType.FILE,
350                       format);
351               source = fa.getAlignFile();
352             }
353             else
354             {
355               al = fa.readFile(file, protocol, format);
356               source = fa.getAlignFile(); // keep reference for later if
357                                           // necessary.
358             }
359           }
360         } catch (java.io.IOException ex)
361         {
362           error = ex.getMessage();
363         }
364
365         if ((al != null) && (al.getHeight() > 0) && al.hasValidSequence())
366         {
367           // construct and register dataset sequences
368           for (SequenceI sq : al.getSequences())
369           {
370             while (sq.getDatasetSequence() != null)
371             {
372               sq = sq.getDatasetSequence();
373             }
374             if (sq.getAllPDBEntries() != null)
375             {
376               for (PDBEntry pdbe : sq.getAllPDBEntries())
377               {
378                 // register PDB entries with desktop's structure selection
379                 // manager
380                 StructureSelectionManager.getStructureSelectionManager(
381                         Desktop.instance).registerPDBEntry(pdbe);
382               }
383             }
384           }
385
386           FeatureSettingsModelI proxyColourScheme = source
387                   .getFeatureColourScheme();
388           if (viewport != null)
389           {
390             if (proxyColourScheme != null)
391             {
392               viewport.applyFeaturesStyle(proxyColourScheme);
393             }
394             // append to existing alignment
395             viewport.addAlignment(al, title);
396             if (source instanceof HMMFile)
397             {
398               AlignmentI alignment = viewport.getAlignment();
399               SequenceI seq = alignment
400                       .getSequenceAt(alignment.getAbsoluteHeight() - 1);
401               alignment.deleteSequence(alignment.getAbsoluteHeight() - 1);
402               SequenceGroup sg = viewport.getSelectionGroup();
403               if (sg != null)
404               {
405                 seq.insertCharAt(0, sg.getStartRes(), '-');
406                 seq.insertCharAt(sg.getEndRes() + 1,
407                         alignment.getWidth() - sg.getEndRes(), '-');
408                 SequenceI topSeq = sg.getSequencesInOrder(alignment)[0];
409                 int topIndex = alignment.findIndex(topSeq);
410                 alignment.getSequences().add(topIndex, seq);
411                 sg.setSeqrep(seq);
412                 viewport.getSelectionGroup().addSequence(seq, false);
413               }
414               else
415               {
416                 for (int i = 0; i < alignment.getAbsoluteHeight(); i++)
417                 {
418                   if (!alignment.getSequenceAt(i).isHMMConsensusSequence())
419                   {
420                     alignment.getSequences().add(i, seq);
421                     break;
422                   }
423
424                 }
425               }
426               viewport.setAlignment(alignment);
427               viewport.initInformation();
428               viewport.updateInformation(viewport.getAlignPanel());
429               viewport.getAlignPanel().adjustAnnotationHeight();
430               viewport.updateSequenceIdColours();
431               viewport.getAlignPanel().paintAlignment(true);
432               viewport.alignmentChanged(viewport.getAlignPanel());
433             }
434           }
435           else
436           {
437             // otherwise construct the alignFrame
438
439             if (source instanceof ComplexAlignFile)
440             {
441               HiddenColumns colSel = ((ComplexAlignFile) source)
442                       .getHiddenColumns();
443               SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
444                       .getHiddenSequences();
445               String colourSchemeName = ((ComplexAlignFile) source)
446                       .getGlobalColourScheme();
447               FeaturesDisplayedI fd = ((ComplexAlignFile) source)
448                       .getDisplayedFeatures();
449               alignFrame = new AlignFrame(al, hiddenSeqs, colSel,
450                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
451               alignFrame.getViewport().setFeaturesDisplayed(fd);
452               alignFrame.getViewport().setShowSequenceFeatures(
453                       ((ComplexAlignFile) source).isShowSeqFeatures());
454               ColourSchemeI cs = ColourSchemeMapper.getJalviewColourScheme(
455                       colourSchemeName, al);
456               if (cs != null)
457               {
458                 alignFrame.changeColour(cs);
459               }
460             }
461             else
462             {
463               alignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
464                       AlignFrame.DEFAULT_HEIGHT);
465               if (source instanceof FeaturesSourceI)
466               {
467                 alignFrame.getViewport().setShowSequenceFeatures(true);
468               }
469             }
470             // add metadata and update ui
471             if (!(protocol == DataSourceType.PASTE))
472             {
473               alignFrame.setFileName(file, format);
474             }
475             if (proxyColourScheme != null)
476             {
477               alignFrame.getViewport()
478                       .applyFeaturesStyle(proxyColourScheme);
479             }
480             alignFrame.statusBar.setText(MessageManager.formatMessage(
481                     "label.successfully_loaded_file",
482                     new String[] { title }));
483
484             if (raiseGUI)
485             {
486               // add the window to the GUI
487               // note - this actually should happen regardless of raiseGUI
488               // status in Jalview 3
489               // TODO: define 'virtual desktop' for benefit of headless scripts
490               // that perform queries to find the 'current working alignment'
491               Desktop.addInternalFrame(alignFrame, title,
492                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
493             }
494
495             try
496             {
497               alignFrame.setMaximum(jalview.bin.Cache.getDefault(
498                       "SHOW_FULLSCREEN", false));
499             } catch (java.beans.PropertyVetoException ex)
500             {
501             }
502           }
503         }
504         else
505         {
506           if (Desktop.instance != null)
507           {
508             Desktop.instance.stopLoading();
509           }
510
511           final String errorMessage = MessageManager
512                   .getString("label.couldnt_load_file")
513                   + " "
514                   + title
515                   + "\n" + error;
516           // TODO: refactor FileLoader to be independent of Desktop / Applet GUI
517           // bits ?
518           if (raiseGUI && Desktop.desktop != null)
519           {
520             javax.swing.SwingUtilities.invokeLater(new Runnable()
521             {
522               @Override
523               public void run()
524               {
525                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
526                         errorMessage, MessageManager
527                                 .getString("label.error_loading_file"),
528                         JvOptionPane.WARNING_MESSAGE);
529               }
530             });
531           }
532           else
533           {
534             System.err.println(errorMessage);
535           }
536         }
537       }
538
539       updateRecentlyOpened();
540
541     } catch (Exception er)
542     {
543       System.err.println("Exception whilst opening file '" + file);
544       er.printStackTrace();
545       if (raiseGUI)
546       {
547         javax.swing.SwingUtilities.invokeLater(new Runnable()
548         {
549           @Override
550           public void run()
551           {
552             JvOptionPane.showInternalMessageDialog(
553                     Desktop.desktop, MessageManager.formatMessage(
554                             "label.problems_opening_file",
555                             new String[] { file }), MessageManager
556                             .getString("label.file_open_error"),
557                     JvOptionPane.WARNING_MESSAGE);
558           }
559         });
560       }
561       alignFrame = null;
562     } catch (OutOfMemoryError er)
563     {
564
565       er.printStackTrace();
566       alignFrame = null;
567       if (raiseGUI)
568       {
569         javax.swing.SwingUtilities.invokeLater(new Runnable()
570         {
571           @Override
572           public void run()
573           {
574             JvOptionPane.showInternalMessageDialog(
575                     Desktop.desktop, MessageManager.formatMessage(
576                             "warn.out_of_memory_loading_file", new String[]
577                             { file }), MessageManager
578                             .getString("label.out_of_memory"),
579                     JvOptionPane.WARNING_MESSAGE);
580           }
581         });
582       }
583       System.err.println("Out of memory loading file " + file + "!!");
584
585     }
586     loadtime += System.currentTimeMillis();
587     // TODO: Estimate percentage of memory used by a newly loaded alignment -
588     // warn if more memory will be needed to work with it
589     // System.gc();
590     memused = memused
591             - (rt.maxMemory() - rt.totalMemory() + rt.freeMemory()); // difference
592     // in free
593     // memory
594     // after
595     // load
596     if (Desktop.desktop != null && Desktop.desktop.isShowMemoryUsage())
597     {
598       if (alignFrame != null)
599       {
600         AlignmentI al = alignFrame.getViewport().getAlignment();
601
602         System.out.println("Loaded '" + title + "' in "
603                 + (loadtime / 1000.0) + "s, took an additional "
604                 + (1.0 * memused / (1024.0 * 1024.0)) + " MB ("
605                 + al.getHeight() + " seqs by " + al.getWidth() + " cols)");
606       }
607       else
608       {
609         // report that we didn't load anything probably due to an out of memory
610         // error
611         System.out.println("Failed to load '" + title + "' in "
612                 + (loadtime / 1000.0) + "s, took an additional "
613                 + (1.0 * memused / (1024.0 * 1024.0))
614                 + " MB (alignment is null)");
615       }
616     }
617     // remove the visual delay indicator
618     if (Desktop.instance != null)
619     {
620       Desktop.instance.stopLoading();
621     }
622
623   }
624
625   /**
626    * This method creates the file -
627    * {tmpdir}/jalview/{current_timestamp}/fileName.exetnsion using the supplied
628    * file name and extension
629    * 
630    * @param fileName
631    *          the name of the temp file to be created
632    * @param extension
633    *          the extension of the temp file to be created
634    * @return
635    */
636   private static String createNamedJvTempFile(String fileName,
637           String extension) throws IOException
638   {
639     String seprator = System.getProperty("file.separator");
640     String jvTempDir = System.getProperty("java.io.tmpdir") + "jalview"
641             + seprator + System.currentTimeMillis();
642     File tempStructFile = new File(jvTempDir + seprator + fileName + "."
643             + extension);
644     tempStructFile.mkdirs();
645     return tempStructFile.toString();
646   }
647
648   /*
649    * (non-Javadoc)
650    * 
651    * @see java.lang.Object#finalize()
652    */
653   @Override
654   protected void finalize() throws Throwable
655   {
656     source = null;
657     alignFrame = null;
658     viewport = null;
659     super.finalize();
660   }
661
662 }