2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
20 import java.awt.Rectangle;
22 import java.lang.reflect.InvocationTargetException;
25 import java.util.Map.Entry;
26 import java.util.jar.*;
30 import org.exolab.castor.xml.*;
32 import uk.ac.vamsas.objects.utils.MapList;
33 import jalview.bin.Cache;
34 import jalview.datamodel.Alignment;
35 import jalview.datamodel.AlignmentAnnotation;
36 import jalview.datamodel.AlignmentI;
37 import jalview.datamodel.SequenceI;
38 import jalview.schemabinding.version2.*;
39 import jalview.schemes.*;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.jarInputStreamProvider;
44 * Write out the current jalview desktop state as a Jalview XML stream.
46 * Note: the vamsas objects referred to here are primitive versions of the
47 * VAMSAS project schema elements - they are not the same and most likely never
51 * @version $Revision: 1.134 $
53 public class Jalview2XML
56 * create/return unique hash string for sq
59 * @return new or existing unique string for sq
61 String seqHash(SequenceI sq)
63 if (seqsToIds == null)
67 if (seqsToIds.containsKey(sq))
69 return (String) seqsToIds.get(sq);
73 // create sequential key
74 String key = "sq" + (seqsToIds.size() + 1);
75 key = makeHashCode(sq, key); // check we don't have an external reference
77 seqsToIds.put(sq, key);
86 if (seqRefIds != null)
90 if (seqsToIds != null)
100 warn("clearSeqRefs called when _cleartables was not set. Doing nothing.");
101 // seqRefIds = new Hashtable();
102 // seqsToIds = new IdentityHashMap();
108 if (seqsToIds == null)
110 seqsToIds = new IdentityHashMap();
112 if (seqRefIds == null)
114 seqRefIds = new Hashtable();
119 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
120 * of sequence objects are created.
122 java.util.IdentityHashMap seqsToIds = null;
125 * jalview XML Sequence ID to jalview sequence object reference (both dataset
126 * and alignment sequences. Populated as XML reps of sequence objects are
129 java.util.Hashtable seqRefIds = null; // key->SequenceI resolution
131 Vector frefedSequence = null;
133 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
139 public Jalview2XML(boolean raiseGUI)
141 this.raiseGUI = raiseGUI;
144 public void resolveFrefedSequences()
146 if (frefedSequence.size() > 0)
148 int r = 0, rSize = frefedSequence.size();
151 Object[] ref = (Object[]) frefedSequence.elementAt(r);
154 String sref = (String) ref[0];
155 if (seqRefIds.containsKey(sref))
157 if (ref[1] instanceof jalview.datamodel.Mapping)
159 SequenceI seq = (SequenceI) seqRefIds.get(sref);
160 while (seq.getDatasetSequence() != null)
162 seq = seq.getDatasetSequence();
164 ((jalview.datamodel.Mapping) ref[1]).setTo(seq);
168 if (ref[1] instanceof jalview.datamodel.AlignedCodonFrame)
170 SequenceI seq = (SequenceI) seqRefIds.get(sref);
171 while (seq.getDatasetSequence() != null)
173 seq = seq.getDatasetSequence();
176 && ref[2] instanceof jalview.datamodel.Mapping)
178 jalview.datamodel.Mapping mp = (jalview.datamodel.Mapping) ref[2];
179 ((jalview.datamodel.AlignedCodonFrame) ref[1]).addMap(
180 seq, mp.getTo(), mp.getMap());
185 .println("IMPLEMENTATION ERROR: Unimplemented forward sequence references for AlcodonFrames involving "
186 + ref[2].getClass() + " type objects.");
192 .println("IMPLEMENTATION ERROR: Unimplemented forward sequence references for "
193 + ref[1].getClass() + " type objects.");
196 frefedSequence.remove(r);
202 .println("IMPLEMENTATION WARNING: Unresolved forward reference for hash string "
204 + " with objecttype "
205 + ref[1].getClass());
212 frefedSequence.remove(r);
220 * This maintains a list of viewports, the key being the seqSetId. Important
221 * to set historyItem and redoList for multiple views
223 Hashtable viewportsAdded;
225 Hashtable annotationIds = new Hashtable();
227 String uniqueSetSuffix = "";
230 * List of pdbfiles added to Jar
232 Vector pdbfiles = null;
234 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
235 public void SaveState(File statefile)
239 FileOutputStream fos = new FileOutputStream(statefile);
240 JarOutputStream jout = new JarOutputStream(fos);
243 } catch (Exception e)
245 // TODO: inform user of the problem - they need to know if their data was
247 if (errorMessage == null)
249 errorMessage = "Couldn't write Jalview Archive to output file '"
250 + statefile + "' - See console error log for details";
254 errorMessage += "(output file was '" + statefile + "')";
262 * Writes a jalview project archive to the given Jar output stream.
266 public void SaveState(JarOutputStream jout)
268 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
278 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
279 // //////////////////////////////////////////////////
280 // NOTE ALSO new PrintWriter must be used for each new JarEntry
281 PrintWriter out = null;
283 Vector shortNames = new Vector();
286 for (int i = frames.length - 1; i > -1; i--)
288 if (frames[i] instanceof AlignFrame)
290 AlignFrame af = (AlignFrame) frames[i];
293 && skipList.containsKey(af.getViewport()
294 .getSequenceSetId()))
299 String shortName = af.getTitle();
301 if (shortName.indexOf(File.separatorChar) > -1)
303 shortName = shortName.substring(shortName
304 .lastIndexOf(File.separatorChar) + 1);
309 while (shortNames.contains(shortName))
311 if (shortName.endsWith("_" + (count - 1)))
313 shortName = shortName
314 .substring(0, shortName.lastIndexOf("_"));
317 shortName = shortName.concat("_" + count);
321 shortNames.addElement(shortName);
323 if (!shortName.endsWith(".xml"))
325 shortName = shortName + ".xml";
328 int ap, apSize = af.alignPanels.size();
329 for (ap = 0; ap < apSize; ap++)
331 AlignmentPanel apanel = (AlignmentPanel) af.alignPanels
333 String fileName = apSize == 1 ? shortName : ap + shortName;
334 if (!fileName.endsWith(".xml"))
336 fileName = fileName + ".xml";
339 SaveState(apanel, fileName, jout);
346 } catch (Exception foo)
351 } catch (Exception ex)
353 // TODO: inform user of the problem - they need to know if their data was
355 if (errorMessage == null)
357 errorMessage = "Couldn't write Jalview Archive - see error output for details";
359 ex.printStackTrace();
363 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
364 public boolean SaveAlignment(AlignFrame af, String jarFile,
369 int ap, apSize = af.alignPanels.size();
370 FileOutputStream fos = new FileOutputStream(jarFile);
371 JarOutputStream jout = new JarOutputStream(fos);
372 for (ap = 0; ap < apSize; ap++)
374 AlignmentPanel apanel = (AlignmentPanel) af.alignPanels
376 String jfileName = apSize == 1 ? fileName : fileName + ap;
377 if (!jfileName.endsWith(".xml"))
379 jfileName = jfileName + ".xml";
381 SaveState(apanel, jfileName, jout);
387 } catch (Exception foo)
393 } catch (Exception ex)
395 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
396 ex.printStackTrace();
402 * create a JalviewModel from an algnment view and marshall it to a
406 * panel to create jalview model for
408 * name of alignment panel written to output stream
414 public JalviewModel SaveState(AlignmentPanel ap, String fileName,
415 JarOutputStream jout)
418 Vector jmolViewIds = new Vector(); //
419 Vector userColours = new Vector();
421 AlignViewport av = ap.av;
423 JalviewModel object = new JalviewModel();
424 object.setVamsasModel(new jalview.schemabinding.version2.VamsasModel());
426 object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
427 object.setVersion(jalview.bin.Cache.getProperty("VERSION"));
429 jalview.datamodel.AlignmentI jal = av.alignment;
431 if (av.hasHiddenRows)
433 jal = jal.getHiddenSequences().getFullAlignment();
436 SequenceSet vamsasSet = new SequenceSet();
438 JalviewModelSequence jms = new JalviewModelSequence();
440 vamsasSet.setGapChar(jal.getGapCharacter() + "");
442 if (jal.getDataset() != null)
444 // dataset id is the dataset's hashcode
445 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
447 if (jal.getProperties() != null)
449 Enumeration en = jal.getProperties().keys();
450 while (en.hasMoreElements())
452 String key = en.nextElement().toString();
453 SequenceSetProperties ssp = new SequenceSetProperties();
455 ssp.setValue(jal.getProperties().get(key).toString());
456 vamsasSet.addSequenceSetProperties(ssp);
464 jalview.datamodel.SequenceI jds;
465 for (int i = 0; i < jal.getHeight(); i++)
467 jds = jal.getSequenceAt(i);
470 if (seqRefIds.get(id) != null)
472 // This happens for two reasons: 1. multiple views are being serialised.
473 // 2. the hashCode has collided with another sequence's code. This DOES
474 // HAPPEN! (PF00072.15.stk does this)
475 // JBPNote: Uncomment to debug writing out of files that do not read
476 // back in due to ArrayOutOfBoundExceptions.
477 // System.err.println("vamsasSeq backref: "+id+"");
478 // System.err.println(jds.getName()+"
479 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
480 // System.err.println("Hashcode: "+seqHash(jds));
481 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
482 // System.err.println(rsq.getName()+"
483 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
484 // System.err.println("Hashcode: "+seqHash(rsq));
488 vamsasSeq = createVamsasSequence(id, jds);
489 vamsasSet.addSequence(vamsasSeq);
490 seqRefIds.put(id, jds);
494 jseq.setStart(jds.getStart());
495 jseq.setEnd(jds.getEnd());
496 jseq.setColour(av.getSequenceColour(jds).getRGB());
498 jseq.setId(id); // jseq id should be a string not a number
500 if (av.hasHiddenRows)
502 jseq.setHidden(av.alignment.getHiddenSequences().isHidden(jds));
504 if (av.hiddenRepSequences != null
505 && av.hiddenRepSequences.containsKey(jal.getSequenceAt(i)))
507 jalview.datamodel.SequenceI[] reps = ((jalview.datamodel.SequenceGroup) av.hiddenRepSequences
508 .get(jal.getSequenceAt(i))).getSequencesInOrder(jal);
510 for (int h = 0; h < reps.length; h++)
512 if (reps[h] != jal.getSequenceAt(i))
514 jseq.addHiddenSequences(jal.findIndex(reps[h]));
520 if (jds.getDatasetSequence().getSequenceFeatures() != null)
522 jalview.datamodel.SequenceFeature[] sf = jds.getDatasetSequence()
523 .getSequenceFeatures();
525 while (index < sf.length)
527 Features features = new Features();
529 features.setBegin(sf[index].getBegin());
530 features.setEnd(sf[index].getEnd());
531 features.setDescription(sf[index].getDescription());
532 features.setType(sf[index].getType());
533 features.setFeatureGroup(sf[index].getFeatureGroup());
534 features.setScore(sf[index].getScore());
535 if (sf[index].links != null)
537 for (int l = 0; l < sf[index].links.size(); l++)
539 OtherData keyValue = new OtherData();
540 keyValue.setKey("LINK_" + l);
541 keyValue.setValue(sf[index].links.elementAt(l).toString());
542 features.addOtherData(keyValue);
545 if (sf[index].otherDetails != null)
548 Enumeration keys = sf[index].otherDetails.keys();
549 while (keys.hasMoreElements())
551 key = keys.nextElement().toString();
552 OtherData keyValue = new OtherData();
553 keyValue.setKey(key);
554 keyValue.setValue(sf[index].otherDetails.get(key).toString());
555 features.addOtherData(keyValue);
559 jseq.addFeatures(features);
564 if (jds.getDatasetSequence().getPDBId() != null)
566 Enumeration en = jds.getDatasetSequence().getPDBId().elements();
567 while (en.hasMoreElements())
569 Pdbids pdb = new Pdbids();
570 jalview.datamodel.PDBEntry entry = (jalview.datamodel.PDBEntry) en
573 pdb.setId(entry.getId());
574 pdb.setType(entry.getType());
577 // This must have been loaded, is it still visible?
578 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
579 String matchedFile = null;
580 for (int f = frames.length - 1; f > -1; f--)
582 if (frames[f] instanceof AppJmol)
584 jmol = (AppJmol) frames[f];
585 for (int peid = 0; peid < jmol.jmb.pdbentry.length; peid++)
587 if (!jmol.jmb.pdbentry[peid].getId().equals(entry.getId())
588 && !(entry.getId().length() > 4 && entry
592 jmol.jmb.pdbentry[peid].getId()
595 if (matchedFile == null)
597 matchedFile = jmol.jmb.pdbentry[peid].getFile();
599 else if (!matchedFile.equals(jmol.jmb.pdbentry[peid]
603 .warn("Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
604 + jmol.jmb.pdbentry[peid].getFile());
608 // can get at it if the ID
609 // match is ambiguous (e.g.
611 String statestring = jmol.jmb.viewer.getStateInfo();
613 for (int smap = 0; smap < jmol.jmb.sequence[peid].length; smap++)
615 if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
617 StructureState state = new StructureState();
618 state.setVisible(true);
619 state.setXpos(jmol.getX());
620 state.setYpos(jmol.getY());
621 state.setWidth(jmol.getWidth());
622 state.setHeight(jmol.getHeight());
623 state.setViewId(jmol.getViewId());
624 state.setAlignwithAlignPanel(jmol.isUsedforaligment(ap));
625 state.setColourwithAlignPanel(jmol
626 .isUsedforcolourby(ap));
627 state.setColourByJmol(jmol.isColouredByJmol());
628 if (!jmolViewIds.contains(state.getViewId()))
630 // Make sure we only store a Jmol state once in each XML
632 jmolViewIds.addElement(state.getViewId());
633 state.setContent(statestring.replaceAll("\n", ""));
637 state.setContent("# duplicate state");
639 pdb.addStructureState(state);
646 if (matchedFile != null || entry.getFile() != null)
648 if (entry.getFile() != null)
651 matchedFile = entry.getFile();
653 pdb.setFile(matchedFile); // entry.getFile());
654 if (pdbfiles == null)
656 pdbfiles = new Vector();
659 if (!pdbfiles.contains(entry.getId()))
661 pdbfiles.addElement(entry.getId());
664 File file = new File(matchedFile);
665 if (file.exists() && jout != null)
667 byte[] data = new byte[(int) file.length()];
668 jout.putNextEntry(new JarEntry(entry.getId()));
669 DataInputStream dis = new DataInputStream(
670 new FileInputStream(file));
673 DataOutputStream dout = new DataOutputStream(jout);
674 dout.write(data, 0, data.length);
678 } catch (Exception ex)
680 ex.printStackTrace();
686 if (entry.getProperty() != null)
688 PdbentryItem item = new PdbentryItem();
689 Hashtable properties = entry.getProperty();
690 Enumeration en2 = properties.keys();
691 while (en2.hasMoreElements())
693 Property prop = new Property();
694 String key = en2.nextElement().toString();
696 prop.setValue(properties.get(key).toString());
697 item.addProperty(prop);
699 pdb.addPdbentryItem(item);
709 if (av.hasHiddenRows)
714 if (jal.getCodonFrames() != null && jal.getCodonFrames().length > 0)
716 jalview.datamodel.AlignedCodonFrame[] jac = jal.getCodonFrames();
717 for (int i = 0; i < jac.length; i++)
719 AlcodonFrame alc = new AlcodonFrame();
720 vamsasSet.addAlcodonFrame(alc);
721 for (int p = 0; p < jac[i].aaWidth; p++)
723 Alcodon cmap = new Alcodon();
724 if (jac[i].codons[p] != null)
726 // Null codons indicate a gapped column in the translated peptide
728 cmap.setPos1(jac[i].codons[p][0]);
729 cmap.setPos2(jac[i].codons[p][1]);
730 cmap.setPos3(jac[i].codons[p][2]);
732 alc.addAlcodon(cmap);
734 if (jac[i].getProtMappings() != null
735 && jac[i].getProtMappings().length > 0)
737 SequenceI[] dnas = jac[i].getdnaSeqs();
738 jalview.datamodel.Mapping[] pmaps = jac[i].getProtMappings();
739 for (int m = 0; m < pmaps.length; m++)
741 AlcodMap alcmap = new AlcodMap();
742 alcmap.setDnasq(seqHash(dnas[m]));
743 alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
745 alc.addAlcodMap(alcmap);
752 // /////////////////////////////////
753 if (av.currentTree != null)
755 // FIND ANY ASSOCIATED TREES
756 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
757 if (Desktop.desktop != null)
759 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
761 for (int t = 0; t < frames.length; t++)
763 if (frames[t] instanceof TreePanel)
765 TreePanel tp = (TreePanel) frames[t];
767 if (tp.treeCanvas.av.alignment == jal)
769 Tree tree = new Tree();
770 tree.setTitle(tp.getTitle());
771 tree.setCurrentTree((av.currentTree == tp.getTree()));
772 tree.setNewick(tp.getTree().toString());
773 tree.setThreshold(tp.treeCanvas.threshold);
775 tree.setFitToWindow(tp.fitToWindow.getState());
776 tree.setFontName(tp.getTreeFont().getName());
777 tree.setFontSize(tp.getTreeFont().getSize());
778 tree.setFontStyle(tp.getTreeFont().getStyle());
779 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
781 tree.setShowBootstrap(tp.bootstrapMenu.getState());
782 tree.setShowDistances(tp.distanceMenu.getState());
784 tree.setHeight(tp.getHeight());
785 tree.setWidth(tp.getWidth());
786 tree.setXpos(tp.getX());
787 tree.setYpos(tp.getY());
788 tree.setId(makeHashCode(tp, null));
798 * store forward refs from an annotationRow to any groups
800 IdentityHashMap groupRefs = new IdentityHashMap();
801 if (jal.getAlignmentAnnotation() != null)
803 jalview.datamodel.AlignmentAnnotation[] aa = jal
804 .getAlignmentAnnotation();
806 for (int i = 0; i < aa.length; i++)
808 Annotation an = new Annotation();
810 if (aa[i].annotationId != null)
812 annotationIds.put(aa[i].annotationId, aa[i]);
815 an.setId(aa[i].annotationId);
817 an.setVisible(aa[i].visible);
819 an.setDescription(aa[i].description);
821 if (aa[i].sequenceRef != null)
823 // TODO later annotation sequenceRef should be the XML ID of the
824 // sequence rather than its display name
825 an.setSequenceRef(aa[i].sequenceRef.getName());
827 if (aa[i].groupRef != null)
829 Object groupIdr = groupRefs.get(aa[i].groupRef);
830 if (groupIdr == null)
832 // make a locally unique String
833 groupRefs.put(aa[i].groupRef,
834 groupIdr = ("" + System.currentTimeMillis()
835 + aa[i].groupRef.getName() + groupRefs.size()));
837 an.setGroupRef(groupIdr.toString());
840 // store all visualization attributes for annotation
841 an.setGraphHeight(aa[i].graphHeight);
842 an.setCentreColLabels(aa[i].centreColLabels);
843 an.setScaleColLabels(aa[i].scaleColLabel);
844 an.setShowAllColLabels(aa[i].showAllColLabels);
849 an.setGraphType(aa[i].graph);
850 an.setGraphGroup(aa[i].graphGroup);
851 if (aa[i].getThreshold() != null)
853 ThresholdLine line = new ThresholdLine();
854 line.setLabel(aa[i].getThreshold().label);
855 line.setValue(aa[i].getThreshold().value);
856 line.setColour(aa[i].getThreshold().colour.getRGB());
857 an.setThresholdLine(line);
865 an.setLabel(aa[i].label);
867 if (aa[i] == av.quality || aa[i] == av.conservation
868 || aa[i] == av.consensus || aa[i].autoCalculated)
870 // new way of indicating autocalculated annotation -
871 an.setAutoCalculated(aa[i].autoCalculated);
873 if (aa[i].hasScore())
875 an.setScore(aa[i].getScore());
877 AnnotationElement ae;
878 if (aa[i].annotations != null)
880 an.setScoreOnly(false);
881 for (int a = 0; a < aa[i].annotations.length; a++)
883 if ((aa[i] == null) || (aa[i].annotations[a] == null))
888 ae = new AnnotationElement();
889 if (aa[i].annotations[a].description != null)
890 ae.setDescription(aa[i].annotations[a].description);
891 if (aa[i].annotations[a].displayCharacter != null)
892 ae.setDisplayCharacter(aa[i].annotations[a].displayCharacter);
894 if (!Float.isNaN(aa[i].annotations[a].value))
895 ae.setValue(aa[i].annotations[a].value);
898 if (aa[i].annotations[a].secondaryStructure != ' '
899 && aa[i].annotations[a].secondaryStructure != '\0')
900 ae.setSecondaryStructure(aa[i].annotations[a].secondaryStructure
903 if (aa[i].annotations[a].colour != null
904 && aa[i].annotations[a].colour != java.awt.Color.black)
906 ae.setColour(aa[i].annotations[a].colour.getRGB());
909 an.addAnnotationElement(ae);
910 if (aa[i].autoCalculated)
912 // only write one non-null entry into the annotation row - sufficient to get the visualization attributes necessary to display data
919 an.setScoreOnly(true);
921 vamsasSet.addAnnotation(an);
925 if (jal.getGroups() != null)
927 JGroup[] groups = new JGroup[jal.getGroups().size()];
929 for (int i = 0; i < groups.length; i++)
931 groups[i] = new JGroup();
933 jalview.datamodel.SequenceGroup sg = (jalview.datamodel.SequenceGroup) jal
934 .getGroups().elementAt(i);
935 groups[i].setStart(sg.getStartRes());
936 groups[i].setEnd(sg.getEndRes());
937 groups[i].setName(sg.getName());
938 if (groupRefs.containsKey(sg))
940 // group has references so set it's ID field
941 groups[i].setId(groupRefs.get(sg).toString());
945 if (sg.cs.conservationApplied())
947 groups[i].setConsThreshold(sg.cs.getConservationInc());
949 if (sg.cs instanceof jalview.schemes.UserColourScheme)
951 groups[i].setColour(SetUserColourScheme(sg.cs, userColours,
957 .setColour(ColourSchemeProperty.getColourName(sg.cs));
960 else if (sg.cs instanceof jalview.schemes.AnnotationColourGradient)
963 .setColour(ColourSchemeProperty
964 .getColourName(((jalview.schemes.AnnotationColourGradient) sg.cs)
967 else if (sg.cs instanceof jalview.schemes.UserColourScheme)
970 .setColour(SetUserColourScheme(sg.cs, userColours, jms));
974 groups[i].setColour(ColourSchemeProperty.getColourName(sg.cs));
977 groups[i].setPidThreshold(sg.cs.getThreshold());
980 groups[i].setOutlineColour(sg.getOutlineColour().getRGB());
981 groups[i].setDisplayBoxes(sg.getDisplayBoxes());
982 groups[i].setDisplayText(sg.getDisplayText());
983 groups[i].setColourText(sg.getColourText());
984 groups[i].setTextCol1(sg.textColour.getRGB());
985 groups[i].setTextCol2(sg.textColour2.getRGB());
986 groups[i].setTextColThreshold(sg.thresholdTextColour);
987 groups[i].setShowUnconserved(sg.getShowNonconserved());
988 groups[i].setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
989 groups[i].setShowConsensusHistogram(sg.isShowConsensusHistogram());
990 groups[i].setShowSequenceLogo(sg.isShowSequenceLogo());
991 for (int s = 0; s < sg.getSize(); s++)
993 jalview.datamodel.Sequence seq = (jalview.datamodel.Sequence) sg
995 groups[i].addSeq(seqHash(seq));
999 jms.setJGroup(groups);
1002 // /////////SAVE VIEWPORT
1003 Viewport view = new Viewport();
1004 view.setTitle(ap.alignFrame.getTitle());
1005 view.setSequenceSetId(makeHashCode(av.getSequenceSetId(),
1006 av.getSequenceSetId()));
1007 view.setId(av.getViewId());
1008 view.setViewName(av.viewName);
1009 view.setGatheredViews(av.gatherViewsHere);
1011 if (ap.av.explodedPosition != null)
1013 view.setXpos(av.explodedPosition.x);
1014 view.setYpos(av.explodedPosition.y);
1015 view.setWidth(av.explodedPosition.width);
1016 view.setHeight(av.explodedPosition.height);
1020 view.setXpos(ap.alignFrame.getBounds().x);
1021 view.setYpos(ap.alignFrame.getBounds().y);
1022 view.setWidth(ap.alignFrame.getBounds().width);
1023 view.setHeight(ap.alignFrame.getBounds().height);
1026 view.setStartRes(av.startRes);
1027 view.setStartSeq(av.startSeq);
1029 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1031 view.setBgColour(SetUserColourScheme(av.getGlobalColourScheme(),
1034 else if (av.getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1036 jalview.schemes.AnnotationColourGradient acg = (jalview.schemes.AnnotationColourGradient) av
1037 .getGlobalColourScheme();
1039 AnnotationColours ac = new AnnotationColours();
1040 ac.setAboveThreshold(acg.getAboveThreshold());
1041 ac.setThreshold(acg.getAnnotationThreshold());
1042 ac.setAnnotation(acg.getAnnotation());
1043 if (acg.getBaseColour() instanceof jalview.schemes.UserColourScheme)
1045 ac.setColourScheme(SetUserColourScheme(acg.getBaseColour(),
1050 ac.setColourScheme(ColourSchemeProperty.getColourName(acg
1054 ac.setMaxColour(acg.getMaxColour().getRGB());
1055 ac.setMinColour(acg.getMinColour().getRGB());
1056 view.setAnnotationColours(ac);
1057 view.setBgColour("AnnotationColourGradient");
1061 view.setBgColour(ColourSchemeProperty.getColourName(av
1062 .getGlobalColourScheme()));
1065 ColourSchemeI cs = av.getGlobalColourScheme();
1069 if (cs.conservationApplied())
1071 view.setConsThreshold(cs.getConservationInc());
1072 if (cs instanceof jalview.schemes.UserColourScheme)
1074 view.setBgColour(SetUserColourScheme(cs, userColours, jms));
1078 if (cs instanceof ResidueColourScheme)
1080 view.setPidThreshold(cs.getThreshold());
1084 view.setConservationSelected(av.getConservationSelected());
1085 view.setPidSelected(av.getAbovePIDThreshold());
1086 view.setFontName(av.font.getName());
1087 view.setFontSize(av.font.getSize());
1088 view.setFontStyle(av.font.getStyle());
1089 view.setRenderGaps(av.renderGaps);
1090 view.setShowAnnotation(av.getShowAnnotation());
1091 view.setShowBoxes(av.getShowBoxes());
1092 view.setShowColourText(av.getColourText());
1093 view.setShowFullId(av.getShowJVSuffix());
1094 view.setRightAlignIds(av.rightAlignIds);
1095 view.setShowSequenceFeatures(av.showSequenceFeatures);
1096 view.setShowText(av.getShowText());
1097 view.setShowUnconserved(av.getShowUnconserved());
1098 view.setWrapAlignment(av.getWrapAlignment());
1099 view.setTextCol1(av.textColour.getRGB());
1100 view.setTextCol2(av.textColour2.getRGB());
1101 view.setTextColThreshold(av.thresholdTextColour);
1102 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1103 view.setShowSequenceLogo(av.isShowSequenceLogo());
1104 view.setShowGroupConsensus(av.isShowGroupConsensus());
1105 view.setShowGroupConservation(av.isShowGroupConservation());
1106 view.setShowNPfeatureTooltip(av.isShowNpFeats());
1107 view.setShowDbRefTooltip(av.isShowDbRefs());
1108 view.setFollowHighlight(av.followHighlight);
1109 view.setFollowSelection(av.followSelection);
1110 view.setIgnoreGapsinConsensus(av.getIgnoreGapsConsensus());
1111 if (av.featuresDisplayed != null)
1113 jalview.schemabinding.version2.FeatureSettings fs = new jalview.schemabinding.version2.FeatureSettings();
1115 String[] renderOrder = ap.seqPanel.seqCanvas.getFeatureRenderer().renderOrder;
1117 Vector settingsAdded = new Vector();
1118 Object gstyle = null;
1119 GraduatedColor gcol = null;
1120 for (int ro = 0; ro < renderOrder.length; ro++)
1122 gstyle = ap.seqPanel.seqCanvas.getFeatureRenderer()
1123 .getFeatureStyle(renderOrder[ro]);
1124 Setting setting = new Setting();
1125 setting.setType(renderOrder[ro]);
1126 if (gstyle instanceof GraduatedColor)
1128 gcol = (GraduatedColor) gstyle;
1129 setting.setColour(gcol.getMaxColor().getRGB());
1130 setting.setMincolour(gcol.getMinColor().getRGB());
1131 setting.setMin(gcol.getMin());
1132 setting.setMax(gcol.getMax());
1133 setting.setColourByLabel(gcol.isColourByLabel());
1134 setting.setAutoScale(gcol.isAutoScale());
1135 setting.setThreshold(gcol.getThresh());
1136 setting.setThreshstate(gcol.getThreshType());
1140 setting.setColour(ap.seqPanel.seqCanvas.getFeatureRenderer()
1141 .getColour(renderOrder[ro]).getRGB());
1144 setting.setDisplay(av.featuresDisplayed
1145 .containsKey(renderOrder[ro]));
1146 float rorder = ap.seqPanel.seqCanvas.getFeatureRenderer().getOrder(
1150 setting.setOrder(rorder);
1152 fs.addSetting(setting);
1153 settingsAdded.addElement(renderOrder[ro]);
1156 // Make sure we save none displayed feature settings
1157 Enumeration en = ap.seqPanel.seqCanvas.getFeatureRenderer().featureColours
1159 while (en.hasMoreElements())
1161 String key = en.nextElement().toString();
1162 if (settingsAdded.contains(key))
1167 Setting setting = new Setting();
1168 setting.setType(key);
1169 setting.setColour(ap.seqPanel.seqCanvas.getFeatureRenderer()
1170 .getColour(key).getRGB());
1172 setting.setDisplay(false);
1173 float rorder = ap.seqPanel.seqCanvas.getFeatureRenderer().getOrder(
1177 setting.setOrder(rorder);
1179 fs.addSetting(setting);
1180 settingsAdded.addElement(key);
1182 en = ap.seqPanel.seqCanvas.getFeatureRenderer().featureGroups.keys();
1183 Vector groupsAdded = new Vector();
1184 while (en.hasMoreElements())
1186 String grp = en.nextElement().toString();
1187 if (groupsAdded.contains(grp))
1191 Group g = new Group();
1193 g.setDisplay(((Boolean) ap.seqPanel.seqCanvas.getFeatureRenderer().featureGroups
1194 .get(grp)).booleanValue());
1196 groupsAdded.addElement(grp);
1198 jms.setFeatureSettings(fs);
1202 if (av.hasHiddenColumns)
1204 if (av.getColumnSelection() == null
1205 || av.getColumnSelection().getHiddenColumns() == null)
1207 warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1211 for (int c = 0; c < av.getColumnSelection().getHiddenColumns()
1214 int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
1216 HiddenColumns hc = new HiddenColumns();
1217 hc.setStart(region[0]);
1218 hc.setEnd(region[1]);
1219 view.addHiddenColumns(hc);
1224 jms.addViewport(view);
1226 object.setJalviewModelSequence(jms);
1227 object.getVamsasModel().addSequenceSet(vamsasSet);
1229 if (jout != null && fileName != null)
1231 // We may not want to write the object to disk,
1232 // eg we can copy the alignViewport to a new view object
1233 // using save and then load
1236 JarEntry entry = new JarEntry(fileName);
1237 jout.putNextEntry(entry);
1238 PrintWriter pout = new PrintWriter(new OutputStreamWriter(jout,
1240 org.exolab.castor.xml.Marshaller marshaller = new org.exolab.castor.xml.Marshaller(
1242 marshaller.marshal(object);
1245 } catch (Exception ex)
1247 // TODO: raise error in GUI if marshalling failed.
1248 ex.printStackTrace();
1255 * External mapping between jalview objects and objects yielding a valid and
1256 * unique object ID string. This is null for normal Jalview project IO, but
1257 * non-null when a jalview project is being read or written as part of a
1260 IdentityHashMap jv2vobj = null;
1263 * Construct a unique ID for jvobj using either existing bindings or if none
1264 * exist, the result of the hashcode call for the object.
1267 * jalview data object
1268 * @return unique ID for referring to jvobj
1270 private String makeHashCode(Object jvobj, String altCode)
1272 if (jv2vobj != null)
1274 Object id = jv2vobj.get(jvobj);
1277 return id.toString();
1279 // check string ID mappings
1280 if (jvids2vobj != null && jvobj instanceof String)
1282 id = jvids2vobj.get(jvobj);
1286 return id.toString();
1288 // give up and warn that something has gone wrong
1289 warn("Cannot find ID for object in external mapping : " + jvobj);
1295 * return local jalview object mapped to ID, if it exists
1299 * @return null or object bound to idcode
1301 private Object retrieveExistingObj(String idcode)
1303 if (idcode != null && vobj2jv != null)
1305 return vobj2jv.get(idcode);
1311 * binding from ID strings from external mapping table to jalview data model
1314 private Hashtable vobj2jv;
1316 private Sequence createVamsasSequence(String id, SequenceI jds)
1318 return createVamsasSequence(true, id, jds, null);
1321 private Sequence createVamsasSequence(boolean recurse, String id,
1322 SequenceI jds, SequenceI parentseq)
1324 Sequence vamsasSeq = new Sequence();
1325 vamsasSeq.setId(id);
1326 vamsasSeq.setName(jds.getName());
1327 vamsasSeq.setSequence(jds.getSequenceAsString());
1328 vamsasSeq.setDescription(jds.getDescription());
1329 jalview.datamodel.DBRefEntry[] dbrefs = null;
1330 if (jds.getDatasetSequence() != null)
1332 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
1333 if (jds.getDatasetSequence().getDBRef() != null)
1335 dbrefs = jds.getDatasetSequence().getDBRef();
1340 vamsasSeq.setDsseqid(id); // so we can tell which sequences really are
1341 // dataset sequences only
1342 dbrefs = jds.getDBRef();
1346 for (int d = 0; d < dbrefs.length; d++)
1348 DBRef dbref = new DBRef();
1349 dbref.setSource(dbrefs[d].getSource());
1350 dbref.setVersion(dbrefs[d].getVersion());
1351 dbref.setAccessionId(dbrefs[d].getAccessionId());
1352 if (dbrefs[d].hasMap())
1354 Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
1356 dbref.setMapping(mp);
1358 vamsasSeq.addDBRef(dbref);
1364 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
1365 SequenceI parentseq, SequenceI jds, boolean recurse)
1368 if (jmp.getMap() != null)
1372 jalview.util.MapList mlst = jmp.getMap();
1373 int r[] = mlst.getFromRanges();
1374 for (int s = 0; s < r.length; s += 2)
1376 MapListFrom mfrom = new MapListFrom();
1377 mfrom.setStart(r[s]);
1378 mfrom.setEnd(r[s + 1]);
1379 mp.addMapListFrom(mfrom);
1381 r = mlst.getToRanges();
1382 for (int s = 0; s < r.length; s += 2)
1384 MapListTo mto = new MapListTo();
1386 mto.setEnd(r[s + 1]);
1387 mp.addMapListTo(mto);
1389 mp.setMapFromUnit(mlst.getFromRatio());
1390 mp.setMapToUnit(mlst.getToRatio());
1391 if (jmp.getTo() != null)
1393 MappingChoice mpc = new MappingChoice();
1395 && (parentseq != jmp.getTo() || parentseq
1396 .getDatasetSequence() != jmp.getTo()))
1398 mpc.setSequence(createVamsasSequence(false, seqHash(jmp.getTo()),
1404 SequenceI ps = null;
1405 if (parentseq != jmp.getTo()
1406 && parentseq.getDatasetSequence() != jmp.getTo())
1408 // chaining dbref rather than a handshaking one
1409 jmpid = seqHash(ps = jmp.getTo());
1413 jmpid = seqHash(ps = parentseq);
1415 mpc.setDseqFor(jmpid);
1416 if (!seqRefIds.containsKey(mpc.getDseqFor()))
1418 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
1419 seqRefIds.put(mpc.getDseqFor(), ps);
1423 jalview.bin.Cache.log.debug("reusing DseqFor ID");
1426 mp.setMappingChoice(mpc);
1432 String SetUserColourScheme(jalview.schemes.ColourSchemeI cs,
1433 Vector userColours, JalviewModelSequence jms)
1436 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
1437 boolean newucs = false;
1438 if (!userColours.contains(ucs))
1440 userColours.add(ucs);
1443 id = "ucs" + userColours.indexOf(ucs);
1446 // actually create the scheme's entry in the XML model
1447 java.awt.Color[] colours = ucs.getColours();
1448 jalview.schemabinding.version2.UserColours uc = new jalview.schemabinding.version2.UserColours();
1449 jalview.schemabinding.version2.UserColourScheme jbucs = new jalview.schemabinding.version2.UserColourScheme();
1451 for (int i = 0; i < colours.length; i++)
1453 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
1454 col.setName(ResidueProperties.aa[i]);
1455 col.setRGB(jalview.util.Format.getHexString(colours[i]));
1456 jbucs.addColour(col);
1458 if (ucs.getLowerCaseColours() != null)
1460 colours = ucs.getLowerCaseColours();
1461 for (int i = 0; i < colours.length; i++)
1463 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
1464 col.setName(ResidueProperties.aa[i].toLowerCase());
1465 col.setRGB(jalview.util.Format.getHexString(colours[i]));
1466 jbucs.addColour(col);
1471 uc.setUserColourScheme(jbucs);
1472 jms.addUserColours(uc);
1478 jalview.schemes.UserColourScheme GetUserColourScheme(
1479 JalviewModelSequence jms, String id)
1481 UserColours[] uc = jms.getUserColours();
1482 UserColours colours = null;
1484 for (int i = 0; i < uc.length; i++)
1486 if (uc[i].getId().equals(id))
1494 java.awt.Color[] newColours = new java.awt.Color[24];
1496 for (int i = 0; i < 24; i++)
1498 newColours[i] = new java.awt.Color(Integer.parseInt(colours
1499 .getUserColourScheme().getColour(i).getRGB(), 16));
1502 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
1505 if (colours.getUserColourScheme().getColourCount() > 24)
1507 newColours = new java.awt.Color[23];
1508 for (int i = 0; i < 23; i++)
1510 newColours[i] = new java.awt.Color(Integer.parseInt(colours
1511 .getUserColourScheme().getColour(i + 24).getRGB(), 16));
1513 ucs.setLowerCaseColours(newColours);
1520 * contains last error message (if any) encountered by XML loader.
1522 String errorMessage = null;
1525 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
1526 * exceptions are raised during project XML parsing
1528 public boolean attemptversion1parse = true;
1531 * Load a jalview project archive from a jar file
1534 * - HTTP URL or filename
1536 public AlignFrame LoadJalviewAlign(final String file)
1539 jalview.gui.AlignFrame af = null;
1543 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
1544 // Workaround is to make sure caller implements the JarInputStreamProvider
1546 // so we can re-open the jar input stream for each entry.
1548 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
1549 af = LoadJalviewAlign(jprovider);
1550 } catch (MalformedURLException e)
1552 errorMessage = "Invalid URL format for '" + file + "'";
1558 private jarInputStreamProvider createjarInputStreamProvider(
1559 final String file) throws MalformedURLException
1562 errorMessage = null;
1563 uniqueSetSuffix = null;
1565 viewportsAdded = null;
1566 frefedSequence = null;
1568 if (file.startsWith("http://"))
1570 url = new URL(file);
1572 final URL _url = url;
1573 return new jarInputStreamProvider()
1576 public JarInputStream getJarInputStream() throws IOException
1580 return new JarInputStream(_url.openStream());
1584 return new JarInputStream(new FileInputStream(file));
1588 public String getFilename()
1596 * Recover jalview session from a jalview project archive. Caller may
1597 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
1598 * themselves. Any null fields will be initialised with default values,
1599 * non-null fields are left alone.
1604 public AlignFrame LoadJalviewAlign(final jarInputStreamProvider jprovider)
1606 errorMessage = null;
1607 if (uniqueSetSuffix == null)
1609 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
1611 if (seqRefIds == null)
1613 seqRefIds = new Hashtable();
1615 if (viewportsAdded == null)
1617 viewportsAdded = new Hashtable();
1619 if (frefedSequence == null)
1621 frefedSequence = new Vector();
1624 jalview.gui.AlignFrame af = null;
1625 Hashtable gatherToThisFrame = new Hashtable();
1626 final String file = jprovider.getFilename();
1629 JarInputStream jin = null;
1630 JarEntry jarentry = null;
1635 jin = jprovider.getJarInputStream();
1636 for (int i = 0; i < entryCount; i++)
1638 jarentry = jin.getNextJarEntry();
1641 if (jarentry != null && jarentry.getName().endsWith(".xml"))
1643 InputStreamReader in = new InputStreamReader(jin, "UTF-8");
1644 JalviewModel object = new JalviewModel();
1646 Unmarshaller unmar = new Unmarshaller(object);
1647 unmar.setValidation(false);
1648 object = (JalviewModel) unmar.unmarshal(in);
1649 if (true) // !skipViewport(object))
1651 af = LoadFromObject(object, file, true, jprovider);
1652 if (af.viewport.gatherViewsHere)
1654 gatherToThisFrame.put(af.viewport.getSequenceSetId(), af);
1659 else if (jarentry != null)
1661 // Some other file here.
1664 } while (jarentry != null);
1665 resolveFrefedSequences();
1666 } catch (java.io.FileNotFoundException ex)
1668 ex.printStackTrace();
1669 errorMessage = "Couldn't locate Jalview XML file : " + file;
1670 System.err.println("Exception whilst loading jalview XML file : "
1672 } catch (java.net.UnknownHostException ex)
1674 ex.printStackTrace();
1675 errorMessage = "Couldn't locate Jalview XML file : " + file;
1676 System.err.println("Exception whilst loading jalview XML file : "
1678 } catch (Exception ex)
1680 System.err.println("Parsing as Jalview Version 2 file failed.");
1681 ex.printStackTrace(System.err);
1682 if (attemptversion1parse)
1684 // Is Version 1 Jar file?
1687 af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
1688 } catch (Exception ex2)
1690 System.err.println("Exception whilst loading as jalviewXMLV1:");
1691 ex2.printStackTrace();
1695 if (Desktop.instance != null)
1697 Desktop.instance.stopLoading();
1701 System.out.println("Successfully loaded archive file");
1704 ex.printStackTrace();
1706 System.err.println("Exception whilst loading jalview XML file : "
1708 } catch (OutOfMemoryError e)
1710 // Don't use the OOM Window here
1711 errorMessage = "Out of memory loading jalview XML file";
1712 System.err.println("Out of memory whilst loading jalview XML file");
1713 e.printStackTrace();
1716 if (Desktop.instance != null)
1718 Desktop.instance.stopLoading();
1721 Enumeration en = gatherToThisFrame.elements();
1722 while (en.hasMoreElements())
1724 Desktop.instance.gatherViews((AlignFrame) en.nextElement());
1726 if (errorMessage != null)
1734 * check errorMessage for a valid error message and raise an error box in the
1735 * GUI or write the current errorMessage to stderr and then clear the error
1738 protected void reportErrors()
1740 reportErrors(false);
1743 protected void reportErrors(final boolean saving)
1745 if (errorMessage != null)
1747 final String finalErrorMessage = errorMessage;
1750 javax.swing.SwingUtilities.invokeLater(new Runnable()
1754 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1755 finalErrorMessage, "Error "
1756 + (saving ? "saving" : "loading")
1757 + " Jalview file", JOptionPane.WARNING_MESSAGE);
1763 System.err.println("Problem loading Jalview file: " + errorMessage);
1766 errorMessage = null;
1769 Hashtable alreadyLoadedPDB;
1772 * when set, local views will be updated from view stored in JalviewXML
1773 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
1774 * sync if this is set to true.
1776 private boolean updateLocalViews = false;
1778 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId)
1780 if (alreadyLoadedPDB == null)
1781 alreadyLoadedPDB = new Hashtable();
1783 if (alreadyLoadedPDB.containsKey(pdbId))
1784 return alreadyLoadedPDB.get(pdbId).toString();
1788 JarInputStream jin = jprovider.getJarInputStream();
1790 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
1791 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
1792 * FileInputStream(jprovider)); }
1795 JarEntry entry = null;
1798 entry = jin.getNextJarEntry();
1799 } while (entry != null && !entry.getName().equals(pdbId));
1802 BufferedReader in = new BufferedReader(new InputStreamReader(jin));
1803 File outFile = File.createTempFile("jalview_pdb", ".txt");
1804 outFile.deleteOnExit();
1805 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
1808 while ((data = in.readLine()) != null)
1815 } catch (Exception foo)
1821 alreadyLoadedPDB.put(pdbId, outFile.getAbsolutePath());
1822 return outFile.getAbsolutePath();
1826 warn("Couldn't find PDB file entry in Jalview Jar for " + pdbId);
1828 } catch (Exception ex)
1830 ex.printStackTrace();
1836 private class JvAnnotRow
1838 public JvAnnotRow(int i, AlignmentAnnotation jaa)
1845 * persisted version of annotation row from which to take vis properties
1847 public jalview.datamodel.AlignmentAnnotation template;
1850 * original position of the annotation row in the alignment
1856 * Load alignment frame from jalview XML DOM object
1861 * filename source string
1862 * @param loadTreesAndStructures
1863 * when false only create Viewport
1865 * data source provider
1866 * @return alignment frame created from view stored in DOM
1868 AlignFrame LoadFromObject(JalviewModel object, String file,
1869 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
1871 SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
1872 Sequence[] vamsasSeq = vamsasSet.getSequence();
1874 JalviewModelSequence jms = object.getJalviewModelSequence();
1876 Viewport view = jms.getViewport(0);
1877 // ////////////////////////////////
1880 Vector hiddenSeqs = null;
1881 jalview.datamodel.Sequence jseq;
1883 ArrayList tmpseqs = new ArrayList();
1885 boolean multipleView = false;
1887 JSeq[] JSEQ = object.getJalviewModelSequence().getJSeq();
1888 int vi = 0; // counter in vamsasSeq array
1889 for (int i = 0; i < JSEQ.length; i++)
1891 String seqId = JSEQ[i].getId();
1893 if (seqRefIds.get(seqId) != null)
1895 tmpseqs.add((jalview.datamodel.Sequence) seqRefIds.get(seqId));
1896 multipleView = true;
1900 jseq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
1901 vamsasSeq[vi].getSequence());
1902 jseq.setDescription(vamsasSeq[vi].getDescription());
1903 jseq.setStart(JSEQ[i].getStart());
1904 jseq.setEnd(JSEQ[i].getEnd());
1905 jseq.setVamsasId(uniqueSetSuffix + seqId);
1906 seqRefIds.put(vamsasSeq[vi].getId(), jseq);
1911 if (JSEQ[i].getHidden())
1913 if (hiddenSeqs == null)
1915 hiddenSeqs = new Vector();
1918 hiddenSeqs.addElement((jalview.datamodel.Sequence) seqRefIds
1925 // Create the alignment object from the sequence set
1926 // ///////////////////////////////
1927 jalview.datamodel.Sequence[] orderedSeqs = new jalview.datamodel.Sequence[tmpseqs
1930 tmpseqs.toArray(orderedSeqs);
1932 jalview.datamodel.Alignment al = new jalview.datamodel.Alignment(
1935 // / Add the alignment properties
1936 for (int i = 0; i < vamsasSet.getSequenceSetPropertiesCount(); i++)
1938 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties(i);
1939 al.setProperty(ssp.getKey(), ssp.getValue());
1943 // SequenceFeatures are added to the DatasetSequence,
1944 // so we must create or recover the dataset before loading features
1945 // ///////////////////////////////
1946 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
1948 // older jalview projects do not have a dataset id.
1949 al.setDataset(null);
1953 recoverDatasetFor(vamsasSet, al);
1955 // ///////////////////////////////
1957 Hashtable pdbloaded = new Hashtable();
1960 // load sequence features, database references and any associated PDB
1961 // structures for the alignment
1962 for (int i = 0; i < vamsasSeq.length; i++)
1964 if (JSEQ[i].getFeaturesCount() > 0)
1966 Features[] features = JSEQ[i].getFeatures();
1967 for (int f = 0; f < features.length; f++)
1969 jalview.datamodel.SequenceFeature sf = new jalview.datamodel.SequenceFeature(
1970 features[f].getType(), features[f].getDescription(),
1971 features[f].getStatus(), features[f].getBegin(),
1972 features[f].getEnd(), features[f].getFeatureGroup());
1974 sf.setScore(features[f].getScore());
1975 for (int od = 0; od < features[f].getOtherDataCount(); od++)
1977 OtherData keyValue = features[f].getOtherData(od);
1978 if (keyValue.getKey().startsWith("LINK"))
1980 sf.addLink(keyValue.getValue());
1984 sf.setValue(keyValue.getKey(), keyValue.getValue());
1989 al.getSequenceAt(i).getDatasetSequence().addSequenceFeature(sf);
1992 if (vamsasSeq[i].getDBRefCount() > 0)
1994 addDBRefs(al.getSequenceAt(i).getDatasetSequence(), vamsasSeq[i]);
1996 if (JSEQ[i].getPdbidsCount() > 0)
1998 Pdbids[] ids = JSEQ[i].getPdbids();
1999 for (int p = 0; p < ids.length; p++)
2001 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
2002 entry.setId(ids[p].getId());
2003 entry.setType(ids[p].getType());
2004 if (ids[p].getFile() != null)
2006 if (!pdbloaded.containsKey(ids[p].getFile()))
2008 entry.setFile(loadPDBFile(jprovider, ids[p].getId()));
2012 entry.setFile(pdbloaded.get(ids[p].getId()).toString());
2016 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
2020 } // end !multipleview
2022 // ///////////////////////////////
2023 // LOAD SEQUENCE MAPPINGS
2025 if (vamsasSet.getAlcodonFrameCount() > 0)
2027 // TODO Potentially this should only be done once for all views of an
2029 AlcodonFrame[] alc = vamsasSet.getAlcodonFrame();
2030 for (int i = 0; i < alc.length; i++)
2032 jalview.datamodel.AlignedCodonFrame cf = new jalview.datamodel.AlignedCodonFrame(
2033 alc[i].getAlcodonCount());
2034 if (alc[i].getAlcodonCount() > 0)
2036 Alcodon[] alcods = alc[i].getAlcodon();
2037 for (int p = 0; p < cf.codons.length; p++)
2039 if (alcods[p].hasPos1() && alcods[p].hasPos2()
2040 && alcods[p].hasPos3())
2042 // translated codons require three valid positions
2043 cf.codons[p] = new int[3];
2044 cf.codons[p][0] = (int) alcods[p].getPos1();
2045 cf.codons[p][1] = (int) alcods[p].getPos2();
2046 cf.codons[p][2] = (int) alcods[p].getPos3();
2050 cf.codons[p] = null;
2054 if (alc[i].getAlcodMapCount() > 0)
2056 AlcodMap[] maps = alc[i].getAlcodMap();
2057 for (int m = 0; m < maps.length; m++)
2059 SequenceI dnaseq = (SequenceI) seqRefIds
2060 .get(maps[m].getDnasq());
2062 jalview.datamodel.Mapping mapping = null;
2063 // attach to dna sequence reference.
2064 if (maps[m].getMapping() != null)
2066 mapping = addMapping(maps[m].getMapping());
2070 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
2075 frefedSequence.add(new Object[]
2076 { maps[m].getDnasq(), cf, mapping });
2080 al.addCodonFrame(cf);
2085 // ////////////////////////////////
2087 ArrayList<JvAnnotRow> autoAlan = new ArrayList<JvAnnotRow>();
2089 * store any annotations which forward reference a group's ID
2091 Hashtable<String,ArrayList<jalview.datamodel.AlignmentAnnotation>> groupAnnotRefs = new Hashtable<String,ArrayList<jalview.datamodel.AlignmentAnnotation>>();
2093 if (vamsasSet.getAnnotationCount() > 0)
2095 Annotation[] an = vamsasSet.getAnnotation();
2097 for (int i = 0; i < an.length; i++)
2100 * test if annotation is automatically calculated for this view only
2102 boolean autoForView = false;
2103 if (an[i].getLabel().equals("Quality")
2104 || an[i].getLabel().equals("Conservation")
2105 || an[i].getLabel().equals("Consensus"))
2107 // Kludge for pre 2.5 projects which lacked the autocalculated flag
2109 if (!an[i].hasAutoCalculated())
2111 an[i].setAutoCalculated(true);
2114 if (autoForView || (an[i].hasAutoCalculated() && an[i].isAutoCalculated())) {
2115 // remove ID - we don't recover annotation from other views for
2116 // view-specific annotation
2120 // set visiblity for other annotation in this view
2121 if (an[i].getId() != null
2122 && annotationIds.containsKey(an[i].getId()))
2124 jalview.datamodel.AlignmentAnnotation jda = (jalview.datamodel.AlignmentAnnotation) annotationIds
2125 .get(an[i].getId());
2126 // in principle Visible should always be true for annotation displayed
2127 // in multiple views
2128 if (an[i].hasVisible())
2129 jda.visible = an[i].getVisible();
2131 al.addAnnotation(jda);
2135 // Construct new annotation from model.
2136 AnnotationElement[] ae = an[i].getAnnotationElement();
2137 jalview.datamodel.Annotation[] anot = null;
2139 if (!an[i].getScoreOnly())
2141 anot = new jalview.datamodel.Annotation[al.getWidth()];
2142 for (int aa = 0; aa < ae.length && aa < anot.length; aa++)
2144 if (ae[aa].getPosition() >= anot.length)
2147 anot[ae[aa].getPosition()] = new jalview.datamodel.Annotation(
2149 ae[aa].getDisplayCharacter(), ae[aa].getDescription(),
2150 (ae[aa].getSecondaryStructure() == null || ae[aa]
2151 .getSecondaryStructure().length() == 0) ? ' '
2152 : ae[aa].getSecondaryStructure().charAt(0),
2156 // JBPNote: Consider verifying dataflow for IO of secondary
2157 // structure annotation read from Stockholm files
2158 // this was added to try to ensure that
2159 // if (anot[ae[aa].getPosition()].secondaryStructure>' ')
2161 // anot[ae[aa].getPosition()].displayCharacter = "";
2163 anot[ae[aa].getPosition()].colour = new java.awt.Color(
2164 ae[aa].getColour());
2167 jalview.datamodel.AlignmentAnnotation jaa = null;
2169 if (an[i].getGraph())
2171 float llim=0,hlim=0;
2172 // if (autoForView || an[i].isAutoCalculated()) {
2175 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
2176 an[i].getDescription(), anot, llim, hlim, an[i].getGraphType());
2178 jaa.graphGroup = an[i].getGraphGroup();
2180 if (an[i].getThresholdLine() != null)
2182 jaa.setThreshold(new jalview.datamodel.GraphLine(an[i]
2183 .getThresholdLine().getValue(), an[i]
2184 .getThresholdLine().getLabel(), new java.awt.Color(
2185 an[i].getThresholdLine().getColour())));
2188 if (autoForView || an[i].isAutoCalculated()) {
2189 // Hardwire the symbol display line to ensure that labels for histograms are displayed
2195 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
2196 an[i].getDescription(), anot);
2200 // register new annotation
2201 if (an[i].getId() != null)
2203 annotationIds.put(an[i].getId(), jaa);
2204 jaa.annotationId = an[i].getId();
2206 // recover sequence association
2207 if (an[i].getSequenceRef() != null)
2209 if (al.findName(an[i].getSequenceRef()) != null)
2211 jaa.createSequenceMapping(
2212 al.findName(an[i].getSequenceRef()), 1, true);
2213 al.findName(an[i].getSequenceRef()).addAlignmentAnnotation(
2218 // and make a note of any group association
2219 if (an[i].getGroupRef() != null && an[i].getGroupRef().length() > 0)
2221 ArrayList<jalview.datamodel.AlignmentAnnotation> aal=groupAnnotRefs.get(an[i].getGroupRef());
2223 aal = new ArrayList<jalview.datamodel.AlignmentAnnotation>();
2224 groupAnnotRefs.put(an[i].getGroupRef(),aal);
2229 if (an[i].hasScore())
2231 jaa.setScore(an[i].getScore());
2233 if (an[i].hasVisible())
2234 jaa.visible = an[i].getVisible();
2236 if (an[i].hasCentreColLabels())
2237 jaa.centreColLabels = an[i].getCentreColLabels();
2239 if (an[i].hasScaleColLabels())
2241 jaa.scaleColLabel = an[i].getScaleColLabels();
2243 if (an[i].hasAutoCalculated() && an[i].isAutoCalculated())
2245 // newer files have an 'autoCalculated' flag and store calculation
2246 // state in viewport properties
2247 jaa.autoCalculated = true; // means annotation will be marked for
2248 // update at end of load.
2250 if (an[i].hasGraphHeight())
2252 jaa.graphHeight = an[i].getGraphHeight();
2254 if (jaa.autoCalculated)
2256 autoAlan.add(new JvAnnotRow(i, jaa));
2258 // if (!autoForView)
2260 // add autocalculated group annotation and any user created annotation for the view
2261 al.addAnnotation(jaa);
2266 // ///////////////////////
2268 // Create alignment markup and styles for this view
2269 if (jms.getJGroupCount() > 0)
2271 JGroup[] groups = jms.getJGroup();
2273 for (int i = 0; i < groups.length; i++)
2275 ColourSchemeI cs = null;
2277 if (groups[i].getColour() != null)
2279 if (groups[i].getColour().startsWith("ucs"))
2281 cs = GetUserColourScheme(jms, groups[i].getColour());
2285 cs = ColourSchemeProperty.getColour(al, groups[i].getColour());
2290 cs.setThreshold(groups[i].getPidThreshold(), true);
2294 Vector seqs = new Vector();
2296 for (int s = 0; s < groups[i].getSeqCount(); s++)
2298 String seqId = groups[i].getSeq(s) + "";
2299 jalview.datamodel.SequenceI ts = (jalview.datamodel.SequenceI) seqRefIds
2304 seqs.addElement(ts);
2308 if (seqs.size() < 1)
2313 jalview.datamodel.SequenceGroup sg = new jalview.datamodel.SequenceGroup(
2314 seqs, groups[i].getName(), cs, groups[i].getDisplayBoxes(),
2315 groups[i].getDisplayText(), groups[i].getColourText(),
2316 groups[i].getStart(), groups[i].getEnd());
2318 sg.setOutlineColour(new java.awt.Color(groups[i].getOutlineColour()));
2320 sg.textColour = new java.awt.Color(groups[i].getTextCol1());
2321 sg.textColour2 = new java.awt.Color(groups[i].getTextCol2());
2322 sg.setShowNonconserved(groups[i].hasShowUnconserved() ? groups[i]
2323 .isShowUnconserved() : false);
2324 sg.thresholdTextColour = groups[i].getTextColThreshold();
2325 if (groups[i].hasShowConsensusHistogram())
2327 sg.setShowConsensusHistogram(groups[i].isShowConsensusHistogram());
2330 if (groups[i].hasShowSequenceLogo())
2332 sg.setshowSequenceLogo(groups[i].isShowSequenceLogo());
2334 if (groups[i].hasIgnoreGapsinConsensus())
2336 sg.setIgnoreGapsConsensus(groups[i].getIgnoreGapsinConsensus());
2338 if (groups[i].getConsThreshold() != 0)
2340 jalview.analysis.Conservation c = new jalview.analysis.Conservation(
2341 "All", ResidueProperties.propHash, 3,
2342 sg.getSequences(null), 0, sg.getWidth() - 1);
2344 c.verdict(false, 25);
2345 sg.cs.setConservation(c);
2348 if (groups[i].getId() != null && groupAnnotRefs.size() > 0)
2350 // re-instate unique group/annotation row reference
2351 ArrayList<jalview.datamodel.AlignmentAnnotation> jaal = groupAnnotRefs
2352 .get(groups[i].getId());
2355 for (jalview.datamodel.AlignmentAnnotation jaa:jaal) {
2357 if (jaa.autoCalculated)
2359 // match up and try to set group autocalc alignment row for this annotation
2360 if (jaa.label.startsWith("Consensus for ")) {
2361 sg.setConsensus(jaa);
2363 // match up and try to set group autocalc alignment row for this annotation
2364 if (jaa.label.startsWith("Conservation for ")) {
2365 sg.setConservationRow(jaa);
2376 // ///////////////////////////////
2379 // If we just load in the same jar file again, the sequenceSetId
2380 // will be the same, and we end up with multiple references
2381 // to the same sequenceSet. We must modify this id on load
2382 // so that each load of the file gives a unique id
2383 String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
2384 String viewId = (view.getId() == null ? null : view.getId()
2386 AlignFrame af = null;
2387 AlignViewport av = null;
2388 // now check to see if we really need to create a new viewport.
2389 if (multipleView && viewportsAdded.size() == 0)
2391 // We recovered an alignment for which a viewport already exists.
2392 // TODO: fix up any settings necessary for overlaying stored state onto
2393 // state recovered from another document. (may not be necessary).
2394 // we may need a binding from a viewport in memory to one recovered from
2396 // and then recover its containing af to allow the settings to be applied.
2397 // TODO: fix for vamsas demo
2399 .println("About to recover a viewport for existing alignment: Sequence set ID is "
2401 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
2402 if (seqsetobj != null)
2404 if (seqsetobj instanceof String)
2406 uniqueSeqSetId = (String) seqsetobj;
2408 .println("Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
2414 .println("Warning : Collision between sequence set ID string and existing jalview object mapping.");
2419 AlignmentPanel ap = null;
2420 boolean isnewview = true;
2423 // Check to see if this alignment already has a view id == viewId
2424 jalview.gui.AlignmentPanel views[] = Desktop
2425 .getAlignmentPanels(uniqueSeqSetId);
2426 if (views != null && views.length > 0)
2428 for (int v = 0; v < views.length; v++)
2430 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
2432 // recover the existing alignpanel, alignframe, viewport
2433 af = views[v].alignFrame;
2436 // TODO: could even skip resetting view settings if we don't want to
2437 // change the local settings from other jalview processes
2446 af = loadViewport(file, JSEQ, hiddenSeqs, al, jms, view,
2447 uniqueSeqSetId, viewId, autoAlan);
2452 // /////////////////////////////////////
2453 if (loadTreesAndStructures && jms.getTreeCount() > 0)
2457 for (int t = 0; t < jms.getTreeCount(); t++)
2460 Tree tree = jms.getTree(t);
2462 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
2465 tp = af.ShowNewickTree(
2466 new jalview.io.NewickFile(tree.getNewick()),
2467 tree.getTitle(), tree.getWidth(), tree.getHeight(),
2468 tree.getXpos(), tree.getYpos());
2469 if (tree.getId() != null)
2471 // perhaps bind the tree id to something ?
2476 // update local tree attributes ?
2477 // TODO: should check if tp has been manipulated by user - if so its
2478 // settings shouldn't be modified
2479 tp.setTitle(tree.getTitle());
2480 tp.setBounds(new Rectangle(tree.getXpos(), tree.getYpos(), tree
2481 .getWidth(), tree.getHeight()));
2482 tp.av = av; // af.viewport; // TODO: verify 'associate with all
2485 tp.treeCanvas.av = av; // af.viewport;
2486 tp.treeCanvas.ap = ap; // af.alignPanel;
2491 warn("There was a problem recovering stored Newick tree: \n"
2492 + tree.getNewick());
2496 tp.fitToWindow.setState(tree.getFitToWindow());
2497 tp.fitToWindow_actionPerformed(null);
2499 if (tree.getFontName() != null)
2501 tp.setTreeFont(new java.awt.Font(tree.getFontName(), tree
2502 .getFontStyle(), tree.getFontSize()));
2506 tp.setTreeFont(new java.awt.Font(view.getFontName(), view
2507 .getFontStyle(), tree.getFontSize()));
2510 tp.showPlaceholders(tree.getMarkUnlinked());
2511 tp.showBootstrap(tree.getShowBootstrap());
2512 tp.showDistances(tree.getShowDistances());
2514 tp.treeCanvas.threshold = tree.getThreshold();
2516 if (tree.getCurrentTree())
2518 af.viewport.setCurrentTree(tp.getTree());
2522 } catch (Exception ex)
2524 ex.printStackTrace();
2528 // //LOAD STRUCTURES
2529 if (loadTreesAndStructures)
2531 // run through all PDB ids on the alignment, and collect mappings between
2532 // jmol view ids and all sequences referring to it
2533 Hashtable<String, Object[]> jmolViewIds = new Hashtable();
2535 for (int i = 0; i < JSEQ.length; i++)
2537 if (JSEQ[i].getPdbidsCount() > 0)
2539 Pdbids[] ids = JSEQ[i].getPdbids();
2540 for (int p = 0; p < ids.length; p++)
2542 for (int s = 0; s < ids[p].getStructureStateCount(); s++)
2544 // check to see if we haven't already created this structure view
2545 String sviewid = (ids[p].getStructureState(s).getViewId() == null) ? null
2546 : ids[p].getStructureState(s).getViewId()
2548 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
2549 // Originally : ids[p].getFile()
2550 // : TODO: verify external PDB file recovery still works in normal
2551 // jalview project load
2552 jpdb.setFile(loadPDBFile(jprovider, ids[p].getId()));
2553 jpdb.setId(ids[p].getId());
2555 int x = ids[p].getStructureState(s).getXpos();
2556 int y = ids[p].getStructureState(s).getYpos();
2557 int width = ids[p].getStructureState(s).getWidth();
2558 int height = ids[p].getStructureState(s).getHeight();
2560 // Probably don't need to do this anymore...
2561 // Desktop.desktop.getComponentAt(x, y);
2562 // TODO: NOW: check that this recovers the PDB file correctly.
2563 String pdbFile = loadPDBFile(jprovider, ids[p].getId());
2564 jalview.datamodel.SequenceI seq = (jalview.datamodel.SequenceI) seqRefIds
2565 .get(JSEQ[i].getId() + "");
2566 if (sviewid == null)
2568 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width
2571 if (!jmolViewIds.containsKey(sviewid))
2573 jmolViewIds.put(sviewid, new Object[]
2575 { x, y, width, height }, "",
2576 new Hashtable<String, Object[]>(), new boolean[]
2577 { false, false, true } });
2578 // Legacy pre-2.7 conversion JAL-823 :
2579 // do not assume any view has to be linked for colour by sequence
2582 // assemble String[] { pdb files }, String[] { id for each
2583 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
2584 // seqs_file 2}, boolean[] {
2585 // linkAlignPanel,superposeWithAlignpanel}} from hash
2586 Object[] jmoldat = (Object[]) jmolViewIds.get(sviewid);
2587 ((boolean[]) jmoldat[3])[0] |= ids[p].getStructureState(s)
2588 .hasAlignwithAlignPanel() ? ids[p].getStructureState(
2589 s).getAlignwithAlignPanel() : false;
2590 // never colour by linked panel if not specified
2591 ((boolean[]) jmoldat[3])[1] |= ids[p].getStructureState(s)
2592 .hasColourwithAlignPanel() ? ids[p]
2593 .getStructureState(s).getColourwithAlignPanel()
2595 // default for pre-2.7 projects is that Jmol colouring is enabled
2596 ((boolean[])jmoldat[3])[2] &=ids[p].getStructureState(s).hasColourByJmol() ? ids[p].getStructureState(s).getColourByJmol() : true;
2598 if (((String) jmoldat[1]).length() < ids[p]
2599 .getStructureState(s).getContent().length())
2602 jmoldat[1] = ids[p].getStructureState(s).getContent();
2605 if (ids[p].getFile() != null)
2607 Object[] seqstrmaps = (Object[]) ((Hashtable) jmoldat[2])
2608 .get(ids[p].getFile());
2609 if (seqstrmaps == null)
2611 ((Hashtable) jmoldat[2]).put(
2612 new File(ids[p].getFile()).toString(),
2613 seqstrmaps = new Object[]
2614 { pdbFile, ids[p].getId(), new Vector(),
2617 if (!((Vector) seqstrmaps[2]).contains(seq))
2619 ((Vector) seqstrmaps[2]).addElement(seq);
2620 // ((Vector)seqstrmaps[3]).addElement(n) :
2621 // in principle, chains
2622 // should be stored here : do we need to
2623 // TODO: store and recover seq/pdb_id :
2629 errorMessage=("The Jmol views in the Jalview 2 project may\nnot be correctly bound to sequences in the alignment.\nIn the case of problems, see note at\nhttp://issues.jalview.org/browse/JAL-747");
2638 // Instantiate the associated Jmol views
2639 for (Entry<String, Object[]> entry : jmolViewIds.entrySet())
2641 String sviewid = entry.getKey();
2642 Object[] svattrib = entry.getValue();
2643 int[] geom = (int[]) svattrib[0];
2644 String state = (String) svattrib[1];
2645 Hashtable<String, Object[]> oldFiles = (Hashtable<String, Object[]>) svattrib[2];
2646 final boolean useinJmolsuperpos = ((boolean[]) svattrib[3])[0], usetoColourbyseq = ((boolean[]) svattrib[3])[1], jmolColouring=((boolean[])svattrib[3])[2];
2647 int x = geom[0], y = geom[1], width = geom[2], height = geom[3];
2648 // collate the pdbfile -> sequence mappings from this view
2649 Vector<String> pdbfilenames = new Vector<String>();
2650 Vector<SequenceI[]> seqmaps = new Vector<SequenceI[]>();
2651 Vector<String> pdbids = new Vector<String>();
2653 // Search to see if we've already created this Jmol view
2654 AppJmol comp = null;
2655 JInternalFrame[] frames = null;
2660 frames = Desktop.desktop.getAllFrames();
2661 } catch (ArrayIndexOutOfBoundsException e)
2663 // occasional No such child exceptions are thrown here...
2668 } catch (Exception f)
2673 } while (frames == null);
2674 // search for any Jmol windows already open from other
2675 // alignment views that exactly match the stored structure state
2676 for (int f = 0; comp == null && f < frames.length; f++)
2678 if (frames[f] instanceof AppJmol)
2681 && ((AppJmol) frames[f]).getViewId().equals(sviewid))
2683 // post jalview 2.4 schema includes structure view id
2684 comp = (AppJmol) frames[f];
2686 else if (frames[f].getX() == x && frames[f].getY() == y
2687 && frames[f].getHeight() == height
2688 && frames[f].getWidth() == width)
2690 comp = (AppJmol) frames[f];
2697 // create a new Jmol window.
2698 // First parse the Jmol state to translate filenames loaded into the
2699 // view, and record the order in which files are shown in the Jmol
2700 // view, so we can add the sequence mappings in same order.
2701 StringBuffer newFileLoc = null;
2702 int cp = 0, ncp, ecp;
2703 while ((ncp = state.indexOf("load ", cp)) > -1)
2705 if (newFileLoc == null)
2707 newFileLoc = new StringBuffer();
2709 newFileLoc.append(state.substring(cp,
2710 ncp = (state.indexOf("\"", ncp + 1) + 1)));
2711 String oldfilenam = state.substring(ncp,
2712 ecp = state.indexOf("\"", ncp));
2713 // recover the new mapping data for this old filename
2714 // have to normalize filename - since Jmol and jalview do filename
2715 // translation differently.
2716 Object[] filedat = oldFiles.get(new File(oldfilenam)
2718 newFileLoc.append(((String) filedat[0]));
2719 pdbfilenames.addElement((String) filedat[0]);
2720 pdbids.addElement((String) filedat[1]);
2721 seqmaps.addElement((SequenceI[]) ((Vector<SequenceI>) filedat[2])
2722 .toArray(new SequenceI[0]));
2723 newFileLoc.append("\"");
2724 cp = ecp + 1; // advance beyond last \" and set cursor so we can
2725 // look for next file statement.
2729 // just append rest of state
2730 newFileLoc.append(state.substring(cp));
2735 .print("Ignoring incomplete Jmol state for PDB ids: ");
2736 newFileLoc = new StringBuffer(state);
2737 newFileLoc.append("; load append ");
2738 for (String id : oldFiles.keySet())
2740 // add this and any other pdb files that should be present in
2742 Object[] filedat = oldFiles.get(id);
2744 newFileLoc.append(((String) filedat[0]));
2745 pdbfilenames.addElement((String) filedat[0]);
2746 pdbids.addElement((String) filedat[1]);
2747 seqmaps.addElement((SequenceI[]) ((Vector<SequenceI>) filedat[2])
2748 .toArray(new SequenceI[0]));
2749 newFileLoc.append(" \"");
2750 newFileLoc.append((String) filedat[0]);
2751 newFileLoc.append("\"");
2754 newFileLoc.append(";");
2757 if (newFileLoc != null)
2759 int histbug = newFileLoc.indexOf("history = ");
2761 int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";",
2763 String val = (diff == -1) ? null : newFileLoc.substring(
2765 if (val != null && val.length() >= 4)
2767 if (val.contains("e"))
2769 if (val.trim().equals("true"))
2777 newFileLoc.replace(histbug, diff, val);
2780 // TODO: assemble String[] { pdb files }, String[] { id for each
2781 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
2782 // seqs_file 2}} from hash
2783 final String[] pdbf = (String[]) pdbfilenames
2784 .toArray(new String[pdbfilenames.size()]), id = (String[]) pdbids
2785 .toArray(new String[pdbids.size()]);
2786 final SequenceI[][] sq = (SequenceI[][]) seqmaps
2787 .toArray(new SequenceI[seqmaps.size()][]);
2788 final String fileloc = newFileLoc.toString(), vid = sviewid;
2789 final AlignFrame alf = af;
2790 final java.awt.Rectangle rect = new java.awt.Rectangle(x, y,
2794 javax.swing.SwingUtilities.invokeAndWait(new Runnable()
2798 AppJmol sview = null;
2801 sview = new AppJmol(pdbf, id, sq, alf.alignPanel,
2802 useinJmolsuperpos, usetoColourbyseq, jmolColouring, fileloc,
2804 } catch (OutOfMemoryError ex)
2806 new OOMWarning("restoring structure view for PDB id "
2807 + id, (OutOfMemoryError) ex.getCause());
2808 if (sview != null && sview.isVisible())
2810 sview.closeViewer();
2811 sview.setVisible(false);
2817 } catch (InvocationTargetException ex)
2819 warn("Unexpected error when opening Jmol view.", ex);
2821 } catch (InterruptedException e)
2823 // e.printStackTrace();
2829 // if (comp != null)
2831 // NOTE: if the jalview project is part of a shared session then
2832 // view synchronization should/could be done here.
2834 // add mapping for sequences in this view to an already open Jmol
2836 for (String id : oldFiles.keySet())
2838 // add this and any other pdb files that should be present in the
2840 Object[] filedat = oldFiles.get(id);
2841 String pdbFile = (String) filedat[0];
2842 SequenceI[] seq = (SequenceI[]) ((Vector<SequenceI>) filedat[2])
2843 .toArray(new SequenceI[0]);
2844 ((AppJmol) comp).jmb.ssm.setMapping(seq, null, pdbFile,
2845 jalview.io.AppletFormatAdapter.FILE);
2846 ((AppJmol) comp).jmb.addSequenceForStructFile(pdbFile, seq);
2848 // and add the AlignmentPanel's reference to the Jmol view
2849 ((AppJmol) comp).addAlignmentPanel(ap);
2850 if (useinJmolsuperpos)
2852 ((AppJmol) comp).useAlignmentPanelForSuperposition(ap);
2856 ((AppJmol) comp).excludeAlignmentPanelForSuperposition(ap);
2858 if (usetoColourbyseq)
2860 ((AppJmol) comp).useAlignmentPanelForColourbyseq(ap, !jmolColouring);
2864 ((AppJmol) comp).excludeAlignmentPanelForColourbyseq(ap);
2870 // and finally return.
2874 AlignFrame loadViewport(String file, JSeq[] JSEQ, Vector hiddenSeqs,
2875 Alignment al, JalviewModelSequence jms, Viewport view,
2876 String uniqueSeqSetId, String viewId,
2877 ArrayList<JvAnnotRow> autoAlan)
2879 AlignFrame af = null;
2880 af = new AlignFrame(al, view.getWidth(), view.getHeight(),
2881 uniqueSeqSetId, viewId);
2883 af.setFileName(file, "Jalview");
2885 for (int i = 0; i < JSEQ.length; i++)
2887 af.viewport.setSequenceColour(af.viewport.alignment.getSequenceAt(i),
2888 new java.awt.Color(JSEQ[i].getColour()));
2891 af.viewport.gatherViewsHere = view.getGatheredViews();
2893 if (view.getSequenceSetId() != null)
2895 jalview.gui.AlignViewport av = (jalview.gui.AlignViewport) viewportsAdded
2896 .get(uniqueSeqSetId);
2898 af.viewport.sequenceSetID = uniqueSeqSetId;
2901 // propagate shared settings to this new view
2902 af.viewport.historyList = av.historyList;
2903 af.viewport.redoList = av.redoList;
2907 viewportsAdded.put(uniqueSeqSetId, af.viewport);
2909 // TODO: check if this method can be called repeatedly without
2910 // side-effects if alignpanel already registered.
2911 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
2913 // apply Hidden regions to view.
2914 if (hiddenSeqs != null)
2916 for (int s = 0; s < JSEQ.length; s++)
2918 jalview.datamodel.SequenceGroup hidden = new jalview.datamodel.SequenceGroup();
2920 for (int r = 0; r < JSEQ[s].getHiddenSequencesCount(); r++)
2923 al.getSequenceAt(JSEQ[s].getHiddenSequences(r)), false);
2925 af.viewport.hideRepSequences(al.getSequenceAt(s), hidden);
2928 jalview.datamodel.SequenceI[] hseqs = new jalview.datamodel.SequenceI[hiddenSeqs
2931 for (int s = 0; s < hiddenSeqs.size(); s++)
2933 hseqs[s] = (jalview.datamodel.SequenceI) hiddenSeqs.elementAt(s);
2936 af.viewport.hideSequence(hseqs);
2939 // recover view properties and display parameters
2940 if (view.getViewName() != null)
2942 af.viewport.viewName = view.getViewName();
2943 af.setInitialTabVisible();
2945 af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(),
2948 af.viewport.setShowAnnotation(view.getShowAnnotation());
2949 af.viewport.setAbovePIDThreshold(view.getPidSelected());
2951 af.viewport.setColourText(view.getShowColourText());
2953 af.viewport.setConservationSelected(view.getConservationSelected());
2954 af.viewport.setShowJVSuffix(view.getShowFullId());
2955 af.viewport.rightAlignIds = view.getRightAlignIds();
2956 af.viewport.setFont(new java.awt.Font(view.getFontName(), view
2957 .getFontStyle(), view.getFontSize()));
2958 af.alignPanel.fontChanged();
2959 af.viewport.setRenderGaps(view.getRenderGaps());
2960 af.viewport.setWrapAlignment(view.getWrapAlignment());
2961 af.alignPanel.setWrapAlignment(view.getWrapAlignment());
2962 af.viewport.setShowAnnotation(view.getShowAnnotation());
2963 af.alignPanel.setAnnotationVisible(view.getShowAnnotation());
2965 af.viewport.setShowBoxes(view.getShowBoxes());
2967 af.viewport.setShowText(view.getShowText());
2969 af.viewport.textColour = new java.awt.Color(view.getTextCol1());
2970 af.viewport.textColour2 = new java.awt.Color(view.getTextCol2());
2971 af.viewport.thresholdTextColour = view.getTextColThreshold();
2972 af.viewport.setShowUnconserved(view.hasShowUnconserved() ? view
2973 .isShowUnconserved() : false);
2974 af.viewport.setStartRes(view.getStartRes());
2975 af.viewport.setStartSeq(view.getStartSeq());
2977 ColourSchemeI cs = null;
2978 // apply colourschemes
2979 if (view.getBgColour() != null)
2981 if (view.getBgColour().startsWith("ucs"))
2983 cs = GetUserColourScheme(jms, view.getBgColour());
2985 else if (view.getBgColour().startsWith("Annotation"))
2987 // int find annotation
2988 if (af.viewport.alignment.getAlignmentAnnotation() != null)
2990 for (int i = 0; i < af.viewport.alignment
2991 .getAlignmentAnnotation().length; i++)
2993 if (af.viewport.alignment.getAlignmentAnnotation()[i].label
2994 .equals(view.getAnnotationColours().getAnnotation()))
2996 if (af.viewport.alignment.getAlignmentAnnotation()[i]
2997 .getThreshold() == null)
2999 af.viewport.alignment.getAlignmentAnnotation()[i]
3000 .setThreshold(new jalview.datamodel.GraphLine(view
3001 .getAnnotationColours().getThreshold(),
3002 "Threshold", java.awt.Color.black)
3007 if (view.getAnnotationColours().getColourScheme()
3010 cs = new AnnotationColourGradient(
3011 af.viewport.alignment.getAlignmentAnnotation()[i],
3012 new java.awt.Color(view.getAnnotationColours()
3013 .getMinColour()), new java.awt.Color(view
3014 .getAnnotationColours().getMaxColour()),
3015 view.getAnnotationColours().getAboveThreshold());
3017 else if (view.getAnnotationColours().getColourScheme()
3020 cs = new AnnotationColourGradient(
3021 af.viewport.alignment.getAlignmentAnnotation()[i],
3022 GetUserColourScheme(jms, view
3023 .getAnnotationColours().getColourScheme()),
3024 view.getAnnotationColours().getAboveThreshold());
3028 cs = new AnnotationColourGradient(
3029 af.viewport.alignment.getAlignmentAnnotation()[i],
3030 ColourSchemeProperty.getColour(al, view
3031 .getAnnotationColours().getColourScheme()),
3032 view.getAnnotationColours().getAboveThreshold());
3035 // Also use these settings for all the groups
3036 if (al.getGroups() != null)
3038 for (int g = 0; g < al.getGroups().size(); g++)
3040 jalview.datamodel.SequenceGroup sg = (jalview.datamodel.SequenceGroup) al
3041 .getGroups().elementAt(g);
3050 * (view.getAnnotationColours().getColourScheme().equals("None"
3051 * )) { sg.cs = new AnnotationColourGradient(
3052 * af.viewport.alignment.getAlignmentAnnotation()[i], new
3053 * java.awt.Color(view.getAnnotationColours().
3054 * getMinColour()), new
3055 * java.awt.Color(view.getAnnotationColours().
3057 * view.getAnnotationColours().getAboveThreshold()); } else
3060 sg.cs = new AnnotationColourGradient(
3061 af.viewport.alignment.getAlignmentAnnotation()[i],
3062 sg.cs, view.getAnnotationColours()
3063 .getAboveThreshold());
3077 cs = ColourSchemeProperty.getColour(al, view.getBgColour());
3082 cs.setThreshold(view.getPidThreshold(), true);
3083 cs.setConsensus(af.viewport.hconsensus);
3087 af.viewport.setGlobalColourScheme(cs);
3088 af.viewport.setColourAppliesToAllGroups(false);
3090 if (view.getConservationSelected() && cs != null)
3092 cs.setConservationInc(view.getConsThreshold());
3095 af.changeColour(cs);
3097 af.viewport.setColourAppliesToAllGroups(true);
3099 if (view.getShowSequenceFeatures())
3101 af.viewport.showSequenceFeatures = true;
3103 if (view.hasCentreColumnLabels())
3105 af.viewport.setCentreColumnLabels(view.getCentreColumnLabels());
3107 if (view.hasIgnoreGapsinConsensus())
3109 af.viewport.ignoreGapsInConsensusCalculation = view
3110 .getIgnoreGapsinConsensus();
3112 if (view.hasFollowHighlight())
3114 af.viewport.followHighlight = view.getFollowHighlight();
3116 if (view.hasFollowSelection())
3118 af.viewport.followSelection = view.getFollowSelection();
3120 if (view.hasShowConsensusHistogram())
3122 af.viewport.setShowConsensusHistogram(view
3123 .getShowConsensusHistogram());
3127 af.viewport.setShowConsensusHistogram(true);
3129 if (view.hasShowSequenceLogo())
3131 af.viewport.showSequenceLogo = view.getShowSequenceLogo();
3135 af.viewport.showSequenceLogo = false;
3137 if (view.hasShowDbRefTooltip())
3139 af.viewport.setShowDbRefs(view.getShowDbRefTooltip());
3141 if (view.hasShowNPfeatureTooltip())
3143 af.viewport.setShowNpFeats(view.hasShowNPfeatureTooltip());
3145 if (view.hasShowGroupConsensus())
3147 af.viewport.setShowGroupConsensus(view.getShowGroupConsensus());
3151 af.viewport.setShowGroupConsensus(false);
3153 if (view.hasShowGroupConservation())
3155 af.viewport.setShowGroupConservation(view.getShowGroupConservation());
3159 af.viewport.setShowGroupConservation(false);
3162 // recover featre settings
3163 if (jms.getFeatureSettings() != null)
3165 af.viewport.featuresDisplayed = new Hashtable();
3166 String[] renderOrder = new String[jms.getFeatureSettings()
3167 .getSettingCount()];
3168 for (int fs = 0; fs < jms.getFeatureSettings().getSettingCount(); fs++)
3170 Setting setting = jms.getFeatureSettings().getSetting(fs);
3171 if (setting.hasMincolour())
3173 GraduatedColor gc = setting.hasMin() ? new GraduatedColor(
3174 new java.awt.Color(setting.getMincolour()),
3175 new java.awt.Color(setting.getColour()),
3176 setting.getMin(), setting.getMax()) : new GraduatedColor(
3177 new java.awt.Color(setting.getMincolour()),
3178 new java.awt.Color(setting.getColour()), 0, 1);
3179 if (setting.hasThreshold())
3181 gc.setThresh(setting.getThreshold());
3182 gc.setThreshType(setting.getThreshstate());
3184 gc.setAutoScaled(true); // default
3185 if (setting.hasAutoScale())
3187 gc.setAutoScaled(setting.getAutoScale());
3189 if (setting.hasColourByLabel())
3191 gc.setColourByLabel(setting.getColourByLabel());
3193 // and put in the feature colour table.
3194 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setColour(
3195 setting.getType(), gc);
3199 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setColour(
3201 new java.awt.Color(setting.getColour()));
3203 renderOrder[fs] = setting.getType();
3204 if (setting.hasOrder())
3205 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setOrder(
3206 setting.getType(), setting.getOrder());
3208 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setOrder(
3210 fs / jms.getFeatureSettings().getSettingCount());
3211 if (setting.getDisplay())
3213 af.viewport.featuresDisplayed.put(setting.getType(), new Integer(
3214 setting.getColour()));
3217 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().renderOrder = renderOrder;
3219 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().featureGroups = fgtable = new Hashtable();
3220 for (int gs = 0; gs < jms.getFeatureSettings().getGroupCount(); gs++)
3222 Group grp = jms.getFeatureSettings().getGroup(gs);
3223 fgtable.put(grp.getName(), new Boolean(grp.getDisplay()));
3227 if (view.getHiddenColumnsCount() > 0)
3229 for (int c = 0; c < view.getHiddenColumnsCount(); c++)
3231 af.viewport.hideColumns(view.getHiddenColumns(c).getStart(), view
3232 .getHiddenColumns(c).getEnd() // +1
3237 af.setMenusFromViewport(af.viewport);
3238 // TODO: we don't need to do this if the viewport is aready visible.
3239 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
3241 af.alignPanel.updateAnnotation(false); // recompute any autoannotation
3242 reorderAutoannotation(af,al,autoAlan);
3246 private void reorderAutoannotation(AlignFrame af, Alignment al,
3247 ArrayList<JvAnnotRow> autoAlan)
3249 // copy over visualization settings for autocalculated annotation in the
3251 if (al.getAlignmentAnnotation() != null)
3254 * Kludge for magic autoannotation names (see JAL-811)
3256 String[] magicNames = new String[]
3257 { "Consensus", "Quality", "Conservation" };
3258 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
3259 Hashtable<String, JvAnnotRow> visan = new Hashtable<String, JvAnnotRow>();
3260 for (String nm : magicNames)
3262 visan.put(nm, nullAnnot);
3264 for (JvAnnotRow auan : autoAlan)
3266 visan.put(auan.template.label, auan);
3268 int hSize = al.getAlignmentAnnotation().length;
3269 ArrayList<JvAnnotRow> reorder = new ArrayList<JvAnnotRow>();
3270 for (int h = 0; h < hSize; h++)
3272 jalview.datamodel.AlignmentAnnotation jalan = al
3273 .getAlignmentAnnotation()[h];
3274 if (jalan.autoCalculated)
3276 JvAnnotRow valan = visan.get(jalan.label);
3279 // delete the auto calculated row from the alignment
3280 al.deleteAnnotation(al.getAlignmentAnnotation()[h],false);
3283 if (valan != nullAnnot)
3285 if (jalan!=valan.template) {
3286 // newly created autoannotation row instance
3287 // so keep a reference to the visible annotation row
3288 // and copy over all relevant attributes
3289 if (valan.template.graphHeight >= 0)
3292 jalan.graphHeight = valan.template.graphHeight;
3294 jalan.visible = valan.template.visible;
3296 reorder.add(new JvAnnotRow(valan.order, jalan));
3301 int s=0,srt[] = new int[reorder.size()];
3302 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
3303 for (JvAnnotRow jvar:reorder) {
3305 srt[s++]=jvar.order;
3308 jalview.util.QuickSort.sort(srt, rws);
3309 // and re-insert the annotation at its correct position
3310 for (JvAnnotRow jvar : rws)
3312 al.addAnnotation(jvar.template, jvar.order);
3314 af.alignPanel.adjustAnnotationHeight();
3318 Hashtable skipList = null;
3321 * TODO remove this method
3324 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
3325 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
3326 * throw new Error("Implementation Error. No skipList defined for this
3327 * Jalview2XML instance."); } return (AlignFrame)
3328 * skipList.get(view.getSequenceSetId()); }
3332 * Check if the Jalview view contained in object should be skipped or not.
3335 * @return true if view's sequenceSetId is a key in skipList
3337 private boolean skipViewport(JalviewModel object)
3339 if (skipList == null)
3344 if (skipList.containsKey(id = object.getJalviewModelSequence()
3345 .getViewport()[0].getSequenceSetId()))
3347 if (Cache.log != null && Cache.log.isDebugEnabled())
3349 Cache.log.debug("Skipping seuqence set id " + id);
3356 public void AddToSkipList(AlignFrame af)
3358 if (skipList == null)
3360 skipList = new Hashtable();
3362 skipList.put(af.getViewport().getSequenceSetId(), af);
3365 public void clearSkipList()
3367 if (skipList != null)
3374 private void recoverDatasetFor(SequenceSet vamsasSet, Alignment al)
3376 jalview.datamodel.Alignment ds = getDatasetFor(vamsasSet.getDatasetId());
3377 Vector dseqs = null;
3380 // create a list of new dataset sequences
3381 dseqs = new Vector();
3383 for (int i = 0, iSize = vamsasSet.getSequenceCount(); i < iSize; i++)
3385 Sequence vamsasSeq = vamsasSet.getSequence(i);
3386 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs);
3388 // create a new dataset
3391 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
3392 dseqs.copyInto(dsseqs);
3393 ds = new jalview.datamodel.Alignment(dsseqs);
3394 debug("Created new dataset " + vamsasSet.getDatasetId()
3395 + " for alignment " + System.identityHashCode(al));
3396 addDatasetRef(vamsasSet.getDatasetId(), ds);
3398 // set the dataset for the newly imported alignment.
3399 if (al.getDataset() == null)
3408 * sequence definition to create/merge dataset sequence for
3412 * vector to add new dataset sequence to
3414 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
3415 AlignmentI ds, Vector dseqs)
3417 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
3419 jalview.datamodel.Sequence sq = (jalview.datamodel.Sequence) seqRefIds
3420 .get(vamsasSeq.getId());
3421 jalview.datamodel.SequenceI dsq = null;
3422 if (sq != null && sq.getDatasetSequence() != null)
3424 dsq = (jalview.datamodel.SequenceI) sq.getDatasetSequence();
3427 String sqid = vamsasSeq.getDsseqid();
3430 // need to create or add a new dataset sequence reference to this sequence
3433 dsq = (jalview.datamodel.SequenceI) seqRefIds.get(sqid);
3438 // make a new dataset sequence
3439 dsq = sq.createDatasetSequence();
3442 // make up a new dataset reference for this sequence
3443 sqid = seqHash(dsq);
3445 dsq.setVamsasId(uniqueSetSuffix + sqid);
3446 seqRefIds.put(sqid, dsq);
3451 dseqs.addElement(dsq);
3456 ds.addSequence(dsq);
3462 { // make this dataset sequence sq's dataset sequence
3463 sq.setDatasetSequence(dsq);
3467 // TODO: refactor this as a merge dataset sequence function
3468 // now check that sq (the dataset sequence) sequence really is the union of
3469 // all references to it
3470 // boolean pre = sq.getStart() < dsq.getStart();
3471 // boolean post = sq.getEnd() > dsq.getEnd();
3475 StringBuffer sb = new StringBuffer();
3476 String newres = jalview.analysis.AlignSeq.extractGaps(
3477 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
3478 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
3479 && newres.length() > dsq.getLength())
3481 // Update with the longer sequence.
3485 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
3486 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
3487 * sb.append(newres.substring(newres.length() - sq.getEnd() -
3488 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
3490 dsq.setSequence(sb.toString());
3492 // TODO: merges will never happen if we 'know' we have the real dataset
3493 // sequence - this should be detected when id==dssid
3494 System.err.println("DEBUG Notice: Merged dataset sequence"); // ("
3495 // + (pre ? "prepended" : "") + " "
3496 // + (post ? "appended" : ""));
3501 java.util.Hashtable datasetIds = null;
3503 java.util.IdentityHashMap dataset2Ids = null;
3505 private Alignment getDatasetFor(String datasetId)
3507 if (datasetIds == null)
3509 datasetIds = new Hashtable();
3512 if (datasetIds.containsKey(datasetId))
3514 return (Alignment) datasetIds.get(datasetId);
3519 private void addDatasetRef(String datasetId, Alignment dataset)
3521 if (datasetIds == null)
3523 datasetIds = new Hashtable();
3525 datasetIds.put(datasetId, dataset);
3529 * make a new dataset ID for this jalview dataset alignment
3534 private String getDatasetIdRef(jalview.datamodel.Alignment dataset)
3536 if (dataset.getDataset() != null)
3538 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
3540 String datasetId = makeHashCode(dataset, null);
3541 if (datasetId == null)
3543 // make a new datasetId and record it
3544 if (dataset2Ids == null)
3546 dataset2Ids = new IdentityHashMap();
3550 datasetId = (String) dataset2Ids.get(dataset);
3552 if (datasetId == null)
3554 datasetId = "ds" + dataset2Ids.size() + 1;
3555 dataset2Ids.put(dataset, datasetId);
3561 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
3563 for (int d = 0; d < sequence.getDBRefCount(); d++)
3565 DBRef dr = sequence.getDBRef(d);
3566 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
3567 sequence.getDBRef(d).getSource(), sequence.getDBRef(d)
3568 .getVersion(), sequence.getDBRef(d).getAccessionId());
3569 if (dr.getMapping() != null)
3571 entry.setMap(addMapping(dr.getMapping()));
3573 datasetSequence.addDBRef(entry);
3577 private jalview.datamodel.Mapping addMapping(Mapping m)
3579 SequenceI dsto = null;
3580 // Mapping m = dr.getMapping();
3581 int fr[] = new int[m.getMapListFromCount() * 2];
3582 Enumeration f = m.enumerateMapListFrom();
3583 for (int _i = 0; f.hasMoreElements(); _i += 2)
3585 MapListFrom mf = (MapListFrom) f.nextElement();
3586 fr[_i] = mf.getStart();
3587 fr[_i + 1] = mf.getEnd();
3589 int fto[] = new int[m.getMapListToCount() * 2];
3590 f = m.enumerateMapListTo();
3591 for (int _i = 0; f.hasMoreElements(); _i += 2)
3593 MapListTo mf = (MapListTo) f.nextElement();
3594 fto[_i] = mf.getStart();
3595 fto[_i + 1] = mf.getEnd();
3597 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto,
3598 fr, fto, (int) m.getMapFromUnit(), (int) m.getMapToUnit());
3599 if (m.getMappingChoice() != null)
3601 MappingChoice mc = m.getMappingChoice();
3602 if (mc.getDseqFor() != null)
3604 String dsfor = "" + mc.getDseqFor();
3605 if (seqRefIds.containsKey(dsfor))
3610 jmap.setTo((SequenceI) seqRefIds.get(dsfor));
3614 frefedSequence.add(new Object[]
3621 * local sequence definition
3623 Sequence ms = mc.getSequence();
3624 jalview.datamodel.Sequence djs = null;
3625 String sqid = ms.getDsseqid();
3626 if (sqid != null && sqid.length() > 0)
3629 * recover dataset sequence
3631 djs = (jalview.datamodel.Sequence) seqRefIds.get(sqid);
3636 .println("Warning - making up dataset sequence id for DbRef sequence map reference");
3637 sqid = ((Object) ms).toString(); // make up a new hascode for
3638 // undefined dataset sequence hash
3639 // (unlikely to happen)
3645 * make a new dataset sequence and add it to refIds hash
3647 djs = new jalview.datamodel.Sequence(ms.getName(),
3649 djs.setStart(jmap.getMap().getToLowest());
3650 djs.setEnd(jmap.getMap().getToHighest());
3651 djs.setVamsasId(uniqueSetSuffix + sqid);
3653 seqRefIds.put(sqid, djs);
3656 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
3665 public jalview.gui.AlignmentPanel copyAlignPanel(AlignmentPanel ap,
3666 boolean keepSeqRefs)
3669 jalview.schemabinding.version2.JalviewModel jm = SaveState(ap, null,
3675 jm.getJalviewModelSequence().getViewport(0).setSequenceSetId(null);
3679 uniqueSetSuffix = "";
3680 jm.getJalviewModelSequence().getViewport(0).setId(null); // we don't
3685 if (this.frefedSequence == null)
3687 frefedSequence = new Vector();
3690 viewportsAdded = new Hashtable();
3692 AlignFrame af = LoadFromObject(jm, null, false, null);
3693 af.alignPanels.clear();
3694 af.closeMenuItem_actionPerformed(true);
3697 * if(ap.av.alignment.getAlignmentAnnotation()!=null) { for(int i=0;
3698 * i<ap.av.alignment.getAlignmentAnnotation().length; i++) {
3699 * if(!ap.av.alignment.getAlignmentAnnotation()[i].autoCalculated) {
3700 * af.alignPanel.av.alignment.getAlignmentAnnotation()[i] =
3701 * ap.av.alignment.getAlignmentAnnotation()[i]; } } }
3704 return af.alignPanel;
3708 * flag indicating if hashtables should be cleared on finalization TODO this
3709 * flag may not be necessary
3711 private boolean _cleartables = true;
3713 private Hashtable jvids2vobj;
3718 * @see java.lang.Object#finalize()
3720 protected void finalize() throws Throwable
3722 // really make sure we have no buried refs left.
3727 this.seqRefIds = null;
3728 this.seqsToIds = null;
3732 private void warn(String msg)
3737 private void warn(String msg, Exception e)
3739 if (Cache.log != null)
3743 Cache.log.warn(msg, e);
3747 Cache.log.warn(msg);
3752 System.err.println("Warning: " + msg);
3755 e.printStackTrace();
3760 private void debug(String string)
3762 debug(string, null);
3765 private void debug(String msg, Exception e)
3767 if (Cache.log != null)
3771 Cache.log.debug(msg, e);
3775 Cache.log.debug(msg);
3780 System.err.println("Warning: " + msg);
3783 e.printStackTrace();
3789 * set the object to ID mapping tables used to write/recover objects and XML
3790 * ID strings for the jalview project. If external tables are provided then
3791 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
3792 * object goes out of scope. - also populates the datasetIds hashtable with
3793 * alignment objects containing dataset sequences
3796 * Map from ID strings to jalview datamodel
3798 * Map from jalview datamodel to ID strings
3802 public void setObjectMappingTables(Hashtable vobj2jv,
3803 IdentityHashMap jv2vobj)
3805 this.jv2vobj = jv2vobj;
3806 this.vobj2jv = vobj2jv;
3807 Iterator ds = jv2vobj.keySet().iterator();
3809 while (ds.hasNext())
3811 Object jvobj = ds.next();
3812 id = jv2vobj.get(jvobj).toString();
3813 if (jvobj instanceof jalview.datamodel.Alignment)
3815 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
3817 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
3820 else if (jvobj instanceof jalview.datamodel.Sequence)
3822 // register sequence object so the XML parser can recover it.
3823 if (seqRefIds == null)
3825 seqRefIds = new Hashtable();
3827 if (seqsToIds == null)
3829 seqsToIds = new IdentityHashMap();
3831 seqRefIds.put(jv2vobj.get(jvobj).toString(), jvobj);
3832 seqsToIds.put(jvobj, id);
3834 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
3836 if (annotationIds == null)
3838 annotationIds = new Hashtable();
3841 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvobj);
3842 jalview.datamodel.AlignmentAnnotation jvann = (jalview.datamodel.AlignmentAnnotation) jvobj;
3843 if (jvann.annotationId == null)
3845 jvann.annotationId = anid;
3847 if (!jvann.annotationId.equals(anid))
3849 // TODO verify that this is the correct behaviour
3850 this.warn("Overriding Annotation ID for " + anid
3851 + " from different id : " + jvann.annotationId);
3852 jvann.annotationId = anid;
3855 else if (jvobj instanceof String)
3857 if (jvids2vobj == null)
3859 jvids2vobj = new Hashtable();
3860 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
3864 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
3869 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
3870 * objects created from the project archive. If string is null (default for
3871 * construction) then suffix will be set automatically.
3875 public void setUniqueSetSuffix(String string)
3877 uniqueSetSuffix = string;
3882 * uses skipList2 as the skipList for skipping views on sequence sets
3883 * associated with keys in the skipList
3887 public void setSkipList(Hashtable skipList2)
3889 skipList = skipList2;