d2ba95bda4dab0ac255a9862ecb9c5411619e652
[jalview.git] / src / jalview / gui / Jalview2XML_V1.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.gui;
22
23 import jalview.analysis.Conservation;
24 import jalview.api.FeatureColourI;
25 import jalview.binding.Annotation;
26 import jalview.binding.AnnotationElement;
27 import jalview.binding.Features;
28 import jalview.binding.JGroup;
29 import jalview.binding.JSeq;
30 import jalview.binding.JalviewModel;
31 import jalview.binding.JalviewModelSequence;
32 import jalview.binding.Pdbids;
33 import jalview.binding.Sequence;
34 import jalview.binding.SequenceSet;
35 import jalview.binding.Setting;
36 import jalview.binding.Tree;
37 import jalview.binding.UserColours;
38 import jalview.binding.Viewport;
39 import jalview.datamodel.PDBEntry;
40 import jalview.datamodel.SequenceFeature;
41 import jalview.io.FileFormat;
42 import jalview.schemes.ColourSchemeI;
43 import jalview.schemes.ColourSchemeProperty;
44 import jalview.schemes.FeatureColour;
45 import jalview.structure.StructureSelectionManager;
46 import jalview.util.MessageManager;
47 import jalview.util.jarInputStreamProvider;
48 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
49
50 import java.io.InputStreamReader;
51 import java.io.Reader;
52 import java.net.UnknownHostException;
53 import java.util.Hashtable;
54 import java.util.Vector;
55 import java.util.jar.JarEntry;
56 import java.util.jar.JarInputStream;
57
58 /**
59  * DOCUMENT ME!
60  * 
61  * @author $author$
62  * @version $Revision$
63  */
64 public class Jalview2XML_V1
65 {
66   boolean raiseGUI = true;
67
68   public Jalview2XML_V1()
69   {
70
71   };
72
73   public Jalview2XML_V1(boolean raiseGUI)
74   {
75     this.raiseGUI = raiseGUI;
76   };
77
78   jalview.schemes.UserColourScheme GetUserColourScheme(
79           JalviewModelSequence jms, String id)
80   {
81     UserColours[] uc = jms.getUserColours();
82     UserColours colours = null;
83
84     for (int i = 0; i < uc.length; i++)
85     {
86       if (uc[i].getId().equals(id))
87       {
88         colours = uc[i];
89
90         break;
91       }
92     }
93
94     int csize = colours.getUserColourScheme().getColourCount();
95     java.awt.Color[] newColours = new java.awt.Color[csize];
96
97     for (int i = 0; i < csize; i++)
98     {
99       newColours[i] = new java.awt.Color(Integer.parseInt(
100               colours.getUserColourScheme().getColour(i).getRGB(), 16));
101     }
102
103     return new jalview.schemes.UserColourScheme(newColours);
104   }
105
106   /**
107    * DOCUMENT ME!
108    * 
109    * @param file
110    *          DOCUMENT ME!
111    */
112   public AlignFrame LoadJalviewAlign(final jarInputStreamProvider jprovider)
113   {
114     final String file = jprovider.getFilename();
115     jalview.gui.AlignFrame af = null;
116
117     try
118     {
119       JarInputStream jin = null;
120       JarEntry jarentry = null;
121       int entryCount = 1;
122
123       do
124       {
125         jin = jprovider.getJarInputStream();
126
127         for (int i = 0; i < entryCount; i++)
128         {
129           jarentry = jin.getNextJarEntry();
130         }
131
132         if (jarentry != null)
133         {
134           entryCount++;
135           if (jarentry.getName().endsWith(".xml"))
136           {
137             Reader in = new InputStreamReader(jin, "UTF-8");
138             JalviewModel object = new JalviewModel();
139
140             object = object.unmarshal(in);
141
142             af = LoadFromObject(object, file);
143           }
144         }
145         jin.close();
146       } while (jarentry != null);
147     } catch (final UnknownHostException ex)
148     {
149       ex.printStackTrace();
150       if (raiseGUI)
151       {
152         javax.swing.SwingUtilities.invokeLater(new Runnable()
153         {
154           @Override
155           public void run()
156           {
157
158             System.err.println(
159                     "Couldn't locate Jalview XML file : " + ex + "\n");
160             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
161                     MessageManager.formatMessage("label.couldnt_locate",
162                             new String[]
163                             { file }),
164                     MessageManager.getString("label.url_not_found"),
165                     JvOptionPane.WARNING_MESSAGE);
166           }
167         });
168       }
169       ;
170     } catch (Exception ex)
171     {
172       System.err.println("Exception whilst loading jalview XML file : ");
173       ex.printStackTrace();
174       if (raiseGUI)
175       {
176         javax.swing.SwingUtilities.invokeLater(new Runnable()
177         {
178           @Override
179           public void run()
180           {
181
182             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
183                     MessageManager.formatMessage(
184                             "label.error_loading_file_params", new String[]
185                             { file }),
186                     MessageManager
187                             .getString("label.error_loading_jalview_file"),
188                     JvOptionPane.WARNING_MESSAGE);
189           }
190         });
191       }
192     }
193
194     return af;
195   }
196
197   AlignFrame LoadFromObject(JalviewModel object, String file)
198   {
199     Vector seqids = new Vector();
200     SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
201     Sequence[] vamsasSeq = vamsasSet.getSequence();
202
203     JalviewModelSequence jms = object.getJalviewModelSequence();
204
205     // ////////////////////////////////
206     // LOAD SEQUENCES
207     jalview.datamodel.Sequence[] jseqs = new jalview.datamodel.Sequence[vamsasSeq.length];
208     JSeq[] JSEQ = object.getJalviewModelSequence().getJSeq();
209     for (int i = 0; i < vamsasSeq.length; i++)
210     {
211       jseqs[i] = new jalview.datamodel.Sequence(vamsasSeq[i].getName(),
212               vamsasSeq[i].getSequence());
213       jseqs[i].setStart(JSEQ[i].getStart());
214       jseqs[i].setEnd(JSEQ[i].getEnd());
215       seqids.add(jseqs[i]);
216     }
217
218     // /SequenceFeatures are added to the DatasetSequence,
219     // so we must create the dataset before loading features
220     // ///////////////////////////////
221     jalview.datamodel.Alignment al = new jalview.datamodel.Alignment(jseqs);
222     al.setDataset(null);
223     // ///////////////////////////////
224
225     for (int i = 0; i < vamsasSeq.length; i++)
226     {
227       if (JSEQ[i].getFeaturesCount() > 0)
228       {
229         Features[] features = JSEQ[i].getFeatures();
230         for (int f = 0; f < features.length; f++)
231         {
232           SequenceFeature sf = new SequenceFeature(features[f].getType(),
233                   features[f].getDescription(), features[f].getBegin(),
234                   features[f].getEnd(), null);
235           sf.setStatus(features[f].getStatus());
236           al.getSequenceAt(i).getDatasetSequence().addSequenceFeature(sf);
237         }
238       }
239       if (JSEQ[i].getPdbidsCount() > 0)
240       {
241         Pdbids[] ids = JSEQ[i].getPdbids();
242         for (int p = 0; p < ids.length; p++)
243         {
244           jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
245           entry.setId(ids[p].getId());
246           if (ids[p].getType() != null)
247           {
248             if (ids[p].getType().equalsIgnoreCase("PDB"))
249             {
250               entry.setType(PDBEntry.Type.PDB);
251             }
252             else
253             {
254               entry.setType(PDBEntry.Type.FILE);
255             }
256           }
257           al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
258           StructureSelectionManager
259                   .getStructureSelectionManager(Desktop.instance)
260                   .registerPDBEntry(entry);
261         }
262
263       }
264     }
265
266     // ///////////////////////////////
267     // ////////////////////////////////
268     // LOAD ANNOTATIONS
269     if (vamsasSet.getAnnotation() != null)
270     {
271       Annotation[] an = vamsasSet.getAnnotation();
272
273       for (int i = 0; i < an.length; i++)
274       {
275         AnnotationElement[] ae = an[i].getAnnotationElement();
276         jalview.datamodel.Annotation[] anot = new jalview.datamodel.Annotation[al
277                 .getWidth()];
278
279         for (int aa = 0; aa < ae.length; aa++)
280         {
281           anot[ae[aa].getPosition()] = new jalview.datamodel.Annotation(
282                   ae[aa].getDisplayCharacter(), ae[aa].getDescription(),
283                   ae[aa].getSecondaryStructure().charAt(0),
284                   ae[aa].getValue());
285         }
286
287         jalview.datamodel.AlignmentAnnotation jaa = null;
288
289         if (an[i].getGraph())
290         {
291           jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
292                   an[i].getDescription(), anot, 0, 0,
293                   jalview.datamodel.AlignmentAnnotation.BAR_GRAPH);
294         }
295         else
296         {
297           jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
298                   an[i].getDescription(), anot);
299         }
300
301         al.addAnnotation(jaa);
302       }
303     }
304
305     // ///////////////////////////////
306     // LOAD VIEWPORT
307     Viewport[] views = jms.getViewport();
308     Viewport view = views[0]; // DEAL WITH MULTIPLE VIEWPORTS LATER
309
310     AlignFrame af = new AlignFrame(al, view.getWidth(), view.getHeight());
311
312     af.setFileName(file, FileFormat.Jalview);
313
314     for (int i = 0; i < JSEQ.length; i++)
315     {
316       af.viewport.setSequenceColour(
317               af.viewport.getAlignment().getSequenceAt(i),
318               new java.awt.Color(JSEQ[i].getColour()));
319     }
320
321     // af.changeColour() );
322     // ///////////////////////
323     // LOAD GROUPS
324     if (jms.getJGroupCount() > 0)
325     {
326       JGroup[] groups = jms.getJGroup();
327
328       for (int i = 0; i < groups.length; i++)
329       {
330         ColourSchemeI cs = null;
331
332         if (groups[i].getColour() != null)
333         {
334           if (groups[i].getColour().startsWith("ucs"))
335           {
336             cs = GetUserColourScheme(jms, groups[i].getColour());
337           }
338           else
339           {
340             cs = ColourSchemeProperty.getColourScheme(al,
341                     groups[i].getColour());
342           }
343         }
344         int pidThreshold = groups[i].getPidThreshold();
345
346         Vector seqs = new Vector();
347         int[] ids = groups[i].getSeq();
348
349         for (int s = 0; s < ids.length; s++)
350         {
351           seqs.addElement(seqids.elementAt(ids[s]));
352         }
353
354         jalview.datamodel.SequenceGroup sg = new jalview.datamodel.SequenceGroup(
355                 seqs, groups[i].getName(), cs, groups[i].getDisplayBoxes(),
356                 groups[i].getDisplayText(), groups[i].getColourText(),
357                 groups[i].getStart(), groups[i].getEnd());
358         sg.getGroupColourScheme().setThreshold(pidThreshold, true);
359
360         sg.setOutlineColour(
361                 new java.awt.Color(groups[i].getOutlineColour()));
362
363         if (groups[i].getConsThreshold() != 0)
364         {
365           Conservation c = new Conservation("All", sg.getSequences(null), 0,
366                   sg.getWidth() - 1);
367           c.calculate();
368           c.verdict(false, 25);
369           sg.cs.setConservation(c);
370         }
371
372         al.addGroup(sg);
373       }
374     }
375
376     af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(),
377             view.getHeight());
378     af.viewport.getRanges().setStartRes(view.getStartRes());
379     // startSeq set in af.alignPanel.updateLayout below
380     af.viewport.setShowAnnotation(view.getShowAnnotation());
381     af.viewport.setAbovePIDThreshold(view.getPidSelected());
382     af.viewport.setColourText(view.getShowColourText());
383     af.viewport.setConservationSelected(view.getConservationSelected());
384     af.viewport.setShowJVSuffix(view.getShowFullId());
385     af.viewport.setFont(new java.awt.Font(view.getFontName(),
386             view.getFontStyle(), view.getFontSize()), true);
387
388     af.viewport.setRenderGaps(view.getRenderGaps());
389     af.viewport.setWrapAlignment(view.getWrapAlignment());
390
391     af.viewport.setShowAnnotation(view.isShowAnnotation());
392     af.viewport.setShowBoxes(view.getShowBoxes());
393     af.viewport.setShowText(view.getShowText());
394
395     ColourSchemeI cs = null;
396
397     if (view.getBgColour() != null)
398     {
399       if (view.getBgColour().startsWith("ucs"))
400       {
401         cs = GetUserColourScheme(jms, view.getBgColour());
402       }
403       else
404       {
405         cs = ColourSchemeProperty.getColourScheme(al, view.getBgColour());
406       }
407
408       // if (cs != null)
409       // {
410       // cs.setThreshold(view.getPidThreshold(), true);
411       // cs.setConsensus(af.viewport.getSequenceConsensusHash());
412       // }
413     }
414
415     af.viewport.getResidueShading().setThreshold(view.getPidThreshold(),
416             true);
417     af.viewport.getResidueShading()
418             .setConsensus(af.viewport.getSequenceConsensusHash());
419     af.viewport.setColourAppliesToAllGroups(false);
420     af.alignPanel.updateLayout();
421     af.changeColour(cs);
422     if (view.getConservationSelected() && cs != null)
423     {
424       af.viewport.getResidueShading()
425               .setConservationInc(view.getConsThreshold());
426     }
427
428     af.viewport.setColourAppliesToAllGroups(true);
429     af.viewport.setShowSequenceFeatures(view.getShowSequenceFeatures());
430
431     if (jms.getFeatureSettings() != null)
432     {
433       Hashtable<String, Integer> featuresDisplayed = new Hashtable<>();
434       Hashtable<String, FeatureColourI> featureColours = new Hashtable<>();
435       String[] renderOrder = new String[jms.getFeatureSettings()
436               .getSettingCount()];
437       for (int fs = 0; fs < jms.getFeatureSettings()
438               .getSettingCount(); fs++)
439       {
440         Setting setting = jms.getFeatureSettings().getSetting(fs);
441
442         featureColours.put(setting.getType(),
443                 new FeatureColour(new java.awt.Color(setting.getColour())));
444
445         renderOrder[fs] = setting.getType();
446
447         if (setting.getDisplay())
448         {
449           featuresDisplayed.put(setting.getType(),
450                   new Integer(setting.getColour()));
451         }
452       }
453       FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
454               new Hashtable<String, Boolean>(), featureColours, 1.0f, null,
455               null);
456       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
457               .transferSettings(frs);
458     }
459
460     af.setMenusFromViewport(af.viewport);
461
462     Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
463             view.getHeight());
464
465     // LOAD TREES
466     // /////////////////////////////////////
467     if (jms.getTreeCount() > 0)
468     {
469       try
470       {
471         for (int t = 0; t < jms.getTreeCount(); t++)
472         {
473
474           Tree tree = jms.getTree(t);
475
476           TreePanel tp = af.showNewickTree(
477                   new jalview.io.NewickFile(tree.getNewick()),
478                   tree.getTitle(), tree.getWidth(), tree.getHeight(),
479                   tree.getXpos(), tree.getYpos());
480
481           tp.fitToWindow.setState(tree.getFitToWindow());
482           tp.fitToWindow_actionPerformed(null);
483
484           if (tree.getFontName() != null)
485           {
486             tp.setTreeFont(new java.awt.Font(tree.getFontName(),
487                     tree.getFontStyle(), tree.getFontSize()));
488           }
489           else
490           {
491             tp.setTreeFont(new java.awt.Font(view.getFontName(),
492                     view.getFontStyle(), tree.getFontSize()));
493           }
494
495           tp.showPlaceholders(tree.getMarkUnlinked());
496           tp.showBootstrap(tree.getShowBootstrap());
497           tp.showDistances(tree.getShowDistances());
498
499           tp.treeCanvas.threshold = tree.getThreshold();
500
501           if (tree.getCurrentTree())
502           {
503             af.viewport.setCurrentTree(tp.getTree());
504           }
505         }
506
507       } catch (Exception ex)
508       {
509         ex.printStackTrace();
510       }
511
512     }
513
514     return af;
515   }
516 }