right align ids
[jalview.git] / src / jalview / gui / Jalview2XML.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21
22 import jalview.schemes.*;
23
24 import jalview.gui.*;
25
26 import java.io.*;
27
28 import java.net.*;
29
30 import java.util.*;
31
32 import java.util.jar.*;
33
34 import javax.swing.*;
35
36 import org.exolab.castor.xml.*;
37
38 import jalview.schemabinding.version2.*;
39
40
41
42
43 /**
44  * DOCUMENT ME!
45  *
46  * @author $author$
47  * @version $Revision$
48  */
49 public class Jalview2XML
50 {
51
52   Hashtable seqRefIds;
53
54   /**
55    * This maintains a list of viewports, the key being the
56    * seqSetId. Important to set historyItem and redoList
57    * for multiple views
58    */
59   Hashtable viewportsAdded;
60
61   String uniqueSetSuffix = "";
62
63
64     // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
65     public void SaveState(File statefile)
66     {
67         JInternalFrame[] frames = Desktop.desktop.getAllFrames();
68
69         if (frames == null)
70         {
71             return;
72         }
73
74         try
75         {
76             FileOutputStream fos = new FileOutputStream(statefile);
77             JarOutputStream jout = new JarOutputStream(fos);
78
79             //NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
80             ////////////////////////////////////////////////////
81             PrintWriter out = new PrintWriter(new OutputStreamWriter(jout,
82                         "UTF-8"));
83
84             Vector shortNames = new Vector();
85
86             //REVERSE ORDER
87             for (int i = frames.length - 1; i > -1; i--)
88             {
89                 if (frames[i] instanceof AlignFrame)
90                 {
91                     AlignFrame af = (AlignFrame) frames[i];
92
93                     String shortName = af.getTitle();
94
95                     if (shortName.indexOf(File.separatorChar) > -1)
96                     {
97                         shortName = shortName.substring(shortName.lastIndexOf(
98                                     File.separatorChar) + 1);
99                     }
100
101                     int count = 1;
102
103                     while (shortNames.contains(shortName))
104                     {
105                         if (shortName.endsWith("_" + (count - 1)))
106                         {
107                             shortName = shortName.substring(0,
108                                     shortName.lastIndexOf("_"));
109                         }
110
111                         shortName = shortName.concat("_" + count);
112                         count++;
113                     }
114
115                     shortNames.addElement(shortName);
116
117                     if (!shortName.endsWith(".xml"))
118                     {
119                         shortName = shortName + ".xml";
120                     }
121
122                     int ap, apSize= af.alignPanels.size();
123                     for (ap = 0; ap < apSize; ap++)
124                     {
125                       AlignmentPanel apanel = (AlignmentPanel) af.alignPanels.
126                           elementAt(ap);
127
128                       SaveState(apanel,
129                                 apSize == 1 ? shortName : ap+shortName,
130                                 jout, out);
131                     }
132                 }
133             }
134
135             out.close();
136             jout.close();
137         }
138         catch (Exception ex)
139         {
140             ex.printStackTrace();
141         }
142     }
143
144     // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
145     public void SaveAlignment(AlignFrame af, String jarFile,
146         String fileName)
147     {
148         try
149         {
150           int ap, apSize= af.alignPanels.size();
151           FileOutputStream fos = new FileOutputStream(jarFile);
152           JarOutputStream jout = new JarOutputStream(fos);
153           PrintWriter out = new PrintWriter(new OutputStreamWriter(jout,
154                 "UTF-8"));
155           for( ap=0; ap<apSize; ap++)
156           {
157             AlignmentPanel apanel = (AlignmentPanel)af.alignPanels.elementAt(ap);
158
159             SaveState(apanel,
160                       apSize==1?fileName:fileName+ap,
161                       jout, out);
162           }
163
164           out.close();
165           jout.close();
166         }
167         catch (Exception ex)
168         {
169           ex.printStackTrace();
170         }
171     }
172
173     /**
174      * DOCUMENT ME!
175      *
176      * @param af DOCUMENT ME!
177      * @param timeStamp DOCUMENT ME!
178      * @param fileName DOCUMENT ME!
179      * @param jout DOCUMENT ME!
180      * @param out DOCUMENT ME!
181      */
182     public JalviewModel SaveState(AlignmentPanel ap,
183                           String fileName,
184                           JarOutputStream jout,
185                           PrintWriter out)
186     {
187       if (seqRefIds == null)
188         seqRefIds = new Hashtable();
189
190         Vector userColours = new Vector();
191
192         AlignViewport av = ap.av;
193
194         JalviewModel object = new JalviewModel();
195         object.setVamsasModel(new jalview.schemabinding.version2.VamsasModel());
196
197         object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
198         object.setVersion(jalview.bin.Cache.getProperty("VERSION"));
199
200         jalview.datamodel.AlignmentI jal = av.alignment;
201
202         if(av.hasHiddenRows)
203         {
204           jal = jal.getHiddenSequences().getFullAlignment();
205         }
206
207         SequenceSet vamsasSet = new SequenceSet();
208         Sequence vamsasSeq;
209         JalviewModelSequence jms = new JalviewModelSequence();
210
211         vamsasSet.setGapChar(jal.getGapCharacter() + "");
212
213         JSeq jseq;
214         Vector pdbfiles = null;
215
216         //SAVE SEQUENCES
217         int id = 0;
218         jalview.datamodel.SequenceI jds;
219         for (int i = 0; i < jal.getHeight(); i++)
220         {
221             jds = jal.getSequenceAt(i);
222             id = jds.hashCode();
223
224             if(seqRefIds.get(id+"")!=null)
225             {
226
227             }
228             else
229             {
230               vamsasSeq = new Sequence();
231               vamsasSeq.setId(id + "");
232               vamsasSeq.setName(jds.getName());
233               vamsasSeq.setSequence(jds.getSequence());
234               vamsasSeq.setDescription(jds.getDescription());
235
236               if (jds.getDatasetSequence().getDBRef() != null)
237               {
238                 jalview.datamodel.DBRefEntry[] dbrefs =
239                     jds.getDatasetSequence().getDBRef();
240
241                 for (int d = 0; d < dbrefs.length; d++)
242                 {
243                   DBRef dbref = new DBRef();
244                   dbref.setSource(dbrefs[d].getSource());
245                   dbref.setVersion(dbrefs[d].getVersion());
246                   dbref.setAccessionId(dbrefs[d].getAccessionId());
247                   vamsasSeq.addDBRef(dbref);
248                 }
249               }
250
251               vamsasSet.addSequence(vamsasSeq);
252               seqRefIds.put(id+"", jal.getSequenceAt(i));
253             }
254
255             jseq = new JSeq();
256             jseq.setStart(jds.getStart());
257             jseq.setEnd(jds.getEnd());
258             jseq.setColour( av.getSequenceColour(jds).getRGB());
259
260             jseq.setId(id);
261
262             if (av.hasHiddenRows)
263             {
264               jseq.setHidden(av.alignment.getHiddenSequences().isHidden(jds));
265
266               if(jal.getSequenceAt(i).getHiddenSequences()!=null)
267               {
268                 jalview.datamodel.SequenceI [] reps =
269                     jal.getSequenceAt(i).getHiddenSequences().getSequencesInOrder(jal);
270
271                 for(int h=0; h<reps.length; h++)
272                 {
273                   jseq.addHiddenSequences(
274                       jal.findIndex(reps[h])
275                       );
276                 }
277               }
278             }
279
280
281             if(jds.getDatasetSequence().getSequenceFeatures()!=null)
282             {
283               jalview.datamodel.SequenceFeature[] sf
284                   = jds.getDatasetSequence().getSequenceFeatures();
285               int index = 0;
286               while(index < sf.length)
287               {
288                 Features features = new Features();
289
290                 features.setBegin(sf[index].getBegin());
291                 features.setEnd(sf[index].getEnd());
292                 features.setDescription(sf[index].getDescription());
293                 features.setType(sf[index].getType());
294                 features.setFeatureGroup(sf[index].getFeatureGroup());
295                 features.setScore(sf[index].getScore());
296                 if(sf[index].links!=null)
297                 {
298                   for(int l=0; l<sf[index].links.size(); l++)
299                   {
300                     OtherData keyValue = new OtherData();
301                     keyValue.setKey("LINK_"+l);
302                     keyValue.setValue(sf[index].links.elementAt(l).toString());
303                     features.addOtherData(keyValue);
304                   }
305                 }
306                 if(sf[index].otherDetails!=null)
307                 {
308                   String key;
309                   Enumeration keys = sf[index].otherDetails.keys();
310                   while(keys.hasMoreElements())
311                   {
312                     key = keys.nextElement().toString();
313                     OtherData keyValue = new OtherData();
314                     keyValue.setKey( key );
315                     keyValue.setValue(
316                         sf[index].otherDetails.get(key).toString());
317                     features.addOtherData(keyValue);
318                   }
319                 }
320
321                 jseq.addFeatures(features);
322                 index ++;
323               }
324             }
325
326             if(jds.getDatasetSequence().getPDBId()!=null)
327             {
328               Enumeration en = jds.getDatasetSequence().getPDBId().elements();
329               while(en.hasMoreElements())
330               {
331                 Pdbids pdb = new Pdbids();
332                 jalview.datamodel.PDBEntry entry
333                    = (jalview.datamodel.PDBEntry)en.nextElement();
334
335                 pdb.setId(entry.getId());
336                 pdb.setType(entry.getType());
337
338                 if(entry.getFile()!=null)
339                 {
340                   if(pdbfiles==null)
341                     pdbfiles = new Vector();
342
343
344                   if(!pdbfiles.contains(entry.getId()))
345                   {
346                     pdbfiles.addElement(entry.getId());
347                     try
348                     {
349                       File file = new File(entry.getFile());
350                       if(file.exists())
351                       {
352                         byte[] data = new byte[ (int) file.length()];
353                         jout.putNextEntry(new JarEntry(entry.getId()));
354                         DataInputStream dis = new DataInputStream(new
355                             FileInputStream(file));
356                         dis.readFully(data);
357
358                         DataOutputStream dout = new DataOutputStream(jout);
359                         dout.write(data, 0, data.length);
360                         jout.closeEntry();
361                       }
362                     }
363                     catch (Exception ex)
364                     {
365                       ex.printStackTrace();
366                     }
367                   }
368                 }
369
370
371                 if(entry.getProperty()!=null)
372                 {
373                   PdbentryItem item = new PdbentryItem();
374                   Hashtable properties = entry.getProperty();
375                   Enumeration en2 = properties.keys();
376                   while(en2.hasMoreElements())
377                   {
378                     Property prop = new Property();
379                     String key = en2.nextElement().toString();
380                     prop.setName(key);
381                     prop.setValue( properties.get(key).toString() );
382                     item.addProperty(prop);
383                   }
384                   pdb.addPdbentryItem(item);
385                 }
386
387                 jseq.addPdbids(pdb);
388               }
389             }
390
391             jms.addJSeq(jseq);
392         }
393
394         if(av.hasHiddenRows)
395           jal = av.alignment;
396
397
398         //SAVE TREES
399         ///////////////////////////////////
400         if (av.currentTree != null)
401         {
402           // FIND ANY ASSOCIATED TREES
403           // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
404           if (Desktop.desktop != null)
405           {
406             JInternalFrame[] frames = Desktop.desktop.getAllFrames();
407
408             for (int t = 0; t < frames.length; t++)
409             {
410               if (frames[t] instanceof TreePanel)
411               {
412                 TreePanel tp = (TreePanel) frames[t];
413
414                 if (tp.treeCanvas.av.alignment == jal)
415                 {
416                   Tree tree = new Tree();
417                   tree.setTitle(tp.getTitle());
418                   tree.setCurrentTree( (av.currentTree == tp.getTree()));
419                   tree.setNewick(tp.getTree().toString());
420                   tree.setThreshold(tp.treeCanvas.threshold);
421
422                   tree.setFitToWindow(tp.fitToWindow.getState());
423                   tree.setFontName(tp.getTreeFont().getName());
424                   tree.setFontSize(tp.getTreeFont().getSize());
425                   tree.setFontStyle(tp.getTreeFont().getStyle());
426                   tree.setMarkUnlinked(tp.placeholdersMenu.getState());
427
428                   tree.setShowBootstrap(tp.bootstrapMenu.getState());
429                   tree.setShowDistances(tp.distanceMenu.getState());
430
431                   tree.setHeight(tp.getHeight());
432                   tree.setWidth(tp.getWidth());
433                   tree.setXpos(tp.getX());
434                   tree.setYpos(tp.getY());
435
436                   jms.addTree(tree);
437                 }
438               }
439             }
440           }
441         }
442
443         //SAVE ANNOTATIONS
444         if (jal.getAlignmentAnnotation() != null)
445         {
446             jalview.datamodel.AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
447
448             for (int i = 0; i < aa.length; i++)
449             {
450                 Annotation an = new Annotation();
451
452                 if (aa[i].label.equals("Quality") ||
453                         aa[i].label.equals("Conservation") ||
454                         aa[i].label.equals("Consensus"))
455                 {
456                     an.setLabel(aa[i].label);
457                     an.setGraph(true);
458                     vamsasSet.addAnnotation(an);
459                     continue;
460                 }
461
462
463                 an.setDescription(aa[i].description);
464
465                 if(aa[i].sequenceRef!=null)
466                  {
467                    an.setSequenceRef(aa[i].sequenceRef.getName());
468                  }
469
470                 if(aa[i].graph>0)
471                 {
472                   an.setGraph(true);
473                   an.setGraphType(aa[i].graph);
474                   an.setGraphGroup(aa[i].graphGroup);
475                   if(aa[i].getThreshold()!=null)
476                   {
477                     ThresholdLine line = new ThresholdLine();
478                     line.setLabel(aa[i].getThreshold().label);
479                     line.setValue(aa[i].getThreshold().value);
480                     line.setColour(aa[i].getThreshold().colour.getRGB());
481                     an.setThresholdLine(line);
482                   }
483                 }
484                 else
485                   an.setGraph(false);
486
487                 an.setLabel(aa[i].label);
488
489                 AnnotationElement ae;
490
491                 for (int a = 0; a < aa[i].annotations.length; a++)
492                 {
493                     if ((aa[i] == null) || (aa[i].annotations[a] == null))
494                     {
495                         continue;
496                     }
497
498                     ae = new AnnotationElement();
499                     ae.setDescription(aa[i].annotations[a].description);
500                     ae.setDisplayCharacter(aa[i].annotations[a].displayCharacter);
501                     ae.setValue(aa[i].annotations[a].value);
502                     ae.setPosition(a);
503                     ae.setSecondaryStructure(aa[i].annotations[a].secondaryStructure +
504                         "");
505
506                     if(aa[i].annotations[a].colour!=java.awt.Color.black)
507                       ae.setColour(aa[i].annotations[a].colour.getRGB());
508
509                     an.addAnnotationElement(ae);
510                 }
511
512                 vamsasSet.addAnnotation(an);
513             }
514         }
515
516         //SAVE GROUPS
517         if (jal.getGroups() != null)
518         {
519             JGroup[] groups = new JGroup[jal.getGroups().size()];
520
521             for (int i = 0; i < groups.length; i++)
522             {
523                 groups[i] = new JGroup();
524
525                 jalview.datamodel.SequenceGroup sg = (jalview.datamodel.SequenceGroup) jal.getGroups()
526                                                                                           .elementAt(i);
527                 groups[i].setStart(sg.getStartRes());
528                 groups[i].setEnd(sg.getEndRes());
529                 groups[i].setName(sg.getName());
530                 if(sg.cs!=null)
531                 {
532                   if (sg.cs.conservationApplied())
533                   {
534                     groups[i].setConsThreshold(sg.cs.getConservationInc());
535
536                     if (sg.cs instanceof jalview.schemes.UserColourScheme)
537                     {
538                       groups[i].setColour(SetUserColourScheme(sg.cs,
539                           userColours,
540                           jms));
541                     }
542                     else
543                     {
544                       groups[i].setColour(ColourSchemeProperty.getColourName(sg.
545                           cs));
546                     }
547                   }
548                   else if(sg.cs instanceof jalview.schemes.AnnotationColourGradient)
549                   {
550                     groups[i].setColour(
551                         ColourSchemeProperty.getColourName(
552                       ( (jalview.schemes.AnnotationColourGradient) sg.cs).getBaseColour()));
553                   }
554                   else if (sg.cs instanceof jalview.schemes.UserColourScheme)
555                   {
556                     groups[i].setColour(SetUserColourScheme(sg.cs, userColours,
557                         jms));
558                   }
559                   else
560                   {
561                     groups[i].setColour(ColourSchemeProperty.getColourName(
562                         sg.cs));
563                   }
564
565                   groups[i].setPidThreshold(sg.cs.getThreshold());
566                 }
567
568                 groups[i].setOutlineColour(sg.getOutlineColour().getRGB());
569                 groups[i].setDisplayBoxes(sg.getDisplayBoxes());
570                 groups[i].setDisplayText(sg.getDisplayText());
571                 groups[i].setColourText(sg.getColourText());
572                 groups[i].setTextCol1(sg.textColour.getRGB());
573                 groups[i].setTextCol2(sg.textColour2.getRGB());
574                 groups[i].setTextColThreshold(sg.thresholdTextColour);
575
576                 for (int s = 0; s < sg.getSize(false); s++)
577                 {
578                     jalview.datamodel.Sequence seq =
579                         (jalview.datamodel.Sequence) sg.getSequenceAt(s);
580                     groups[i].addSeq(seq.hashCode());
581                 }
582             }
583
584             jms.setJGroup(groups);
585         }
586
587
588         ///////////SAVE VIEWPORT
589         Viewport view = new Viewport();
590         view.setTitle(ap.alignFrame.getTitle());
591         view.setSequenceSetId(av.getSequenceSetId());
592         view.setViewName(av.viewName);
593         view.setGatheredViews(av.gatherViewsHere);
594
595
596         if (ap.av.explodedPosition != null)
597         {
598           view.setXpos(av.explodedPosition.x);
599           view.setYpos(av.explodedPosition.y);
600           view.setWidth(av.explodedPosition.width);
601           view.setHeight(av.explodedPosition.height);
602         }
603         else
604         {
605           view.setXpos(ap.alignFrame.getBounds().x);
606           view.setYpos(ap.alignFrame.getBounds().y);
607           view.setWidth(ap.alignFrame.getBounds().width);
608           view.setHeight(ap.alignFrame.getBounds().height);
609         }
610
611         view.setStartRes(av.startRes);
612         view.setStartSeq(av.startSeq);
613
614         if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
615         {
616             view.setBgColour(SetUserColourScheme(av.getGlobalColourScheme(),
617                     userColours, jms));
618         }
619         else if(av.getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
620         {
621            jalview.schemes.AnnotationColourGradient acg
622               = (jalview.schemes.AnnotationColourGradient)av.getGlobalColourScheme();
623
624             AnnotationColours ac = new AnnotationColours();
625             ac.setAboveThreshold(acg.getAboveThreshold());
626             ac.setThreshold(acg.getAnnotationThreshold());
627             ac.setAnnotation(acg.getAnnotation());
628             if(acg.getBaseColour() instanceof jalview.schemes.UserColourScheme)
629               ac.setColourScheme(SetUserColourScheme(acg.getBaseColour(),
630                     userColours, jms));
631             else
632               ac.setColourScheme(ColourSchemeProperty.getColourName(acg.getBaseColour()));
633
634             ac.setMaxColour(acg.getMaxColour().getRGB());
635             ac.setMinColour(acg.getMinColour().getRGB());
636             view.setAnnotationColours(ac);
637             view.setBgColour("AnnotationColourGradient");
638         }
639         else
640         {
641             view.setBgColour(ColourSchemeProperty.getColourName(
642                     av.getGlobalColourScheme()));
643         }
644
645         ColourSchemeI cs = av.getGlobalColourScheme();
646
647         if(cs!=null)
648         {
649           if (cs.conservationApplied())
650           {
651             view.setConsThreshold(cs.getConservationInc());
652             if (cs instanceof jalview.schemes.UserColourScheme)
653               view.setBgColour(SetUserColourScheme(cs, userColours, jms));
654           }
655
656           if (cs instanceof ResidueColourScheme)
657           {
658             view.setPidThreshold(cs.getThreshold());
659           }
660         }
661
662         view.setConservationSelected(av.getConservationSelected());
663         view.setPidSelected(av.getAbovePIDThreshold());
664         view.setFontName(av.font.getName());
665         view.setFontSize(av.font.getSize());
666         view.setFontStyle(av.font.getStyle());
667         view.setRenderGaps(av.renderGaps);
668         view.setShowAnnotation(av.getShowAnnotation());
669         view.setShowBoxes(av.getShowBoxes());
670         view.setShowColourText(av.getColourText());
671         view.setShowFullId(av.getShowJVSuffix());
672         view.setRightAlignIds(av.idsAlignRight);
673         view.setShowSequenceFeatures(av.showSequenceFeatures);
674         view.setShowText(av.getShowText());
675         view.setWrapAlignment(av.getWrapAlignment());
676         view.setTextCol1(av.textColour.getRGB());
677         view.setTextCol2(av.textColour2.getRGB());
678         view.setTextColThreshold(av.thresholdTextColour);
679
680
681         if(av.featuresDisplayed!=null)
682         {
683           jalview.schemabinding.version2.FeatureSettings fs
684               = new jalview.schemabinding.version2.FeatureSettings();
685
686           String [] renderOrder =
687               ap.seqPanel.seqCanvas.getFeatureRenderer().renderOrder;
688
689           Vector settingsAdded = new Vector();
690           for(int ro=0; ro<renderOrder.length; ro++)
691           {
692             Setting setting = new Setting();
693             setting.setType(renderOrder[ro]);
694             setting.setColour(
695                 ap.seqPanel.seqCanvas.getFeatureRenderer().getColour(renderOrder[ro]).getRGB()
696                 );
697
698             setting.setDisplay(
699                 av.featuresDisplayed.containsKey(renderOrder[ro])
700                 );
701
702             fs.addSetting(setting);
703             settingsAdded.addElement(renderOrder[ro]);
704           }
705
706           //Make sure we save none displayed feature settings
707           Enumeration en =
708               ap.seqPanel.seqCanvas.getFeatureRenderer().featureColours.keys();
709           while(en.hasMoreElements())
710           {
711             String key = en.nextElement().toString();
712             if(settingsAdded.contains(key))
713               continue;
714
715             Setting setting = new Setting();
716             setting.setType(key);
717             setting.setColour(
718                 ap.seqPanel.seqCanvas.getFeatureRenderer().getColour(key).getRGB()
719                 );
720
721             setting.setDisplay(false);
722
723             fs.addSetting(setting);
724             settingsAdded.addElement(key);
725           }
726
727           jms.setFeatureSettings(fs);
728
729         }
730
731         if(av.hasHiddenColumns)
732         {
733           for(int c=0; c<av.getColumnSelection().getHiddenColumns().size(); c++)
734           {
735             int [] region = (int[]) av.getColumnSelection().getHiddenColumns().elementAt(c);
736             HiddenColumns hc = new HiddenColumns();
737             hc.setStart(region[0]);
738             hc.setEnd(region[1]);
739             view.addHiddenColumns(hc);
740           }
741         }
742
743         jms.addViewport(view);
744
745
746         object.setJalviewModelSequence(jms);
747         object.getVamsasModel().addSequenceSet(vamsasSet);
748
749         if(out!=null)
750         {
751           //We may not want to right the object to disk,
752           //eg we can copy the alignViewport to a new view object
753           //using save and then load
754           try
755           {
756             if (!fileName.endsWith(".xml"))
757             {
758               fileName = fileName + ".xml";
759             }
760
761             JarEntry entry = new JarEntry(fileName);
762             jout.putNextEntry(entry);
763
764             object.marshal(out);
765           }
766           catch (Exception ex)
767           {
768             ex.printStackTrace();
769           }
770         }
771         return object;
772     }
773
774     String SetUserColourScheme(jalview.schemes.ColourSchemeI cs,
775         Vector userColours, JalviewModelSequence jms)
776     {
777         String id = null;
778         jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
779
780         if (!userColours.contains(ucs))
781         {
782             userColours.add(ucs);
783
784             java.awt.Color[] colours = ucs.getColours();
785             jalview.schemabinding.version2.UserColours uc = new jalview.schemabinding.version2.UserColours();
786             jalview.schemabinding.version2.UserColourScheme jbucs = new jalview.schemabinding.version2.UserColourScheme();
787
788             for (int i = 0; i < colours.length; i++)
789             {
790                 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
791                 col.setName(ResidueProperties.aa[i]);
792                 col.setRGB(jalview.util.Format.getHexString(colours[i]));
793                 jbucs.addColour(col);
794             }
795             if(ucs.getLowerCaseColours()!=null)
796             {
797               colours = ucs.getLowerCaseColours();
798               for (int i = 0; i < colours.length; i++)
799              {
800                  jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
801                  col.setName(ResidueProperties.aa[i].toLowerCase());
802                  col.setRGB(jalview.util.Format.getHexString(colours[i]));
803                  jbucs.addColour(col);
804              }
805             }
806
807             id = "ucs" + userColours.indexOf(ucs);
808             uc.setId(id);
809             uc.setUserColourScheme(jbucs);
810             jms.addUserColours(uc);
811         }
812
813         return id;
814     }
815
816    jalview.schemes.UserColourScheme GetUserColourScheme(
817         JalviewModelSequence jms, String id)
818     {
819         UserColours[] uc = jms.getUserColours();
820         UserColours colours = null;
821
822         for (int i = 0; i < uc.length; i++)
823         {
824             if (uc[i].getId().equals(id))
825             {
826                 colours = uc[i];
827
828                 break;
829             }
830         }
831
832         java.awt.Color[] newColours = new java.awt.Color[24];
833
834         for (int i = 0; i < 24; i++)
835         {
836             newColours[i] = new java.awt.Color(Integer.parseInt(
837                         colours.getUserColourScheme().getColour(i).getRGB(), 16));
838         }
839
840         jalview.schemes.UserColourScheme ucs =
841             new jalview.schemes.UserColourScheme(newColours);
842
843         if (colours.getUserColourScheme().getColourCount() > 24)
844         {
845           newColours = new java.awt.Color[23];
846           for (int i = 0; i < 23; i++)
847           {
848             newColours[i] = new java.awt.Color(Integer.parseInt(
849                 colours.getUserColourScheme().getColour(i+24).getRGB(), 16));
850           }
851           ucs.setLowerCaseColours(newColours);
852         }
853
854         return ucs;
855     }
856
857
858     /**
859      * DOCUMENT ME!
860      *
861      * @param file DOCUMENT ME!
862      */
863     public AlignFrame LoadJalviewAlign(final String file)
864     {
865         uniqueSetSuffix = System.currentTimeMillis()%100000 +"";
866
867         jalview.gui.AlignFrame af = null;
868
869         seqRefIds = new Hashtable();
870         viewportsAdded = new Hashtable();
871
872         Vector gatherToThisFrame= new Vector();
873
874         try
875         {
876             //UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
877             URL url = null;
878
879             if (file.startsWith("http://"))
880             {
881                 url = new URL(file);
882             }
883
884             JarInputStream jin = null;
885             JarEntry jarentry = null;
886             int entryCount = 1;
887
888             do
889             {
890                 if (url != null)
891                 {
892                     jin = new JarInputStream(url.openStream());
893                 }
894                 else
895                 {
896                     jin = new JarInputStream(new FileInputStream(file));
897                 }
898
899                 for (int i = 0; i < entryCount; i++)
900                 {
901                     jarentry = jin.getNextJarEntry();
902                 }
903
904                 if (jarentry != null && jarentry.getName().endsWith(".xml"))
905                 {
906                     InputStreamReader in = new InputStreamReader(jin, "UTF-8");
907                     JalviewModel object = new JalviewModel();
908
909                     Unmarshaller unmar = new Unmarshaller(object);
910                     unmar.setValidation(false);
911                     object = (JalviewModel) unmar.unmarshal( in );
912
913                     af = LoadFromObject(object, file, true);
914                     if(af.viewport.gatherViewsHere)
915                     {
916                       gatherToThisFrame.add(af);
917                     }
918                     entryCount++;
919                 }
920                 else if (jarentry != null)
921                 {
922                   //Some other file here.
923                   entryCount++;
924                 }
925             }
926             while (jarentry != null);
927         }
928         catch(java.net.UnknownHostException ex)
929         {
930           ex.printStackTrace();
931           System.err.println("Couldn't locate Jalview XML file : " +
932               ex + "\n");
933
934           javax.swing.SwingUtilities.invokeLater(new Runnable()
935           {
936             public void run()
937             {
938               JOptionPane.showInternalMessageDialog(Desktop.desktop,
939                   "Couldn't locate " + file,
940                   "URL not found",
941                   JOptionPane.WARNING_MESSAGE);
942             }
943           });
944         }
945         catch (Exception ex)
946         {
947           //Is Version 1 Jar file?
948           af =  new Jalview2XML_V1().LoadJalviewAlign(file);
949
950           if(af!=null)
951           {
952             System.out.println("Successfully loaded archive file");
953             return af;
954           }
955
956             System.err.println("Exception whilst loading jalview XML file : " +
957                 ex + "\n");
958             javax.swing.SwingUtilities.invokeLater(new Runnable()
959             {
960               public void run()
961               {
962
963                 JOptionPane.showInternalMessageDialog(Desktop.desktop,
964                     "Error loading  " + file,
965                     "Error loading Jalview file",
966                     JOptionPane.WARNING_MESSAGE);
967               }});
968         }
969
970         if (Desktop.instance != null)
971           Desktop.instance.stopLoading();
972
973         for (int i = 0; i < gatherToThisFrame.size(); i++)
974         {
975           Desktop.instance.gatherViews(
976               (AlignFrame) gatherToThisFrame.elementAt(i));
977         }
978
979         return af;
980     }
981
982     String loadPDBFile(String file, String pdbId)
983     {
984       try
985       {
986         JarInputStream jin = null;
987
988         if (file.startsWith("http://"))
989         {
990           jin = new JarInputStream(new URL(file).openStream());
991         }
992         else
993         {
994           jin = new JarInputStream(new FileInputStream(file));
995         }
996
997         JarEntry entry = null;
998         do
999         {
1000           entry = jin.getNextJarEntry();
1001         }
1002         while (!entry.getName().equals(pdbId));
1003
1004         BufferedReader in = new BufferedReader(new InputStreamReader(jin));
1005         File outFile = File.createTempFile("jalview_pdb", ".txt");
1006         outFile.deleteOnExit();
1007         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
1008         String data;
1009
1010         while ( (data = in.readLine()) != null)
1011         {
1012           out.println(data);
1013         }
1014         out.close();
1015         return outFile.getAbsolutePath();
1016
1017       }
1018       catch (Exception ex)
1019       {
1020         ex.printStackTrace();
1021       }
1022
1023       return null;
1024     }
1025
1026
1027     AlignFrame LoadFromObject(JalviewModel object,
1028                               String file,
1029                               boolean loadTrees )
1030     {
1031         SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
1032         Sequence[] vamsasSeq = vamsasSet.getSequence();
1033
1034         JalviewModelSequence jms = object.getJalviewModelSequence();
1035
1036         Viewport view = jms.getViewport(0);
1037
1038         //////////////////////////////////
1039         //LOAD SEQUENCES
1040
1041         Vector hiddenSeqs = null;
1042         jalview.datamodel.Sequence jseq;
1043
1044         ArrayList tmpseqs = new ArrayList();
1045
1046         boolean multipleView = false;
1047
1048         JSeq[] JSEQ = object.getJalviewModelSequence().getJSeq();
1049         for (int i = 0; i < JSEQ.length; i++)
1050         {
1051           String seqId = JSEQ[i].getId() + "";
1052
1053           if (seqRefIds.get(seqId) != null)
1054           {
1055             tmpseqs.add( (jalview.datamodel.Sequence) seqRefIds.get(seqId));
1056             multipleView = true;
1057           }
1058           else
1059           {
1060             jseq = new jalview.datamodel.Sequence(vamsasSeq[i].getName(),
1061                 vamsasSeq[i].getSequence());
1062             jseq.setDescription(vamsasSeq[i].getDescription());
1063             jseq.setStart(JSEQ[i].getStart());
1064             jseq.setEnd(JSEQ[i].getEnd());
1065             seqRefIds.put(vamsasSeq[i].getId(), jseq);
1066             tmpseqs.add( jseq );
1067           }
1068
1069
1070
1071           if (JSEQ[i].getHidden())
1072           {
1073             if (hiddenSeqs == null)
1074               hiddenSeqs = new Vector();
1075
1076
1077             hiddenSeqs.addElement(
1078                 (jalview.datamodel.Sequence) seqRefIds.get(seqId));
1079           }
1080
1081         }
1082
1083         ///SequenceFeatures are added to the DatasetSequence,
1084         // so we must create the dataset before loading features
1085         /////////////////////////////////
1086
1087
1088       jalview.datamodel.Sequence[] orderedSeqs = new jalview.datamodel.Sequence[
1089           tmpseqs.size()];
1090
1091        tmpseqs.toArray(orderedSeqs) ;
1092
1093
1094         jalview.datamodel.Alignment al =
1095             new jalview.datamodel.Alignment(orderedSeqs);
1096
1097         al.setDataset(null);
1098         /////////////////////////////////
1099
1100
1101         Hashtable pdbloaded = new Hashtable();
1102         if(!multipleView)
1103         {
1104           for (int i = 0; i < vamsasSeq.length; i++)
1105           {
1106             if (JSEQ[i].getFeaturesCount() > 0)
1107             {
1108               Features[] features = JSEQ[i].getFeatures();
1109               for (int f = 0; f < features.length; f++)
1110               {
1111                 jalview.datamodel.SequenceFeature sf
1112                     = new jalview.datamodel.SequenceFeature(features[f].getType(),
1113                     features[f].getDescription(), features[f].getStatus(),
1114                     features[f].getBegin(), features[f].getEnd(),
1115                     features[f].getFeatureGroup());
1116
1117                 sf.setScore(features[f].getScore());
1118                 for (int od = 0; od < features[f].getOtherDataCount(); od++)
1119                 {
1120                   OtherData keyValue = features[f].getOtherData(od);
1121                   if (keyValue.getKey().startsWith("LINK"))
1122                     sf.addLink(keyValue.getValue());
1123                   else
1124                     sf.setValue(keyValue.getKey(), keyValue.getValue());
1125
1126                 }
1127
1128                 al.getSequenceAt(i).getDatasetSequence().addSequenceFeature(sf);
1129               }
1130             }
1131             if (JSEQ[i].getPdbidsCount() > 0)
1132             {
1133               Pdbids[] ids = JSEQ[i].getPdbids();
1134               for (int p = 0; p < ids.length; p++)
1135               {
1136                 jalview.datamodel.PDBEntry entry = new jalview.datamodel.
1137                     PDBEntry();
1138                 entry.setId(ids[p].getId());
1139                 entry.setType(ids[p].getType());
1140                 if (ids[p].getFile() != null)
1141                 {
1142                   if (!pdbloaded.containsKey(ids[p].getFile()))
1143                   {
1144                     String tmppdb = loadPDBFile(file, ids[p].getId());
1145                     entry.setFile(tmppdb);
1146                     pdbloaded.put(ids[p].getId(), tmppdb);
1147                   }
1148                   else
1149                     entry.setFile(pdbloaded.get(ids[p].getId()).toString());
1150                 }
1151
1152                 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
1153               }
1154             }
1155             if (vamsasSeq[i].getDBRefCount() > 0)
1156             {
1157               for (int d = 0; d < vamsasSeq[i].getDBRefCount(); d++)
1158               {
1159                 jalview.datamodel.DBRefEntry entry =
1160                     new jalview.datamodel.DBRefEntry(
1161                         vamsasSeq[i].getDBRef(d).getSource(),
1162                         vamsasSeq[i].getDBRef(d).getVersion(),
1163                         vamsasSeq[i].getDBRef(d).getAccessionId()
1164                     );
1165                 al.getSequenceAt(i).getDatasetSequence().addDBRef(entry);
1166               }
1167
1168             }
1169           }
1170         }
1171
1172
1173          /////////////////////////////////
1174         //////////////////////////////////
1175         //LOAD ANNOTATIONS
1176         boolean hideQuality = true,
1177             hideConservation = true,
1178             hideConsensus = true;
1179
1180         if (vamsasSet.getAnnotationCount()>0)
1181         {
1182             Annotation[] an = vamsasSet.getAnnotation();
1183
1184             for (int i = 0; i < an.length; i++)
1185             {
1186                if (an[i].getLabel().equals("Quality"))
1187                 {
1188                  hideQuality = false;
1189                  continue;
1190                 }
1191                else if(an[i].getLabel().equals("Conservation"))
1192                {
1193                  hideConservation = false;
1194                  continue;
1195                }
1196                else if(an[i].getLabel().equals("Consensus"))
1197                {
1198                  hideConsensus = false;
1199                  continue;
1200                }
1201
1202                 AnnotationElement[] ae = an[i].getAnnotationElement();
1203                 jalview.datamodel.Annotation[] anot = new jalview.datamodel.Annotation[al.getWidth()];
1204
1205                 for (int aa = 0; aa < ae.length; aa++)
1206                 {
1207                     anot[ae[aa].getPosition()] = new jalview.datamodel.Annotation(ae[aa].getDisplayCharacter(),
1208                             ae[aa].getDescription(),
1209                             ae[aa].getSecondaryStructure().length()==0?' ':ae[aa].getSecondaryStructure().charAt(0),
1210                             ae[aa].getValue());
1211                     anot[ae[aa].getPosition()].colour = new java.awt.Color( ae[aa].getColour() );
1212                 }
1213
1214                 jalview.datamodel.AlignmentAnnotation jaa = null;
1215
1216                 if (an[i].getGraph())
1217                 {
1218                   jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
1219                       an[i].getDescription(), anot, 0, 0,
1220                       an[i].getGraphType());
1221
1222                   jaa.graphGroup = an[i].getGraphGroup();
1223
1224                   if (an[i].getThresholdLine() != null)
1225                   {
1226                     jaa.setThreshold(new jalview.datamodel.GraphLine(
1227                                   an[i].getThresholdLine().getValue(),
1228                                   an[i].getThresholdLine().getLabel(),
1229                                 new java.awt.Color(an[i].getThresholdLine().getColour()))
1230                              );
1231
1232                   }
1233
1234                 }
1235                 else
1236                 {
1237                     jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
1238                             an[i].getDescription(), anot);
1239                 }
1240
1241                 if(an[i].getSequenceRef()!=null)
1242                 {
1243                   jaa.createSequenceMapping(
1244                       al.findName(an[i].getSequenceRef()), 1, true
1245                       );
1246                   al.findName(an[i].getSequenceRef()).addAlignmentAnnotation(jaa);
1247                 }
1248
1249                 al.addAnnotation(jaa);
1250             }
1251         }
1252
1253         /////////////////////////
1254         //LOAD GROUPS
1255         if (jms.getJGroupCount() > 0)
1256         {
1257             JGroup[] groups = jms.getJGroup();
1258
1259             for (int i = 0; i < groups.length; i++)
1260             {
1261                 ColourSchemeI cs = null;
1262
1263                 if (groups[i].getColour() != null)
1264                 {
1265                     if (groups[i].getColour().startsWith("ucs"))
1266                     {
1267                         cs = GetUserColourScheme(jms, groups[i].getColour());
1268                     }
1269                     else
1270                     {
1271                         cs = ColourSchemeProperty.getColour(al,
1272                                 groups[i].getColour());
1273                     }
1274
1275                     if(cs!=null)
1276                       cs.setThreshold(groups[i].getPidThreshold(), true);
1277                 }
1278
1279                 Vector seqs = new Vector();
1280
1281                 for (int s = 0; s < groups[i].getSeqCount(); s++)
1282                 {
1283                     String seqId = groups[i].getSeq(s)+"";
1284                     seqs.addElement((jalview.datamodel.SequenceI) seqRefIds.get(seqId));
1285                 }
1286
1287                 jalview.datamodel.SequenceGroup sg = new jalview.datamodel.SequenceGroup(seqs,
1288                         groups[i].getName(), cs, groups[i].getDisplayBoxes(),
1289                         groups[i].getDisplayText(), groups[i].getColourText(),
1290                         groups[i].getStart(), groups[i].getEnd());
1291
1292                 sg.setOutlineColour(new java.awt.Color(
1293                         groups[i].getOutlineColour()));
1294
1295                 sg.textColour = new java.awt.Color(groups[i].getTextCol1());
1296                 sg.textColour2 = new java.awt.Color(groups[i].getTextCol2());
1297                 sg.thresholdTextColour = groups[i].getTextColThreshold();
1298
1299                 if (groups[i].getConsThreshold() != 0)
1300                 {
1301                     jalview.analysis.Conservation c = new jalview.analysis.Conservation("All",
1302                             ResidueProperties.propHash, 3, sg.getSequences(false), 0,
1303                             sg.getWidth() - 1);
1304                     c.calculate();
1305                     c.verdict(false, 25);
1306                     sg.cs.setConservation(c);
1307                 }
1308
1309                 al.addGroup(sg);
1310             }
1311         }
1312
1313
1314         /////////////////////////////////
1315         // LOAD VIEWPORT
1316
1317         AlignFrame af = new AlignFrame(al,
1318                                        view.getWidth(),
1319                                        view.getHeight() );
1320
1321         af.setFileName(file, "Jalview");
1322
1323         for (int i = 0; i < JSEQ.length; i++)
1324         {
1325           af.viewport.setSequenceColour(
1326               af.viewport.alignment.getSequenceAt(i),
1327               new java.awt.Color(
1328                   JSEQ[i].getColour()));
1329         }
1330
1331         //If we just load in the same jar file again, the sequenceSetId
1332         //will be the same, and we end up with multiple references
1333         //to the same sequenceSet. We must modify this id on load
1334         //so that each load of the file gives a unique id
1335         String uniqueSeqSetId =  view.getSequenceSetId()+uniqueSetSuffix;
1336
1337         af.viewport.gatherViewsHere = view.getGatheredViews();
1338
1339         if (view.getSequenceSetId() != null)
1340         {
1341           jalview.gui.AlignViewport av =
1342               (jalview.gui.AlignViewport)
1343               viewportsAdded.get(uniqueSeqSetId);
1344
1345           af.viewport.sequenceSetID = uniqueSeqSetId;
1346           if(av!=null)
1347           {
1348
1349             af.viewport.historyList = av.historyList;
1350             af.viewport.redoList = av.redoList;
1351           }
1352           else
1353           {
1354             viewportsAdded.put(uniqueSeqSetId, af.viewport);
1355           }
1356
1357           PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
1358         }
1359         if(hiddenSeqs!=null)
1360         {
1361           for(int s=0; s<JSEQ.length; s++)
1362           {
1363             for(int r=0; r<JSEQ[s].getHiddenSequencesCount(); r++)
1364             {
1365               al.getSequenceAt(s).addHiddenSequence(
1366                   al.getSequenceAt( JSEQ[s].getHiddenSequences(r)  )
1367                   );
1368             }
1369           }
1370
1371           jalview.datamodel.SequenceI [] hseqs = new
1372               jalview.datamodel.SequenceI[hiddenSeqs.size()];
1373
1374           for(int s=0; s<hiddenSeqs.size(); s++)
1375             hseqs[s] = (jalview.datamodel.SequenceI)hiddenSeqs.elementAt(s);
1376
1377           af.viewport.hideSequence( hseqs );
1378
1379         }
1380
1381
1382         if((hideConsensus || hideQuality || hideConservation)
1383             && al.getAlignmentAnnotation()!=null)
1384         {
1385           int hSize = al.getAlignmentAnnotation().length;
1386           for (int h = 0; h < hSize; h++)
1387           {
1388             if (
1389                 (hideConsensus &&
1390                  al.getAlignmentAnnotation()[h].label.equals("Consensus"))
1391                 ||
1392                 (hideQuality &&
1393                  al.getAlignmentAnnotation()[h].label.equals("Quality"))
1394                 ||
1395                 (hideConservation &&
1396                  al.getAlignmentAnnotation()[h].label.equals("Conservation")))
1397             {
1398               al.deleteAnnotation(al.getAlignmentAnnotation()[h]);
1399               hSize--;
1400               h--;
1401             }
1402           }
1403           af.alignPanel.adjustAnnotationHeight();
1404         }
1405
1406         af.viewport.viewName = view.getViewName();
1407         af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(),
1408             view.getHeight());
1409         af.viewport.setStartRes(view.getStartRes());
1410         af.viewport.setStartSeq(view.getStartSeq());
1411         af.viewport.setShowAnnotation(view.getShowAnnotation());
1412         af.viewport.setAbovePIDThreshold(view.getPidSelected());
1413
1414         af.viewport.setColourText(view.getShowColourText());
1415
1416         af.viewport.setConservationSelected(view.getConservationSelected());
1417         af.viewport.setShowJVSuffix(view.getShowFullId());
1418         af.viewport.idsAlignRight=view.getRightAlignIds();
1419         af.viewport.setFont(new java.awt.Font(view.getFontName(),
1420                 view.getFontStyle(), view.getFontSize()));
1421         af.alignPanel.fontChanged();
1422         af.viewport.setRenderGaps(view.getRenderGaps());
1423         af.viewport.setWrapAlignment(view.getWrapAlignment());
1424         af.alignPanel.setWrapAlignment(view.getWrapAlignment());
1425         af.viewport.setShowAnnotation(view.getShowAnnotation());
1426         af.alignPanel.setAnnotationVisible(view.getShowAnnotation());
1427
1428         af.viewport.setShowBoxes(view.getShowBoxes());
1429
1430         af.viewport.setShowText(view.getShowText());
1431
1432         af.viewport.textColour = new java.awt.Color(view.getTextCol1());
1433         af.viewport.textColour2 = new java.awt.Color(view.getTextCol2());
1434         af.viewport.thresholdTextColour = view.getTextColThreshold();
1435
1436
1437         ColourSchemeI cs = null;
1438
1439         if (view.getBgColour() != null)
1440         {
1441             if (view.getBgColour().startsWith("ucs"))
1442             {
1443                 cs = GetUserColourScheme(jms, view.getBgColour());
1444             }
1445             else if(view.getBgColour().startsWith("Annotation"))
1446             {
1447               //int find annotation
1448               for (int i = 0; i < af.viewport.alignment.getAlignmentAnnotation().length; i++)
1449               {
1450                 if (af.viewport.alignment.getAlignmentAnnotation()[i].label.
1451                     equals(view.getAnnotationColours().getAnnotation()))
1452                 {
1453                   if (af.viewport.alignment.getAlignmentAnnotation()[i].
1454                       getThreshold() == null)
1455                   {
1456                     af.viewport.alignment.getAlignmentAnnotation()[i].
1457                         setThreshold(
1458                             new jalview.datamodel.GraphLine(
1459                                 view.getAnnotationColours().getThreshold(),
1460                                 "Threshold", java.awt.Color.black)
1461
1462                         );
1463                   }
1464
1465
1466                   if (view.getAnnotationColours().getColourScheme().equals(
1467                       "None"))
1468                   {
1469                     cs = new AnnotationColourGradient(
1470                         af.viewport.alignment.getAlignmentAnnotation()[i],
1471                         new java.awt.Color(view.getAnnotationColours().
1472                                            getMinColour()),
1473                         new java.awt.Color(view.getAnnotationColours().
1474                                            getMaxColour()),
1475                         view.getAnnotationColours().getAboveThreshold());
1476                   }
1477                   else if (view.getAnnotationColours().getColourScheme().
1478                            startsWith("ucs"))
1479                   {
1480                      cs = new AnnotationColourGradient(
1481                          af.viewport.alignment.getAlignmentAnnotation()[i],
1482                          GetUserColourScheme(jms, view.getAnnotationColours().
1483                                                         getColourScheme()),
1484                          view.getAnnotationColours().getAboveThreshold()
1485                          );
1486                    }
1487                    else
1488                    {
1489                      cs = new AnnotationColourGradient(
1490                          af.viewport.alignment.getAlignmentAnnotation()[i],
1491                          ColourSchemeProperty.getColour(al,
1492                          view.getAnnotationColours().getColourScheme()),
1493                          view.getAnnotationColours().getAboveThreshold()
1494                          );
1495                    }
1496
1497                   // Also use these settings for all the groups
1498                   if (al.getGroups() != null)
1499                     for (int g = 0; g < al.getGroups().size(); g++)
1500                     {
1501                       jalview.datamodel.SequenceGroup sg
1502                           = (jalview.datamodel.SequenceGroup)al.getGroups().elementAt(g);
1503
1504                       if(sg.cs == null)
1505                         continue;
1506
1507
1508                   /*    if (view.getAnnotationColours().getColourScheme().equals("None"))
1509                       {
1510                         sg.cs = new AnnotationColourGradient(
1511                             af.viewport.alignment.getAlignmentAnnotation()[i],
1512                             new java.awt.Color(view.getAnnotationColours().
1513                                                getMinColour()),
1514                             new java.awt.Color(view.getAnnotationColours().
1515                                                getMaxColour()),
1516                             view.getAnnotationColours().getAboveThreshold());
1517                       }
1518                       else*/
1519                       {
1520                         sg.cs = new AnnotationColourGradient(
1521                             af.viewport.alignment.getAlignmentAnnotation()[i],
1522                             sg.cs,
1523                             view.getAnnotationColours().getAboveThreshold()
1524                             );
1525                       }
1526
1527                     }
1528
1529
1530                   break;
1531                 }
1532
1533               }
1534             }
1535             else
1536             {
1537                 cs = ColourSchemeProperty.getColour(al, view.getBgColour());
1538             }
1539
1540             if(cs!=null)
1541             {
1542               cs.setThreshold(view.getPidThreshold(), true);
1543               cs.setConsensus(af.viewport.hconsensus);
1544             }
1545         }
1546
1547
1548         af.viewport.setGlobalColourScheme(cs);
1549         af.viewport.setColourAppliesToAllGroups(false);
1550
1551         if (view.getConservationSelected() && cs!=null)
1552         {
1553           cs.setConservationInc(view.getConsThreshold());
1554         }
1555
1556         af.changeColour(cs);
1557
1558         af.viewport.setColourAppliesToAllGroups(true);
1559
1560
1561
1562         if (view.getShowSequenceFeatures())
1563         {
1564            af.viewport.showSequenceFeatures = true;
1565         }
1566
1567         if(jms.getFeatureSettings()!=null)
1568         {
1569           af.viewport.featuresDisplayed = new Hashtable();
1570           String [] renderOrder = new String[jms.getFeatureSettings().getSettingCount()];
1571          for(int fs=0; fs<jms.getFeatureSettings().getSettingCount(); fs++)
1572          {
1573            Setting setting = jms.getFeatureSettings().getSetting(fs);
1574
1575            af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setColour(setting.getType(),
1576                new java.awt.Color(setting.getColour()));
1577
1578            renderOrder[fs] = setting.getType();
1579
1580            if(setting.getDisplay())
1581              af.viewport.featuresDisplayed.put(
1582                  setting.getType(), new Integer(setting.getColour()));
1583          }
1584          af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().renderOrder = renderOrder;
1585         }
1586
1587         if (view.getHiddenColumnsCount() > 0)
1588         {
1589           for (int c = 0; c < view.getHiddenColumnsCount(); c++)
1590           {
1591               af.viewport.hideColumns(
1592                 view.getHiddenColumns(c).getStart(),
1593                 view.getHiddenColumns(c).getEnd() //+1
1594                 );
1595           }
1596         }
1597
1598         af.setMenusFromViewport(af.viewport);
1599
1600
1601         Desktop.addInternalFrame(af, view.getTitle(),
1602              view.getWidth(), view.getHeight());
1603
1604         //LOAD TREES
1605         ///////////////////////////////////////
1606         if (loadTrees && jms.getTreeCount() > 0)
1607         {
1608             try
1609             {
1610                 for (int t = 0; t < jms.getTreeCount(); t++)
1611                 {
1612
1613                     Tree tree = jms.getTree(t);
1614
1615                     TreePanel tp = af.ShowNewickTree(new jalview.io.NewickFile(
1616                                 tree.getNewick()), tree.getTitle(),
1617                                 tree.getWidth(), tree.getHeight(),
1618                                 tree.getXpos(), tree.getYpos());
1619
1620                     tp.fitToWindow.setState(tree.getFitToWindow());
1621                     tp.fitToWindow_actionPerformed(null);
1622
1623                     if(tree.getFontName()!=null)
1624                       tp.setTreeFont(new java.awt.Font(tree.getFontName(),
1625                                           tree.getFontStyle(),
1626                                           tree.getFontSize()));
1627                     else
1628                       tp.setTreeFont(new java.awt.Font(view.getFontName(),
1629                                             view.getFontStyle(),
1630                                             tree.getFontSize()));
1631
1632                     tp.showPlaceholders(tree.getMarkUnlinked());
1633                     tp.showBootstrap(tree.getShowBootstrap());
1634                     tp.showDistances(tree.getShowDistances());
1635
1636                     tp.treeCanvas.threshold = tree.getThreshold();
1637
1638                     if (tree.getCurrentTree())
1639                       af.viewport.setCurrentTree(tp.getTree());
1640                 }
1641
1642             }
1643             catch (Exception ex)
1644             {
1645                 ex.printStackTrace();
1646             }
1647
1648         }
1649
1650         return af;
1651     }
1652
1653     public jalview.gui.AlignmentPanel copyAlignPanel(AlignmentPanel ap, boolean keepSeqRefs )
1654     {
1655       jalview.schemabinding.version2.JalviewModel jm
1656           = SaveState(ap, null, null, null);
1657
1658       if (!keepSeqRefs)
1659       {
1660         seqRefIds.clear();
1661         jm.getJalviewModelSequence().getViewport(0).setSequenceSetId(null);
1662       }
1663       else
1664         uniqueSetSuffix = "";
1665
1666       viewportsAdded = new Hashtable();
1667
1668       AlignFrame af = LoadFromObject(jm, null, false);
1669       af.alignPanels.clear();
1670       af.closeMenuItem_actionPerformed(true);
1671
1672       return af.alignPanel;
1673     }
1674 }
1675