2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3 * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
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.
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.
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
21 import java.awt.Rectangle;
25 import java.util.jar.*;
29 import org.exolab.castor.xml.*;
31 import uk.ac.vamsas.objects.utils.MapList;
32 import jalview.bin.Cache;
33 import jalview.datamodel.Alignment;
34 import jalview.datamodel.AlignmentI;
35 import jalview.datamodel.SequenceI;
36 import jalview.schemabinding.version2.*;
37 import jalview.schemes.*;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.util.jarInputStreamProvider;
42 * Write out the current jalview desktop state as a Jalview XML stream.
44 * Note: the vamsas objects referred to here are primitive versions of the
45 * VAMSAS project schema elements - they are not the same and most likely never
51 public class Jalview2XML
54 * create/return unique hash string for sq
57 * @return new or existing unique string for sq
59 String seqHash(SequenceI sq)
61 if (seqsToIds == null)
65 if (seqsToIds.containsKey(sq))
67 return (String) seqsToIds.get(sq);
71 // create sequential key
72 String key = "sq" + (seqsToIds.size() + 1);
73 key = makeHashCode(sq, key); // check we don't have an external reference
75 seqsToIds.put(sq, key);
84 if (seqRefIds != null)
88 if (seqsToIds != null)
98 warn("clearSeqRefs called when _cleartables was not set. Doing nothing.");
99 // seqRefIds = new Hashtable();
100 // seqsToIds = new IdentityHashMap();
106 if (seqsToIds == null)
108 seqsToIds = new IdentityHashMap();
110 if (seqRefIds == null)
112 seqRefIds = new Hashtable();
117 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
118 * of sequence objects are created.
120 java.util.IdentityHashMap seqsToIds = null;
123 * jalview XML Sequence ID to jalview sequence object reference (both dataset
124 * and alignment sequences. Populated as XML reps of sequence objects are
127 java.util.Hashtable seqRefIds = null; // key->SequenceI resolution
129 Vector frefedSequence = null;
131 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
137 public Jalview2XML(boolean raiseGUI)
139 this.raiseGUI = raiseGUI;
142 public void resolveFrefedSequences()
144 if (frefedSequence.size() > 0)
146 int r = 0, rSize = frefedSequence.size();
149 Object[] ref = (Object[]) frefedSequence.elementAt(r);
152 String sref = (String) ref[0];
153 if (seqRefIds.containsKey(sref))
155 if (ref[1] instanceof jalview.datamodel.Mapping)
157 SequenceI seq = (SequenceI) seqRefIds.get(sref);
158 while (seq.getDatasetSequence() != null)
160 seq = seq.getDatasetSequence();
162 ((jalview.datamodel.Mapping) ref[1]).setTo(seq);
166 if (ref[1] instanceof jalview.datamodel.AlignedCodonFrame)
168 SequenceI seq = (SequenceI) seqRefIds.get(sref);
169 while (seq.getDatasetSequence() != null)
171 seq = seq.getDatasetSequence();
174 && ref[2] instanceof jalview.datamodel.Mapping)
176 jalview.datamodel.Mapping mp = (jalview.datamodel.Mapping) ref[2];
177 ((jalview.datamodel.AlignedCodonFrame) ref[1]).addMap(
178 seq, mp.getTo(), mp.getMap());
183 .println("IMPLEMENTATION ERROR: Unimplemented forward sequence references for AlcodonFrames involving "
184 + ref[2].getClass() + " type objects.");
190 .println("IMPLEMENTATION ERROR: Unimplemented forward sequence references for "
191 + ref[1].getClass() + " type objects.");
194 frefedSequence.remove(r);
200 .println("IMPLEMENTATION WARNING: Unresolved forward reference for hash string "
202 + " with objecttype "
203 + ref[1].getClass());
210 frefedSequence.remove(r);
218 * This maintains a list of viewports, the key being the seqSetId. Important
219 * to set historyItem and redoList for multiple views
221 Hashtable viewportsAdded;
223 Hashtable annotationIds = new Hashtable();
225 String uniqueSetSuffix = "";
228 * List of pdbfiles added to Jar
230 Vector pdbfiles = null;
232 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
233 public void SaveState(File statefile)
237 FileOutputStream fos = new FileOutputStream(statefile);
238 JarOutputStream jout = new JarOutputStream(fos);
241 } catch (Exception e)
243 // TODO: inform user of the problem - they need to know if their data was
245 if (errorMessage == null)
247 errorMessage = "Couldn't write Jalview Archive to output file '"
248 + statefile + "' - See console error log for details";
252 errorMessage += "(output file was '" + statefile + "')";
260 * Writes a jalview project archive to the given Jar output stream.
264 public void SaveState(JarOutputStream jout)
266 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
276 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
277 // //////////////////////////////////////////////////
278 // NOTE ALSO new PrintWriter must be used for each new JarEntry
279 PrintWriter out = null;
281 Vector shortNames = new Vector();
284 for (int i = frames.length - 1; i > -1; i--)
286 if (frames[i] instanceof AlignFrame)
288 AlignFrame af = (AlignFrame) frames[i];
291 && skipList.containsKey(af.getViewport()
292 .getSequenceSetId()))
297 String shortName = af.getTitle();
299 if (shortName.indexOf(File.separatorChar) > -1)
301 shortName = shortName.substring(shortName
302 .lastIndexOf(File.separatorChar) + 1);
307 while (shortNames.contains(shortName))
309 if (shortName.endsWith("_" + (count - 1)))
311 shortName = shortName
312 .substring(0, shortName.lastIndexOf("_"));
315 shortName = shortName.concat("_" + count);
319 shortNames.addElement(shortName);
321 if (!shortName.endsWith(".xml"))
323 shortName = shortName + ".xml";
326 int ap, apSize = af.alignPanels.size();
327 for (ap = 0; ap < apSize; ap++)
329 AlignmentPanel apanel = (AlignmentPanel) af.alignPanels
331 String fileName = apSize == 1 ? shortName : ap + shortName;
332 if (!fileName.endsWith(".xml"))
334 fileName = fileName + ".xml";
337 SaveState(apanel, fileName, jout);
344 } catch (Exception foo)
349 } catch (Exception ex)
351 // TODO: inform user of the problem - they need to know if their data was
353 if (errorMessage == null)
355 errorMessage = "Couldn't write Jalview Archive - see error output for details";
357 ex.printStackTrace();
361 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
362 public boolean SaveAlignment(AlignFrame af, String jarFile,
367 int ap, apSize = af.alignPanels.size();
368 FileOutputStream fos = new FileOutputStream(jarFile);
369 JarOutputStream jout = new JarOutputStream(fos);
370 for (ap = 0; ap < apSize; ap++)
372 AlignmentPanel apanel = (AlignmentPanel) af.alignPanels
374 String jfileName = apSize == 1 ? fileName : fileName + ap;
375 if (!jfileName.endsWith(".xml"))
377 jfileName = jfileName + ".xml";
379 SaveState(apanel, jfileName, jout);
385 } catch (Exception foo)
391 } catch (Exception ex)
393 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
394 ex.printStackTrace();
400 * create a JalviewModel from an algnment view and marshall it to a
404 * panel to create jalview model for
406 * name of alignment panel written to output stream
412 public JalviewModel SaveState(AlignmentPanel ap, String fileName,
413 JarOutputStream jout)
417 Vector userColours = new Vector();
419 AlignViewport av = ap.av;
421 JalviewModel object = new JalviewModel();
422 object.setVamsasModel(new jalview.schemabinding.version2.VamsasModel());
424 object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
425 object.setVersion(jalview.bin.Cache.getProperty("VERSION"));
427 jalview.datamodel.AlignmentI jal = av.alignment;
429 if (av.hasHiddenRows)
431 jal = jal.getHiddenSequences().getFullAlignment();
434 SequenceSet vamsasSet = new SequenceSet();
436 JalviewModelSequence jms = new JalviewModelSequence();
438 vamsasSet.setGapChar(jal.getGapCharacter() + "");
440 if (jal.getDataset() != null)
442 // dataset id is the dataset's hashcode
443 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
445 if (jal.getProperties() != null)
447 Enumeration en = jal.getProperties().keys();
448 while (en.hasMoreElements())
450 String key = en.nextElement().toString();
451 SequenceSetProperties ssp = new SequenceSetProperties();
453 ssp.setValue(jal.getProperties().get(key).toString());
454 vamsasSet.addSequenceSetProperties(ssp);
462 jalview.datamodel.SequenceI jds;
463 for (int i = 0; i < jal.getHeight(); i++)
465 jds = jal.getSequenceAt(i);
468 if (seqRefIds.get(id) != null)
470 // This happens for two reasons: 1. multiple views are being serialised.
471 // 2. the hashCode has collided with another sequence's code. This DOES
472 // HAPPEN! (PF00072.15.stk does this)
473 // JBPNote: Uncomment to debug writing out of files that do not read
474 // back in due to ArrayOutOfBoundExceptions.
475 // System.err.println("vamsasSeq backref: "+id+"");
476 // System.err.println(jds.getName()+"
477 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
478 // System.err.println("Hashcode: "+seqHash(jds));
479 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
480 // System.err.println(rsq.getName()+"
481 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
482 // System.err.println("Hashcode: "+seqHash(rsq));
486 vamsasSeq = createVamsasSequence(id, jds);
487 vamsasSet.addSequence(vamsasSeq);
488 seqRefIds.put(id, jds);
492 jseq.setStart(jds.getStart());
493 jseq.setEnd(jds.getEnd());
494 jseq.setColour(av.getSequenceColour(jds).getRGB());
496 jseq.setId(id); // jseq id should be a string not a number
498 if (av.hasHiddenRows)
500 jseq.setHidden(av.alignment.getHiddenSequences().isHidden(jds));
502 if (av.hiddenRepSequences != null
503 && av.hiddenRepSequences.containsKey(jal.getSequenceAt(i)))
505 jalview.datamodel.SequenceI[] reps = ((jalview.datamodel.SequenceGroup) av.hiddenRepSequences
506 .get(jal.getSequenceAt(i))).getSequencesInOrder(jal);
508 for (int h = 0; h < reps.length; h++)
510 if (reps[h] != jal.getSequenceAt(i))
512 jseq.addHiddenSequences(jal.findIndex(reps[h]));
518 if (jds.getDatasetSequence().getSequenceFeatures() != null)
520 jalview.datamodel.SequenceFeature[] sf = jds.getDatasetSequence()
521 .getSequenceFeatures();
523 while (index < sf.length)
525 Features features = new Features();
527 features.setBegin(sf[index].getBegin());
528 features.setEnd(sf[index].getEnd());
529 features.setDescription(sf[index].getDescription());
530 features.setType(sf[index].getType());
531 features.setFeatureGroup(sf[index].getFeatureGroup());
532 features.setScore(sf[index].getScore());
533 if (sf[index].links != null)
535 for (int l = 0; l < sf[index].links.size(); l++)
537 OtherData keyValue = new OtherData();
538 keyValue.setKey("LINK_" + l);
539 keyValue.setValue(sf[index].links.elementAt(l).toString());
540 features.addOtherData(keyValue);
543 if (sf[index].otherDetails != null)
546 Enumeration keys = sf[index].otherDetails.keys();
547 while (keys.hasMoreElements())
549 key = keys.nextElement().toString();
550 OtherData keyValue = new OtherData();
551 keyValue.setKey(key);
552 keyValue.setValue(sf[index].otherDetails.get(key).toString());
553 features.addOtherData(keyValue);
557 jseq.addFeatures(features);
562 if (jds.getDatasetSequence().getPDBId() != null)
564 Enumeration en = jds.getDatasetSequence().getPDBId().elements();
565 while (en.hasMoreElements())
567 Pdbids pdb = new Pdbids();
568 jalview.datamodel.PDBEntry entry = (jalview.datamodel.PDBEntry) en
571 pdb.setId(entry.getId());
572 pdb.setType(entry.getType());
575 // This must have been loaded, is it still visible?
576 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
577 for (int f = frames.length - 1; f > -1; f--)
579 if (frames[f] instanceof AppJmol)
581 jmol = (AppJmol) frames[f];
582 if (!jmol.pdbentry.getId().equals(entry.getId())
583 && !(entry.getId().length()>4
584 && entry.getId().startsWith(jmol.pdbentry.getId())))
587 StructureState state = new StructureState();
588 state.setVisible(true);
589 state.setXpos(jmol.getX());
590 state.setYpos(jmol.getY());
591 state.setWidth(jmol.getWidth());
592 state.setHeight(jmol.getHeight());
593 state.setViewId(jmol.getViewId());
594 String statestring = jmol.viewer.getStateInfo();
597 state.setContent(statestring.replaceAll("\n", ""));
599 for (int s = 0; s < jmol.sequence.length; s++)
601 if (jal.findIndex(jmol.sequence[s]) > -1)
603 pdb.addStructureState(state);
609 if (entry.getFile() != null)
611 pdb.setFile(entry.getFile());
612 if (pdbfiles == null)
614 pdbfiles = new Vector();
617 if (!pdbfiles.contains(entry.getId()))
619 pdbfiles.addElement(entry.getId());
622 File file = new File(entry.getFile());
623 if (file.exists() && jout != null)
625 byte[] data = new byte[(int) file.length()];
626 jout.putNextEntry(new JarEntry(entry.getId()));
627 DataInputStream dis = new DataInputStream(
628 new FileInputStream(file));
631 DataOutputStream dout = new DataOutputStream(jout);
632 dout.write(data, 0, data.length);
636 } catch (Exception ex)
638 ex.printStackTrace();
644 if (entry.getProperty() != null)
646 PdbentryItem item = new PdbentryItem();
647 Hashtable properties = entry.getProperty();
648 Enumeration en2 = properties.keys();
649 while (en2.hasMoreElements())
651 Property prop = new Property();
652 String key = en2.nextElement().toString();
654 prop.setValue(properties.get(key).toString());
655 item.addProperty(prop);
657 pdb.addPdbentryItem(item);
667 if (av.hasHiddenRows)
672 if (jal.getCodonFrames() != null && jal.getCodonFrames().length > 0)
674 jalview.datamodel.AlignedCodonFrame[] jac = jal.getCodonFrames();
675 for (int i = 0; i < jac.length; i++)
677 AlcodonFrame alc = new AlcodonFrame();
678 vamsasSet.addAlcodonFrame(alc);
679 for (int p = 0; p < jac[i].aaWidth; p++)
681 Alcodon cmap = new Alcodon();
682 if (jac[i].codons[p]!=null)
684 // Null codons indicate a gapped column in the translated peptide alignment.
685 cmap.setPos1(jac[i].codons[p][0]);
686 cmap.setPos2(jac[i].codons[p][1]);
687 cmap.setPos3(jac[i].codons[p][2]);
689 alc.addAlcodon(cmap);
691 if (jac[i].getProtMappings() != null
692 && jac[i].getProtMappings().length > 0)
694 SequenceI[] dnas = jac[i].getdnaSeqs();
695 jalview.datamodel.Mapping[] pmaps = jac[i].getProtMappings();
696 for (int m = 0; m < pmaps.length; m++)
698 AlcodMap alcmap = new AlcodMap();
699 alcmap.setDnasq(seqHash(dnas[m]));
700 alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
702 alc.addAlcodMap(alcmap);
709 // /////////////////////////////////
710 if (av.currentTree != null)
712 // FIND ANY ASSOCIATED TREES
713 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
714 if (Desktop.desktop != null)
716 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
718 for (int t = 0; t < frames.length; t++)
720 if (frames[t] instanceof TreePanel)
722 TreePanel tp = (TreePanel) frames[t];
724 if (tp.treeCanvas.av.alignment == jal)
726 Tree tree = new Tree();
727 tree.setTitle(tp.getTitle());
728 tree.setCurrentTree((av.currentTree == tp.getTree()));
729 tree.setNewick(tp.getTree().toString());
730 tree.setThreshold(tp.treeCanvas.threshold);
732 tree.setFitToWindow(tp.fitToWindow.getState());
733 tree.setFontName(tp.getTreeFont().getName());
734 tree.setFontSize(tp.getTreeFont().getSize());
735 tree.setFontStyle(tp.getTreeFont().getStyle());
736 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
738 tree.setShowBootstrap(tp.bootstrapMenu.getState());
739 tree.setShowDistances(tp.distanceMenu.getState());
741 tree.setHeight(tp.getHeight());
742 tree.setWidth(tp.getWidth());
743 tree.setXpos(tp.getX());
744 tree.setYpos(tp.getY());
745 tree.setId(makeHashCode(tp, null));
754 if (jal.getAlignmentAnnotation() != null)
756 jalview.datamodel.AlignmentAnnotation[] aa = jal
757 .getAlignmentAnnotation();
759 for (int i = 0; i < aa.length; i++)
761 Annotation an = new Annotation();
763 if (aa[i].annotationId != null)
765 annotationIds.put(aa[i].annotationId, aa[i]);
768 an.setId(aa[i].annotationId);
770 if (aa[i] == av.quality || aa[i] == av.conservation
771 || aa[i] == av.consensus)
773 an.setLabel(aa[i].label);
775 vamsasSet.addAnnotation(an);
779 an.setVisible(aa[i].visible);
781 an.setDescription(aa[i].description);
783 if (aa[i].sequenceRef != null)
785 // TODO later annotation sequenceRef should be the XML ID of the
786 // sequence rather than its display name
787 an.setSequenceRef(aa[i].sequenceRef.getName());
793 an.setGraphType(aa[i].graph);
794 an.setGraphGroup(aa[i].graphGroup);
795 if (aa[i].getThreshold() != null)
797 ThresholdLine line = new ThresholdLine();
798 line.setLabel(aa[i].getThreshold().label);
799 line.setValue(aa[i].getThreshold().value);
800 line.setColour(aa[i].getThreshold().colour.getRGB());
801 an.setThresholdLine(line);
809 an.setLabel(aa[i].label);
810 if (aa[i].hasScore())
812 an.setScore(aa[i].getScore());
814 AnnotationElement ae;
815 if (aa[i].annotations != null)
817 an.setScoreOnly(false);
818 for (int a = 0; a < aa[i].annotations.length; a++)
820 if ((aa[i] == null) || (aa[i].annotations[a] == null))
825 ae = new AnnotationElement();
826 if (aa[i].annotations[a].description != null)
827 ae.setDescription(aa[i].annotations[a].description);
828 if (aa[i].annotations[a].displayCharacter != null)
829 ae.setDisplayCharacter(aa[i].annotations[a].displayCharacter);
831 if (!Float.isNaN(aa[i].annotations[a].value))
832 ae.setValue(aa[i].annotations[a].value);
835 if (aa[i].annotations[a].secondaryStructure != ' '
836 && aa[i].annotations[a].secondaryStructure != '\0')
838 .setSecondaryStructure(aa[i].annotations[a].secondaryStructure
841 if (aa[i].annotations[a].colour != null
842 && aa[i].annotations[a].colour != java.awt.Color.black)
844 ae.setColour(aa[i].annotations[a].colour.getRGB());
847 an.addAnnotationElement(ae);
852 an.setScoreOnly(true);
854 vamsasSet.addAnnotation(an);
859 if (jal.getGroups() != null)
861 JGroup[] groups = new JGroup[jal.getGroups().size()];
863 for (int i = 0; i < groups.length; i++)
865 groups[i] = new JGroup();
867 jalview.datamodel.SequenceGroup sg = (jalview.datamodel.SequenceGroup) jal
868 .getGroups().elementAt(i);
869 groups[i].setStart(sg.getStartRes());
870 groups[i].setEnd(sg.getEndRes());
871 groups[i].setName(sg.getName()); // TODO later sequence group should
872 // specify IDs of sequences, not just
876 if (sg.cs.conservationApplied())
878 groups[i].setConsThreshold(sg.cs.getConservationInc());
880 if (sg.cs instanceof jalview.schemes.UserColourScheme)
882 groups[i].setColour(SetUserColourScheme(sg.cs, userColours,
888 .setColour(ColourSchemeProperty.getColourName(sg.cs));
891 else if (sg.cs instanceof jalview.schemes.AnnotationColourGradient)
894 .setColour(ColourSchemeProperty
895 .getColourName(((jalview.schemes.AnnotationColourGradient) sg.cs)
898 else if (sg.cs instanceof jalview.schemes.UserColourScheme)
901 .setColour(SetUserColourScheme(sg.cs, userColours, jms));
905 groups[i].setColour(ColourSchemeProperty.getColourName(sg.cs));
908 groups[i].setPidThreshold(sg.cs.getThreshold());
911 groups[i].setOutlineColour(sg.getOutlineColour().getRGB());
912 groups[i].setDisplayBoxes(sg.getDisplayBoxes());
913 groups[i].setDisplayText(sg.getDisplayText());
914 groups[i].setColourText(sg.getColourText());
915 groups[i].setTextCol1(sg.textColour.getRGB());
916 groups[i].setTextCol2(sg.textColour2.getRGB());
917 groups[i].setTextColThreshold(sg.thresholdTextColour);
919 for (int s = 0; s < sg.getSize(); s++)
921 jalview.datamodel.Sequence seq = (jalview.datamodel.Sequence) sg
923 groups[i].addSeq(seqHash(seq));
927 jms.setJGroup(groups);
930 // /////////SAVE VIEWPORT
931 Viewport view = new Viewport();
932 view.setTitle(ap.alignFrame.getTitle());
933 view.setSequenceSetId(makeHashCode(av.getSequenceSetId(), av
934 .getSequenceSetId()));
935 view.setId(av.getViewId());
936 view.setViewName(av.viewName);
937 view.setGatheredViews(av.gatherViewsHere);
939 if (ap.av.explodedPosition != null)
941 view.setXpos(av.explodedPosition.x);
942 view.setYpos(av.explodedPosition.y);
943 view.setWidth(av.explodedPosition.width);
944 view.setHeight(av.explodedPosition.height);
948 view.setXpos(ap.alignFrame.getBounds().x);
949 view.setYpos(ap.alignFrame.getBounds().y);
950 view.setWidth(ap.alignFrame.getBounds().width);
951 view.setHeight(ap.alignFrame.getBounds().height);
954 view.setStartRes(av.startRes);
955 view.setStartSeq(av.startSeq);
957 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
959 view.setBgColour(SetUserColourScheme(av.getGlobalColourScheme(),
962 else if (av.getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
964 jalview.schemes.AnnotationColourGradient acg = (jalview.schemes.AnnotationColourGradient) av
965 .getGlobalColourScheme();
967 AnnotationColours ac = new AnnotationColours();
968 ac.setAboveThreshold(acg.getAboveThreshold());
969 ac.setThreshold(acg.getAnnotationThreshold());
970 ac.setAnnotation(acg.getAnnotation());
971 if (acg.getBaseColour() instanceof jalview.schemes.UserColourScheme)
973 ac.setColourScheme(SetUserColourScheme(acg.getBaseColour(),
978 ac.setColourScheme(ColourSchemeProperty.getColourName(acg
982 ac.setMaxColour(acg.getMaxColour().getRGB());
983 ac.setMinColour(acg.getMinColour().getRGB());
984 view.setAnnotationColours(ac);
985 view.setBgColour("AnnotationColourGradient");
989 view.setBgColour(ColourSchemeProperty.getColourName(av
990 .getGlobalColourScheme()));
993 ColourSchemeI cs = av.getGlobalColourScheme();
997 if (cs.conservationApplied())
999 view.setConsThreshold(cs.getConservationInc());
1000 if (cs instanceof jalview.schemes.UserColourScheme)
1002 view.setBgColour(SetUserColourScheme(cs, userColours, jms));
1006 if (cs instanceof ResidueColourScheme)
1008 view.setPidThreshold(cs.getThreshold());
1012 view.setConservationSelected(av.getConservationSelected());
1013 view.setPidSelected(av.getAbovePIDThreshold());
1014 view.setFontName(av.font.getName());
1015 view.setFontSize(av.font.getSize());
1016 view.setFontStyle(av.font.getStyle());
1017 view.setRenderGaps(av.renderGaps);
1018 view.setShowAnnotation(av.getShowAnnotation());
1019 view.setShowBoxes(av.getShowBoxes());
1020 view.setShowColourText(av.getColourText());
1021 view.setShowFullId(av.getShowJVSuffix());
1022 view.setRightAlignIds(av.rightAlignIds);
1023 view.setShowSequenceFeatures(av.showSequenceFeatures);
1024 view.setShowText(av.getShowText());
1025 view.setWrapAlignment(av.getWrapAlignment());
1026 view.setTextCol1(av.textColour.getRGB());
1027 view.setTextCol2(av.textColour2.getRGB());
1028 view.setTextColThreshold(av.thresholdTextColour);
1030 if (av.featuresDisplayed != null)
1032 jalview.schemabinding.version2.FeatureSettings fs = new jalview.schemabinding.version2.FeatureSettings();
1034 String[] renderOrder = ap.seqPanel.seqCanvas.getFeatureRenderer().renderOrder;
1036 Vector settingsAdded = new Vector();
1037 for (int ro = 0; ro < renderOrder.length; ro++)
1039 Setting setting = new Setting();
1040 setting.setType(renderOrder[ro]);
1041 setting.setColour(ap.seqPanel.seqCanvas.getFeatureRenderer()
1042 .getColour(renderOrder[ro]).getRGB());
1044 setting.setDisplay(av.featuresDisplayed
1045 .containsKey(renderOrder[ro]));
1046 float rorder = ap.seqPanel.seqCanvas.getFeatureRenderer().getOrder(
1050 setting.setOrder(rorder);
1052 fs.addSetting(setting);
1053 settingsAdded.addElement(renderOrder[ro]);
1056 // Make sure we save none displayed feature settings
1057 Enumeration en = ap.seqPanel.seqCanvas.getFeatureRenderer().featureColours
1059 while (en.hasMoreElements())
1061 String key = en.nextElement().toString();
1062 if (settingsAdded.contains(key))
1067 Setting setting = new Setting();
1068 setting.setType(key);
1069 setting.setColour(ap.seqPanel.seqCanvas.getFeatureRenderer()
1070 .getColour(key).getRGB());
1072 setting.setDisplay(false);
1073 float rorder = ap.seqPanel.seqCanvas.getFeatureRenderer().getOrder(
1077 setting.setOrder(rorder);
1079 fs.addSetting(setting);
1080 settingsAdded.addElement(key);
1082 en = ap.seqPanel.seqCanvas.getFeatureRenderer().featureGroups.keys();
1083 Vector groupsAdded = new Vector();
1084 while (en.hasMoreElements())
1086 String grp = en.nextElement().toString();
1087 if (groupsAdded.contains(grp))
1091 Group g = new Group();
1094 .setDisplay(((Boolean) ap.seqPanel.seqCanvas
1095 .getFeatureRenderer().featureGroups.get(grp))
1098 groupsAdded.addElement(grp);
1100 jms.setFeatureSettings(fs);
1104 if (av.hasHiddenColumns)
1106 for (int c = 0; c < av.getColumnSelection().getHiddenColumns().size(); c++)
1108 int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
1110 HiddenColumns hc = new HiddenColumns();
1111 hc.setStart(region[0]);
1112 hc.setEnd(region[1]);
1113 view.addHiddenColumns(hc);
1117 jms.addViewport(view);
1119 object.setJalviewModelSequence(jms);
1120 object.getVamsasModel().addSequenceSet(vamsasSet);
1122 if (jout != null && fileName != null)
1124 // We may not want to write the object to disk,
1125 // eg we can copy the alignViewport to a new view object
1126 // using save and then load
1129 JarEntry entry = new JarEntry(fileName);
1130 jout.putNextEntry(entry);
1131 PrintWriter pout = new PrintWriter(new OutputStreamWriter(jout,
1133 org.exolab.castor.xml.Marshaller marshaller = new org.exolab.castor.xml.Marshaller(
1135 marshaller.marshal(object);
1138 } catch (Exception ex)
1140 // TODO: raise error in GUI if marshalling failed.
1141 ex.printStackTrace();
1148 * External mapping between jalview objects and objects yielding a valid and
1149 * unique object ID string. This is null for normal Jalview project IO, but
1150 * non-null when a jalview project is being read or written as part of a
1153 IdentityHashMap jv2vobj = null;
1156 * Construct a unique ID for jvobj using either existing bindings or if none
1157 * exist, the result of the hashcode call for the object.
1160 * jalview data object
1161 * @return unique ID for referring to jvobj
1163 private String makeHashCode(Object jvobj, String altCode)
1165 if (jv2vobj != null)
1167 Object id = jv2vobj.get(jvobj);
1170 return id.toString();
1172 // check string ID mappings
1173 if (jvids2vobj != null && jvobj instanceof String)
1175 id = jvids2vobj.get(jvobj);
1179 return id.toString();
1181 // give up and warn that something has gone wrong
1182 warn("Cannot find ID for object in external mapping : " + jvobj);
1188 * return local jalview object mapped to ID, if it exists
1192 * @return null or object bound to idcode
1194 private Object retrieveExistingObj(String idcode)
1196 if (idcode != null && vobj2jv != null)
1198 return vobj2jv.get(idcode);
1204 * binding from ID strings from external mapping table to jalview data model
1207 private Hashtable vobj2jv;
1209 private Sequence createVamsasSequence(String id, SequenceI jds)
1211 return createVamsasSequence(true, id, jds, null);
1214 private Sequence createVamsasSequence(boolean recurse, String id,
1215 SequenceI jds, SequenceI parentseq)
1217 Sequence vamsasSeq = new Sequence();
1218 vamsasSeq.setId(id);
1219 vamsasSeq.setName(jds.getName());
1220 vamsasSeq.setSequence(jds.getSequenceAsString());
1221 vamsasSeq.setDescription(jds.getDescription());
1222 jalview.datamodel.DBRefEntry[] dbrefs = null;
1223 if (jds.getDatasetSequence() != null)
1225 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
1226 if (jds.getDatasetSequence().getDBRef() != null)
1228 dbrefs = jds.getDatasetSequence().getDBRef();
1233 vamsasSeq.setDsseqid(id); // so we can tell which sequences really are
1234 // dataset sequences only
1235 dbrefs = jds.getDBRef();
1239 for (int d = 0; d < dbrefs.length; d++)
1241 DBRef dbref = new DBRef();
1242 dbref.setSource(dbrefs[d].getSource());
1243 dbref.setVersion(dbrefs[d].getVersion());
1244 dbref.setAccessionId(dbrefs[d].getAccessionId());
1245 if (dbrefs[d].hasMap())
1247 Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
1249 dbref.setMapping(mp);
1251 vamsasSeq.addDBRef(dbref);
1257 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
1258 SequenceI parentseq, SequenceI jds, boolean recurse)
1261 if (jmp.getMap() != null)
1265 jalview.util.MapList mlst = jmp.getMap();
1266 int r[] = mlst.getFromRanges();
1267 for (int s = 0; s < r.length; s += 2)
1269 MapListFrom mfrom = new MapListFrom();
1270 mfrom.setStart(r[s]);
1271 mfrom.setEnd(r[s + 1]);
1272 mp.addMapListFrom(mfrom);
1274 r = mlst.getToRanges();
1275 for (int s = 0; s < r.length; s += 2)
1277 MapListTo mto = new MapListTo();
1279 mto.setEnd(r[s + 1]);
1280 mp.addMapListTo(mto);
1282 mp.setMapFromUnit(mlst.getFromRatio());
1283 mp.setMapToUnit(mlst.getToRatio());
1284 if (jmp.getTo() != null)
1286 MappingChoice mpc = new MappingChoice();
1288 && (parentseq != jmp.getTo() || parentseq
1289 .getDatasetSequence() != jmp.getTo()))
1291 mpc.setSequence(createVamsasSequence(false, seqHash(jmp.getTo()),
1297 SequenceI ps = null;
1298 if (parentseq != jmp.getTo()
1299 && parentseq.getDatasetSequence() != jmp.getTo())
1301 // chaining dbref rather than a handshaking one
1302 jmpid = seqHash(ps = jmp.getTo());
1306 jmpid = seqHash(ps = parentseq);
1308 mpc.setDseqFor(jmpid);
1309 if (!seqRefIds.containsKey(mpc.getDseqFor()))
1311 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
1312 seqRefIds.put(mpc.getDseqFor(), ps);
1316 jalview.bin.Cache.log.debug("reusing DseqFor ID");
1319 mp.setMappingChoice(mpc);
1325 String SetUserColourScheme(jalview.schemes.ColourSchemeI cs,
1326 Vector userColours, JalviewModelSequence jms)
1329 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
1331 if (!userColours.contains(ucs))
1333 userColours.add(ucs);
1335 java.awt.Color[] colours = ucs.getColours();
1336 jalview.schemabinding.version2.UserColours uc = new jalview.schemabinding.version2.UserColours();
1337 jalview.schemabinding.version2.UserColourScheme jbucs = new jalview.schemabinding.version2.UserColourScheme();
1339 for (int i = 0; i < colours.length; i++)
1341 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
1342 col.setName(ResidueProperties.aa[i]);
1343 col.setRGB(jalview.util.Format.getHexString(colours[i]));
1344 jbucs.addColour(col);
1346 if (ucs.getLowerCaseColours() != null)
1348 colours = ucs.getLowerCaseColours();
1349 for (int i = 0; i < colours.length; i++)
1351 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
1352 col.setName(ResidueProperties.aa[i].toLowerCase());
1353 col.setRGB(jalview.util.Format.getHexString(colours[i]));
1354 jbucs.addColour(col);
1358 id = "ucs" + userColours.indexOf(ucs);
1360 uc.setUserColourScheme(jbucs);
1361 jms.addUserColours(uc);
1367 jalview.schemes.UserColourScheme GetUserColourScheme(
1368 JalviewModelSequence jms, String id)
1370 UserColours[] uc = jms.getUserColours();
1371 UserColours colours = null;
1373 for (int i = 0; i < uc.length; i++)
1375 if (uc[i].getId().equals(id))
1383 java.awt.Color[] newColours = new java.awt.Color[24];
1385 for (int i = 0; i < 24; i++)
1387 newColours[i] = new java.awt.Color(Integer.parseInt(colours
1388 .getUserColourScheme().getColour(i).getRGB(), 16));
1391 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
1394 if (colours.getUserColourScheme().getColourCount() > 24)
1396 newColours = new java.awt.Color[23];
1397 for (int i = 0; i < 23; i++)
1399 newColours[i] = new java.awt.Color(Integer.parseInt(colours
1400 .getUserColourScheme().getColour(i + 24).getRGB(), 16));
1402 ucs.setLowerCaseColours(newColours);
1409 * contains last error message (if any) encountered by XML loader.
1411 String errorMessage = null;
1414 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
1415 * exceptions are raised during project XML parsing
1417 public boolean attemptversion1parse = true;
1420 * Load a jalview project archive from a jar file
1423 * HTTP URL or filename
1425 public AlignFrame LoadJalviewAlign(final String file)
1428 jalview.gui.AlignFrame af = null;
1432 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
1433 // Workaround is to make sure caller implements the JarInputStreamProvider
1435 // so we can re-open the jar input stream for each entry.
1437 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
1438 af = LoadJalviewAlign(jprovider);
1439 } catch (MalformedURLException e)
1441 errorMessage = "Invalid URL format for '" + file + "'";
1447 private jarInputStreamProvider createjarInputStreamProvider(
1448 final String file) throws MalformedURLException
1451 errorMessage = null;
1452 uniqueSetSuffix = null;
1454 viewportsAdded = null;
1455 frefedSequence = null;
1457 if (file.startsWith("http://"))
1459 url = new URL(file);
1461 final URL _url = url;
1462 return new jarInputStreamProvider()
1465 public JarInputStream getJarInputStream() throws IOException
1469 return new JarInputStream(_url.openStream());
1473 return new JarInputStream(new FileInputStream(file));
1477 public String getFilename()
1485 * Recover jalview session from a jalview project archive. Caller may
1486 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
1487 * themselves. Any null fields will be initialised with default values,
1488 * non-null fields are left alone.
1493 public AlignFrame LoadJalviewAlign(final jarInputStreamProvider jprovider)
1495 errorMessage = null;
1496 if (uniqueSetSuffix == null)
1498 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
1500 if (seqRefIds == null)
1502 seqRefIds = new Hashtable();
1504 if (viewportsAdded == null)
1506 viewportsAdded = new Hashtable();
1508 if (frefedSequence == null)
1510 frefedSequence = new Vector();
1513 jalview.gui.AlignFrame af = null;
1514 Hashtable gatherToThisFrame = new Hashtable();
1515 final String file = jprovider.getFilename();
1518 JarInputStream jin = null;
1519 JarEntry jarentry = null;
1524 jin = jprovider.getJarInputStream();
1525 for (int i = 0; i < entryCount; i++)
1527 jarentry = jin.getNextJarEntry();
1530 if (jarentry != null && jarentry.getName().endsWith(".xml"))
1532 InputStreamReader in = new InputStreamReader(jin, "UTF-8");
1533 JalviewModel object = new JalviewModel();
1535 Unmarshaller unmar = new Unmarshaller(object);
1536 unmar.setValidation(false);
1537 object = (JalviewModel) unmar.unmarshal(in);
1538 if (true) // !skipViewport(object))
1540 af = LoadFromObject(object, file, true, jprovider);
1541 if (af.viewport.gatherViewsHere)
1543 gatherToThisFrame.put(af.viewport.getSequenceSetId(), af);
1548 else if (jarentry != null)
1550 // Some other file here.
1553 } while (jarentry != null);
1554 resolveFrefedSequences();
1555 } catch (java.io.FileNotFoundException ex)
1557 ex.printStackTrace();
1558 errorMessage = "Couldn't locate Jalview XML file : " + file;
1559 System.err.println("Exception whilst loading jalview XML file : "
1561 } catch (java.net.UnknownHostException ex)
1563 ex.printStackTrace();
1564 errorMessage = "Couldn't locate Jalview XML file : " + file;
1565 System.err.println("Exception whilst loading jalview XML file : "
1567 } catch (Exception ex)
1569 System.err.println("Parsing as Jalview Version 2 file failed.");
1570 ex.printStackTrace(System.err);
1571 if (attemptversion1parse)
1573 // Is Version 1 Jar file?
1576 af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
1577 } catch (Exception ex2)
1579 System.err.println("Exception whilst loading as jalviewXMLV1:");
1580 ex2.printStackTrace();
1584 if (Desktop.instance != null)
1586 Desktop.instance.stopLoading();
1590 System.out.println("Successfully loaded archive file");
1593 ex.printStackTrace();
1595 System.err.println("Exception whilst loading jalview XML file : "
1597 } catch (OutOfMemoryError e)
1599 new jalview.gui.OOMWarning("loading jalview XML file", e,
1603 if (Desktop.instance != null)
1605 Desktop.instance.stopLoading();
1608 Enumeration en = gatherToThisFrame.elements();
1609 while (en.hasMoreElements())
1611 Desktop.instance.gatherViews((AlignFrame) en.nextElement());
1613 if (errorMessage != null)
1621 * check errorMessage for a valid error message and raise an error box in the
1622 * GUI or write the current errorMessage to stderr and then clear the error
1625 protected void reportErrors()
1627 reportErrors(false);
1630 protected void reportErrors(final boolean saving)
1632 if (errorMessage != null)
1634 final String finalErrorMessage = errorMessage;
1637 javax.swing.SwingUtilities.invokeLater(new Runnable()
1641 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1642 finalErrorMessage, "Error "
1643 + (saving ? "saving" : "loading")
1644 + " Jalview file", JOptionPane.WARNING_MESSAGE);
1650 System.err.println("Problem loading Jalview file: " + errorMessage);
1653 errorMessage = null;
1656 Hashtable alreadyLoadedPDB;
1659 * when set, local views will be updated from view stored in JalviewXML
1660 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
1661 * sync if this is set to true.
1663 private boolean updateLocalViews = false;
1665 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId)
1667 if (alreadyLoadedPDB == null)
1668 alreadyLoadedPDB = new Hashtable();
1670 if (alreadyLoadedPDB.containsKey(pdbId))
1671 return alreadyLoadedPDB.get(pdbId).toString();
1675 JarInputStream jin = jprovider.getJarInputStream();
1677 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
1678 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
1679 * FileInputStream(jprovider)); }
1682 JarEntry entry = null;
1685 entry = jin.getNextJarEntry();
1686 } while (entry != null && !entry.getName().equals(pdbId));
1689 BufferedReader in = new BufferedReader(new InputStreamReader(jin));
1690 File outFile = File.createTempFile("jalview_pdb", ".txt");
1691 outFile.deleteOnExit();
1692 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
1695 while ((data = in.readLine()) != null)
1702 } catch (Exception foo)
1708 alreadyLoadedPDB.put(pdbId, outFile.getAbsolutePath());
1709 return outFile.getAbsolutePath();
1713 warn("Couldn't find PDB file entry in Jalview Jar for " + pdbId);
1715 } catch (Exception ex)
1717 ex.printStackTrace();
1724 * Load alignment frame from jalview XML DOM object
1729 * filename source string
1730 * @param loadTreesAndStructures
1731 * when false only create Viewport
1733 * data source provider
1734 * @return alignment frame created from view stored in DOM
1736 AlignFrame LoadFromObject(JalviewModel object, String file,
1737 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
1739 SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
1740 Sequence[] vamsasSeq = vamsasSet.getSequence();
1742 JalviewModelSequence jms = object.getJalviewModelSequence();
1744 Viewport view = jms.getViewport(0);
1745 // ////////////////////////////////
1748 Vector hiddenSeqs = null;
1749 jalview.datamodel.Sequence jseq;
1751 ArrayList tmpseqs = new ArrayList();
1753 boolean multipleView = false;
1755 JSeq[] JSEQ = object.getJalviewModelSequence().getJSeq();
1756 int vi = 0; // counter in vamsasSeq array
1757 for (int i = 0; i < JSEQ.length; i++)
1759 String seqId = JSEQ[i].getId();
1761 if (seqRefIds.get(seqId) != null)
1763 tmpseqs.add((jalview.datamodel.Sequence) seqRefIds.get(seqId));
1764 multipleView = true;
1768 jseq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
1769 vamsasSeq[vi].getSequence());
1770 jseq.setDescription(vamsasSeq[vi].getDescription());
1771 jseq.setStart(JSEQ[i].getStart());
1772 jseq.setEnd(JSEQ[i].getEnd());
1773 jseq.setVamsasId(uniqueSetSuffix + seqId);
1774 seqRefIds.put(vamsasSeq[vi].getId(), jseq);
1779 if (JSEQ[i].getHidden())
1781 if (hiddenSeqs == null)
1783 hiddenSeqs = new Vector();
1786 hiddenSeqs.addElement((jalview.datamodel.Sequence) seqRefIds
1793 // Create the alignment object from the sequence set
1794 // ///////////////////////////////
1795 jalview.datamodel.Sequence[] orderedSeqs = new jalview.datamodel.Sequence[tmpseqs
1798 tmpseqs.toArray(orderedSeqs);
1800 jalview.datamodel.Alignment al = new jalview.datamodel.Alignment(
1803 // / Add the alignment properties
1804 for (int i = 0; i < vamsasSet.getSequenceSetPropertiesCount(); i++)
1806 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties(i);
1807 al.setProperty(ssp.getKey(), ssp.getValue());
1811 // SequenceFeatures are added to the DatasetSequence,
1812 // so we must create or recover the dataset before loading features
1813 // ///////////////////////////////
1814 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
1816 // older jalview projects do not have a dataset id.
1817 al.setDataset(null);
1821 recoverDatasetFor(vamsasSet, al);
1823 // ///////////////////////////////
1825 Hashtable pdbloaded = new Hashtable();
1828 // load sequence features, database references and any associated PDB
1829 // structures for the alignment
1830 for (int i = 0; i < vamsasSeq.length; i++)
1832 if (JSEQ[i].getFeaturesCount() > 0)
1834 Features[] features = JSEQ[i].getFeatures();
1835 for (int f = 0; f < features.length; f++)
1837 jalview.datamodel.SequenceFeature sf = new jalview.datamodel.SequenceFeature(
1838 features[f].getType(), features[f].getDescription(),
1839 features[f].getStatus(), features[f].getBegin(),
1840 features[f].getEnd(), features[f].getFeatureGroup());
1842 sf.setScore(features[f].getScore());
1843 for (int od = 0; od < features[f].getOtherDataCount(); od++)
1845 OtherData keyValue = features[f].getOtherData(od);
1846 if (keyValue.getKey().startsWith("LINK"))
1848 sf.addLink(keyValue.getValue());
1852 sf.setValue(keyValue.getKey(), keyValue.getValue());
1857 al.getSequenceAt(i).getDatasetSequence().addSequenceFeature(sf);
1860 if (vamsasSeq[i].getDBRefCount() > 0)
1862 addDBRefs(al.getSequenceAt(i).getDatasetSequence(), vamsasSeq[i]);
1864 if (JSEQ[i].getPdbidsCount() > 0)
1866 Pdbids[] ids = JSEQ[i].getPdbids();
1867 for (int p = 0; p < ids.length; p++)
1869 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
1870 entry.setId(ids[p].getId());
1871 entry.setType(ids[p].getType());
1872 if (ids[p].getFile() != null)
1874 if (!pdbloaded.containsKey(ids[p].getFile()))
1876 entry.setFile(loadPDBFile(jprovider, ids[p].getId()));
1880 entry.setFile(pdbloaded.get(ids[p].getId()).toString());
1884 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
1888 } // end !multipleview
1890 // ///////////////////////////////
1891 // LOAD SEQUENCE MAPPINGS
1893 if (vamsasSet.getAlcodonFrameCount() > 0)
1895 // TODO Potentially this should only be done once for all views of an
1897 AlcodonFrame[] alc = vamsasSet.getAlcodonFrame();
1898 for (int i = 0; i < alc.length; i++)
1900 jalview.datamodel.AlignedCodonFrame cf = new jalview.datamodel.AlignedCodonFrame(
1901 alc[i].getAlcodonCount());
1902 if (alc[i].getAlcodonCount() > 0)
1904 Alcodon[] alcods = alc[i].getAlcodon();
1905 for (int p = 0; p < cf.codons.length; p++)
1907 if (alcods[p].hasPos1() && alcods[p].hasPos2() && alcods[p].hasPos3())
1909 // translated codons require three valid positions
1910 cf.codons[p] = new int[3];
1911 cf.codons[p][0] = (int) alcods[p].getPos1();
1912 cf.codons[p][1] = (int) alcods[p].getPos2();
1913 cf.codons[p][2] = (int) alcods[p].getPos3();
1915 cf.codons[p] = null;
1919 if (alc[i].getAlcodMapCount() > 0)
1921 AlcodMap[] maps = alc[i].getAlcodMap();
1922 for (int m = 0; m < maps.length; m++)
1924 SequenceI dnaseq = (SequenceI) seqRefIds
1925 .get(maps[m].getDnasq());
1927 jalview.datamodel.Mapping mapping = null;
1928 // attach to dna sequence reference.
1929 if (maps[m].getMapping() != null)
1931 mapping = addMapping(maps[m].getMapping());
1935 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
1940 frefedSequence.add(new Object[]
1941 { maps[m].getDnasq(), cf, mapping });
1945 al.addCodonFrame(cf);
1950 // ////////////////////////////////
1952 boolean hideQuality = true, hideConservation = true, hideConsensus = true;
1954 if (vamsasSet.getAnnotationCount() > 0)
1956 Annotation[] an = vamsasSet.getAnnotation();
1958 for (int i = 0; i < an.length; i++)
1960 // set visibility for automatic annotation for this view
1961 if (an[i].getLabel().equals("Quality"))
1963 hideQuality = false;
1966 else if (an[i].getLabel().equals("Conservation"))
1968 hideConservation = false;
1971 else if (an[i].getLabel().equals("Consensus"))
1973 hideConsensus = false;
1976 // set visiblity for other annotation in this view
1977 if (an[i].getId() != null
1978 && annotationIds.containsKey(an[i].getId()))
1980 jalview.datamodel.AlignmentAnnotation jda = (jalview.datamodel.AlignmentAnnotation) annotationIds
1981 .get(an[i].getId());
1982 // in principle Visible should always be true for annotation displayed
1983 // in multiple views
1984 if (an[i].hasVisible())
1985 jda.visible = an[i].getVisible();
1987 al.addAnnotation(jda);
1991 // Construct new annotation from model.
1992 AnnotationElement[] ae = an[i].getAnnotationElement();
1993 jalview.datamodel.Annotation[] anot = null;
1995 if (!an[i].getScoreOnly())
1997 anot = new jalview.datamodel.Annotation[al.getWidth()];
1999 for (int aa = 0; aa < ae.length && aa < anot.length; aa++)
2001 if (ae[aa].getPosition() >= anot.length)
2004 anot[ae[aa].getPosition()] = new jalview.datamodel.Annotation(
2006 ae[aa].getDisplayCharacter(), ae[aa].getDescription(), (ae[aa]
2007 .getSecondaryStructure() == null || ae[aa]
2008 .getSecondaryStructure().length() == 0) ? ' ' : ae[aa]
2009 .getSecondaryStructure().charAt(0), ae[aa].getValue()
2012 // JBPNote: Consider verifying dataflow for IO of secondary
2013 // structure annotation read from Stockholm files
2014 // this was added to try to ensure that
2015 // if (anot[ae[aa].getPosition()].secondaryStructure>' ')
2017 // anot[ae[aa].getPosition()].displayCharacter = "";
2019 anot[ae[aa].getPosition()].colour = new java.awt.Color(ae[aa]
2023 jalview.datamodel.AlignmentAnnotation jaa = null;
2025 if (an[i].getGraph())
2027 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
2028 an[i].getDescription(), anot, 0, 0, an[i].getGraphType());
2030 jaa.graphGroup = an[i].getGraphGroup();
2032 if (an[i].getThresholdLine() != null)
2034 jaa.setThreshold(new jalview.datamodel.GraphLine(an[i]
2035 .getThresholdLine().getValue(), an[i]
2036 .getThresholdLine().getLabel(), new java.awt.Color(
2037 an[i].getThresholdLine().getColour())));
2044 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
2045 an[i].getDescription(), anot);
2047 // register new annotation
2048 if (an[i].getId() != null)
2050 annotationIds.put(an[i].getId(), jaa);
2051 jaa.annotationId = an[i].getId();
2053 // recover sequence association
2054 if (an[i].getSequenceRef() != null)
2056 if (al.findName(an[i].getSequenceRef()) != null)
2058 jaa.createSequenceMapping(al.findName(an[i].getSequenceRef()),
2060 al.findName(an[i].getSequenceRef()).addAlignmentAnnotation(jaa);
2063 if (an[i].hasScore())
2065 jaa.setScore(an[i].getScore());
2068 if (an[i].hasVisible())
2069 jaa.visible = an[i].getVisible();
2071 al.addAnnotation(jaa);
2075 // ///////////////////////
2077 // Create alignment markup and styles for this view
2078 if (jms.getJGroupCount() > 0)
2080 JGroup[] groups = jms.getJGroup();
2082 for (int i = 0; i < groups.length; i++)
2084 ColourSchemeI cs = null;
2086 if (groups[i].getColour() != null)
2088 if (groups[i].getColour().startsWith("ucs"))
2090 cs = GetUserColourScheme(jms, groups[i].getColour());
2094 cs = ColourSchemeProperty.getColour(al, groups[i].getColour());
2099 cs.setThreshold(groups[i].getPidThreshold(), true);
2103 Vector seqs = new Vector();
2105 for (int s = 0; s < groups[i].getSeqCount(); s++)
2107 String seqId = groups[i].getSeq(s) + "";
2108 jalview.datamodel.SequenceI ts = (jalview.datamodel.SequenceI) seqRefIds
2113 seqs.addElement(ts);
2117 if (seqs.size() < 1)
2122 jalview.datamodel.SequenceGroup sg = new jalview.datamodel.SequenceGroup(
2123 seqs, groups[i].getName(), cs, groups[i].getDisplayBoxes(),
2124 groups[i].getDisplayText(), groups[i].getColourText(),
2125 groups[i].getStart(), groups[i].getEnd());
2128 .setOutlineColour(new java.awt.Color(groups[i]
2129 .getOutlineColour()));
2131 sg.textColour = new java.awt.Color(groups[i].getTextCol1());
2132 sg.textColour2 = new java.awt.Color(groups[i].getTextCol2());
2133 sg.thresholdTextColour = groups[i].getTextColThreshold();
2135 if (groups[i].getConsThreshold() != 0)
2137 jalview.analysis.Conservation c = new jalview.analysis.Conservation(
2138 "All", ResidueProperties.propHash, 3, sg
2139 .getSequences(null), 0, sg.getWidth() - 1);
2141 c.verdict(false, 25);
2142 sg.cs.setConservation(c);
2149 // ///////////////////////////////
2152 // If we just load in the same jar file again, the sequenceSetId
2153 // will be the same, and we end up with multiple references
2154 // to the same sequenceSet. We must modify this id on load
2155 // so that each load of the file gives a unique id
2156 String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
2157 String viewId = (view.getId() == null ? null : view.getId()
2159 AlignFrame af = null;
2160 AlignViewport av = null;
2161 // now check to see if we really need to create a new viewport.
2162 if (multipleView && viewportsAdded.size() == 0)
2164 // We recovered an alignment for which a viewport already exists.
2165 // TODO: fix up any settings necessary for overlaying stored state onto
2166 // state recovered from another document. (may not be necessary).
2167 // we may need a binding from a viewport in memory to one recovered from
2169 // and then recover its containing af to allow the settings to be applied.
2170 // TODO: fix for vamsas demo
2172 .println("About to recover a viewport for existing alignment: Sequence set ID is "
2174 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
2175 if (seqsetobj != null)
2177 if (seqsetobj instanceof String)
2179 uniqueSeqSetId = (String) seqsetobj;
2181 .println("Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
2187 .println("Warning : Collision between sequence set ID string and existing jalview object mapping.");
2192 AlignmentPanel ap = null;
2193 boolean isnewview = true;
2196 // Check to see if this alignment already has a view id == viewId
2197 jalview.gui.AlignmentPanel views[] = Desktop
2198 .getAlignmentPanels(uniqueSeqSetId);
2199 if (views != null && views.length > 0)
2201 for (int v = 0; v < views.length; v++)
2203 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
2205 // recover the existing alignpanel, alignframe, viewport
2206 af = views[v].alignFrame;
2209 // TODO: could even skip resetting view settings if we don't want to
2210 // change the local settings from other jalview processes
2219 af = loadViewport(file, JSEQ, hiddenSeqs, al, hideConsensus,
2220 hideQuality, hideConservation, jms, view, uniqueSeqSetId,
2226 // /////////////////////////////////////
2227 if (loadTreesAndStructures && jms.getTreeCount() > 0)
2231 for (int t = 0; t < jms.getTreeCount(); t++)
2234 Tree tree = jms.getTree(t);
2236 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
2239 tp = af.ShowNewickTree(new jalview.io.NewickFile(tree
2240 .getNewick()), tree.getTitle(), tree.getWidth(), tree
2241 .getHeight(), tree.getXpos(), tree.getYpos());
2242 if (tree.getId() != null)
2249 // update local tree attributes ?
2250 tp.setTitle(tree.getTitle());
2251 tp.setBounds(new Rectangle(tree.getXpos(), tree.getYpos(), tree
2252 .getWidth(), tree.getHeight()));
2253 tp.av = av; // af.viewport; // TODO: verify 'associate with all
2256 tp.treeCanvas.av = av; // af.viewport;
2257 tp.treeCanvas.ap = ap; // af.alignPanel;
2262 warn("There was a problem recovering stored Newick tree: \n"+tree.getNewick());
2266 tp.fitToWindow.setState(tree.getFitToWindow());
2267 tp.fitToWindow_actionPerformed(null);
2269 if (tree.getFontName() != null)
2271 tp.setTreeFont(new java.awt.Font(tree.getFontName(), tree
2272 .getFontStyle(), tree.getFontSize()));
2276 tp.setTreeFont(new java.awt.Font(view.getFontName(), view
2277 .getFontStyle(), tree.getFontSize()));
2280 tp.showPlaceholders(tree.getMarkUnlinked());
2281 tp.showBootstrap(tree.getShowBootstrap());
2282 tp.showDistances(tree.getShowDistances());
2284 tp.treeCanvas.threshold = tree.getThreshold();
2286 if (tree.getCurrentTree())
2288 af.viewport.setCurrentTree(tp.getTree());
2292 } catch (Exception ex)
2294 ex.printStackTrace();
2298 // //LOAD STRUCTURES
2299 if (loadTreesAndStructures)
2301 for (int i = 0; i < JSEQ.length; i++)
2303 if (JSEQ[i].getPdbidsCount() > 0)
2305 Pdbids[] ids = JSEQ[i].getPdbids();
2306 for (int p = 0; p < ids.length; p++)
2308 for (int s = 0; s < ids[p].getStructureStateCount(); s++)
2310 // check to see if we haven't already created this structure view
2311 String sviewid = (ids[p].getStructureState(s).getViewId() == null) ? null
2312 : ids[p].getStructureState(s).getViewId()
2314 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
2315 // Originally : ids[p].getFile()
2316 // : TODO: verify external PDB file recovery still works in normal
2317 // jalview project load
2318 jpdb.setFile(loadPDBFile(jprovider, ids[p].getId()));
2319 jpdb.setId(ids[p].getId());
2321 int x = ids[p].getStructureState(s).getXpos();
2322 int y = ids[p].getStructureState(s).getYpos();
2323 int width = ids[p].getStructureState(s).getWidth();
2324 int height = ids[p].getStructureState(s).getHeight();
2325 AppJmol comp = null;
2326 JInternalFrame[] frames = null;
2331 frames = Desktop.desktop.getAllFrames();
2332 } catch (ArrayIndexOutOfBoundsException e)
2334 // occasional No such child exceptions are thrown here...
2339 } catch (Exception f)
2344 } while (frames == null);
2345 // search for any Jmol windows already open from other
2346 // alignment views that exactly match the stored structure state
2347 for (int f = 0; comp == null && f < frames.length; f++)
2349 if (frames[f] instanceof AppJmol)
2352 && ((AppJmol) frames[f]).getViewId().equals(
2355 // post jalview 2.4 schema includes structure view id
2356 comp = (AppJmol) frames[f];
2358 else if (frames[f].getX() == x && frames[f].getY() == y
2359 && frames[f].getHeight() == height
2360 && frames[f].getWidth() == width)
2362 comp = (AppJmol) frames[f];
2366 Desktop.desktop.getComponentAt(x, y);
2368 String pdbFile = loadPDBFile(jprovider, ids[p].getId());
2370 jalview.datamodel.SequenceI[] seq = new jalview.datamodel.SequenceI[]
2371 { (jalview.datamodel.SequenceI) seqRefIds.get(JSEQ[i].getId()
2376 // create a new Jmol window
2377 String state = ids[p].getStructureState(s).getContent();
2379 StringBuffer newFileLoc = new StringBuffer(state.substring(
2380 0, state.indexOf("\"", state.indexOf("load")) + 1));
2382 newFileLoc.append(jpdb.getFile());
2383 newFileLoc.append(state.substring(state.indexOf("\"", state
2384 .indexOf("load \"") + 6)));
2386 new AppJmol(pdbFile, ids[p].getId(), seq, af.alignPanel,
2387 newFileLoc.toString(), new java.awt.Rectangle(x, y,
2388 width, height), sviewid);
2392 // if (comp != null)
2394 // NOTE: if the jalview project is part of a shared session then
2395 // view synchronization should/could be done here.
2397 // add mapping for this sequence to the already open Jmol
2398 // instance (if it doesn't already exist)
2400 StructureSelectionManager.getStructureSelectionManager()
2401 .setMapping(seq, null, pdbFile,
2402 jalview.io.AppletFormatAdapter.FILE);
2404 ((AppJmol) comp).addSequence(seq);
2415 AlignFrame loadViewport(String file, JSeq[] JSEQ, Vector hiddenSeqs,
2416 Alignment al, boolean hideConsensus, boolean hideQuality,
2417 boolean hideConservation, JalviewModelSequence jms,
2418 Viewport view, String uniqueSeqSetId, String viewId)
2420 AlignFrame af = null;
2421 af = new AlignFrame(al, view.getWidth(), view.getHeight(),
2422 uniqueSeqSetId, viewId);
2424 af.setFileName(file, "Jalview");
2426 for (int i = 0; i < JSEQ.length; i++)
2428 af.viewport.setSequenceColour(af.viewport.alignment.getSequenceAt(i),
2429 new java.awt.Color(JSEQ[i].getColour()));
2432 af.viewport.gatherViewsHere = view.getGatheredViews();
2434 if (view.getSequenceSetId() != null)
2436 jalview.gui.AlignViewport av = (jalview.gui.AlignViewport) viewportsAdded
2437 .get(uniqueSeqSetId);
2439 af.viewport.sequenceSetID = uniqueSeqSetId;
2442 // propagate shared settings to this new view
2443 af.viewport.historyList = av.historyList;
2444 af.viewport.redoList = av.redoList;
2448 viewportsAdded.put(uniqueSeqSetId, af.viewport);
2450 // TODO: check if this method can be called repeatedly without
2451 // side-effects if alignpanel already registered.
2452 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
2454 // apply Hidden regions to view.
2455 if (hiddenSeqs != null)
2457 for (int s = 0; s < JSEQ.length; s++)
2459 jalview.datamodel.SequenceGroup hidden = new jalview.datamodel.SequenceGroup();
2461 for (int r = 0; r < JSEQ[s].getHiddenSequencesCount(); r++)
2463 hidden.addSequence(al
2464 .getSequenceAt(JSEQ[s].getHiddenSequences(r)), false);
2466 af.viewport.hideRepSequences(al.getSequenceAt(s), hidden);
2469 jalview.datamodel.SequenceI[] hseqs = new jalview.datamodel.SequenceI[hiddenSeqs
2472 for (int s = 0; s < hiddenSeqs.size(); s++)
2474 hseqs[s] = (jalview.datamodel.SequenceI) hiddenSeqs.elementAt(s);
2477 af.viewport.hideSequence(hseqs);
2480 // set visibility of annotation in view
2481 if ((hideConsensus || hideQuality || hideConservation)
2482 && al.getAlignmentAnnotation() != null)
2484 int hSize = al.getAlignmentAnnotation().length;
2485 for (int h = 0; h < hSize; h++)
2487 if ((hideConsensus && al.getAlignmentAnnotation()[h].label
2488 .equals("Consensus"))
2489 || (hideQuality && al.getAlignmentAnnotation()[h].label
2491 || (hideConservation && al.getAlignmentAnnotation()[h].label
2492 .equals("Conservation")))
2494 al.deleteAnnotation(al.getAlignmentAnnotation()[h]);
2499 af.alignPanel.adjustAnnotationHeight();
2501 // recover view properties and display parameters
2502 if (view.getViewName() != null)
2504 af.viewport.viewName = view.getViewName();
2505 af.setInitialTabVisible();
2507 af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(), view
2510 af.viewport.setShowAnnotation(view.getShowAnnotation());
2511 af.viewport.setAbovePIDThreshold(view.getPidSelected());
2513 af.viewport.setColourText(view.getShowColourText());
2515 af.viewport.setConservationSelected(view.getConservationSelected());
2516 af.viewport.setShowJVSuffix(view.getShowFullId());
2517 af.viewport.rightAlignIds = view.getRightAlignIds();
2518 af.viewport.setFont(new java.awt.Font(view.getFontName(), view
2519 .getFontStyle(), view.getFontSize()));
2520 af.alignPanel.fontChanged();
2521 af.viewport.setRenderGaps(view.getRenderGaps());
2522 af.viewport.setWrapAlignment(view.getWrapAlignment());
2523 af.alignPanel.setWrapAlignment(view.getWrapAlignment());
2524 af.viewport.setShowAnnotation(view.getShowAnnotation());
2525 af.alignPanel.setAnnotationVisible(view.getShowAnnotation());
2527 af.viewport.setShowBoxes(view.getShowBoxes());
2529 af.viewport.setShowText(view.getShowText());
2531 af.viewport.textColour = new java.awt.Color(view.getTextCol1());
2532 af.viewport.textColour2 = new java.awt.Color(view.getTextCol2());
2533 af.viewport.thresholdTextColour = view.getTextColThreshold();
2535 af.viewport.setStartRes(view.getStartRes());
2536 af.viewport.setStartSeq(view.getStartSeq());
2538 ColourSchemeI cs = null;
2539 // apply colourschemes
2540 if (view.getBgColour() != null)
2542 if (view.getBgColour().startsWith("ucs"))
2544 cs = GetUserColourScheme(jms, view.getBgColour());
2546 else if (view.getBgColour().startsWith("Annotation"))
2548 // int find annotation
2549 for (int i = 0; i < af.viewport.alignment.getAlignmentAnnotation().length; i++)
2551 if (af.viewport.alignment.getAlignmentAnnotation()[i].label
2552 .equals(view.getAnnotationColours().getAnnotation()))
2554 if (af.viewport.alignment.getAlignmentAnnotation()[i]
2555 .getThreshold() == null)
2557 af.viewport.alignment.getAlignmentAnnotation()[i]
2558 .setThreshold(new jalview.datamodel.GraphLine(view
2559 .getAnnotationColours().getThreshold(),
2560 "Threshold", java.awt.Color.black)
2565 if (view.getAnnotationColours().getColourScheme()
2568 cs = new AnnotationColourGradient(af.viewport.alignment
2569 .getAlignmentAnnotation()[i], new java.awt.Color(view
2570 .getAnnotationColours().getMinColour()),
2571 new java.awt.Color(view.getAnnotationColours()
2572 .getMaxColour()), view.getAnnotationColours()
2573 .getAboveThreshold());
2575 else if (view.getAnnotationColours().getColourScheme()
2578 cs = new AnnotationColourGradient(af.viewport.alignment
2579 .getAlignmentAnnotation()[i], GetUserColourScheme(
2580 jms, view.getAnnotationColours().getColourScheme()),
2581 view.getAnnotationColours().getAboveThreshold());
2585 cs = new AnnotationColourGradient(af.viewport.alignment
2586 .getAlignmentAnnotation()[i], ColourSchemeProperty
2587 .getColour(al, view.getAnnotationColours()
2588 .getColourScheme()), view
2589 .getAnnotationColours().getAboveThreshold());
2592 // Also use these settings for all the groups
2593 if (al.getGroups() != null)
2595 for (int g = 0; g < al.getGroups().size(); g++)
2597 jalview.datamodel.SequenceGroup sg = (jalview.datamodel.SequenceGroup) al
2598 .getGroups().elementAt(g);
2607 * (view.getAnnotationColours().getColourScheme().equals("None")) {
2608 * sg.cs = new AnnotationColourGradient(
2609 * af.viewport.alignment.getAlignmentAnnotation()[i], new
2610 * java.awt.Color(view.getAnnotationColours(). getMinColour()),
2611 * new java.awt.Color(view.getAnnotationColours().
2613 * view.getAnnotationColours().getAboveThreshold()); } else
2616 sg.cs = new AnnotationColourGradient(
2617 af.viewport.alignment.getAlignmentAnnotation()[i],
2618 sg.cs, view.getAnnotationColours()
2619 .getAboveThreshold());
2632 cs = ColourSchemeProperty.getColour(al, view.getBgColour());
2637 cs.setThreshold(view.getPidThreshold(), true);
2638 cs.setConsensus(af.viewport.hconsensus);
2642 af.viewport.setGlobalColourScheme(cs);
2643 af.viewport.setColourAppliesToAllGroups(false);
2645 if (view.getConservationSelected() && cs != null)
2647 cs.setConservationInc(view.getConsThreshold());
2650 af.changeColour(cs);
2652 af.viewport.setColourAppliesToAllGroups(true);
2654 if (view.getShowSequenceFeatures())
2656 af.viewport.showSequenceFeatures = true;
2658 // recover featre settings
2659 if (jms.getFeatureSettings() != null)
2661 af.viewport.featuresDisplayed = new Hashtable();
2662 String[] renderOrder = new String[jms.getFeatureSettings()
2663 .getSettingCount()];
2664 for (int fs = 0; fs < jms.getFeatureSettings().getSettingCount(); fs++)
2666 Setting setting = jms.getFeatureSettings().getSetting(fs);
2668 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setColour(
2669 setting.getType(), new java.awt.Color(setting.getColour()));
2670 renderOrder[fs] = setting.getType();
2671 if (setting.hasOrder())
2672 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setOrder(
2673 setting.getType(), setting.getOrder());
2675 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setOrder(
2677 fs / jms.getFeatureSettings().getSettingCount());
2678 if (setting.getDisplay())
2680 af.viewport.featuresDisplayed.put(setting.getType(), new Integer(
2681 setting.getColour()));
2684 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().renderOrder = renderOrder;
2686 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().featureGroups = fgtable = new Hashtable();
2687 for (int gs = 0; gs < jms.getFeatureSettings().getGroupCount(); gs++)
2689 Group grp = jms.getFeatureSettings().getGroup(gs);
2690 fgtable.put(grp.getName(), new Boolean(grp.getDisplay()));
2694 if (view.getHiddenColumnsCount() > 0)
2696 for (int c = 0; c < view.getHiddenColumnsCount(); c++)
2698 af.viewport.hideColumns(view.getHiddenColumns(c).getStart(), view
2699 .getHiddenColumns(c).getEnd() // +1
2704 af.setMenusFromViewport(af.viewport);
2705 // TODO: we don't need to do this if the viewport is aready visible.
2706 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(), view
2711 Hashtable skipList = null;
2714 * TODO remove this method
2717 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
2718 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
2719 * throw new Error("Implementation Error. No skipList defined for this
2720 * Jalview2XML instance."); } return (AlignFrame)
2721 * skipList.get(view.getSequenceSetId()); }
2725 * Check if the Jalview view contained in object should be skipped or not.
2728 * @return true if view's sequenceSetId is a key in skipList
2730 private boolean skipViewport(JalviewModel object)
2732 if (skipList == null)
2737 if (skipList.containsKey(id = object.getJalviewModelSequence()
2738 .getViewport()[0].getSequenceSetId()))
2740 if (Cache.log != null && Cache.log.isDebugEnabled())
2742 Cache.log.debug("Skipping seuqence set id " + id);
2749 public void AddToSkipList(AlignFrame af)
2751 if (skipList == null)
2753 skipList = new Hashtable();
2755 skipList.put(af.getViewport().getSequenceSetId(), af);
2758 public void clearSkipList()
2760 if (skipList != null)
2767 private void recoverDatasetFor(SequenceSet vamsasSet, Alignment al)
2769 jalview.datamodel.Alignment ds = getDatasetFor(vamsasSet.getDatasetId());
2770 Vector dseqs = null;
2773 // create a list of new dataset sequences
2774 dseqs = new Vector();
2776 for (int i = 0, iSize = vamsasSet.getSequenceCount(); i < iSize; i++)
2778 Sequence vamsasSeq = vamsasSet.getSequence(i);
2779 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs);
2781 // create a new dataset
2784 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
2785 dseqs.copyInto(dsseqs);
2786 ds = new jalview.datamodel.Alignment(dsseqs);
2787 addDatasetRef(vamsasSet.getDatasetId(), ds);
2789 // set the dataset for the newly imported alignment.
2790 if (al.getDataset() == null)
2799 * sequence definition to create/merge dataset sequence for
2803 * vector to add new dataset sequence to
2805 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
2806 AlignmentI ds, Vector dseqs)
2808 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
2810 jalview.datamodel.Sequence sq = (jalview.datamodel.Sequence) seqRefIds
2811 .get(vamsasSeq.getId());
2812 jalview.datamodel.SequenceI dsq = null;
2813 if (sq != null && sq.getDatasetSequence() != null)
2815 dsq = (jalview.datamodel.SequenceI) sq.getDatasetSequence();
2818 String sqid = vamsasSeq.getDsseqid();
2821 // need to create or add a new dataset sequence reference to this sequence
2824 dsq = (jalview.datamodel.SequenceI) seqRefIds.get(sqid);
2829 // make a new dataset sequence
2830 dsq = sq.createDatasetSequence();
2833 // make up a new dataset reference for this sequence
2834 sqid = seqHash(dsq);
2836 dsq.setVamsasId(uniqueSetSuffix + sqid);
2837 seqRefIds.put(sqid, dsq);
2842 dseqs.addElement(dsq);
2847 ds.addSequence(dsq);
2853 { // make this dataset sequence sq's dataset sequence
2854 sq.setDatasetSequence(dsq);
2858 // TODO: refactor this as a merge dataset sequence function
2859 // now check that sq (the dataset sequence) sequence really is the union of
2860 // all references to it
2861 // boolean pre = sq.getStart() < dsq.getStart();
2862 // boolean post = sq.getEnd() > dsq.getEnd();
2866 StringBuffer sb = new StringBuffer();
2867 String newres = jalview.analysis.AlignSeq.extractGaps(
2868 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
2869 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
2870 && newres.length() > dsq.getLength())
2872 // Update with the longer sequence.
2876 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
2877 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
2878 * sb.append(newres.substring(newres.length() - sq.getEnd() -
2879 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
2881 dsq.setSequence(sb.toString());
2883 // TODO: merges will never happen if we 'know' we have the real dataset
2884 // sequence - this should be detected when id==dssid
2885 System.err.println("DEBUG Notice: Merged dataset sequence"); // ("
2886 // + (pre ? "prepended" : "") + " "
2887 // + (post ? "appended" : ""));
2892 java.util.Hashtable datasetIds = null;
2893 java.util.IdentityHashMap dataset2Ids = null;
2894 private Alignment getDatasetFor(String datasetId)
2896 if (datasetIds == null)
2898 datasetIds = new Hashtable();
2901 if (datasetIds.containsKey(datasetId))
2903 return (Alignment) datasetIds.get(datasetId);
2908 private void addDatasetRef(String datasetId, Alignment dataset)
2910 if (datasetIds == null)
2912 datasetIds = new Hashtable();
2914 datasetIds.put(datasetId, dataset);
2917 * make a new dataset ID for this jalview dataset alignment
2921 private String getDatasetIdRef(jalview.datamodel.Alignment dataset)
2923 if (dataset.getDataset()!=null)
2925 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
2927 String datasetId=makeHashCode(dataset, null);
2928 if (datasetId==null)
2930 // make a new datasetId and record it
2931 if (dataset2Ids == null)
2933 dataset2Ids = new IdentityHashMap();
2935 datasetId = (String) dataset2Ids.get(dataset);
2937 if (datasetId==null)
2939 datasetId = "ds"+dataset2Ids.size()+1;
2940 dataset2Ids.put(dataset,datasetId);
2945 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
2947 for (int d = 0; d < sequence.getDBRefCount(); d++)
2949 DBRef dr = sequence.getDBRef(d);
2950 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
2951 sequence.getDBRef(d).getSource(), sequence.getDBRef(d)
2952 .getVersion(), sequence.getDBRef(d).getAccessionId());
2953 if (dr.getMapping() != null)
2955 entry.setMap(addMapping(dr.getMapping()));
2957 datasetSequence.addDBRef(entry);
2961 private jalview.datamodel.Mapping addMapping(Mapping m)
2963 SequenceI dsto = null;
2964 // Mapping m = dr.getMapping();
2965 int fr[] = new int[m.getMapListFromCount() * 2];
2966 Enumeration f = m.enumerateMapListFrom();
2967 for (int _i = 0; f.hasMoreElements(); _i += 2)
2969 MapListFrom mf = (MapListFrom) f.nextElement();
2970 fr[_i] = mf.getStart();
2971 fr[_i + 1] = mf.getEnd();
2973 int fto[] = new int[m.getMapListToCount() * 2];
2974 f = m.enumerateMapListTo();
2975 for (int _i = 0; f.hasMoreElements(); _i += 2)
2977 MapListTo mf = (MapListTo) f.nextElement();
2978 fto[_i] = mf.getStart();
2979 fto[_i + 1] = mf.getEnd();
2981 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto,
2982 fr, fto, (int) m.getMapFromUnit(), (int) m.getMapToUnit());
2983 if (m.getMappingChoice() != null)
2985 MappingChoice mc = m.getMappingChoice();
2986 if (mc.getDseqFor() != null)
2988 String dsfor = ""+mc.getDseqFor();
2989 if (seqRefIds.containsKey(dsfor))
2994 jmap.setTo((SequenceI) seqRefIds.get(dsfor));
2998 frefedSequence.add(new Object[]
3005 * local sequence definition
3007 Sequence ms = mc.getSequence();
3008 jalview.datamodel.Sequence djs = null;
3009 String sqid = ms.getDsseqid();
3010 if (sqid != null && sqid.length() > 0)
3013 * recover dataset sequence
3015 djs = (jalview.datamodel.Sequence) seqRefIds.get(sqid);
3020 .println("Warning - making up dataset sequence id for DbRef sequence map reference");
3021 sqid = ((Object) ms).toString(); // make up a new hascode for
3022 // undefined dataset sequence hash
3023 // (unlikely to happen)
3029 * make a new dataset sequence and add it to refIds hash
3031 djs = new jalview.datamodel.Sequence(ms.getName(), ms
3033 djs.setStart(jmap.getMap().getToLowest());
3034 djs.setEnd(jmap.getMap().getToHighest());
3035 djs.setVamsasId(uniqueSetSuffix + sqid);
3037 seqRefIds.put(sqid, djs);
3040 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
3049 public jalview.gui.AlignmentPanel copyAlignPanel(AlignmentPanel ap,
3050 boolean keepSeqRefs)
3053 jalview.schemabinding.version2.JalviewModel jm = SaveState(ap, null,
3059 jm.getJalviewModelSequence().getViewport(0).setSequenceSetId(null);
3063 uniqueSetSuffix = "";
3064 jm.getJalviewModelSequence().getViewport(0).setId(null); // we don't overwrite the view we just copied
3066 if (this.frefedSequence==null)
3068 frefedSequence = new Vector();
3071 viewportsAdded = new Hashtable();
3073 AlignFrame af = LoadFromObject(jm, null, false, null);
3074 af.alignPanels.clear();
3075 af.closeMenuItem_actionPerformed(true);
3078 * if(ap.av.alignment.getAlignmentAnnotation()!=null) { for(int i=0; i<ap.av.alignment.getAlignmentAnnotation().length;
3079 * i++) { if(!ap.av.alignment.getAlignmentAnnotation()[i].autoCalculated) {
3080 * af.alignPanel.av.alignment.getAlignmentAnnotation()[i] =
3081 * ap.av.alignment.getAlignmentAnnotation()[i]; } } }
3084 return af.alignPanel;
3088 * flag indicating if hashtables should be cleared on finalization TODO this
3089 * flag may not be necessary
3091 private boolean _cleartables = true;
3093 private Hashtable jvids2vobj;
3098 * @see java.lang.Object#finalize()
3100 protected void finalize() throws Throwable
3102 // really make sure we have no buried refs left.
3107 this.seqRefIds = null;
3108 this.seqsToIds = null;
3112 private void warn(String msg)
3117 private void warn(String msg, Exception e)
3119 if (Cache.log != null)
3123 Cache.log.warn(msg, e);
3127 Cache.log.warn(msg);
3132 System.err.println("Warning: " + msg);
3135 e.printStackTrace();
3141 * set the object to ID mapping tables used to write/recover objects and XML
3142 * ID strings for the jalview project. If external tables are provided then
3143 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
3144 * object goes out of scope. - also populates the datasetIds hashtable with
3145 * alignment objects containing dataset sequences
3148 * Map from ID strings to jalview datamodel
3150 * Map from jalview datamodel to ID strings
3154 public void setObjectMappingTables(Hashtable vobj2jv,
3155 IdentityHashMap jv2vobj)
3157 this.jv2vobj = jv2vobj;
3158 this.vobj2jv = vobj2jv;
3159 Iterator ds = jv2vobj.keySet().iterator();
3161 while (ds.hasNext())
3163 Object jvobj = ds.next();
3164 id = jv2vobj.get(jvobj).toString();
3165 if (jvobj instanceof jalview.datamodel.Alignment)
3167 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
3169 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
3172 else if (jvobj instanceof jalview.datamodel.Sequence)
3174 // register sequence object so the XML parser can recover it.
3175 if (seqRefIds == null)
3177 seqRefIds = new Hashtable();
3179 if (seqsToIds == null)
3181 seqsToIds = new IdentityHashMap();
3183 seqRefIds.put(jv2vobj.get(jvobj).toString(), jvobj);
3184 seqsToIds.put(jvobj, id);
3186 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
3188 if (annotationIds == null)
3190 annotationIds = new Hashtable();
3193 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvobj);
3194 jalview.datamodel.AlignmentAnnotation jvann = (jalview.datamodel.AlignmentAnnotation) jvobj;
3195 if (jvann.annotationId == null)
3197 jvann.annotationId = anid;
3199 if (!jvann.annotationId.equals(anid))
3201 // TODO verify that this is the correct behaviour
3202 this.warn("Overriding Annotation ID for " + anid
3203 + " from different id : " + jvann.annotationId);
3204 jvann.annotationId = anid;
3207 else if (jvobj instanceof String)
3209 if (jvids2vobj == null)
3211 jvids2vobj = new Hashtable();
3212 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
3216 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
3221 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
3222 * objects created from the project archive. If string is null (default for
3223 * construction) then suffix will be set automatically.
3227 public void setUniqueSetSuffix(String string)
3229 uniqueSetSuffix = string;
3234 * uses skipList2 as the skipList for skipping views on sequence sets
3235 * associated with keys in the skipList
3239 public void setSkipList(Hashtable skipList2)
3241 skipList = skipList2;