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
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 if (!jmolViewIds.contains(state.getViewId()))
629 // Make sure we only store a Jmol state once in each XML
631 jmolViewIds.addElement(state.getViewId());
632 state.setContent(statestring.replaceAll("\n", ""));
636 state.setContent("# duplicate state");
638 pdb.addStructureState(state);
645 if (matchedFile != null || entry.getFile() != null)
647 if (entry.getFile() != null)
650 matchedFile = entry.getFile();
652 pdb.setFile(matchedFile); // entry.getFile());
653 if (pdbfiles == null)
655 pdbfiles = new Vector();
658 if (!pdbfiles.contains(entry.getId()))
660 pdbfiles.addElement(entry.getId());
663 File file = new File(matchedFile);
664 if (file.exists() && jout != null)
666 byte[] data = new byte[(int) file.length()];
667 jout.putNextEntry(new JarEntry(entry.getId()));
668 DataInputStream dis = new DataInputStream(
669 new FileInputStream(file));
672 DataOutputStream dout = new DataOutputStream(jout);
673 dout.write(data, 0, data.length);
677 } catch (Exception ex)
679 ex.printStackTrace();
685 if (entry.getProperty() != null)
687 PdbentryItem item = new PdbentryItem();
688 Hashtable properties = entry.getProperty();
689 Enumeration en2 = properties.keys();
690 while (en2.hasMoreElements())
692 Property prop = new Property();
693 String key = en2.nextElement().toString();
695 prop.setValue(properties.get(key).toString());
696 item.addProperty(prop);
698 pdb.addPdbentryItem(item);
708 if (av.hasHiddenRows)
713 if (jal.getCodonFrames() != null && jal.getCodonFrames().length > 0)
715 jalview.datamodel.AlignedCodonFrame[] jac = jal.getCodonFrames();
716 for (int i = 0; i < jac.length; i++)
718 AlcodonFrame alc = new AlcodonFrame();
719 vamsasSet.addAlcodonFrame(alc);
720 for (int p = 0; p < jac[i].aaWidth; p++)
722 Alcodon cmap = new Alcodon();
723 if (jac[i].codons[p] != null)
725 // Null codons indicate a gapped column in the translated peptide
727 cmap.setPos1(jac[i].codons[p][0]);
728 cmap.setPos2(jac[i].codons[p][1]);
729 cmap.setPos3(jac[i].codons[p][2]);
731 alc.addAlcodon(cmap);
733 if (jac[i].getProtMappings() != null
734 && jac[i].getProtMappings().length > 0)
736 SequenceI[] dnas = jac[i].getdnaSeqs();
737 jalview.datamodel.Mapping[] pmaps = jac[i].getProtMappings();
738 for (int m = 0; m < pmaps.length; m++)
740 AlcodMap alcmap = new AlcodMap();
741 alcmap.setDnasq(seqHash(dnas[m]));
742 alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
744 alc.addAlcodMap(alcmap);
751 // /////////////////////////////////
752 if (av.currentTree != null)
754 // FIND ANY ASSOCIATED TREES
755 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
756 if (Desktop.desktop != null)
758 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
760 for (int t = 0; t < frames.length; t++)
762 if (frames[t] instanceof TreePanel)
764 TreePanel tp = (TreePanel) frames[t];
766 if (tp.treeCanvas.av.alignment == jal)
768 Tree tree = new Tree();
769 tree.setTitle(tp.getTitle());
770 tree.setCurrentTree((av.currentTree == tp.getTree()));
771 tree.setNewick(tp.getTree().toString());
772 tree.setThreshold(tp.treeCanvas.threshold);
774 tree.setFitToWindow(tp.fitToWindow.getState());
775 tree.setFontName(tp.getTreeFont().getName());
776 tree.setFontSize(tp.getTreeFont().getSize());
777 tree.setFontStyle(tp.getTreeFont().getStyle());
778 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
780 tree.setShowBootstrap(tp.bootstrapMenu.getState());
781 tree.setShowDistances(tp.distanceMenu.getState());
783 tree.setHeight(tp.getHeight());
784 tree.setWidth(tp.getWidth());
785 tree.setXpos(tp.getX());
786 tree.setYpos(tp.getY());
787 tree.setId(makeHashCode(tp, null));
797 * store forward refs from an annotationRow to any groups
799 IdentityHashMap groupRefs = new IdentityHashMap();
800 if (jal.getAlignmentAnnotation() != null)
802 jalview.datamodel.AlignmentAnnotation[] aa = jal
803 .getAlignmentAnnotation();
805 for (int i = 0; i < aa.length; i++)
807 Annotation an = new Annotation();
809 if (aa[i].annotationId != null)
811 annotationIds.put(aa[i].annotationId, aa[i]);
814 an.setId(aa[i].annotationId);
816 an.setVisible(aa[i].visible);
818 an.setDescription(aa[i].description);
820 if (aa[i].sequenceRef != null)
822 // TODO later annotation sequenceRef should be the XML ID of the
823 // sequence rather than its display name
824 an.setSequenceRef(aa[i].sequenceRef.getName());
826 if (aa[i].groupRef != null)
828 Object groupIdr = groupRefs.get(aa[i].groupRef);
829 if (groupIdr == null)
831 // make a locally unique String
832 groupRefs.put(aa[i].groupRef,
833 groupIdr = ("" + System.currentTimeMillis()
834 + aa[i].groupRef.getName() + groupRefs.size()));
836 an.setGroupRef(groupIdr.toString());
839 // store all visualization attributes for annotation
840 an.setGraphHeight(aa[i].graphHeight);
841 an.setCentreColLabels(aa[i].centreColLabels);
842 an.setScaleColLabels(aa[i].scaleColLabel);
843 an.setShowAllColLabels(aa[i].showAllColLabels);
848 an.setGraphType(aa[i].graph);
849 an.setGraphGroup(aa[i].graphGroup);
850 if (aa[i].getThreshold() != null)
852 ThresholdLine line = new ThresholdLine();
853 line.setLabel(aa[i].getThreshold().label);
854 line.setValue(aa[i].getThreshold().value);
855 line.setColour(aa[i].getThreshold().colour.getRGB());
856 an.setThresholdLine(line);
864 an.setLabel(aa[i].label);
866 if (aa[i] == av.quality || aa[i] == av.conservation
867 || aa[i] == av.consensus || aa[i].autoCalculated)
869 // new way of indicating autocalculated annotation -
870 an.setAutoCalculated(aa[i].autoCalculated);
872 if (aa[i].hasScore())
874 an.setScore(aa[i].getScore());
876 AnnotationElement ae;
877 if (aa[i].annotations != null)
879 an.setScoreOnly(false);
880 for (int a = 0; a < aa[i].annotations.length; a++)
882 if ((aa[i] == null) || (aa[i].annotations[a] == null))
887 ae = new AnnotationElement();
888 if (aa[i].annotations[a].description != null)
889 ae.setDescription(aa[i].annotations[a].description);
890 if (aa[i].annotations[a].displayCharacter != null)
891 ae.setDisplayCharacter(aa[i].annotations[a].displayCharacter);
893 if (!Float.isNaN(aa[i].annotations[a].value))
894 ae.setValue(aa[i].annotations[a].value);
897 if (aa[i].annotations[a].secondaryStructure != ' '
898 && aa[i].annotations[a].secondaryStructure != '\0')
899 ae.setSecondaryStructure(aa[i].annotations[a].secondaryStructure
902 if (aa[i].annotations[a].colour != null
903 && aa[i].annotations[a].colour != java.awt.Color.black)
905 ae.setColour(aa[i].annotations[a].colour.getRGB());
908 an.addAnnotationElement(ae);
909 if (aa[i].autoCalculated)
911 // only write one non-null entry into the annotation row - sufficient to get the visualization attributes necessary to display data
918 an.setScoreOnly(true);
920 vamsasSet.addAnnotation(an);
924 if (jal.getGroups() != null)
926 JGroup[] groups = new JGroup[jal.getGroups().size()];
928 for (int i = 0; i < groups.length; i++)
930 groups[i] = new JGroup();
932 jalview.datamodel.SequenceGroup sg = (jalview.datamodel.SequenceGroup) jal
933 .getGroups().elementAt(i);
934 groups[i].setStart(sg.getStartRes());
935 groups[i].setEnd(sg.getEndRes());
936 groups[i].setName(sg.getName());
937 if (groupRefs.containsKey(sg))
939 // group has references so set it's ID field
940 groups[i].setId(groupRefs.get(sg).toString());
944 if (sg.cs.conservationApplied())
946 groups[i].setConsThreshold(sg.cs.getConservationInc());
948 if (sg.cs instanceof jalview.schemes.UserColourScheme)
950 groups[i].setColour(SetUserColourScheme(sg.cs, userColours,
956 .setColour(ColourSchemeProperty.getColourName(sg.cs));
959 else if (sg.cs instanceof jalview.schemes.AnnotationColourGradient)
962 .setColour(ColourSchemeProperty
963 .getColourName(((jalview.schemes.AnnotationColourGradient) sg.cs)
966 else if (sg.cs instanceof jalview.schemes.UserColourScheme)
969 .setColour(SetUserColourScheme(sg.cs, userColours, jms));
973 groups[i].setColour(ColourSchemeProperty.getColourName(sg.cs));
976 groups[i].setPidThreshold(sg.cs.getThreshold());
979 groups[i].setOutlineColour(sg.getOutlineColour().getRGB());
980 groups[i].setDisplayBoxes(sg.getDisplayBoxes());
981 groups[i].setDisplayText(sg.getDisplayText());
982 groups[i].setColourText(sg.getColourText());
983 groups[i].setTextCol1(sg.textColour.getRGB());
984 groups[i].setTextCol2(sg.textColour2.getRGB());
985 groups[i].setTextColThreshold(sg.thresholdTextColour);
986 groups[i].setShowUnconserved(sg.getShowNonconserved());
987 groups[i].setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
988 groups[i].setShowConsensusHistogram(sg.isShowConsensusHistogram());
989 groups[i].setShowSequenceLogo(sg.isShowSequenceLogo());
990 for (int s = 0; s < sg.getSize(); s++)
992 jalview.datamodel.Sequence seq = (jalview.datamodel.Sequence) sg
994 groups[i].addSeq(seqHash(seq));
998 jms.setJGroup(groups);
1001 // /////////SAVE VIEWPORT
1002 Viewport view = new Viewport();
1003 view.setTitle(ap.alignFrame.getTitle());
1004 view.setSequenceSetId(makeHashCode(av.getSequenceSetId(),
1005 av.getSequenceSetId()));
1006 view.setId(av.getViewId());
1007 view.setViewName(av.viewName);
1008 view.setGatheredViews(av.gatherViewsHere);
1010 if (ap.av.explodedPosition != null)
1012 view.setXpos(av.explodedPosition.x);
1013 view.setYpos(av.explodedPosition.y);
1014 view.setWidth(av.explodedPosition.width);
1015 view.setHeight(av.explodedPosition.height);
1019 view.setXpos(ap.alignFrame.getBounds().x);
1020 view.setYpos(ap.alignFrame.getBounds().y);
1021 view.setWidth(ap.alignFrame.getBounds().width);
1022 view.setHeight(ap.alignFrame.getBounds().height);
1025 view.setStartRes(av.startRes);
1026 view.setStartSeq(av.startSeq);
1028 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1030 view.setBgColour(SetUserColourScheme(av.getGlobalColourScheme(),
1033 else if (av.getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1035 jalview.schemes.AnnotationColourGradient acg = (jalview.schemes.AnnotationColourGradient) av
1036 .getGlobalColourScheme();
1038 AnnotationColours ac = new AnnotationColours();
1039 ac.setAboveThreshold(acg.getAboveThreshold());
1040 ac.setThreshold(acg.getAnnotationThreshold());
1041 ac.setAnnotation(acg.getAnnotation());
1042 if (acg.getBaseColour() instanceof jalview.schemes.UserColourScheme)
1044 ac.setColourScheme(SetUserColourScheme(acg.getBaseColour(),
1049 ac.setColourScheme(ColourSchemeProperty.getColourName(acg
1053 ac.setMaxColour(acg.getMaxColour().getRGB());
1054 ac.setMinColour(acg.getMinColour().getRGB());
1055 view.setAnnotationColours(ac);
1056 view.setBgColour("AnnotationColourGradient");
1060 view.setBgColour(ColourSchemeProperty.getColourName(av
1061 .getGlobalColourScheme()));
1064 ColourSchemeI cs = av.getGlobalColourScheme();
1068 if (cs.conservationApplied())
1070 view.setConsThreshold(cs.getConservationInc());
1071 if (cs instanceof jalview.schemes.UserColourScheme)
1073 view.setBgColour(SetUserColourScheme(cs, userColours, jms));
1077 if (cs instanceof ResidueColourScheme)
1079 view.setPidThreshold(cs.getThreshold());
1083 view.setConservationSelected(av.getConservationSelected());
1084 view.setPidSelected(av.getAbovePIDThreshold());
1085 view.setFontName(av.font.getName());
1086 view.setFontSize(av.font.getSize());
1087 view.setFontStyle(av.font.getStyle());
1088 view.setRenderGaps(av.renderGaps);
1089 view.setShowAnnotation(av.getShowAnnotation());
1090 view.setShowBoxes(av.getShowBoxes());
1091 view.setShowColourText(av.getColourText());
1092 view.setShowFullId(av.getShowJVSuffix());
1093 view.setRightAlignIds(av.rightAlignIds);
1094 view.setShowSequenceFeatures(av.showSequenceFeatures);
1095 view.setShowText(av.getShowText());
1096 view.setShowUnconserved(av.getShowUnconserved());
1097 view.setWrapAlignment(av.getWrapAlignment());
1098 view.setTextCol1(av.textColour.getRGB());
1099 view.setTextCol2(av.textColour2.getRGB());
1100 view.setTextColThreshold(av.thresholdTextColour);
1101 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1102 view.setShowSequenceLogo(av.isShowSequenceLogo());
1103 view.setShowGroupConsensus(av.isShowGroupConsensus());
1104 view.setShowGroupConservation(av.isShowGroupConservation());
1105 view.setShowNPfeatureTooltip(av.isShowNpFeats());
1106 view.setShowDbRefTooltip(av.isShowDbRefs());
1107 view.setFollowHighlight(av.followHighlight);
1108 view.setFollowSelection(av.followSelection);
1109 view.setIgnoreGapsinConsensus(av.getIgnoreGapsConsensus());
1110 if (av.featuresDisplayed != null)
1112 jalview.schemabinding.version2.FeatureSettings fs = new jalview.schemabinding.version2.FeatureSettings();
1114 String[] renderOrder = ap.seqPanel.seqCanvas.getFeatureRenderer().renderOrder;
1116 Vector settingsAdded = new Vector();
1117 Object gstyle = null;
1118 GraduatedColor gcol = null;
1119 for (int ro = 0; ro < renderOrder.length; ro++)
1121 gstyle = ap.seqPanel.seqCanvas.getFeatureRenderer()
1122 .getFeatureStyle(renderOrder[ro]);
1123 Setting setting = new Setting();
1124 setting.setType(renderOrder[ro]);
1125 if (gstyle instanceof GraduatedColor)
1127 gcol = (GraduatedColor) gstyle;
1128 setting.setColour(gcol.getMaxColor().getRGB());
1129 setting.setMincolour(gcol.getMinColor().getRGB());
1130 setting.setMin(gcol.getMin());
1131 setting.setMax(gcol.getMax());
1132 setting.setColourByLabel(gcol.isColourByLabel());
1133 setting.setAutoScale(gcol.isAutoScale());
1134 setting.setThreshold(gcol.getThresh());
1135 setting.setThreshstate(gcol.getThreshType());
1139 setting.setColour(ap.seqPanel.seqCanvas.getFeatureRenderer()
1140 .getColour(renderOrder[ro]).getRGB());
1143 setting.setDisplay(av.featuresDisplayed
1144 .containsKey(renderOrder[ro]));
1145 float rorder = ap.seqPanel.seqCanvas.getFeatureRenderer().getOrder(
1149 setting.setOrder(rorder);
1151 fs.addSetting(setting);
1152 settingsAdded.addElement(renderOrder[ro]);
1155 // Make sure we save none displayed feature settings
1156 Enumeration en = ap.seqPanel.seqCanvas.getFeatureRenderer().featureColours
1158 while (en.hasMoreElements())
1160 String key = en.nextElement().toString();
1161 if (settingsAdded.contains(key))
1166 Setting setting = new Setting();
1167 setting.setType(key);
1168 setting.setColour(ap.seqPanel.seqCanvas.getFeatureRenderer()
1169 .getColour(key).getRGB());
1171 setting.setDisplay(false);
1172 float rorder = ap.seqPanel.seqCanvas.getFeatureRenderer().getOrder(
1176 setting.setOrder(rorder);
1178 fs.addSetting(setting);
1179 settingsAdded.addElement(key);
1181 en = ap.seqPanel.seqCanvas.getFeatureRenderer().featureGroups.keys();
1182 Vector groupsAdded = new Vector();
1183 while (en.hasMoreElements())
1185 String grp = en.nextElement().toString();
1186 if (groupsAdded.contains(grp))
1190 Group g = new Group();
1192 g.setDisplay(((Boolean) ap.seqPanel.seqCanvas.getFeatureRenderer().featureGroups
1193 .get(grp)).booleanValue());
1195 groupsAdded.addElement(grp);
1197 jms.setFeatureSettings(fs);
1201 if (av.hasHiddenColumns)
1203 if (av.getColumnSelection() == null
1204 || av.getColumnSelection().getHiddenColumns() == null)
1206 warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1210 for (int c = 0; c < av.getColumnSelection().getHiddenColumns()
1213 int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
1215 HiddenColumns hc = new HiddenColumns();
1216 hc.setStart(region[0]);
1217 hc.setEnd(region[1]);
1218 view.addHiddenColumns(hc);
1223 jms.addViewport(view);
1225 object.setJalviewModelSequence(jms);
1226 object.getVamsasModel().addSequenceSet(vamsasSet);
1228 if (jout != null && fileName != null)
1230 // We may not want to write the object to disk,
1231 // eg we can copy the alignViewport to a new view object
1232 // using save and then load
1235 JarEntry entry = new JarEntry(fileName);
1236 jout.putNextEntry(entry);
1237 PrintWriter pout = new PrintWriter(new OutputStreamWriter(jout,
1239 org.exolab.castor.xml.Marshaller marshaller = new org.exolab.castor.xml.Marshaller(
1241 marshaller.marshal(object);
1244 } catch (Exception ex)
1246 // TODO: raise error in GUI if marshalling failed.
1247 ex.printStackTrace();
1254 * External mapping between jalview objects and objects yielding a valid and
1255 * unique object ID string. This is null for normal Jalview project IO, but
1256 * non-null when a jalview project is being read or written as part of a
1259 IdentityHashMap jv2vobj = null;
1262 * Construct a unique ID for jvobj using either existing bindings or if none
1263 * exist, the result of the hashcode call for the object.
1266 * jalview data object
1267 * @return unique ID for referring to jvobj
1269 private String makeHashCode(Object jvobj, String altCode)
1271 if (jv2vobj != null)
1273 Object id = jv2vobj.get(jvobj);
1276 return id.toString();
1278 // check string ID mappings
1279 if (jvids2vobj != null && jvobj instanceof String)
1281 id = jvids2vobj.get(jvobj);
1285 return id.toString();
1287 // give up and warn that something has gone wrong
1288 warn("Cannot find ID for object in external mapping : " + jvobj);
1294 * return local jalview object mapped to ID, if it exists
1298 * @return null or object bound to idcode
1300 private Object retrieveExistingObj(String idcode)
1302 if (idcode != null && vobj2jv != null)
1304 return vobj2jv.get(idcode);
1310 * binding from ID strings from external mapping table to jalview data model
1313 private Hashtable vobj2jv;
1315 private Sequence createVamsasSequence(String id, SequenceI jds)
1317 return createVamsasSequence(true, id, jds, null);
1320 private Sequence createVamsasSequence(boolean recurse, String id,
1321 SequenceI jds, SequenceI parentseq)
1323 Sequence vamsasSeq = new Sequence();
1324 vamsasSeq.setId(id);
1325 vamsasSeq.setName(jds.getName());
1326 vamsasSeq.setSequence(jds.getSequenceAsString());
1327 vamsasSeq.setDescription(jds.getDescription());
1328 jalview.datamodel.DBRefEntry[] dbrefs = null;
1329 if (jds.getDatasetSequence() != null)
1331 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
1332 if (jds.getDatasetSequence().getDBRef() != null)
1334 dbrefs = jds.getDatasetSequence().getDBRef();
1339 vamsasSeq.setDsseqid(id); // so we can tell which sequences really are
1340 // dataset sequences only
1341 dbrefs = jds.getDBRef();
1345 for (int d = 0; d < dbrefs.length; d++)
1347 DBRef dbref = new DBRef();
1348 dbref.setSource(dbrefs[d].getSource());
1349 dbref.setVersion(dbrefs[d].getVersion());
1350 dbref.setAccessionId(dbrefs[d].getAccessionId());
1351 if (dbrefs[d].hasMap())
1353 Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
1355 dbref.setMapping(mp);
1357 vamsasSeq.addDBRef(dbref);
1363 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
1364 SequenceI parentseq, SequenceI jds, boolean recurse)
1367 if (jmp.getMap() != null)
1371 jalview.util.MapList mlst = jmp.getMap();
1372 int r[] = mlst.getFromRanges();
1373 for (int s = 0; s < r.length; s += 2)
1375 MapListFrom mfrom = new MapListFrom();
1376 mfrom.setStart(r[s]);
1377 mfrom.setEnd(r[s + 1]);
1378 mp.addMapListFrom(mfrom);
1380 r = mlst.getToRanges();
1381 for (int s = 0; s < r.length; s += 2)
1383 MapListTo mto = new MapListTo();
1385 mto.setEnd(r[s + 1]);
1386 mp.addMapListTo(mto);
1388 mp.setMapFromUnit(mlst.getFromRatio());
1389 mp.setMapToUnit(mlst.getToRatio());
1390 if (jmp.getTo() != null)
1392 MappingChoice mpc = new MappingChoice();
1394 && (parentseq != jmp.getTo() || parentseq
1395 .getDatasetSequence() != jmp.getTo()))
1397 mpc.setSequence(createVamsasSequence(false, seqHash(jmp.getTo()),
1403 SequenceI ps = null;
1404 if (parentseq != jmp.getTo()
1405 && parentseq.getDatasetSequence() != jmp.getTo())
1407 // chaining dbref rather than a handshaking one
1408 jmpid = seqHash(ps = jmp.getTo());
1412 jmpid = seqHash(ps = parentseq);
1414 mpc.setDseqFor(jmpid);
1415 if (!seqRefIds.containsKey(mpc.getDseqFor()))
1417 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
1418 seqRefIds.put(mpc.getDseqFor(), ps);
1422 jalview.bin.Cache.log.debug("reusing DseqFor ID");
1425 mp.setMappingChoice(mpc);
1431 String SetUserColourScheme(jalview.schemes.ColourSchemeI cs,
1432 Vector userColours, JalviewModelSequence jms)
1435 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
1436 boolean newucs = false;
1437 if (!userColours.contains(ucs))
1439 userColours.add(ucs);
1442 id = "ucs" + userColours.indexOf(ucs);
1445 // actually create the scheme's entry in the XML model
1446 java.awt.Color[] colours = ucs.getColours();
1447 jalview.schemabinding.version2.UserColours uc = new jalview.schemabinding.version2.UserColours();
1448 jalview.schemabinding.version2.UserColourScheme jbucs = new jalview.schemabinding.version2.UserColourScheme();
1450 for (int i = 0; i < colours.length; i++)
1452 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
1453 col.setName(ResidueProperties.aa[i]);
1454 col.setRGB(jalview.util.Format.getHexString(colours[i]));
1455 jbucs.addColour(col);
1457 if (ucs.getLowerCaseColours() != null)
1459 colours = ucs.getLowerCaseColours();
1460 for (int i = 0; i < colours.length; i++)
1462 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
1463 col.setName(ResidueProperties.aa[i].toLowerCase());
1464 col.setRGB(jalview.util.Format.getHexString(colours[i]));
1465 jbucs.addColour(col);
1470 uc.setUserColourScheme(jbucs);
1471 jms.addUserColours(uc);
1477 jalview.schemes.UserColourScheme GetUserColourScheme(
1478 JalviewModelSequence jms, String id)
1480 UserColours[] uc = jms.getUserColours();
1481 UserColours colours = null;
1483 for (int i = 0; i < uc.length; i++)
1485 if (uc[i].getId().equals(id))
1493 java.awt.Color[] newColours = new java.awt.Color[24];
1495 for (int i = 0; i < 24; i++)
1497 newColours[i] = new java.awt.Color(Integer.parseInt(colours
1498 .getUserColourScheme().getColour(i).getRGB(), 16));
1501 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
1504 if (colours.getUserColourScheme().getColourCount() > 24)
1506 newColours = new java.awt.Color[23];
1507 for (int i = 0; i < 23; i++)
1509 newColours[i] = new java.awt.Color(Integer.parseInt(colours
1510 .getUserColourScheme().getColour(i + 24).getRGB(), 16));
1512 ucs.setLowerCaseColours(newColours);
1519 * contains last error message (if any) encountered by XML loader.
1521 String errorMessage = null;
1524 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
1525 * exceptions are raised during project XML parsing
1527 public boolean attemptversion1parse = true;
1530 * Load a jalview project archive from a jar file
1533 * - HTTP URL or filename
1535 public AlignFrame LoadJalviewAlign(final String file)
1538 jalview.gui.AlignFrame af = null;
1542 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
1543 // Workaround is to make sure caller implements the JarInputStreamProvider
1545 // so we can re-open the jar input stream for each entry.
1547 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
1548 af = LoadJalviewAlign(jprovider);
1549 } catch (MalformedURLException e)
1551 errorMessage = "Invalid URL format for '" + file + "'";
1557 private jarInputStreamProvider createjarInputStreamProvider(
1558 final String file) throws MalformedURLException
1561 errorMessage = null;
1562 uniqueSetSuffix = null;
1564 viewportsAdded = null;
1565 frefedSequence = null;
1567 if (file.startsWith("http://"))
1569 url = new URL(file);
1571 final URL _url = url;
1572 return new jarInputStreamProvider()
1575 public JarInputStream getJarInputStream() throws IOException
1579 return new JarInputStream(_url.openStream());
1583 return new JarInputStream(new FileInputStream(file));
1587 public String getFilename()
1595 * Recover jalview session from a jalview project archive. Caller may
1596 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
1597 * themselves. Any null fields will be initialised with default values,
1598 * non-null fields are left alone.
1603 public AlignFrame LoadJalviewAlign(final jarInputStreamProvider jprovider)
1605 errorMessage = null;
1606 if (uniqueSetSuffix == null)
1608 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
1610 if (seqRefIds == null)
1612 seqRefIds = new Hashtable();
1614 if (viewportsAdded == null)
1616 viewportsAdded = new Hashtable();
1618 if (frefedSequence == null)
1620 frefedSequence = new Vector();
1623 jalview.gui.AlignFrame af = null;
1624 Hashtable gatherToThisFrame = new Hashtable();
1625 final String file = jprovider.getFilename();
1628 JarInputStream jin = null;
1629 JarEntry jarentry = null;
1634 jin = jprovider.getJarInputStream();
1635 for (int i = 0; i < entryCount; i++)
1637 jarentry = jin.getNextJarEntry();
1640 if (jarentry != null && jarentry.getName().endsWith(".xml"))
1642 InputStreamReader in = new InputStreamReader(jin, "UTF-8");
1643 JalviewModel object = new JalviewModel();
1645 Unmarshaller unmar = new Unmarshaller(object);
1646 unmar.setValidation(false);
1647 object = (JalviewModel) unmar.unmarshal(in);
1648 if (true) // !skipViewport(object))
1650 af = LoadFromObject(object, file, true, jprovider);
1651 if (af.viewport.gatherViewsHere)
1653 gatherToThisFrame.put(af.viewport.getSequenceSetId(), af);
1658 else if (jarentry != null)
1660 // Some other file here.
1663 } while (jarentry != null);
1664 resolveFrefedSequences();
1665 } catch (java.io.FileNotFoundException ex)
1667 ex.printStackTrace();
1668 errorMessage = "Couldn't locate Jalview XML file : " + file;
1669 System.err.println("Exception whilst loading jalview XML file : "
1671 } catch (java.net.UnknownHostException ex)
1673 ex.printStackTrace();
1674 errorMessage = "Couldn't locate Jalview XML file : " + file;
1675 System.err.println("Exception whilst loading jalview XML file : "
1677 } catch (Exception ex)
1679 System.err.println("Parsing as Jalview Version 2 file failed.");
1680 ex.printStackTrace(System.err);
1681 if (attemptversion1parse)
1683 // Is Version 1 Jar file?
1686 af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
1687 } catch (Exception ex2)
1689 System.err.println("Exception whilst loading as jalviewXMLV1:");
1690 ex2.printStackTrace();
1694 if (Desktop.instance != null)
1696 Desktop.instance.stopLoading();
1700 System.out.println("Successfully loaded archive file");
1703 ex.printStackTrace();
1705 System.err.println("Exception whilst loading jalview XML file : "
1707 } catch (OutOfMemoryError e)
1709 // Don't use the OOM Window here
1710 errorMessage = "Out of memory loading jalview XML file";
1711 System.err.println("Out of memory whilst loading jalview XML file");
1712 e.printStackTrace();
1715 if (Desktop.instance != null)
1717 Desktop.instance.stopLoading();
1720 Enumeration en = gatherToThisFrame.elements();
1721 while (en.hasMoreElements())
1723 Desktop.instance.gatherViews((AlignFrame) en.nextElement());
1725 if (errorMessage != null)
1733 * check errorMessage for a valid error message and raise an error box in the
1734 * GUI or write the current errorMessage to stderr and then clear the error
1737 protected void reportErrors()
1739 reportErrors(false);
1742 protected void reportErrors(final boolean saving)
1744 if (errorMessage != null)
1746 final String finalErrorMessage = errorMessage;
1749 javax.swing.SwingUtilities.invokeLater(new Runnable()
1753 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1754 finalErrorMessage, "Error "
1755 + (saving ? "saving" : "loading")
1756 + " Jalview file", JOptionPane.WARNING_MESSAGE);
1762 System.err.println("Problem loading Jalview file: " + errorMessage);
1765 errorMessage = null;
1768 Hashtable alreadyLoadedPDB;
1771 * when set, local views will be updated from view stored in JalviewXML
1772 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
1773 * sync if this is set to true.
1775 private boolean updateLocalViews = false;
1777 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId)
1779 if (alreadyLoadedPDB == null)
1780 alreadyLoadedPDB = new Hashtable();
1782 if (alreadyLoadedPDB.containsKey(pdbId))
1783 return alreadyLoadedPDB.get(pdbId).toString();
1787 JarInputStream jin = jprovider.getJarInputStream();
1789 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
1790 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
1791 * FileInputStream(jprovider)); }
1794 JarEntry entry = null;
1797 entry = jin.getNextJarEntry();
1798 } while (entry != null && !entry.getName().equals(pdbId));
1801 BufferedReader in = new BufferedReader(new InputStreamReader(jin));
1802 File outFile = File.createTempFile("jalview_pdb", ".txt");
1803 outFile.deleteOnExit();
1804 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
1807 while ((data = in.readLine()) != null)
1814 } catch (Exception foo)
1820 alreadyLoadedPDB.put(pdbId, outFile.getAbsolutePath());
1821 return outFile.getAbsolutePath();
1825 warn("Couldn't find PDB file entry in Jalview Jar for " + pdbId);
1827 } catch (Exception ex)
1829 ex.printStackTrace();
1835 private class JvAnnotRow
1837 public JvAnnotRow(int i, AlignmentAnnotation jaa)
1844 * persisted version of annotation row from which to take vis properties
1846 public jalview.datamodel.AlignmentAnnotation template;
1849 * original position of the annotation row in the alignment
1855 * Load alignment frame from jalview XML DOM object
1860 * filename source string
1861 * @param loadTreesAndStructures
1862 * when false only create Viewport
1864 * data source provider
1865 * @return alignment frame created from view stored in DOM
1867 AlignFrame LoadFromObject(JalviewModel object, String file,
1868 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
1870 SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
1871 Sequence[] vamsasSeq = vamsasSet.getSequence();
1873 JalviewModelSequence jms = object.getJalviewModelSequence();
1875 Viewport view = jms.getViewport(0);
1876 // ////////////////////////////////
1879 Vector hiddenSeqs = null;
1880 jalview.datamodel.Sequence jseq;
1882 ArrayList tmpseqs = new ArrayList();
1884 boolean multipleView = false;
1886 JSeq[] JSEQ = object.getJalviewModelSequence().getJSeq();
1887 int vi = 0; // counter in vamsasSeq array
1888 for (int i = 0; i < JSEQ.length; i++)
1890 String seqId = JSEQ[i].getId();
1892 if (seqRefIds.get(seqId) != null)
1894 tmpseqs.add((jalview.datamodel.Sequence) seqRefIds.get(seqId));
1895 multipleView = true;
1899 jseq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
1900 vamsasSeq[vi].getSequence());
1901 jseq.setDescription(vamsasSeq[vi].getDescription());
1902 jseq.setStart(JSEQ[i].getStart());
1903 jseq.setEnd(JSEQ[i].getEnd());
1904 jseq.setVamsasId(uniqueSetSuffix + seqId);
1905 seqRefIds.put(vamsasSeq[vi].getId(), jseq);
1910 if (JSEQ[i].getHidden())
1912 if (hiddenSeqs == null)
1914 hiddenSeqs = new Vector();
1917 hiddenSeqs.addElement((jalview.datamodel.Sequence) seqRefIds
1924 // Create the alignment object from the sequence set
1925 // ///////////////////////////////
1926 jalview.datamodel.Sequence[] orderedSeqs = new jalview.datamodel.Sequence[tmpseqs
1929 tmpseqs.toArray(orderedSeqs);
1931 jalview.datamodel.Alignment al = new jalview.datamodel.Alignment(
1934 // / Add the alignment properties
1935 for (int i = 0; i < vamsasSet.getSequenceSetPropertiesCount(); i++)
1937 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties(i);
1938 al.setProperty(ssp.getKey(), ssp.getValue());
1942 // SequenceFeatures are added to the DatasetSequence,
1943 // so we must create or recover the dataset before loading features
1944 // ///////////////////////////////
1945 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
1947 // older jalview projects do not have a dataset id.
1948 al.setDataset(null);
1952 recoverDatasetFor(vamsasSet, al);
1954 // ///////////////////////////////
1956 Hashtable pdbloaded = new Hashtable();
1959 // load sequence features, database references and any associated PDB
1960 // structures for the alignment
1961 for (int i = 0; i < vamsasSeq.length; i++)
1963 if (JSEQ[i].getFeaturesCount() > 0)
1965 Features[] features = JSEQ[i].getFeatures();
1966 for (int f = 0; f < features.length; f++)
1968 jalview.datamodel.SequenceFeature sf = new jalview.datamodel.SequenceFeature(
1969 features[f].getType(), features[f].getDescription(),
1970 features[f].getStatus(), features[f].getBegin(),
1971 features[f].getEnd(), features[f].getFeatureGroup());
1973 sf.setScore(features[f].getScore());
1974 for (int od = 0; od < features[f].getOtherDataCount(); od++)
1976 OtherData keyValue = features[f].getOtherData(od);
1977 if (keyValue.getKey().startsWith("LINK"))
1979 sf.addLink(keyValue.getValue());
1983 sf.setValue(keyValue.getKey(), keyValue.getValue());
1988 al.getSequenceAt(i).getDatasetSequence().addSequenceFeature(sf);
1991 if (vamsasSeq[i].getDBRefCount() > 0)
1993 addDBRefs(al.getSequenceAt(i).getDatasetSequence(), vamsasSeq[i]);
1995 if (JSEQ[i].getPdbidsCount() > 0)
1997 Pdbids[] ids = JSEQ[i].getPdbids();
1998 for (int p = 0; p < ids.length; p++)
2000 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
2001 entry.setId(ids[p].getId());
2002 entry.setType(ids[p].getType());
2003 if (ids[p].getFile() != null)
2005 if (!pdbloaded.containsKey(ids[p].getFile()))
2007 entry.setFile(loadPDBFile(jprovider, ids[p].getId()));
2011 entry.setFile(pdbloaded.get(ids[p].getId()).toString());
2015 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
2019 } // end !multipleview
2021 // ///////////////////////////////
2022 // LOAD SEQUENCE MAPPINGS
2024 if (vamsasSet.getAlcodonFrameCount() > 0)
2026 // TODO Potentially this should only be done once for all views of an
2028 AlcodonFrame[] alc = vamsasSet.getAlcodonFrame();
2029 for (int i = 0; i < alc.length; i++)
2031 jalview.datamodel.AlignedCodonFrame cf = new jalview.datamodel.AlignedCodonFrame(
2032 alc[i].getAlcodonCount());
2033 if (alc[i].getAlcodonCount() > 0)
2035 Alcodon[] alcods = alc[i].getAlcodon();
2036 for (int p = 0; p < cf.codons.length; p++)
2038 if (alcods[p].hasPos1() && alcods[p].hasPos2()
2039 && alcods[p].hasPos3())
2041 // translated codons require three valid positions
2042 cf.codons[p] = new int[3];
2043 cf.codons[p][0] = (int) alcods[p].getPos1();
2044 cf.codons[p][1] = (int) alcods[p].getPos2();
2045 cf.codons[p][2] = (int) alcods[p].getPos3();
2049 cf.codons[p] = null;
2053 if (alc[i].getAlcodMapCount() > 0)
2055 AlcodMap[] maps = alc[i].getAlcodMap();
2056 for (int m = 0; m < maps.length; m++)
2058 SequenceI dnaseq = (SequenceI) seqRefIds
2059 .get(maps[m].getDnasq());
2061 jalview.datamodel.Mapping mapping = null;
2062 // attach to dna sequence reference.
2063 if (maps[m].getMapping() != null)
2065 mapping = addMapping(maps[m].getMapping());
2069 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
2074 frefedSequence.add(new Object[]
2075 { maps[m].getDnasq(), cf, mapping });
2079 al.addCodonFrame(cf);
2084 // ////////////////////////////////
2086 ArrayList<JvAnnotRow> autoAlan = new ArrayList<JvAnnotRow>();
2088 * store any annotations which forward reference a group's ID
2090 Hashtable<String,ArrayList<jalview.datamodel.AlignmentAnnotation>> groupAnnotRefs = new Hashtable<String,ArrayList<jalview.datamodel.AlignmentAnnotation>>();
2092 if (vamsasSet.getAnnotationCount() > 0)
2094 Annotation[] an = vamsasSet.getAnnotation();
2096 for (int i = 0; i < an.length; i++)
2099 * test if annotation is automatically calculated for this view only
2101 boolean autoForView = false;
2102 if (an[i].getLabel().equals("Quality")
2103 || an[i].getLabel().equals("Conservation")
2104 || an[i].getLabel().equals("Consensus"))
2106 // Kludge for pre 2.5 projects which lacked the autocalculated flag
2108 if (!an[i].hasAutoCalculated())
2110 an[i].setAutoCalculated(true);
2113 if (autoForView || (an[i].hasAutoCalculated() && an[i].isAutoCalculated())) {
2114 // remove ID - we don't recover annotation from other views for
2115 // view-specific annotation
2119 // set visiblity for other annotation in this view
2120 if (an[i].getId() != null
2121 && annotationIds.containsKey(an[i].getId()))
2123 jalview.datamodel.AlignmentAnnotation jda = (jalview.datamodel.AlignmentAnnotation) annotationIds
2124 .get(an[i].getId());
2125 // in principle Visible should always be true for annotation displayed
2126 // in multiple views
2127 if (an[i].hasVisible())
2128 jda.visible = an[i].getVisible();
2130 al.addAnnotation(jda);
2134 // Construct new annotation from model.
2135 AnnotationElement[] ae = an[i].getAnnotationElement();
2136 jalview.datamodel.Annotation[] anot = null;
2138 if (!an[i].getScoreOnly())
2140 anot = new jalview.datamodel.Annotation[al.getWidth()];
2141 for (int aa = 0; aa < ae.length && aa < anot.length; aa++)
2143 if (ae[aa].getPosition() >= anot.length)
2146 anot[ae[aa].getPosition()] = new jalview.datamodel.Annotation(
2148 ae[aa].getDisplayCharacter(), ae[aa].getDescription(),
2149 (ae[aa].getSecondaryStructure() == null || ae[aa]
2150 .getSecondaryStructure().length() == 0) ? ' '
2151 : ae[aa].getSecondaryStructure().charAt(0),
2155 // JBPNote: Consider verifying dataflow for IO of secondary
2156 // structure annotation read from Stockholm files
2157 // this was added to try to ensure that
2158 // if (anot[ae[aa].getPosition()].secondaryStructure>' ')
2160 // anot[ae[aa].getPosition()].displayCharacter = "";
2162 anot[ae[aa].getPosition()].colour = new java.awt.Color(
2163 ae[aa].getColour());
2166 jalview.datamodel.AlignmentAnnotation jaa = null;
2168 if (an[i].getGraph())
2170 float llim=0,hlim=0;
2171 // if (autoForView || an[i].isAutoCalculated()) {
2174 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
2175 an[i].getDescription(), anot, llim, hlim, an[i].getGraphType());
2177 jaa.graphGroup = an[i].getGraphGroup();
2179 if (an[i].getThresholdLine() != null)
2181 jaa.setThreshold(new jalview.datamodel.GraphLine(an[i]
2182 .getThresholdLine().getValue(), an[i]
2183 .getThresholdLine().getLabel(), new java.awt.Color(
2184 an[i].getThresholdLine().getColour())));
2187 if (autoForView || an[i].isAutoCalculated()) {
2188 // Hardwire the symbol display line to ensure that labels for histograms are displayed
2194 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
2195 an[i].getDescription(), anot);
2199 // register new annotation
2200 if (an[i].getId() != null)
2202 annotationIds.put(an[i].getId(), jaa);
2203 jaa.annotationId = an[i].getId();
2205 // recover sequence association
2206 if (an[i].getSequenceRef() != null)
2208 if (al.findName(an[i].getSequenceRef()) != null)
2210 jaa.createSequenceMapping(
2211 al.findName(an[i].getSequenceRef()), 1, true);
2212 al.findName(an[i].getSequenceRef()).addAlignmentAnnotation(
2217 // and make a note of any group association
2218 if (an[i].getGroupRef() != null && an[i].getGroupRef().length() > 0)
2220 ArrayList<jalview.datamodel.AlignmentAnnotation> aal=groupAnnotRefs.get(an[i].getGroupRef());
2222 aal = new ArrayList<jalview.datamodel.AlignmentAnnotation>();
2223 groupAnnotRefs.put(an[i].getGroupRef(),aal);
2228 if (an[i].hasScore())
2230 jaa.setScore(an[i].getScore());
2232 if (an[i].hasVisible())
2233 jaa.visible = an[i].getVisible();
2235 if (an[i].hasCentreColLabels())
2236 jaa.centreColLabels = an[i].getCentreColLabels();
2238 if (an[i].hasScaleColLabels())
2240 jaa.scaleColLabel = an[i].getScaleColLabels();
2242 if (an[i].hasAutoCalculated() && an[i].isAutoCalculated())
2244 // newer files have an 'autoCalculated' flag and store calculation
2245 // state in viewport properties
2246 jaa.autoCalculated = true; // means annotation will be marked for
2247 // update at end of load.
2249 if (an[i].hasGraphHeight())
2251 jaa.graphHeight = an[i].getGraphHeight();
2253 if (jaa.autoCalculated)
2255 autoAlan.add(new JvAnnotRow(i, jaa));
2257 // if (!autoForView)
2259 // add autocalculated group annotation and any user created annotation for the view
2260 al.addAnnotation(jaa);
2265 // ///////////////////////
2267 // Create alignment markup and styles for this view
2268 if (jms.getJGroupCount() > 0)
2270 JGroup[] groups = jms.getJGroup();
2272 for (int i = 0; i < groups.length; i++)
2274 ColourSchemeI cs = null;
2276 if (groups[i].getColour() != null)
2278 if (groups[i].getColour().startsWith("ucs"))
2280 cs = GetUserColourScheme(jms, groups[i].getColour());
2284 cs = ColourSchemeProperty.getColour(al, groups[i].getColour());
2289 cs.setThreshold(groups[i].getPidThreshold(), true);
2293 Vector seqs = new Vector();
2295 for (int s = 0; s < groups[i].getSeqCount(); s++)
2297 String seqId = groups[i].getSeq(s) + "";
2298 jalview.datamodel.SequenceI ts = (jalview.datamodel.SequenceI) seqRefIds
2303 seqs.addElement(ts);
2307 if (seqs.size() < 1)
2312 jalview.datamodel.SequenceGroup sg = new jalview.datamodel.SequenceGroup(
2313 seqs, groups[i].getName(), cs, groups[i].getDisplayBoxes(),
2314 groups[i].getDisplayText(), groups[i].getColourText(),
2315 groups[i].getStart(), groups[i].getEnd());
2317 sg.setOutlineColour(new java.awt.Color(groups[i].getOutlineColour()));
2319 sg.textColour = new java.awt.Color(groups[i].getTextCol1());
2320 sg.textColour2 = new java.awt.Color(groups[i].getTextCol2());
2321 sg.setShowNonconserved(groups[i].hasShowUnconserved() ? groups[i]
2322 .isShowUnconserved() : false);
2323 sg.thresholdTextColour = groups[i].getTextColThreshold();
2324 if (groups[i].hasShowConsensusHistogram())
2326 sg.setShowConsensusHistogram(groups[i].isShowConsensusHistogram());
2329 if (groups[i].hasShowSequenceLogo())
2331 sg.setshowSequenceLogo(groups[i].isShowSequenceLogo());
2333 if (groups[i].hasIgnoreGapsinConsensus())
2335 sg.setIgnoreGapsConsensus(groups[i].getIgnoreGapsinConsensus());
2337 if (groups[i].getConsThreshold() != 0)
2339 jalview.analysis.Conservation c = new jalview.analysis.Conservation(
2340 "All", ResidueProperties.propHash, 3,
2341 sg.getSequences(null), 0, sg.getWidth() - 1);
2343 c.verdict(false, 25);
2344 sg.cs.setConservation(c);
2347 if (groups[i].getId() != null && groupAnnotRefs.size() > 0)
2349 // re-instate unique group/annotation row reference
2350 ArrayList<jalview.datamodel.AlignmentAnnotation> jaal = groupAnnotRefs
2351 .get(groups[i].getId());
2354 for (jalview.datamodel.AlignmentAnnotation jaa:jaal) {
2356 if (jaa.autoCalculated)
2358 // match up and try to set group autocalc alignment row for this annotation
2359 if (jaa.label.startsWith("Consensus for ")) {
2360 sg.setConsensus(jaa);
2362 // match up and try to set group autocalc alignment row for this annotation
2363 if (jaa.label.startsWith("Conservation for ")) {
2364 sg.setConservationRow(jaa);
2375 // ///////////////////////////////
2378 // If we just load in the same jar file again, the sequenceSetId
2379 // will be the same, and we end up with multiple references
2380 // to the same sequenceSet. We must modify this id on load
2381 // so that each load of the file gives a unique id
2382 String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
2383 String viewId = (view.getId() == null ? null : view.getId()
2385 AlignFrame af = null;
2386 AlignViewport av = null;
2387 // now check to see if we really need to create a new viewport.
2388 if (multipleView && viewportsAdded.size() == 0)
2390 // We recovered an alignment for which a viewport already exists.
2391 // TODO: fix up any settings necessary for overlaying stored state onto
2392 // state recovered from another document. (may not be necessary).
2393 // we may need a binding from a viewport in memory to one recovered from
2395 // and then recover its containing af to allow the settings to be applied.
2396 // TODO: fix for vamsas demo
2398 .println("About to recover a viewport for existing alignment: Sequence set ID is "
2400 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
2401 if (seqsetobj != null)
2403 if (seqsetobj instanceof String)
2405 uniqueSeqSetId = (String) seqsetobj;
2407 .println("Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
2413 .println("Warning : Collision between sequence set ID string and existing jalview object mapping.");
2418 AlignmentPanel ap = null;
2419 boolean isnewview = true;
2422 // Check to see if this alignment already has a view id == viewId
2423 jalview.gui.AlignmentPanel views[] = Desktop
2424 .getAlignmentPanels(uniqueSeqSetId);
2425 if (views != null && views.length > 0)
2427 for (int v = 0; v < views.length; v++)
2429 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
2431 // recover the existing alignpanel, alignframe, viewport
2432 af = views[v].alignFrame;
2435 // TODO: could even skip resetting view settings if we don't want to
2436 // change the local settings from other jalview processes
2445 af = loadViewport(file, JSEQ, hiddenSeqs, al, jms, view,
2446 uniqueSeqSetId, viewId, autoAlan);
2451 // /////////////////////////////////////
2452 if (loadTreesAndStructures && jms.getTreeCount() > 0)
2456 for (int t = 0; t < jms.getTreeCount(); t++)
2459 Tree tree = jms.getTree(t);
2461 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
2464 tp = af.ShowNewickTree(
2465 new jalview.io.NewickFile(tree.getNewick()),
2466 tree.getTitle(), tree.getWidth(), tree.getHeight(),
2467 tree.getXpos(), tree.getYpos());
2468 if (tree.getId() != null)
2470 // perhaps bind the tree id to something ?
2475 // update local tree attributes ?
2476 // TODO: should check if tp has been manipulated by user - if so its
2477 // settings shouldn't be modified
2478 tp.setTitle(tree.getTitle());
2479 tp.setBounds(new Rectangle(tree.getXpos(), tree.getYpos(), tree
2480 .getWidth(), tree.getHeight()));
2481 tp.av = av; // af.viewport; // TODO: verify 'associate with all
2484 tp.treeCanvas.av = av; // af.viewport;
2485 tp.treeCanvas.ap = ap; // af.alignPanel;
2490 warn("There was a problem recovering stored Newick tree: \n"
2491 + tree.getNewick());
2495 tp.fitToWindow.setState(tree.getFitToWindow());
2496 tp.fitToWindow_actionPerformed(null);
2498 if (tree.getFontName() != null)
2500 tp.setTreeFont(new java.awt.Font(tree.getFontName(), tree
2501 .getFontStyle(), tree.getFontSize()));
2505 tp.setTreeFont(new java.awt.Font(view.getFontName(), view
2506 .getFontStyle(), tree.getFontSize()));
2509 tp.showPlaceholders(tree.getMarkUnlinked());
2510 tp.showBootstrap(tree.getShowBootstrap());
2511 tp.showDistances(tree.getShowDistances());
2513 tp.treeCanvas.threshold = tree.getThreshold();
2515 if (tree.getCurrentTree())
2517 af.viewport.setCurrentTree(tp.getTree());
2521 } catch (Exception ex)
2523 ex.printStackTrace();
2527 // //LOAD STRUCTURES
2528 if (loadTreesAndStructures)
2530 // run through all PDB ids on the alignment, and collect mappings between
2531 // jmol view ids and all sequences referring to it
2532 Hashtable<String, Object[]> jmolViewIds = new Hashtable();
2534 for (int i = 0; i < JSEQ.length; i++)
2536 if (JSEQ[i].getPdbidsCount() > 0)
2538 Pdbids[] ids = JSEQ[i].getPdbids();
2539 for (int p = 0; p < ids.length; p++)
2541 for (int s = 0; s < ids[p].getStructureStateCount(); s++)
2543 // check to see if we haven't already created this structure view
2544 String sviewid = (ids[p].getStructureState(s).getViewId() == null) ? null
2545 : ids[p].getStructureState(s).getViewId()
2547 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
2548 // Originally : ids[p].getFile()
2549 // : TODO: verify external PDB file recovery still works in normal
2550 // jalview project load
2551 jpdb.setFile(loadPDBFile(jprovider, ids[p].getId()));
2552 jpdb.setId(ids[p].getId());
2554 int x = ids[p].getStructureState(s).getXpos();
2555 int y = ids[p].getStructureState(s).getYpos();
2556 int width = ids[p].getStructureState(s).getWidth();
2557 int height = ids[p].getStructureState(s).getHeight();
2559 // Probably don't need to do this anymore...
2560 // Desktop.desktop.getComponentAt(x, y);
2561 // TODO: NOW: check that this recovers the PDB file correctly.
2562 String pdbFile = loadPDBFile(jprovider, ids[p].getId());
2563 jalview.datamodel.SequenceI seq = (jalview.datamodel.SequenceI) seqRefIds
2564 .get(JSEQ[i].getId() + "");
2565 if (sviewid == null)
2567 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width
2570 if (!jmolViewIds.containsKey(sviewid))
2572 jmolViewIds.put(sviewid, new Object[]
2574 { x, y, width, height }, "",
2575 new Hashtable<String, Object[]>(), new boolean[]
2576 { false, false } });
2577 // Legacy pre-2.7 conversion JAL-823 :
2578 // do not assume any view has to be linked for colour by sequence
2581 // assemble String[] { pdb files }, String[] { id for each
2582 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
2583 // seqs_file 2}, boolean[] {
2584 // linkAlignPanel,superposeWithAlignpanel}} from hash
2585 Object[] jmoldat = (Object[]) jmolViewIds.get(sviewid);
2586 ((boolean[]) jmoldat[3])[0] |= ids[p].getStructureState(s)
2587 .hasAlignwithAlignPanel() ? ids[p].getStructureState(
2588 s).getAlignwithAlignPanel() : false;
2589 // never colour by linked panel if not specified
2590 ((boolean[]) jmoldat[3])[1] |= ids[p].getStructureState(s)
2591 .hasColourwithAlignPanel() ? ids[p]
2592 .getStructureState(s).getColourwithAlignPanel()
2595 if (((String) jmoldat[1]).length() < ids[p]
2596 .getStructureState(s).getContent().length())
2599 jmoldat[1] = ids[p].getStructureState(s).getContent();
2602 Object[] seqstrmaps = (Object[]) ((Hashtable) jmoldat[2])
2603 .get(ids[p].getFile());
2604 if (seqstrmaps == null)
2606 ((Hashtable) jmoldat[2]).put(
2607 new File(ids[p].getFile()).toString(),
2608 seqstrmaps = new Object[]
2609 { pdbFile, ids[p].getId(), new Vector(),
2612 if (!((Vector) seqstrmaps[2]).contains(seq))
2614 ((Vector) seqstrmaps[2]).addElement(seq);
2615 // ((Vector)seqstrmaps[3]).addElement(n) : in principle, chains
2616 // should be stored here : do we need to
2617 // TODO: store and recover seq/pdb_id : chain mappings
2625 // Instantiate the associated Jmol views
2626 for (Entry<String, Object[]> entry : jmolViewIds.entrySet())
2628 String sviewid = entry.getKey();
2629 Object[] svattrib = entry.getValue();
2630 int[] geom = (int[]) svattrib[0];
2631 String state = (String) svattrib[1];
2632 Hashtable<String, Object[]> oldFiles = (Hashtable<String, Object[]>) svattrib[2];
2633 final boolean useinJmolsuperpos = ((boolean[]) svattrib[3])[0], usetoColourbyseq = ((boolean[]) svattrib[3])[1];
2634 int x = geom[0], y = geom[1], width = geom[2], height = geom[3];
2635 // collate the pdbfile -> sequence mappings from this view
2636 Vector<String> pdbfilenames = new Vector<String>();
2637 Vector<SequenceI[]> seqmaps = new Vector<SequenceI[]>();
2638 Vector<String> pdbids = new Vector<String>();
2640 // Search to see if we've already created this Jmol view
2641 AppJmol comp = null;
2642 JInternalFrame[] frames = null;
2647 frames = Desktop.desktop.getAllFrames();
2648 } catch (ArrayIndexOutOfBoundsException e)
2650 // occasional No such child exceptions are thrown here...
2655 } catch (Exception f)
2660 } while (frames == null);
2661 // search for any Jmol windows already open from other
2662 // alignment views that exactly match the stored structure state
2663 for (int f = 0; comp == null && f < frames.length; f++)
2665 if (frames[f] instanceof AppJmol)
2668 && ((AppJmol) frames[f]).getViewId().equals(sviewid))
2670 // post jalview 2.4 schema includes structure view id
2671 comp = (AppJmol) frames[f];
2673 else if (frames[f].getX() == x && frames[f].getY() == y
2674 && frames[f].getHeight() == height
2675 && frames[f].getWidth() == width)
2677 comp = (AppJmol) frames[f];
2684 // create a new Jmol window.
2685 // First parse the Jmol state to translate filenames loaded into the
2686 // view, and record the order in which files are shown in the Jmol
2687 // view, so we can add the sequence mappings in same order.
2688 StringBuffer newFileLoc = null;
2689 int cp = 0, ncp, ecp;
2690 while ((ncp = state.indexOf("load ", cp)) > -1)
2692 if (newFileLoc == null)
2694 newFileLoc = new StringBuffer();
2696 newFileLoc.append(state.substring(cp,
2697 ncp = (state.indexOf("\"", ncp + 1) + 1)));
2698 String oldfilenam = state.substring(ncp,
2699 ecp = state.indexOf("\"", ncp));
2700 // recover the new mapping data for this old filename
2701 // have to normalize filename - since Jmol and jalview do filename
2702 // translation differently.
2703 Object[] filedat = oldFiles.get(new File(oldfilenam)
2705 newFileLoc.append(((String) filedat[0]));
2706 pdbfilenames.addElement((String) filedat[0]);
2707 pdbids.addElement((String) filedat[1]);
2708 seqmaps.addElement((SequenceI[]) ((Vector<SequenceI>) filedat[2])
2709 .toArray(new SequenceI[0]));
2710 newFileLoc.append("\"");
2711 cp = ecp + 1; // advance beyond last \" and set cursor so we can
2712 // look for next file statement.
2716 // just append rest of state
2717 newFileLoc.append(state.substring(cp));
2722 .print("Ignoring incomplete Jmol state for PDB ids: ");
2723 newFileLoc = new StringBuffer(state);
2724 newFileLoc.append("; load append ");
2725 for (String id : oldFiles.keySet())
2727 // add this and any other pdb files that should be present in
2729 Object[] filedat = oldFiles.get(id);
2731 newFileLoc.append(((String) filedat[0]));
2732 pdbfilenames.addElement((String) filedat[0]);
2733 pdbids.addElement((String) filedat[1]);
2734 seqmaps.addElement((SequenceI[]) ((Vector<SequenceI>) filedat[2])
2735 .toArray(new SequenceI[0]));
2736 newFileLoc.append(" \"");
2737 newFileLoc.append((String) filedat[0]);
2738 newFileLoc.append("\"");
2741 newFileLoc.append(";");
2744 if (newFileLoc != null)
2746 int histbug = newFileLoc.indexOf("history = ");
2748 int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";",
2750 String val = (diff == -1) ? null : newFileLoc.substring(
2752 if (val != null && val.length() >= 4)
2754 if (val.contains("e"))
2756 if (val.trim().equals("true"))
2764 newFileLoc.replace(histbug, diff, val);
2767 // TODO: assemble String[] { pdb files }, String[] { id for each
2768 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
2769 // seqs_file 2}} from hash
2770 final String[] pdbf = (String[]) pdbfilenames
2771 .toArray(new String[pdbfilenames.size()]), id = (String[]) pdbids
2772 .toArray(new String[pdbids.size()]);
2773 final SequenceI[][] sq = (SequenceI[][]) seqmaps
2774 .toArray(new SequenceI[seqmaps.size()][]);
2775 final String fileloc = newFileLoc.toString(), vid = sviewid;
2776 final AlignFrame alf = af;
2777 final java.awt.Rectangle rect = new java.awt.Rectangle(x, y,
2781 javax.swing.SwingUtilities.invokeAndWait(new Runnable()
2785 AppJmol sview = null;
2788 sview = new AppJmol(pdbf, id, sq, alf.alignPanel,
2789 useinJmolsuperpos, usetoColourbyseq, fileloc,
2791 } catch (OutOfMemoryError ex)
2793 new OOMWarning("restoring structure view for PDB id "
2794 + id, (OutOfMemoryError) ex.getCause());
2795 if (sview != null && sview.isVisible())
2797 sview.closeViewer();
2798 sview.setVisible(false);
2804 } catch (InvocationTargetException ex)
2806 warn("Unexpected error when opening Jmol view.", ex);
2808 } catch (InterruptedException e)
2810 // e.printStackTrace();
2816 // if (comp != null)
2818 // NOTE: if the jalview project is part of a shared session then
2819 // view synchronization should/could be done here.
2821 // add mapping for sequences in this view to an already open Jmol
2823 for (String id : oldFiles.keySet())
2825 // add this and any other pdb files that should be present in the
2827 Object[] filedat = oldFiles.get(id);
2828 String pdbFile = (String) filedat[0];
2829 SequenceI[] seq = (SequenceI[]) ((Vector<SequenceI>) filedat[2])
2830 .toArray(new SequenceI[0]);
2831 StructureSelectionManager.getStructureSelectionManager()
2832 .setMapping(seq, null, pdbFile,
2833 jalview.io.AppletFormatAdapter.FILE);
2834 ((AppJmol) comp).jmb.addSequenceForStructFile(pdbFile, seq);
2836 // and add the AlignmentPanel's reference to the Jmol view
2837 ((AppJmol) comp).addAlignmentPanel(ap);
2838 if (useinJmolsuperpos)
2840 ((AppJmol) comp).useAlignmentPanelForSuperposition(ap);
2844 ((AppJmol) comp).excludeAlignmentPanelForSuperposition(ap);
2846 if (usetoColourbyseq)
2848 ((AppJmol) comp).useAlignmentPanelForColourbyseq(ap);
2852 ((AppJmol) comp).excludeAlignmentPanelForColourbyseq(ap);
2858 // and finally return.
2862 AlignFrame loadViewport(String file, JSeq[] JSEQ, Vector hiddenSeqs,
2863 Alignment al, JalviewModelSequence jms, Viewport view,
2864 String uniqueSeqSetId, String viewId,
2865 ArrayList<JvAnnotRow> autoAlan)
2867 AlignFrame af = null;
2868 af = new AlignFrame(al, view.getWidth(), view.getHeight(),
2869 uniqueSeqSetId, viewId);
2871 af.setFileName(file, "Jalview");
2873 for (int i = 0; i < JSEQ.length; i++)
2875 af.viewport.setSequenceColour(af.viewport.alignment.getSequenceAt(i),
2876 new java.awt.Color(JSEQ[i].getColour()));
2879 af.viewport.gatherViewsHere = view.getGatheredViews();
2881 if (view.getSequenceSetId() != null)
2883 jalview.gui.AlignViewport av = (jalview.gui.AlignViewport) viewportsAdded
2884 .get(uniqueSeqSetId);
2886 af.viewport.sequenceSetID = uniqueSeqSetId;
2889 // propagate shared settings to this new view
2890 af.viewport.historyList = av.historyList;
2891 af.viewport.redoList = av.redoList;
2895 viewportsAdded.put(uniqueSeqSetId, af.viewport);
2897 // TODO: check if this method can be called repeatedly without
2898 // side-effects if alignpanel already registered.
2899 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
2901 // apply Hidden regions to view.
2902 if (hiddenSeqs != null)
2904 for (int s = 0; s < JSEQ.length; s++)
2906 jalview.datamodel.SequenceGroup hidden = new jalview.datamodel.SequenceGroup();
2908 for (int r = 0; r < JSEQ[s].getHiddenSequencesCount(); r++)
2911 al.getSequenceAt(JSEQ[s].getHiddenSequences(r)), false);
2913 af.viewport.hideRepSequences(al.getSequenceAt(s), hidden);
2916 jalview.datamodel.SequenceI[] hseqs = new jalview.datamodel.SequenceI[hiddenSeqs
2919 for (int s = 0; s < hiddenSeqs.size(); s++)
2921 hseqs[s] = (jalview.datamodel.SequenceI) hiddenSeqs.elementAt(s);
2924 af.viewport.hideSequence(hseqs);
2927 // recover view properties and display parameters
2928 if (view.getViewName() != null)
2930 af.viewport.viewName = view.getViewName();
2931 af.setInitialTabVisible();
2933 af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(),
2936 af.viewport.setShowAnnotation(view.getShowAnnotation());
2937 af.viewport.setAbovePIDThreshold(view.getPidSelected());
2939 af.viewport.setColourText(view.getShowColourText());
2941 af.viewport.setConservationSelected(view.getConservationSelected());
2942 af.viewport.setShowJVSuffix(view.getShowFullId());
2943 af.viewport.rightAlignIds = view.getRightAlignIds();
2944 af.viewport.setFont(new java.awt.Font(view.getFontName(), view
2945 .getFontStyle(), view.getFontSize()));
2946 af.alignPanel.fontChanged();
2947 af.viewport.setRenderGaps(view.getRenderGaps());
2948 af.viewport.setWrapAlignment(view.getWrapAlignment());
2949 af.alignPanel.setWrapAlignment(view.getWrapAlignment());
2950 af.viewport.setShowAnnotation(view.getShowAnnotation());
2951 af.alignPanel.setAnnotationVisible(view.getShowAnnotation());
2953 af.viewport.setShowBoxes(view.getShowBoxes());
2955 af.viewport.setShowText(view.getShowText());
2957 af.viewport.textColour = new java.awt.Color(view.getTextCol1());
2958 af.viewport.textColour2 = new java.awt.Color(view.getTextCol2());
2959 af.viewport.thresholdTextColour = view.getTextColThreshold();
2960 af.viewport.setShowUnconserved(view.hasShowUnconserved() ? view
2961 .isShowUnconserved() : false);
2962 af.viewport.setStartRes(view.getStartRes());
2963 af.viewport.setStartSeq(view.getStartSeq());
2965 ColourSchemeI cs = null;
2966 // apply colourschemes
2967 if (view.getBgColour() != null)
2969 if (view.getBgColour().startsWith("ucs"))
2971 cs = GetUserColourScheme(jms, view.getBgColour());
2973 else if (view.getBgColour().startsWith("Annotation"))
2975 // int find annotation
2976 if (af.viewport.alignment.getAlignmentAnnotation() != null)
2978 for (int i = 0; i < af.viewport.alignment
2979 .getAlignmentAnnotation().length; i++)
2981 if (af.viewport.alignment.getAlignmentAnnotation()[i].label
2982 .equals(view.getAnnotationColours().getAnnotation()))
2984 if (af.viewport.alignment.getAlignmentAnnotation()[i]
2985 .getThreshold() == null)
2987 af.viewport.alignment.getAlignmentAnnotation()[i]
2988 .setThreshold(new jalview.datamodel.GraphLine(view
2989 .getAnnotationColours().getThreshold(),
2990 "Threshold", java.awt.Color.black)
2995 if (view.getAnnotationColours().getColourScheme()
2998 cs = new AnnotationColourGradient(
2999 af.viewport.alignment.getAlignmentAnnotation()[i],
3000 new java.awt.Color(view.getAnnotationColours()
3001 .getMinColour()), new java.awt.Color(view
3002 .getAnnotationColours().getMaxColour()),
3003 view.getAnnotationColours().getAboveThreshold());
3005 else if (view.getAnnotationColours().getColourScheme()
3008 cs = new AnnotationColourGradient(
3009 af.viewport.alignment.getAlignmentAnnotation()[i],
3010 GetUserColourScheme(jms, view
3011 .getAnnotationColours().getColourScheme()),
3012 view.getAnnotationColours().getAboveThreshold());
3016 cs = new AnnotationColourGradient(
3017 af.viewport.alignment.getAlignmentAnnotation()[i],
3018 ColourSchemeProperty.getColour(al, view
3019 .getAnnotationColours().getColourScheme()),
3020 view.getAnnotationColours().getAboveThreshold());
3023 // Also use these settings for all the groups
3024 if (al.getGroups() != null)
3026 for (int g = 0; g < al.getGroups().size(); g++)
3028 jalview.datamodel.SequenceGroup sg = (jalview.datamodel.SequenceGroup) al
3029 .getGroups().elementAt(g);
3038 * (view.getAnnotationColours().getColourScheme().equals("None"
3039 * )) { sg.cs = new AnnotationColourGradient(
3040 * af.viewport.alignment.getAlignmentAnnotation()[i], new
3041 * java.awt.Color(view.getAnnotationColours().
3042 * getMinColour()), new
3043 * java.awt.Color(view.getAnnotationColours().
3045 * view.getAnnotationColours().getAboveThreshold()); } else
3048 sg.cs = new AnnotationColourGradient(
3049 af.viewport.alignment.getAlignmentAnnotation()[i],
3050 sg.cs, view.getAnnotationColours()
3051 .getAboveThreshold());
3065 cs = ColourSchemeProperty.getColour(al, view.getBgColour());
3070 cs.setThreshold(view.getPidThreshold(), true);
3071 cs.setConsensus(af.viewport.hconsensus);
3075 af.viewport.setGlobalColourScheme(cs);
3076 af.viewport.setColourAppliesToAllGroups(false);
3078 if (view.getConservationSelected() && cs != null)
3080 cs.setConservationInc(view.getConsThreshold());
3083 af.changeColour(cs);
3085 af.viewport.setColourAppliesToAllGroups(true);
3087 if (view.getShowSequenceFeatures())
3089 af.viewport.showSequenceFeatures = true;
3091 if (view.hasCentreColumnLabels())
3093 af.viewport.setCentreColumnLabels(view.getCentreColumnLabels());
3095 if (view.hasIgnoreGapsinConsensus())
3097 af.viewport.ignoreGapsInConsensusCalculation = view
3098 .getIgnoreGapsinConsensus();
3100 if (view.hasFollowHighlight())
3102 af.viewport.followHighlight = view.getFollowHighlight();
3104 if (view.hasFollowSelection())
3106 af.viewport.followSelection = view.getFollowSelection();
3108 if (view.hasShowConsensusHistogram())
3110 af.viewport.setShowConsensusHistogram(view
3111 .getShowConsensusHistogram());
3115 af.viewport.setShowConsensusHistogram(true);
3117 if (view.hasShowSequenceLogo())
3119 af.viewport.showSequenceLogo = view.getShowSequenceLogo();
3123 af.viewport.showSequenceLogo = false;
3125 if (view.hasShowDbRefTooltip())
3127 af.viewport.setShowDbRefs(view.getShowDbRefTooltip());
3129 if (view.hasShowNPfeatureTooltip())
3131 af.viewport.setShowNpFeats(view.hasShowNPfeatureTooltip());
3133 if (view.hasShowGroupConsensus())
3135 af.viewport.setShowGroupConsensus(view.getShowGroupConsensus());
3139 af.viewport.setShowGroupConsensus(false);
3141 if (view.hasShowGroupConservation())
3143 af.viewport.setShowGroupConservation(view.getShowGroupConservation());
3147 af.viewport.setShowGroupConservation(false);
3150 // recover featre settings
3151 if (jms.getFeatureSettings() != null)
3153 af.viewport.featuresDisplayed = new Hashtable();
3154 String[] renderOrder = new String[jms.getFeatureSettings()
3155 .getSettingCount()];
3156 for (int fs = 0; fs < jms.getFeatureSettings().getSettingCount(); fs++)
3158 Setting setting = jms.getFeatureSettings().getSetting(fs);
3159 if (setting.hasMincolour())
3161 GraduatedColor gc = setting.hasMin() ? new GraduatedColor(
3162 new java.awt.Color(setting.getMincolour()),
3163 new java.awt.Color(setting.getColour()),
3164 setting.getMin(), setting.getMax()) : new GraduatedColor(
3165 new java.awt.Color(setting.getMincolour()),
3166 new java.awt.Color(setting.getColour()), 0, 1);
3167 if (setting.hasThreshold())
3169 gc.setThresh(setting.getThreshold());
3170 gc.setThreshType(setting.getThreshstate());
3172 gc.setAutoScaled(true); // default
3173 if (setting.hasAutoScale())
3175 gc.setAutoScaled(setting.getAutoScale());
3177 if (setting.hasColourByLabel())
3179 gc.setColourByLabel(setting.getColourByLabel());
3181 // and put in the feature colour table.
3182 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setColour(
3183 setting.getType(), gc);
3187 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setColour(
3189 new java.awt.Color(setting.getColour()));
3191 renderOrder[fs] = setting.getType();
3192 if (setting.hasOrder())
3193 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setOrder(
3194 setting.getType(), setting.getOrder());
3196 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().setOrder(
3198 fs / jms.getFeatureSettings().getSettingCount());
3199 if (setting.getDisplay())
3201 af.viewport.featuresDisplayed.put(setting.getType(), new Integer(
3202 setting.getColour()));
3205 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().renderOrder = renderOrder;
3207 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().featureGroups = fgtable = new Hashtable();
3208 for (int gs = 0; gs < jms.getFeatureSettings().getGroupCount(); gs++)
3210 Group grp = jms.getFeatureSettings().getGroup(gs);
3211 fgtable.put(grp.getName(), new Boolean(grp.getDisplay()));
3215 if (view.getHiddenColumnsCount() > 0)
3217 for (int c = 0; c < view.getHiddenColumnsCount(); c++)
3219 af.viewport.hideColumns(view.getHiddenColumns(c).getStart(), view
3220 .getHiddenColumns(c).getEnd() // +1
3225 af.setMenusFromViewport(af.viewport);
3226 // TODO: we don't need to do this if the viewport is aready visible.
3227 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
3229 af.alignPanel.updateAnnotation(false); // recompute any autoannotation
3230 reorderAutoannotation(af,al,autoAlan);
3234 private void reorderAutoannotation(AlignFrame af, Alignment al,
3235 ArrayList<JvAnnotRow> autoAlan)
3237 // copy over visualization settings for autocalculated annotation in the
3239 if (al.getAlignmentAnnotation() != null)
3242 * Kludge for magic autoannotation names (see JAL-811)
3244 String[] magicNames = new String[]
3245 { "Consensus", "Quality", "Conservation" };
3246 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
3247 Hashtable<String, JvAnnotRow> visan = new Hashtable<String, JvAnnotRow>();
3248 for (String nm : magicNames)
3250 visan.put(nm, nullAnnot);
3252 for (JvAnnotRow auan : autoAlan)
3254 visan.put(auan.template.label, auan);
3256 int hSize = al.getAlignmentAnnotation().length;
3257 ArrayList<JvAnnotRow> reorder = new ArrayList<JvAnnotRow>();
3258 for (int h = 0; h < hSize; h++)
3260 jalview.datamodel.AlignmentAnnotation jalan = al
3261 .getAlignmentAnnotation()[h];
3262 if (jalan.autoCalculated)
3264 JvAnnotRow valan = visan.get(jalan.label);
3267 // delete the auto calculated row from the alignment
3268 al.deleteAnnotation(al.getAlignmentAnnotation()[h],false);
3271 if (valan != nullAnnot)
3273 if (jalan!=valan.template) {
3274 // newly created autoannotation row instance
3275 // so keep a reference to the visible annotation row
3276 // and copy over all relevant attributes
3277 if (valan.template.graphHeight >= 0)
3280 jalan.graphHeight = valan.template.graphHeight;
3282 jalan.visible = valan.template.visible;
3284 reorder.add(new JvAnnotRow(valan.order, jalan));
3289 int s=0,srt[] = new int[reorder.size()];
3290 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
3291 for (JvAnnotRow jvar:reorder) {
3293 srt[s++]=jvar.order;
3296 jalview.util.QuickSort.sort(srt, rws);
3297 // and re-insert the annotation at its correct position
3298 for (JvAnnotRow jvar : rws)
3300 al.addAnnotation(jvar.template, jvar.order);
3302 af.alignPanel.adjustAnnotationHeight();
3306 Hashtable skipList = null;
3309 * TODO remove this method
3312 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
3313 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
3314 * throw new Error("Implementation Error. No skipList defined for this
3315 * Jalview2XML instance."); } return (AlignFrame)
3316 * skipList.get(view.getSequenceSetId()); }
3320 * Check if the Jalview view contained in object should be skipped or not.
3323 * @return true if view's sequenceSetId is a key in skipList
3325 private boolean skipViewport(JalviewModel object)
3327 if (skipList == null)
3332 if (skipList.containsKey(id = object.getJalviewModelSequence()
3333 .getViewport()[0].getSequenceSetId()))
3335 if (Cache.log != null && Cache.log.isDebugEnabled())
3337 Cache.log.debug("Skipping seuqence set id " + id);
3344 public void AddToSkipList(AlignFrame af)
3346 if (skipList == null)
3348 skipList = new Hashtable();
3350 skipList.put(af.getViewport().getSequenceSetId(), af);
3353 public void clearSkipList()
3355 if (skipList != null)
3362 private void recoverDatasetFor(SequenceSet vamsasSet, Alignment al)
3364 jalview.datamodel.Alignment ds = getDatasetFor(vamsasSet.getDatasetId());
3365 Vector dseqs = null;
3368 // create a list of new dataset sequences
3369 dseqs = new Vector();
3371 for (int i = 0, iSize = vamsasSet.getSequenceCount(); i < iSize; i++)
3373 Sequence vamsasSeq = vamsasSet.getSequence(i);
3374 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs);
3376 // create a new dataset
3379 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
3380 dseqs.copyInto(dsseqs);
3381 ds = new jalview.datamodel.Alignment(dsseqs);
3382 debug("Created new dataset " + vamsasSet.getDatasetId()
3383 + " for alignment " + System.identityHashCode(al));
3384 addDatasetRef(vamsasSet.getDatasetId(), ds);
3386 // set the dataset for the newly imported alignment.
3387 if (al.getDataset() == null)
3396 * sequence definition to create/merge dataset sequence for
3400 * vector to add new dataset sequence to
3402 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
3403 AlignmentI ds, Vector dseqs)
3405 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
3407 jalview.datamodel.Sequence sq = (jalview.datamodel.Sequence) seqRefIds
3408 .get(vamsasSeq.getId());
3409 jalview.datamodel.SequenceI dsq = null;
3410 if (sq != null && sq.getDatasetSequence() != null)
3412 dsq = (jalview.datamodel.SequenceI) sq.getDatasetSequence();
3415 String sqid = vamsasSeq.getDsseqid();
3418 // need to create or add a new dataset sequence reference to this sequence
3421 dsq = (jalview.datamodel.SequenceI) seqRefIds.get(sqid);
3426 // make a new dataset sequence
3427 dsq = sq.createDatasetSequence();
3430 // make up a new dataset reference for this sequence
3431 sqid = seqHash(dsq);
3433 dsq.setVamsasId(uniqueSetSuffix + sqid);
3434 seqRefIds.put(sqid, dsq);
3439 dseqs.addElement(dsq);
3444 ds.addSequence(dsq);
3450 { // make this dataset sequence sq's dataset sequence
3451 sq.setDatasetSequence(dsq);
3455 // TODO: refactor this as a merge dataset sequence function
3456 // now check that sq (the dataset sequence) sequence really is the union of
3457 // all references to it
3458 // boolean pre = sq.getStart() < dsq.getStart();
3459 // boolean post = sq.getEnd() > dsq.getEnd();
3463 StringBuffer sb = new StringBuffer();
3464 String newres = jalview.analysis.AlignSeq.extractGaps(
3465 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
3466 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
3467 && newres.length() > dsq.getLength())
3469 // Update with the longer sequence.
3473 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
3474 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
3475 * sb.append(newres.substring(newres.length() - sq.getEnd() -
3476 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
3478 dsq.setSequence(sb.toString());
3480 // TODO: merges will never happen if we 'know' we have the real dataset
3481 // sequence - this should be detected when id==dssid
3482 System.err.println("DEBUG Notice: Merged dataset sequence"); // ("
3483 // + (pre ? "prepended" : "") + " "
3484 // + (post ? "appended" : ""));
3489 java.util.Hashtable datasetIds = null;
3491 java.util.IdentityHashMap dataset2Ids = null;
3493 private Alignment getDatasetFor(String datasetId)
3495 if (datasetIds == null)
3497 datasetIds = new Hashtable();
3500 if (datasetIds.containsKey(datasetId))
3502 return (Alignment) datasetIds.get(datasetId);
3507 private void addDatasetRef(String datasetId, Alignment dataset)
3509 if (datasetIds == null)
3511 datasetIds = new Hashtable();
3513 datasetIds.put(datasetId, dataset);
3517 * make a new dataset ID for this jalview dataset alignment
3522 private String getDatasetIdRef(jalview.datamodel.Alignment dataset)
3524 if (dataset.getDataset() != null)
3526 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
3528 String datasetId = makeHashCode(dataset, null);
3529 if (datasetId == null)
3531 // make a new datasetId and record it
3532 if (dataset2Ids == null)
3534 dataset2Ids = new IdentityHashMap();
3538 datasetId = (String) dataset2Ids.get(dataset);
3540 if (datasetId == null)
3542 datasetId = "ds" + dataset2Ids.size() + 1;
3543 dataset2Ids.put(dataset, datasetId);
3549 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
3551 for (int d = 0; d < sequence.getDBRefCount(); d++)
3553 DBRef dr = sequence.getDBRef(d);
3554 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
3555 sequence.getDBRef(d).getSource(), sequence.getDBRef(d)
3556 .getVersion(), sequence.getDBRef(d).getAccessionId());
3557 if (dr.getMapping() != null)
3559 entry.setMap(addMapping(dr.getMapping()));
3561 datasetSequence.addDBRef(entry);
3565 private jalview.datamodel.Mapping addMapping(Mapping m)
3567 SequenceI dsto = null;
3568 // Mapping m = dr.getMapping();
3569 int fr[] = new int[m.getMapListFromCount() * 2];
3570 Enumeration f = m.enumerateMapListFrom();
3571 for (int _i = 0; f.hasMoreElements(); _i += 2)
3573 MapListFrom mf = (MapListFrom) f.nextElement();
3574 fr[_i] = mf.getStart();
3575 fr[_i + 1] = mf.getEnd();
3577 int fto[] = new int[m.getMapListToCount() * 2];
3578 f = m.enumerateMapListTo();
3579 for (int _i = 0; f.hasMoreElements(); _i += 2)
3581 MapListTo mf = (MapListTo) f.nextElement();
3582 fto[_i] = mf.getStart();
3583 fto[_i + 1] = mf.getEnd();
3585 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto,
3586 fr, fto, (int) m.getMapFromUnit(), (int) m.getMapToUnit());
3587 if (m.getMappingChoice() != null)
3589 MappingChoice mc = m.getMappingChoice();
3590 if (mc.getDseqFor() != null)
3592 String dsfor = "" + mc.getDseqFor();
3593 if (seqRefIds.containsKey(dsfor))
3598 jmap.setTo((SequenceI) seqRefIds.get(dsfor));
3602 frefedSequence.add(new Object[]
3609 * local sequence definition
3611 Sequence ms = mc.getSequence();
3612 jalview.datamodel.Sequence djs = null;
3613 String sqid = ms.getDsseqid();
3614 if (sqid != null && sqid.length() > 0)
3617 * recover dataset sequence
3619 djs = (jalview.datamodel.Sequence) seqRefIds.get(sqid);
3624 .println("Warning - making up dataset sequence id for DbRef sequence map reference");
3625 sqid = ((Object) ms).toString(); // make up a new hascode for
3626 // undefined dataset sequence hash
3627 // (unlikely to happen)
3633 * make a new dataset sequence and add it to refIds hash
3635 djs = new jalview.datamodel.Sequence(ms.getName(),
3637 djs.setStart(jmap.getMap().getToLowest());
3638 djs.setEnd(jmap.getMap().getToHighest());
3639 djs.setVamsasId(uniqueSetSuffix + sqid);
3641 seqRefIds.put(sqid, djs);
3644 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
3653 public jalview.gui.AlignmentPanel copyAlignPanel(AlignmentPanel ap,
3654 boolean keepSeqRefs)
3657 jalview.schemabinding.version2.JalviewModel jm = SaveState(ap, null,
3663 jm.getJalviewModelSequence().getViewport(0).setSequenceSetId(null);
3667 uniqueSetSuffix = "";
3668 jm.getJalviewModelSequence().getViewport(0).setId(null); // we don't
3673 if (this.frefedSequence == null)
3675 frefedSequence = new Vector();
3678 viewportsAdded = new Hashtable();
3680 AlignFrame af = LoadFromObject(jm, null, false, null);
3681 af.alignPanels.clear();
3682 af.closeMenuItem_actionPerformed(true);
3685 * if(ap.av.alignment.getAlignmentAnnotation()!=null) { for(int i=0;
3686 * i<ap.av.alignment.getAlignmentAnnotation().length; i++) {
3687 * if(!ap.av.alignment.getAlignmentAnnotation()[i].autoCalculated) {
3688 * af.alignPanel.av.alignment.getAlignmentAnnotation()[i] =
3689 * ap.av.alignment.getAlignmentAnnotation()[i]; } } }
3692 return af.alignPanel;
3696 * flag indicating if hashtables should be cleared on finalization TODO this
3697 * flag may not be necessary
3699 private boolean _cleartables = true;
3701 private Hashtable jvids2vobj;
3706 * @see java.lang.Object#finalize()
3708 protected void finalize() throws Throwable
3710 // really make sure we have no buried refs left.
3715 this.seqRefIds = null;
3716 this.seqsToIds = null;
3720 private void warn(String msg)
3725 private void warn(String msg, Exception e)
3727 if (Cache.log != null)
3731 Cache.log.warn(msg, e);
3735 Cache.log.warn(msg);
3740 System.err.println("Warning: " + msg);
3743 e.printStackTrace();
3748 private void debug(String string)
3750 debug(string, null);
3753 private void debug(String msg, Exception e)
3755 if (Cache.log != null)
3759 Cache.log.debug(msg, e);
3763 Cache.log.debug(msg);
3768 System.err.println("Warning: " + msg);
3771 e.printStackTrace();
3777 * set the object to ID mapping tables used to write/recover objects and XML
3778 * ID strings for the jalview project. If external tables are provided then
3779 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
3780 * object goes out of scope. - also populates the datasetIds hashtable with
3781 * alignment objects containing dataset sequences
3784 * Map from ID strings to jalview datamodel
3786 * Map from jalview datamodel to ID strings
3790 public void setObjectMappingTables(Hashtable vobj2jv,
3791 IdentityHashMap jv2vobj)
3793 this.jv2vobj = jv2vobj;
3794 this.vobj2jv = vobj2jv;
3795 Iterator ds = jv2vobj.keySet().iterator();
3797 while (ds.hasNext())
3799 Object jvobj = ds.next();
3800 id = jv2vobj.get(jvobj).toString();
3801 if (jvobj instanceof jalview.datamodel.Alignment)
3803 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
3805 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
3808 else if (jvobj instanceof jalview.datamodel.Sequence)
3810 // register sequence object so the XML parser can recover it.
3811 if (seqRefIds == null)
3813 seqRefIds = new Hashtable();
3815 if (seqsToIds == null)
3817 seqsToIds = new IdentityHashMap();
3819 seqRefIds.put(jv2vobj.get(jvobj).toString(), jvobj);
3820 seqsToIds.put(jvobj, id);
3822 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
3824 if (annotationIds == null)
3826 annotationIds = new Hashtable();
3829 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvobj);
3830 jalview.datamodel.AlignmentAnnotation jvann = (jalview.datamodel.AlignmentAnnotation) jvobj;
3831 if (jvann.annotationId == null)
3833 jvann.annotationId = anid;
3835 if (!jvann.annotationId.equals(anid))
3837 // TODO verify that this is the correct behaviour
3838 this.warn("Overriding Annotation ID for " + anid
3839 + " from different id : " + jvann.annotationId);
3840 jvann.annotationId = anid;
3843 else if (jvobj instanceof String)
3845 if (jvids2vobj == null)
3847 jvids2vobj = new Hashtable();
3848 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
3852 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
3857 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
3858 * objects created from the project archive. If string is null (default for
3859 * construction) then suffix will be set automatically.
3863 public void setUniqueSetSuffix(String string)
3865 uniqueSetSuffix = string;
3870 * uses skipList2 as the skipList for skipping views on sequence sets
3871 * associated with keys in the skipList
3875 public void setSkipList(Hashtable skipList2)
3877 skipList = skipList2;