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