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