2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.api.structures.JalviewStructureDisplayI;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignedCodonFrame;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.datamodel.StructureViewerModel;
32 import jalview.datamodel.StructureViewerModel.StructureData;
33 import jalview.schemabinding.version2.AlcodMap;
34 import jalview.schemabinding.version2.AlcodonFrame;
35 import jalview.schemabinding.version2.Annotation;
36 import jalview.schemabinding.version2.AnnotationColours;
37 import jalview.schemabinding.version2.AnnotationElement;
38 import jalview.schemabinding.version2.CalcIdParam;
39 import jalview.schemabinding.version2.DBRef;
40 import jalview.schemabinding.version2.Features;
41 import jalview.schemabinding.version2.Group;
42 import jalview.schemabinding.version2.HiddenColumns;
43 import jalview.schemabinding.version2.JGroup;
44 import jalview.schemabinding.version2.JSeq;
45 import jalview.schemabinding.version2.JalviewModel;
46 import jalview.schemabinding.version2.JalviewModelSequence;
47 import jalview.schemabinding.version2.MapListFrom;
48 import jalview.schemabinding.version2.MapListTo;
49 import jalview.schemabinding.version2.Mapping;
50 import jalview.schemabinding.version2.MappingChoice;
51 import jalview.schemabinding.version2.OtherData;
52 import jalview.schemabinding.version2.PdbentryItem;
53 import jalview.schemabinding.version2.Pdbids;
54 import jalview.schemabinding.version2.Property;
55 import jalview.schemabinding.version2.Sequence;
56 import jalview.schemabinding.version2.SequenceSet;
57 import jalview.schemabinding.version2.SequenceSetProperties;
58 import jalview.schemabinding.version2.Setting;
59 import jalview.schemabinding.version2.StructureState;
60 import jalview.schemabinding.version2.ThresholdLine;
61 import jalview.schemabinding.version2.Tree;
62 import jalview.schemabinding.version2.UserColours;
63 import jalview.schemabinding.version2.Viewport;
64 import jalview.schemes.AnnotationColourGradient;
65 import jalview.schemes.ColourSchemeI;
66 import jalview.schemes.ColourSchemeProperty;
67 import jalview.schemes.GraduatedColor;
68 import jalview.schemes.ResidueColourScheme;
69 import jalview.schemes.ResidueProperties;
70 import jalview.schemes.UserColourScheme;
71 import jalview.structure.StructureSelectionManager;
72 import jalview.structures.models.AAStructureBindingModel;
73 import jalview.util.MessageManager;
74 import jalview.util.Platform;
75 import jalview.util.jarInputStreamProvider;
76 import jalview.viewmodel.AlignmentViewport;
77 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
78 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
79 import jalview.ws.jws2.Jws2Discoverer;
80 import jalview.ws.jws2.dm.AAConSettings;
81 import jalview.ws.jws2.jabaws2.Jws2Instance;
82 import jalview.ws.params.ArgumentI;
83 import jalview.ws.params.AutoCalcSetting;
84 import jalview.ws.params.WsParamSetI;
86 import java.awt.Rectangle;
87 import java.io.BufferedReader;
88 import java.io.DataInputStream;
89 import java.io.DataOutputStream;
91 import java.io.FileInputStream;
92 import java.io.FileOutputStream;
93 import java.io.IOException;
94 import java.io.InputStreamReader;
95 import java.io.OutputStreamWriter;
96 import java.io.PrintWriter;
97 import java.lang.reflect.InvocationTargetException;
98 import java.net.MalformedURLException;
100 import java.util.ArrayList;
101 import java.util.Enumeration;
102 import java.util.HashMap;
103 import java.util.HashSet;
104 import java.util.Hashtable;
105 import java.util.IdentityHashMap;
106 import java.util.Iterator;
107 import java.util.LinkedHashMap;
108 import java.util.List;
109 import java.util.Map;
110 import java.util.Map.Entry;
111 import java.util.Set;
112 import java.util.StringTokenizer;
113 import java.util.Vector;
114 import java.util.jar.JarEntry;
115 import java.util.jar.JarInputStream;
116 import java.util.jar.JarOutputStream;
118 import javax.swing.JInternalFrame;
119 import javax.swing.JOptionPane;
120 import javax.swing.SwingUtilities;
122 import org.exolab.castor.xml.Unmarshaller;
125 * Write out the current jalview desktop state as a Jalview XML stream.
127 * Note: the vamsas objects referred to here are primitive versions of the
128 * VAMSAS project schema elements - they are not the same and most likely never
132 * @version $Revision: 1.134 $
134 public class Jalview2XML
137 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
138 * of sequence objects are created.
140 IdentityHashMap<SequenceI, String> seqsToIds = null;
143 * jalview XML Sequence ID to jalview sequence object reference (both dataset
144 * and alignment sequences. Populated as XML reps of sequence objects are
147 Map<String, SequenceI> seqRefIds = null;
149 Vector frefedSequence = null;
151 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
154 * Map of reconstructed AlignFrame objects that appear to have come from
155 * SplitFrame objects (have a dna/protein complement view).
157 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<Viewport, AlignFrame>();
160 * create/return unique hash string for sq
163 * @return new or existing unique string for sq
165 String seqHash(SequenceI sq)
167 if (seqsToIds == null)
171 if (seqsToIds.containsKey(sq))
173 return seqsToIds.get(sq);
177 // create sequential key
178 String key = "sq" + (seqsToIds.size() + 1);
179 key = makeHashCode(sq, key); // check we don't have an external reference
181 seqsToIds.put(sq, key);
190 if (seqRefIds != null)
194 if (seqsToIds != null)
204 warn("clearSeqRefs called when _cleartables was not set. Doing nothing.");
205 // seqRefIds = new Hashtable();
206 // seqsToIds = new IdentityHashMap();
212 if (seqsToIds == null)
214 seqsToIds = new IdentityHashMap<SequenceI, String>();
216 if (seqRefIds == null)
218 seqRefIds = new HashMap<String, SequenceI>();
226 public Jalview2XML(boolean raiseGUI)
228 this.raiseGUI = raiseGUI;
231 public void resolveFrefedSequences()
233 if (frefedSequence.size() > 0)
235 int r = 0, rSize = frefedSequence.size();
238 Object[] ref = (Object[]) frefedSequence.elementAt(r);
241 String sref = (String) ref[0];
242 if (seqRefIds.containsKey(sref))
244 if (ref[1] instanceof jalview.datamodel.Mapping)
246 SequenceI seq = seqRefIds.get(sref);
247 while (seq.getDatasetSequence() != null)
249 seq = seq.getDatasetSequence();
251 ((jalview.datamodel.Mapping) ref[1]).setTo(seq);
255 if (ref[1] instanceof jalview.datamodel.AlignedCodonFrame)
257 SequenceI seq = seqRefIds.get(sref);
258 while (seq.getDatasetSequence() != null)
260 seq = seq.getDatasetSequence();
263 && ref[2] instanceof jalview.datamodel.Mapping)
265 jalview.datamodel.Mapping mp = (jalview.datamodel.Mapping) ref[2];
266 ((jalview.datamodel.AlignedCodonFrame) ref[1]).addMap(
267 seq, mp.getTo(), mp.getMap());
272 .println("IMPLEMENTATION ERROR: Unimplemented forward sequence references for AlcodonFrames involving "
273 + ref[2].getClass() + " type objects.");
279 .println("IMPLEMENTATION ERROR: Unimplemented forward sequence references for "
280 + ref[1].getClass() + " type objects.");
283 frefedSequence.remove(r);
289 .println("IMPLEMENTATION WARNING: Unresolved forward reference for hash string "
291 + " with objecttype "
292 + ref[1].getClass());
299 frefedSequence.remove(r);
307 * This maintains a map of viewports, the key being the seqSetId. Important to
308 * set historyItem and redoList for multiple views
310 Map<String, AlignViewport> viewportsAdded = new HashMap<String, AlignViewport>();
312 Map<String, AlignmentAnnotation> annotationIds = new HashMap<String, AlignmentAnnotation>();
314 String uniqueSetSuffix = "";
317 * List of pdbfiles added to Jar
319 List<String> pdbfiles = null;
321 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
322 public void saveState(File statefile)
324 FileOutputStream fos = null;
327 fos = new FileOutputStream(statefile);
328 JarOutputStream jout = new JarOutputStream(fos);
331 } catch (Exception e)
333 // TODO: inform user of the problem - they need to know if their data was
335 if (errorMessage == null)
337 errorMessage = "Couldn't write Jalview Archive to output file '"
338 + statefile + "' - See console error log for details";
342 errorMessage += "(output file was '" + statefile + "')";
352 } catch (IOException e)
362 * Writes a jalview project archive to the given Jar output stream.
366 public void saveState(JarOutputStream jout)
368 AlignFrame[] frames = Desktop.getAlignFrames(); // Desktop.desktop.getAllFrames();
375 Hashtable<String, AlignFrame> dsses = new Hashtable<String, AlignFrame>();
380 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
381 // //////////////////////////////////////////////////
383 Vector shortNames = new Vector();
386 for (int i = frames.length - 1; i > -1; i--)
388 AlignFrame af = frames[i];
392 .containsKey(af.getViewport().getSequenceSetId()))
397 String shortName = af.getTitle();
399 if (shortName.indexOf(File.separatorChar) > -1)
401 shortName = shortName.substring(shortName
402 .lastIndexOf(File.separatorChar) + 1);
407 while (shortNames.contains(shortName))
409 if (shortName.endsWith("_" + (count - 1)))
411 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
414 shortName = shortName.concat("_" + count);
418 shortNames.addElement(shortName);
420 if (!shortName.endsWith(".xml"))
422 shortName = shortName + ".xml";
425 int ap, apSize = af.alignPanels.size();
427 for (ap = 0; ap < apSize; ap++)
429 AlignmentPanel apanel = af.alignPanels.get(ap);
430 String fileName = apSize == 1 ? shortName : ap + shortName;
431 if (!fileName.endsWith(".xml"))
433 fileName = fileName + ".xml";
436 saveState(apanel, fileName, jout);
438 String dssid = getDatasetIdRef(af.getViewport().getAlignment()
440 if (!dsses.containsKey(dssid))
442 dsses.put(dssid, af);
447 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
453 } catch (Exception foo)
458 } catch (Exception ex)
460 // TODO: inform user of the problem - they need to know if their data was
462 if (errorMessage == null)
464 errorMessage = "Couldn't write Jalview Archive - see error output for details";
466 ex.printStackTrace();
470 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
471 public boolean saveAlignment(AlignFrame af, String jarFile,
477 int apSize = af.alignPanels.size();
478 FileOutputStream fos = new FileOutputStream(jarFile);
479 JarOutputStream jout = new JarOutputStream(fos);
480 Hashtable<String, AlignFrame> dsses = new Hashtable<String, AlignFrame>();
481 for (AlignmentPanel apanel : af.alignPanels)
483 String jfileName = apSize == 1 ? fileName : fileName + ap;
485 if (!jfileName.endsWith(".xml"))
487 jfileName = jfileName + ".xml";
489 saveState(apanel, jfileName, jout);
490 String dssid = getDatasetIdRef(af.getViewport().getAlignment()
492 if (!dsses.containsKey(dssid))
494 dsses.put(dssid, af);
497 writeDatasetFor(dsses, fileName, jout);
501 } catch (Exception foo)
507 } catch (Exception ex)
509 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
510 ex.printStackTrace();
515 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
516 String fileName, JarOutputStream jout)
519 for (String dssids : dsses.keySet())
521 AlignFrame _af = dsses.get(dssids);
522 String jfileName = fileName + " Dataset for " + _af.getTitle();
523 if (!jfileName.endsWith(".xml"))
525 jfileName = jfileName + ".xml";
527 saveState(_af.alignPanel, jfileName, true, jout);
532 * create a JalviewModel from an alignment view and marshall it to a
536 * panel to create jalview model for
538 * name of alignment panel written to output stream
544 public JalviewModel saveState(AlignmentPanel ap, String fileName,
545 JarOutputStream jout)
547 return saveState(ap, fileName, false, jout);
551 * create a JalviewModel from an alignment view and marshall it to a
555 * panel to create jalview model for
557 * name of alignment panel written to output stream
559 * when true, only write the dataset for the alignment, not the data
560 * associated with the view.
566 public JalviewModel saveState(AlignmentPanel ap, String fileName,
567 boolean storeDS, JarOutputStream jout)
570 List<String> viewIds = new ArrayList<String>();
571 List<UserColourScheme> userColours = new ArrayList<UserColourScheme>();
573 AlignViewport av = ap.av;
575 JalviewModel object = new JalviewModel();
576 object.setVamsasModel(new jalview.schemabinding.version2.VamsasModel());
578 object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
579 object.setVersion(jalview.bin.Cache.getDefault("VERSION",
580 "Development Build"));
582 jalview.datamodel.AlignmentI jal = av.getAlignment();
584 if (av.hasHiddenRows())
586 jal = jal.getHiddenSequences().getFullAlignment();
589 SequenceSet vamsasSet = new SequenceSet();
591 JalviewModelSequence jms = new JalviewModelSequence();
593 vamsasSet.setGapChar(jal.getGapCharacter() + "");
595 if (jal.getDataset() != null)
597 // dataset id is the dataset's hashcode
598 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
601 // switch jal and the dataset
602 jal = jal.getDataset();
605 if (jal.getProperties() != null)
607 Enumeration en = jal.getProperties().keys();
608 while (en.hasMoreElements())
610 String key = en.nextElement().toString();
611 SequenceSetProperties ssp = new SequenceSetProperties();
613 ssp.setValue(jal.getProperties().get(key).toString());
614 vamsasSet.addSequenceSetProperties(ssp);
619 Set<String> calcIdSet = new HashSet<String>();
623 jalview.datamodel.SequenceI jds, jdatasq;
624 for (int i = 0; i < jal.getHeight(); i++)
626 jds = jal.getSequenceAt(i);
627 jdatasq = jds.getDatasetSequence() == null ? jds : jds
628 .getDatasetSequence();
631 if (seqRefIds.get(id) != null)
633 // This happens for two reasons: 1. multiple views are being serialised.
634 // 2. the hashCode has collided with another sequence's code. This DOES
635 // HAPPEN! (PF00072.15.stk does this)
636 // JBPNote: Uncomment to debug writing out of files that do not read
637 // back in due to ArrayOutOfBoundExceptions.
638 // System.err.println("vamsasSeq backref: "+id+"");
639 // System.err.println(jds.getName()+"
640 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
641 // System.err.println("Hashcode: "+seqHash(jds));
642 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
643 // System.err.println(rsq.getName()+"
644 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
645 // System.err.println("Hashcode: "+seqHash(rsq));
649 vamsasSeq = createVamsasSequence(id, jds);
650 vamsasSet.addSequence(vamsasSeq);
651 seqRefIds.put(id, jds);
655 jseq.setStart(jds.getStart());
656 jseq.setEnd(jds.getEnd());
657 jseq.setColour(av.getSequenceColour(jds).getRGB());
659 jseq.setId(id); // jseq id should be a string not a number
662 // Store any sequences this sequence represents
663 if (av.hasHiddenRows())
665 jseq.setHidden(av.getAlignment().getHiddenSequences()
668 if (av.isHiddenRepSequence(jal.getSequenceAt(i)))
670 jalview.datamodel.SequenceI[] reps = av
671 .getRepresentedSequences(jal.getSequenceAt(i))
672 .getSequencesInOrder(jal);
674 for (int h = 0; h < reps.length; h++)
676 if (reps[h] != jal.getSequenceAt(i))
678 jseq.addHiddenSequences(jal.findIndex(reps[h]));
685 if (jdatasq.getSequenceFeatures() != null)
687 jalview.datamodel.SequenceFeature[] sf = jdatasq
688 .getSequenceFeatures();
690 while (index < sf.length)
692 Features features = new Features();
694 features.setBegin(sf[index].getBegin());
695 features.setEnd(sf[index].getEnd());
696 features.setDescription(sf[index].getDescription());
697 features.setType(sf[index].getType());
698 features.setFeatureGroup(sf[index].getFeatureGroup());
699 features.setScore(sf[index].getScore());
700 if (sf[index].links != null)
702 for (int l = 0; l < sf[index].links.size(); l++)
704 OtherData keyValue = new OtherData();
705 keyValue.setKey("LINK_" + l);
706 keyValue.setValue(sf[index].links.elementAt(l).toString());
707 features.addOtherData(keyValue);
710 if (sf[index].otherDetails != null)
713 Enumeration keys = sf[index].otherDetails.keys();
714 while (keys.hasMoreElements())
716 key = keys.nextElement().toString();
717 OtherData keyValue = new OtherData();
718 keyValue.setKey(key);
719 keyValue.setValue(sf[index].otherDetails.get(key).toString());
720 features.addOtherData(keyValue);
724 jseq.addFeatures(features);
729 if (jdatasq.getPDBId() != null)
731 Enumeration en = jdatasq.getPDBId().elements();
732 while (en.hasMoreElements())
734 Pdbids pdb = new Pdbids();
735 jalview.datamodel.PDBEntry entry = (jalview.datamodel.PDBEntry) en
738 pdb.setId(entry.getId());
739 pdb.setType(entry.getType());
742 * Store any structure views associated with this sequence. This
743 * section copes with duplicate entries in the project, so a dataset
744 * only view *should* be coped with sensibly.
746 // This must have been loaded, is it still visible?
747 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
748 String matchedFile = null;
749 for (int f = frames.length - 1; f > -1; f--)
751 if (frames[f] instanceof StructureViewerBase)
753 StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
754 matchedFile = saveStructureState(ap, jds, pdb, entry,
755 viewIds, matchedFile, viewFrame);
759 if (matchedFile != null || entry.getFile() != null)
761 if (entry.getFile() != null)
764 matchedFile = entry.getFile();
766 pdb.setFile(matchedFile); // entry.getFile());
767 if (pdbfiles == null)
769 pdbfiles = new ArrayList<String>();
772 if (!pdbfiles.contains(entry.getId()))
774 pdbfiles.add(entry.getId());
775 DataInputStream dis = null;
778 File file = new File(matchedFile);
779 if (file.exists() && jout != null)
781 byte[] data = new byte[(int) file.length()];
782 jout.putNextEntry(new JarEntry(entry.getId()));
783 dis = new DataInputStream(new FileInputStream(file));
786 DataOutputStream dout = new DataOutputStream(jout);
787 dout.write(data, 0, data.length);
791 } catch (Exception ex)
793 ex.printStackTrace();
801 } catch (IOException e)
811 if (entry.getProperty() != null)
813 PdbentryItem item = new PdbentryItem();
814 Hashtable properties = entry.getProperty();
815 Enumeration en2 = properties.keys();
816 while (en2.hasMoreElements())
818 Property prop = new Property();
819 String key = en2.nextElement().toString();
821 prop.setValue(properties.get(key).toString());
822 item.addProperty(prop);
824 pdb.addPdbentryItem(item);
834 if (!storeDS && av.hasHiddenRows())
836 jal = av.getAlignment();
839 if (jal.getCodonFrames() != null)
841 Set<AlignedCodonFrame> jac = jal.getCodonFrames();
842 for (AlignedCodonFrame acf : jac)
844 AlcodonFrame alc = new AlcodonFrame();
845 vamsasSet.addAlcodonFrame(alc);
846 if (acf.getProtMappings() != null
847 && acf.getProtMappings().length > 0)
849 SequenceI[] dnas = acf.getdnaSeqs();
850 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
851 for (int m = 0; m < pmaps.length; m++)
853 AlcodMap alcmap = new AlcodMap();
854 alcmap.setDnasq(seqHash(dnas[m]));
855 alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
857 alc.addAlcodMap(alcmap);
862 // AlcodonFrame alc = new AlcodonFrame();
863 // vamsasSet.addAlcodonFrame(alc);
864 // for (int p = 0; p < acf.aaWidth; p++)
866 // Alcodon cmap = new Alcodon();
867 // if (acf.codons[p] != null)
869 // // Null codons indicate a gapped column in the translated peptide
871 // cmap.setPos1(acf.codons[p][0]);
872 // cmap.setPos2(acf.codons[p][1]);
873 // cmap.setPos3(acf.codons[p][2]);
875 // alc.addAlcodon(cmap);
877 // if (acf.getProtMappings() != null
878 // && acf.getProtMappings().length > 0)
880 // SequenceI[] dnas = acf.getdnaSeqs();
881 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
882 // for (int m = 0; m < pmaps.length; m++)
884 // AlcodMap alcmap = new AlcodMap();
885 // alcmap.setDnasq(seqHash(dnas[m]));
886 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
888 // alc.addAlcodMap(alcmap);
895 // /////////////////////////////////
896 if (!storeDS && av.currentTree != null)
898 // FIND ANY ASSOCIATED TREES
899 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
900 if (Desktop.desktop != null)
902 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
904 for (int t = 0; t < frames.length; t++)
906 if (frames[t] instanceof TreePanel)
908 TreePanel tp = (TreePanel) frames[t];
910 if (tp.treeCanvas.av.getAlignment() == jal)
912 Tree tree = new Tree();
913 tree.setTitle(tp.getTitle());
914 tree.setCurrentTree((av.currentTree == tp.getTree()));
915 tree.setNewick(tp.getTree().toString());
916 tree.setThreshold(tp.treeCanvas.threshold);
918 tree.setFitToWindow(tp.fitToWindow.getState());
919 tree.setFontName(tp.getTreeFont().getName());
920 tree.setFontSize(tp.getTreeFont().getSize());
921 tree.setFontStyle(tp.getTreeFont().getStyle());
922 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
924 tree.setShowBootstrap(tp.bootstrapMenu.getState());
925 tree.setShowDistances(tp.distanceMenu.getState());
927 tree.setHeight(tp.getHeight());
928 tree.setWidth(tp.getWidth());
929 tree.setXpos(tp.getX());
930 tree.setYpos(tp.getY());
931 tree.setId(makeHashCode(tp, null));
940 * store forward refs from an annotationRow to any groups
942 IdentityHashMap groupRefs = new IdentityHashMap();
945 for (SequenceI sq : jal.getSequences())
947 // Store annotation on dataset sequences only
948 jalview.datamodel.AlignmentAnnotation[] aa = sq.getAnnotation();
949 if (aa != null && aa.length > 0)
951 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
958 if (jal.getAlignmentAnnotation() != null)
960 // Store the annotation shown on the alignment.
961 jalview.datamodel.AlignmentAnnotation[] aa = jal
962 .getAlignmentAnnotation();
963 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
968 if (jal.getGroups() != null)
970 JGroup[] groups = new JGroup[jal.getGroups().size()];
972 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
974 groups[++i] = new JGroup();
976 groups[i].setStart(sg.getStartRes());
977 groups[i].setEnd(sg.getEndRes());
978 groups[i].setName(sg.getName());
979 if (groupRefs.containsKey(sg))
981 // group has references so set it's ID field
982 groups[i].setId(groupRefs.get(sg).toString());
986 if (sg.cs.conservationApplied())
988 groups[i].setConsThreshold(sg.cs.getConservationInc());
990 if (sg.cs instanceof jalview.schemes.UserColourScheme)
992 groups[i].setColour(setUserColourScheme(sg.cs, userColours,
998 .setColour(ColourSchemeProperty.getColourName(sg.cs));
1001 else if (sg.cs instanceof jalview.schemes.AnnotationColourGradient)
1003 groups[i].setColour("AnnotationColourGradient");
1004 groups[i].setAnnotationColours(constructAnnotationColours(
1005 (jalview.schemes.AnnotationColourGradient) sg.cs,
1008 else if (sg.cs instanceof jalview.schemes.UserColourScheme)
1011 .setColour(setUserColourScheme(sg.cs, userColours, jms));
1015 groups[i].setColour(ColourSchemeProperty.getColourName(sg.cs));
1018 groups[i].setPidThreshold(sg.cs.getThreshold());
1021 groups[i].setOutlineColour(sg.getOutlineColour().getRGB());
1022 groups[i].setDisplayBoxes(sg.getDisplayBoxes());
1023 groups[i].setDisplayText(sg.getDisplayText());
1024 groups[i].setColourText(sg.getColourText());
1025 groups[i].setTextCol1(sg.textColour.getRGB());
1026 groups[i].setTextCol2(sg.textColour2.getRGB());
1027 groups[i].setTextColThreshold(sg.thresholdTextColour);
1028 groups[i].setShowUnconserved(sg.getShowNonconserved());
1029 groups[i].setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1030 groups[i].setShowConsensusHistogram(sg.isShowConsensusHistogram());
1031 groups[i].setShowSequenceLogo(sg.isShowSequenceLogo());
1032 groups[i].setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1033 for (int s = 0; s < sg.getSize(); s++)
1035 jalview.datamodel.Sequence seq = (jalview.datamodel.Sequence) sg
1037 groups[i].addSeq(seqHash(seq));
1041 jms.setJGroup(groups);
1045 // /////////SAVE VIEWPORT
1046 Viewport view = new Viewport();
1047 view.setTitle(ap.alignFrame.getTitle());
1048 view.setSequenceSetId(makeHashCode(av.getSequenceSetId(),
1049 av.getSequenceSetId()));
1050 view.setId(av.getViewId());
1051 if (av.getCodingComplement() != null)
1053 view.setComplementId(av.getCodingComplement().getViewId());
1055 view.setViewName(av.viewName);
1056 view.setGatheredViews(av.isGatherViewsHere());
1058 Rectangle position = ap.av.getExplodedGeometry();
1059 if (position != null)
1061 view.setXpos(position.x);
1062 view.setYpos(position.y);
1063 view.setWidth(position.width);
1064 view.setHeight(position.height);
1068 view.setXpos(ap.alignFrame.getBounds().x);
1069 view.setYpos(ap.alignFrame.getBounds().y);
1070 view.setWidth(ap.alignFrame.getBounds().width);
1071 view.setHeight(ap.alignFrame.getBounds().height);
1074 view.setStartRes(av.startRes);
1075 view.setStartSeq(av.startSeq);
1077 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1079 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1082 else if (av.getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1084 AnnotationColours ac = constructAnnotationColours(
1085 (jalview.schemes.AnnotationColourGradient) av
1086 .getGlobalColourScheme(),
1089 view.setAnnotationColours(ac);
1090 view.setBgColour("AnnotationColourGradient");
1094 view.setBgColour(ColourSchemeProperty.getColourName(av
1095 .getGlobalColourScheme()));
1098 ColourSchemeI cs = av.getGlobalColourScheme();
1102 if (cs.conservationApplied())
1104 view.setConsThreshold(cs.getConservationInc());
1105 if (cs instanceof jalview.schemes.UserColourScheme)
1107 view.setBgColour(setUserColourScheme(cs, userColours, jms));
1111 if (cs instanceof ResidueColourScheme)
1113 view.setPidThreshold(cs.getThreshold());
1117 view.setConservationSelected(av.getConservationSelected());
1118 view.setPidSelected(av.getAbovePIDThreshold());
1119 view.setFontName(av.font.getName());
1120 view.setFontSize(av.font.getSize());
1121 view.setFontStyle(av.font.getStyle());
1122 view.setRenderGaps(av.isRenderGaps());
1123 view.setShowAnnotation(av.isShowAnnotation());
1124 view.setShowBoxes(av.getShowBoxes());
1125 view.setShowColourText(av.getColourText());
1126 view.setShowFullId(av.getShowJVSuffix());
1127 view.setRightAlignIds(av.isRightAlignIds());
1128 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1129 view.setShowText(av.getShowText());
1130 view.setShowUnconserved(av.getShowUnconserved());
1131 view.setWrapAlignment(av.getWrapAlignment());
1132 view.setTextCol1(av.getTextColour().getRGB());
1133 view.setTextCol2(av.getTextColour2().getRGB());
1134 view.setTextColThreshold(av.getThresholdTextColour());
1135 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1136 view.setShowSequenceLogo(av.isShowSequenceLogo());
1137 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1138 view.setShowGroupConsensus(av.isShowGroupConsensus());
1139 view.setShowGroupConservation(av.isShowGroupConservation());
1140 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1141 view.setShowDbRefTooltip(av.isShowDBRefs());
1142 view.setFollowHighlight(av.followHighlight);
1143 view.setFollowSelection(av.followSelection);
1144 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1145 if (av.getFeaturesDisplayed() != null)
1147 jalview.schemabinding.version2.FeatureSettings fs = new jalview.schemabinding.version2.FeatureSettings();
1149 String[] renderOrder = ap.getSeqPanel().seqCanvas
1150 .getFeatureRenderer().getRenderOrder()
1151 .toArray(new String[0]);
1153 Vector settingsAdded = new Vector();
1154 Object gstyle = null;
1155 GraduatedColor gcol = null;
1156 if (renderOrder != null)
1158 for (int ro = 0; ro < renderOrder.length; ro++)
1160 gstyle = ap.getSeqPanel().seqCanvas.getFeatureRenderer()
1161 .getFeatureStyle(renderOrder[ro]);
1162 Setting setting = new Setting();
1163 setting.setType(renderOrder[ro]);
1164 if (gstyle instanceof GraduatedColor)
1166 gcol = (GraduatedColor) gstyle;
1167 setting.setColour(gcol.getMaxColor().getRGB());
1168 setting.setMincolour(gcol.getMinColor().getRGB());
1169 setting.setMin(gcol.getMin());
1170 setting.setMax(gcol.getMax());
1171 setting.setColourByLabel(gcol.isColourByLabel());
1172 setting.setAutoScale(gcol.isAutoScale());
1173 setting.setThreshold(gcol.getThresh());
1174 setting.setThreshstate(gcol.getThreshType());
1178 setting.setColour(ap.getSeqPanel().seqCanvas
1179 .getFeatureRenderer()
1180 .getColour(renderOrder[ro]).getRGB());
1183 setting.setDisplay(av.getFeaturesDisplayed().isVisible(
1185 float rorder = ap.getSeqPanel().seqCanvas.getFeatureRenderer()
1186 .getOrder(renderOrder[ro]);
1189 setting.setOrder(rorder);
1191 fs.addSetting(setting);
1192 settingsAdded.addElement(renderOrder[ro]);
1196 // Make sure we save none displayed feature settings
1197 Iterator en = ap.getSeqPanel().seqCanvas.getFeatureRenderer()
1198 .getFeatureColours().keySet().iterator();
1199 while (en.hasNext())
1201 String key = en.next().toString();
1202 if (settingsAdded.contains(key))
1207 Setting setting = new Setting();
1208 setting.setType(key);
1209 setting.setColour(ap.getSeqPanel().seqCanvas.getFeatureRenderer()
1210 .getColour(key).getRGB());
1212 setting.setDisplay(false);
1213 float rorder = ap.getSeqPanel().seqCanvas.getFeatureRenderer()
1217 setting.setOrder(rorder);
1219 fs.addSetting(setting);
1220 settingsAdded.addElement(key);
1222 // is groups actually supposed to be a map here ?
1223 en = ap.getSeqPanel().seqCanvas.getFeatureRenderer()
1224 .getFeatureGroups().iterator();
1225 Vector groupsAdded = new Vector();
1226 while (en.hasNext())
1228 String grp = en.next().toString();
1229 if (groupsAdded.contains(grp))
1233 Group g = new Group();
1235 g.setDisplay(((Boolean) ap.getSeqPanel().seqCanvas
1236 .getFeatureRenderer().checkGroupVisibility(grp, false))
1239 groupsAdded.addElement(grp);
1241 jms.setFeatureSettings(fs);
1245 if (av.hasHiddenColumns())
1247 if (av.getColumnSelection() == null
1248 || av.getColumnSelection().getHiddenColumns() == null)
1250 warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1254 for (int c = 0; c < av.getColumnSelection().getHiddenColumns()
1257 int[] region = av.getColumnSelection().getHiddenColumns()
1259 HiddenColumns hc = new HiddenColumns();
1260 hc.setStart(region[0]);
1261 hc.setEnd(region[1]);
1262 view.addHiddenColumns(hc);
1266 if (calcIdSet.size() > 0)
1268 for (String calcId : calcIdSet)
1270 if (calcId.trim().length() > 0)
1272 CalcIdParam cidp = createCalcIdParam(calcId, av);
1273 // Some calcIds have no parameters.
1276 view.addCalcIdParam(cidp);
1282 jms.addViewport(view);
1284 object.setJalviewModelSequence(jms);
1285 object.getVamsasModel().addSequenceSet(vamsasSet);
1287 if (jout != null && fileName != null)
1289 // We may not want to write the object to disk,
1290 // eg we can copy the alignViewport to a new view object
1291 // using save and then load
1294 JarEntry entry = new JarEntry(fileName);
1295 jout.putNextEntry(entry);
1296 PrintWriter pout = new PrintWriter(new OutputStreamWriter(jout,
1298 org.exolab.castor.xml.Marshaller marshaller = new org.exolab.castor.xml.Marshaller(
1300 marshaller.marshal(object);
1303 } catch (Exception ex)
1305 // TODO: raise error in GUI if marshalling failed.
1306 ex.printStackTrace();
1313 * Save the state of a structure viewer
1318 * the archive XML element under which to save the state
1321 * @param matchedFile
1325 protected String saveStructureState(AlignmentPanel ap, SequenceI jds,
1326 Pdbids pdb, PDBEntry entry, List<String> viewIds,
1327 String matchedFile, StructureViewerBase viewFrame)
1329 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
1330 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
1332 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
1333 final String pdbId = pdbentry.getId();
1334 if (!pdbId.equals(entry.getId())
1335 && !(entry.getId().length() > 4 && entry.getId()
1336 .toLowerCase().startsWith(pdbId.toLowerCase())))
1340 if (matchedFile == null)
1342 matchedFile = pdbentry.getFile();
1344 else if (!matchedFile.equals(pdbentry.getFile()))
1347 .warn("Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
1348 + pdbentry.getFile());
1352 // can get at it if the ID
1353 // match is ambiguous (e.g.
1355 String statestring = viewFrame.getStateInfo();
1357 for (int smap = 0; smap < viewFrame.getBinding().getSequence()[peid].length; smap++)
1359 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
1360 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
1362 StructureState state = new StructureState();
1363 state.setVisible(true);
1364 state.setXpos(viewFrame.getX());
1365 state.setYpos(viewFrame.getY());
1366 state.setWidth(viewFrame.getWidth());
1367 state.setHeight(viewFrame.getHeight());
1368 final String viewId = viewFrame.getViewId();
1369 state.setViewId(viewId);
1370 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
1371 state.setColourwithAlignPanel(viewFrame.isUsedforcolourby(ap));
1372 state.setColourByJmol(viewFrame.isColouredByViewer());
1374 * Only store each structure viewer's state once in each XML document.
1376 if (!viewIds.contains(viewId))
1378 viewIds.add(viewId);
1379 state.setContent(statestring.replaceAll("\n", ""));
1383 state.setContent("# duplicate state");
1385 pdb.addStructureState(state);
1392 private AnnotationColours constructAnnotationColours(
1393 AnnotationColourGradient acg, List<UserColourScheme> userColours,
1394 JalviewModelSequence jms)
1396 AnnotationColours ac = new AnnotationColours();
1397 ac.setAboveThreshold(acg.getAboveThreshold());
1398 ac.setThreshold(acg.getAnnotationThreshold());
1399 ac.setAnnotation(acg.getAnnotation());
1400 if (acg.getBaseColour() instanceof jalview.schemes.UserColourScheme)
1402 ac.setColourScheme(setUserColourScheme(acg.getBaseColour(),
1407 ac.setColourScheme(ColourSchemeProperty.getColourName(acg
1411 ac.setMaxColour(acg.getMaxColour().getRGB());
1412 ac.setMinColour(acg.getMinColour().getRGB());
1413 ac.setPerSequence(acg.isSeqAssociated());
1414 ac.setPredefinedColours(acg.isPredefinedColours());
1418 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
1419 IdentityHashMap groupRefs, AlignmentViewport av,
1420 Set<String> calcIdSet, boolean storeDS, SequenceSet vamsasSet)
1423 for (int i = 0; i < aa.length; i++)
1425 Annotation an = new Annotation();
1427 if (aa[i].annotationId != null)
1429 annotationIds.put(aa[i].annotationId, aa[i]);
1432 an.setId(aa[i].annotationId);
1434 an.setVisible(aa[i].visible);
1436 an.setDescription(aa[i].description);
1438 if (aa[i].sequenceRef != null)
1440 // TODO later annotation sequenceRef should be the XML ID of the
1441 // sequence rather than its display name
1442 an.setSequenceRef(aa[i].sequenceRef.getName());
1444 if (aa[i].groupRef != null)
1446 Object groupIdr = groupRefs.get(aa[i].groupRef);
1447 if (groupIdr == null)
1449 // make a locally unique String
1450 groupRefs.put(aa[i].groupRef,
1451 groupIdr = ("" + System.currentTimeMillis()
1452 + aa[i].groupRef.getName() + groupRefs.size()));
1454 an.setGroupRef(groupIdr.toString());
1457 // store all visualization attributes for annotation
1458 an.setGraphHeight(aa[i].graphHeight);
1459 an.setCentreColLabels(aa[i].centreColLabels);
1460 an.setScaleColLabels(aa[i].scaleColLabel);
1461 an.setShowAllColLabels(aa[i].showAllColLabels);
1462 an.setBelowAlignment(aa[i].belowAlignment);
1464 if (aa[i].graph > 0)
1467 an.setGraphType(aa[i].graph);
1468 an.setGraphGroup(aa[i].graphGroup);
1469 if (aa[i].getThreshold() != null)
1471 ThresholdLine line = new ThresholdLine();
1472 line.setLabel(aa[i].getThreshold().label);
1473 line.setValue(aa[i].getThreshold().value);
1474 line.setColour(aa[i].getThreshold().colour.getRGB());
1475 an.setThresholdLine(line);
1483 an.setLabel(aa[i].label);
1485 if (aa[i] == av.getAlignmentQualityAnnot()
1486 || aa[i] == av.getAlignmentConservationAnnotation()
1487 || aa[i] == av.getAlignmentConsensusAnnotation()
1488 || aa[i].autoCalculated)
1490 // new way of indicating autocalculated annotation -
1491 an.setAutoCalculated(aa[i].autoCalculated);
1493 if (aa[i].hasScore())
1495 an.setScore(aa[i].getScore());
1498 if (aa[i].getCalcId() != null)
1500 calcIdSet.add(aa[i].getCalcId());
1501 an.setCalcId(aa[i].getCalcId());
1503 if (aa[i].hasProperties())
1505 for (String pr : aa[i].getProperties())
1507 Property prop = new Property();
1509 prop.setValue(aa[i].getProperty(pr));
1510 an.addProperty(prop);
1514 AnnotationElement ae;
1515 if (aa[i].annotations != null)
1517 an.setScoreOnly(false);
1518 for (int a = 0; a < aa[i].annotations.length; a++)
1520 if ((aa[i] == null) || (aa[i].annotations[a] == null))
1525 ae = new AnnotationElement();
1526 if (aa[i].annotations[a].description != null)
1528 ae.setDescription(aa[i].annotations[a].description);
1530 if (aa[i].annotations[a].displayCharacter != null)
1532 ae.setDisplayCharacter(aa[i].annotations[a].displayCharacter);
1535 if (!Float.isNaN(aa[i].annotations[a].value))
1537 ae.setValue(aa[i].annotations[a].value);
1541 if (aa[i].annotations[a].secondaryStructure > ' ')
1543 ae.setSecondaryStructure(aa[i].annotations[a].secondaryStructure
1547 if (aa[i].annotations[a].colour != null
1548 && aa[i].annotations[a].colour != java.awt.Color.black)
1550 ae.setColour(aa[i].annotations[a].colour.getRGB());
1553 an.addAnnotationElement(ae);
1554 if (aa[i].autoCalculated)
1556 // only write one non-null entry into the annotation row -
1557 // sufficient to get the visualization attributes necessary to
1565 an.setScoreOnly(true);
1567 if (!storeDS || (storeDS && !aa[i].autoCalculated))
1569 // skip autocalculated annotation - these are only provided for
1571 vamsasSet.addAnnotation(an);
1577 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
1579 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
1580 if (settings != null)
1582 CalcIdParam vCalcIdParam = new CalcIdParam();
1583 vCalcIdParam.setCalcId(calcId);
1584 vCalcIdParam.addServiceURL(settings.getServiceURI());
1585 // generic URI allowing a third party to resolve another instance of the
1586 // service used for this calculation
1587 for (String urls : settings.getServiceURLs())
1589 vCalcIdParam.addServiceURL(urls);
1591 vCalcIdParam.setVersion("1.0");
1592 if (settings.getPreset() != null)
1594 WsParamSetI setting = settings.getPreset();
1595 vCalcIdParam.setName(setting.getName());
1596 vCalcIdParam.setDescription(setting.getDescription());
1600 vCalcIdParam.setName("");
1601 vCalcIdParam.setDescription("Last used parameters");
1603 // need to be able to recover 1) settings 2) user-defined presets or
1604 // recreate settings from preset 3) predefined settings provided by
1605 // service - or settings that can be transferred (or discarded)
1606 vCalcIdParam.setParameters(settings.getWsParamFile().replace("\n",
1608 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
1609 // todo - decide if updateImmediately is needed for any projects.
1611 return vCalcIdParam;
1616 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
1619 if (calcIdParam.getVersion().equals("1.0"))
1621 Jws2Instance service = Jws2Discoverer.getDiscoverer()
1622 .getPreferredServiceFor(calcIdParam.getServiceURL());
1623 if (service != null)
1625 WsParamSetI parmSet = null;
1628 parmSet = service.getParamStore().parseServiceParameterFile(
1629 calcIdParam.getName(), calcIdParam.getDescription(),
1630 calcIdParam.getServiceURL(),
1631 calcIdParam.getParameters().replace("|\\n|", "\n"));
1632 } catch (IOException x)
1634 warn("Couldn't parse parameter data for "
1635 + calcIdParam.getCalcId(), x);
1638 List<ArgumentI> argList = null;
1639 if (calcIdParam.getName().length() > 0)
1641 parmSet = service.getParamStore()
1642 .getPreset(calcIdParam.getName());
1643 if (parmSet != null)
1645 // TODO : check we have a good match with settings in AACon -
1646 // otherwise we'll need to create a new preset
1651 argList = parmSet.getArguments();
1654 AAConSettings settings = new AAConSettings(
1655 calcIdParam.isAutoUpdate(), service, parmSet, argList);
1656 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
1657 calcIdParam.isNeedsUpdate());
1662 warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
1666 throw new Error(MessageManager.formatMessage(
1667 "error.unsupported_version_calcIdparam", new Object[]
1668 { calcIdParam.toString() }));
1672 * External mapping between jalview objects and objects yielding a valid and
1673 * unique object ID string. This is null for normal Jalview project IO, but
1674 * non-null when a jalview project is being read or written as part of a
1677 IdentityHashMap jv2vobj = null;
1680 * Construct a unique ID for jvobj using either existing bindings or if none
1681 * exist, the result of the hashcode call for the object.
1684 * jalview data object
1685 * @return unique ID for referring to jvobj
1687 private String makeHashCode(Object jvobj, String altCode)
1689 if (jv2vobj != null)
1691 Object id = jv2vobj.get(jvobj);
1694 return id.toString();
1696 // check string ID mappings
1697 if (jvids2vobj != null && jvobj instanceof String)
1699 id = jvids2vobj.get(jvobj);
1703 return id.toString();
1705 // give up and warn that something has gone wrong
1706 warn("Cannot find ID for object in external mapping : " + jvobj);
1712 * return local jalview object mapped to ID, if it exists
1716 * @return null or object bound to idcode
1718 private Object retrieveExistingObj(String idcode)
1720 if (idcode != null && vobj2jv != null)
1722 return vobj2jv.get(idcode);
1728 * binding from ID strings from external mapping table to jalview data model
1731 private Hashtable vobj2jv;
1733 private Sequence createVamsasSequence(String id, SequenceI jds)
1735 return createVamsasSequence(true, id, jds, null);
1738 private Sequence createVamsasSequence(boolean recurse, String id,
1739 SequenceI jds, SequenceI parentseq)
1741 Sequence vamsasSeq = new Sequence();
1742 vamsasSeq.setId(id);
1743 vamsasSeq.setName(jds.getName());
1744 vamsasSeq.setSequence(jds.getSequenceAsString());
1745 vamsasSeq.setDescription(jds.getDescription());
1746 jalview.datamodel.DBRefEntry[] dbrefs = null;
1747 if (jds.getDatasetSequence() != null)
1749 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
1750 if (jds.getDatasetSequence().getDBRef() != null)
1752 dbrefs = jds.getDatasetSequence().getDBRef();
1757 vamsasSeq.setDsseqid(id); // so we can tell which sequences really are
1758 // dataset sequences only
1759 dbrefs = jds.getDBRef();
1763 for (int d = 0; d < dbrefs.length; d++)
1765 DBRef dbref = new DBRef();
1766 dbref.setSource(dbrefs[d].getSource());
1767 dbref.setVersion(dbrefs[d].getVersion());
1768 dbref.setAccessionId(dbrefs[d].getAccessionId());
1769 if (dbrefs[d].hasMap())
1771 Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
1773 dbref.setMapping(mp);
1775 vamsasSeq.addDBRef(dbref);
1781 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
1782 SequenceI parentseq, SequenceI jds, boolean recurse)
1785 if (jmp.getMap() != null)
1789 jalview.util.MapList mlst = jmp.getMap();
1790 int r[] = mlst.getFromRanges();
1791 for (int s = 0; s < r.length; s += 2)
1793 MapListFrom mfrom = new MapListFrom();
1794 mfrom.setStart(r[s]);
1795 mfrom.setEnd(r[s + 1]);
1796 mp.addMapListFrom(mfrom);
1798 r = mlst.getToRanges();
1799 for (int s = 0; s < r.length; s += 2)
1801 MapListTo mto = new MapListTo();
1803 mto.setEnd(r[s + 1]);
1804 mp.addMapListTo(mto);
1806 mp.setMapFromUnit(mlst.getFromRatio());
1807 mp.setMapToUnit(mlst.getToRatio());
1808 if (jmp.getTo() != null)
1810 MappingChoice mpc = new MappingChoice();
1812 && (parentseq != jmp.getTo() || parentseq
1813 .getDatasetSequence() != jmp.getTo()))
1815 mpc.setSequence(createVamsasSequence(false, seqHash(jmp.getTo()),
1821 SequenceI ps = null;
1822 if (parentseq != jmp.getTo()
1823 && parentseq.getDatasetSequence() != jmp.getTo())
1825 // chaining dbref rather than a handshaking one
1826 jmpid = seqHash(ps = jmp.getTo());
1830 jmpid = seqHash(ps = parentseq);
1832 mpc.setDseqFor(jmpid);
1833 if (!seqRefIds.containsKey(mpc.getDseqFor()))
1835 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
1836 seqRefIds.put(mpc.getDseqFor(), ps);
1840 jalview.bin.Cache.log.debug("reusing DseqFor ID");
1843 mp.setMappingChoice(mpc);
1849 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
1850 List<UserColourScheme> userColours, JalviewModelSequence jms)
1853 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
1854 boolean newucs = false;
1855 if (!userColours.contains(ucs))
1857 userColours.add(ucs);
1860 id = "ucs" + userColours.indexOf(ucs);
1863 // actually create the scheme's entry in the XML model
1864 java.awt.Color[] colours = ucs.getColours();
1865 jalview.schemabinding.version2.UserColours uc = new jalview.schemabinding.version2.UserColours();
1866 jalview.schemabinding.version2.UserColourScheme jbucs = new jalview.schemabinding.version2.UserColourScheme();
1868 for (int i = 0; i < colours.length; i++)
1870 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
1871 col.setName(ResidueProperties.aa[i]);
1872 col.setRGB(jalview.util.Format.getHexString(colours[i]));
1873 jbucs.addColour(col);
1875 if (ucs.getLowerCaseColours() != null)
1877 colours = ucs.getLowerCaseColours();
1878 for (int i = 0; i < colours.length; i++)
1880 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
1881 col.setName(ResidueProperties.aa[i].toLowerCase());
1882 col.setRGB(jalview.util.Format.getHexString(colours[i]));
1883 jbucs.addColour(col);
1888 uc.setUserColourScheme(jbucs);
1889 jms.addUserColours(uc);
1895 jalview.schemes.UserColourScheme getUserColourScheme(
1896 JalviewModelSequence jms, String id)
1898 UserColours[] uc = jms.getUserColours();
1899 UserColours colours = null;
1901 for (int i = 0; i < uc.length; i++)
1903 if (uc[i].getId().equals(id))
1911 java.awt.Color[] newColours = new java.awt.Color[24];
1913 for (int i = 0; i < 24; i++)
1915 newColours[i] = new java.awt.Color(Integer.parseInt(colours
1916 .getUserColourScheme().getColour(i).getRGB(), 16));
1919 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
1922 if (colours.getUserColourScheme().getColourCount() > 24)
1924 newColours = new java.awt.Color[23];
1925 for (int i = 0; i < 23; i++)
1927 newColours[i] = new java.awt.Color(Integer.parseInt(colours
1928 .getUserColourScheme().getColour(i + 24).getRGB(), 16));
1930 ucs.setLowerCaseColours(newColours);
1937 * contains last error message (if any) encountered by XML loader.
1939 String errorMessage = null;
1942 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
1943 * exceptions are raised during project XML parsing
1945 public boolean attemptversion1parse = true;
1948 * Load a jalview project archive from a jar file
1951 * - HTTP URL or filename
1953 public AlignFrame loadJalviewAlign(final String file)
1956 jalview.gui.AlignFrame af = null;
1960 // create list to store references for any new Jmol viewers created
1961 newStructureViewers = new Vector<JalviewStructureDisplayI>();
1962 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
1963 // Workaround is to make sure caller implements the JarInputStreamProvider
1965 // so we can re-open the jar input stream for each entry.
1967 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
1968 af = loadJalviewAlign(jprovider);
1970 } catch (MalformedURLException e)
1972 errorMessage = "Invalid URL format for '" + file + "'";
1978 SwingUtilities.invokeAndWait(new Runnable()
1982 setLoadingFinishedForNewStructureViewers();
1985 } catch (Exception x)
1993 private jarInputStreamProvider createjarInputStreamProvider(
1994 final String file) throws MalformedURLException
1997 errorMessage = null;
1998 uniqueSetSuffix = null;
2000 viewportsAdded.clear();
2001 frefedSequence = null;
2003 if (file.startsWith("http://"))
2005 url = new URL(file);
2007 final URL _url = url;
2008 return new jarInputStreamProvider()
2012 public JarInputStream getJarInputStream() throws IOException
2016 return new JarInputStream(_url.openStream());
2020 return new JarInputStream(new FileInputStream(file));
2025 public String getFilename()
2033 * Recover jalview session from a jalview project archive. Caller may
2034 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
2035 * themselves. Any null fields will be initialised with default values,
2036 * non-null fields are left alone.
2041 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
2043 errorMessage = null;
2044 if (uniqueSetSuffix == null)
2046 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
2048 if (seqRefIds == null)
2050 seqRefIds = new HashMap<String, SequenceI>();
2052 if (frefedSequence == null)
2054 frefedSequence = new Vector();
2057 AlignFrame af = null, _af = null;
2058 Map<String, AlignFrame> gatherToThisFrame = new HashMap<String, AlignFrame>();
2059 final String file = jprovider.getFilename();
2062 JarInputStream jin = null;
2063 JarEntry jarentry = null;
2068 jin = jprovider.getJarInputStream();
2069 for (int i = 0; i < entryCount; i++)
2071 jarentry = jin.getNextJarEntry();
2074 if (jarentry != null && jarentry.getName().endsWith(".xml"))
2076 InputStreamReader in = new InputStreamReader(jin, "UTF-8");
2077 JalviewModel object = new JalviewModel();
2079 Unmarshaller unmar = new Unmarshaller(object);
2080 unmar.setValidation(false);
2081 object = (JalviewModel) unmar.unmarshal(in);
2082 if (true) // !skipViewport(object))
2084 _af = loadFromObject(object, file, true, jprovider);
2085 if (object.getJalviewModelSequence().getViewportCount() > 0)
2088 if (af.viewport.isGatherViewsHere())
2090 gatherToThisFrame.put(af.viewport.getSequenceSetId(), af);
2096 else if (jarentry != null)
2098 // Some other file here.
2101 } while (jarentry != null);
2102 resolveFrefedSequences();
2103 } catch (java.io.FileNotFoundException ex)
2105 ex.printStackTrace();
2106 errorMessage = "Couldn't locate Jalview XML file : " + file;
2107 System.err.println("Exception whilst loading jalview XML file : "
2109 } catch (java.net.UnknownHostException ex)
2111 ex.printStackTrace();
2112 errorMessage = "Couldn't locate Jalview XML file : " + file;
2113 System.err.println("Exception whilst loading jalview XML file : "
2115 } catch (Exception ex)
2117 System.err.println("Parsing as Jalview Version 2 file failed.");
2118 ex.printStackTrace(System.err);
2119 if (attemptversion1parse)
2121 // Is Version 1 Jar file?
2124 af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
2125 } catch (Exception ex2)
2127 System.err.println("Exception whilst loading as jalviewXMLV1:");
2128 ex2.printStackTrace();
2132 if (Desktop.instance != null)
2134 Desktop.instance.stopLoading();
2138 System.out.println("Successfully loaded archive file");
2141 ex.printStackTrace();
2143 System.err.println("Exception whilst loading jalview XML file : "
2145 } catch (OutOfMemoryError e)
2147 // Don't use the OOM Window here
2148 errorMessage = "Out of memory loading jalview XML file";
2149 System.err.println("Out of memory whilst loading jalview XML file");
2150 e.printStackTrace();
2153 if (Desktop.instance != null)
2155 Desktop.instance.stopLoading();
2158 for (AlignFrame fr : gatherToThisFrame.values())
2160 Desktop.instance.gatherViews(fr);
2163 restoreSplitFrames();
2165 if (errorMessage != null)
2173 * Try to reconstruct and display SplitFrame windows, where each contains
2174 * complementary dna and protein alignments. Done by pairing up AlignFrame
2175 * objects (created earlier) which have complementary viewport ids associated.
2177 protected void restoreSplitFrames()
2179 List<SplitFrame> gatherTo = new ArrayList<SplitFrame>();
2180 List<AlignFrame> addedToSplitFrames = new ArrayList<AlignFrame>();
2181 Map<String, AlignFrame> dna = new HashMap<String, AlignFrame>();
2184 * Identify the DNA alignments
2186 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2189 AlignFrame af = candidate.getValue();
2190 if (af.getViewport().getAlignment().isNucleotide())
2192 dna.put(candidate.getKey().getId(), af);
2197 * Try to match up the protein complements
2199 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2202 AlignFrame af = candidate.getValue();
2203 if (!af.getViewport().getAlignment().isNucleotide())
2205 String complementId = candidate.getKey().getComplementId();
2206 // only non-null complements should be in the Map
2207 if (complementId != null && dna.containsKey(complementId))
2209 final AlignFrame dnaFrame = dna.get(complementId);
2210 SplitFrame sf = createSplitFrame(dnaFrame, af);
2211 addedToSplitFrames.add(dnaFrame);
2212 addedToSplitFrames.add(af);
2213 if (af.viewport.isGatherViewsHere())
2222 * Open any that we failed to pair up (which shouldn't happen!) as
2223 * standalone AlignFrame's.
2225 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2228 AlignFrame af = candidate.getValue();
2229 if (!addedToSplitFrames.contains(af)) {
2230 Viewport view = candidate.getKey();
2231 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
2233 System.err.println("Failed to restore view " + view.getTitle()
2234 + " to split frame");
2239 * Gather back into tabbed views as flagged.
2241 for (SplitFrame sf : gatherTo)
2243 Desktop.instance.gatherViews(sf);
2246 splitFrameCandidates.clear();
2250 * Construct and display one SplitFrame holding DNA and protein alignments.
2253 * @param proteinFrame
2256 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
2257 AlignFrame proteinFrame)
2259 dnaFrame.setVisible(true);
2260 proteinFrame.setVisible(true);
2261 proteinFrame.getViewport().setCodingComplement(dnaFrame.getViewport());
2262 final StructureSelectionManager ssm = StructureSelectionManager
2263 .getStructureSelectionManager(Desktop.instance);
2264 ssm.addCommandListener(proteinFrame.getViewport());
2265 ssm.addCommandListener(dnaFrame.getViewport());
2267 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
2268 String title = MessageManager.getString("label.linked_view_title");
2269 Desktop.addInternalFrame(splitFrame, title, -1, -1);
2274 * check errorMessage for a valid error message and raise an error box in the
2275 * GUI or write the current errorMessage to stderr and then clear the error
2278 protected void reportErrors()
2280 reportErrors(false);
2283 protected void reportErrors(final boolean saving)
2285 if (errorMessage != null)
2287 final String finalErrorMessage = errorMessage;
2290 javax.swing.SwingUtilities.invokeLater(new Runnable()
2295 JOptionPane.showInternalMessageDialog(Desktop.desktop,
2296 finalErrorMessage, "Error "
2297 + (saving ? "saving" : "loading")
2298 + " Jalview file", JOptionPane.WARNING_MESSAGE);
2304 System.err.println("Problem loading Jalview file: " + errorMessage);
2307 errorMessage = null;
2310 Map<String, String> alreadyLoadedPDB = new HashMap<String, String>();
2313 * when set, local views will be updated from view stored in JalviewXML
2314 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
2315 * sync if this is set to true.
2317 private final boolean updateLocalViews = false;
2319 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId)
2321 if (alreadyLoadedPDB.containsKey(pdbId))
2323 return alreadyLoadedPDB.get(pdbId).toString();
2328 JarInputStream jin = jprovider.getJarInputStream();
2330 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
2331 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
2332 * FileInputStream(jprovider)); }
2335 JarEntry entry = null;
2338 entry = jin.getNextJarEntry();
2339 } while (entry != null && !entry.getName().equals(pdbId));
2342 BufferedReader in = new BufferedReader(new InputStreamReader(jin));
2343 File outFile = File.createTempFile("jalview_pdb", ".txt");
2344 outFile.deleteOnExit();
2345 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
2348 while ((data = in.readLine()) != null)
2355 } catch (Exception foo)
2360 String t = outFile.getAbsolutePath();
2361 alreadyLoadedPDB.put(pdbId, t);
2366 warn("Couldn't find PDB file entry in Jalview Jar for " + pdbId);
2368 } catch (Exception ex)
2370 ex.printStackTrace();
2376 private class JvAnnotRow
2378 public JvAnnotRow(int i, AlignmentAnnotation jaa)
2385 * persisted version of annotation row from which to take vis properties
2387 public jalview.datamodel.AlignmentAnnotation template;
2390 * original position of the annotation row in the alignment
2396 * Load alignment frame from jalview XML DOM object
2401 * filename source string
2402 * @param loadTreesAndStructures
2403 * when false only create Viewport
2405 * data source provider
2406 * @return alignment frame created from view stored in DOM
2408 AlignFrame loadFromObject(JalviewModel object, String file,
2409 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
2411 SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
2412 Sequence[] vamsasSeq = vamsasSet.getSequence();
2414 JalviewModelSequence jms = object.getJalviewModelSequence();
2416 Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
2419 // ////////////////////////////////
2422 List<SequenceI> hiddenSeqs = null;
2423 jalview.datamodel.Sequence jseq;
2425 List<SequenceI> tmpseqs = new ArrayList<SequenceI>();
2427 boolean multipleView = false;
2429 JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
2430 int vi = 0; // counter in vamsasSeq array
2431 for (int i = 0; i < jseqs.length; i++)
2433 String seqId = jseqs[i].getId();
2435 if (seqRefIds.get(seqId) != null)
2437 tmpseqs.add(seqRefIds.get(seqId));
2438 multipleView = true;
2442 jseq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
2443 vamsasSeq[vi].getSequence());
2444 jseq.setDescription(vamsasSeq[vi].getDescription());
2445 jseq.setStart(jseqs[i].getStart());
2446 jseq.setEnd(jseqs[i].getEnd());
2447 jseq.setVamsasId(uniqueSetSuffix + seqId);
2448 seqRefIds.put(vamsasSeq[vi].getId(), jseq);
2453 if (jseqs[i].getHidden())
2455 if (hiddenSeqs == null)
2457 hiddenSeqs = new ArrayList<SequenceI>();
2460 hiddenSeqs.add(seqRefIds.get(seqId));
2466 // Create the alignment object from the sequence set
2467 // ///////////////////////////////
2468 SequenceI[] orderedSeqs = tmpseqs
2469 .toArray(new SequenceI[tmpseqs.size()]);
2471 Alignment al = new Alignment(orderedSeqs);
2473 // / Add the alignment properties
2474 for (int i = 0; i < vamsasSet.getSequenceSetPropertiesCount(); i++)
2476 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties(i);
2477 al.setProperty(ssp.getKey(), ssp.getValue());
2481 // SequenceFeatures are added to the DatasetSequence,
2482 // so we must create or recover the dataset before loading features
2483 // ///////////////////////////////
2484 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
2486 // older jalview projects do not have a dataset id.
2487 al.setDataset(null);
2491 // recover dataset - passing on flag indicating if this a 'viewless'
2492 // sequence set (a.k.a. a stored dataset for the project)
2493 recoverDatasetFor(vamsasSet, al, object.getJalviewModelSequence()
2494 .getViewportCount() == 0);
2496 // ///////////////////////////////
2498 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
2501 // load sequence features, database references and any associated PDB
2502 // structures for the alignment
2503 for (int i = 0; i < vamsasSeq.length; i++)
2505 if (jseqs[i].getFeaturesCount() > 0)
2507 Features[] features = jseqs[i].getFeatures();
2508 for (int f = 0; f < features.length; f++)
2510 jalview.datamodel.SequenceFeature sf = new jalview.datamodel.SequenceFeature(
2511 features[f].getType(), features[f].getDescription(),
2512 features[f].getStatus(), features[f].getBegin(),
2513 features[f].getEnd(), features[f].getFeatureGroup());
2515 sf.setScore(features[f].getScore());
2516 for (int od = 0; od < features[f].getOtherDataCount(); od++)
2518 OtherData keyValue = features[f].getOtherData(od);
2519 if (keyValue.getKey().startsWith("LINK"))
2521 sf.addLink(keyValue.getValue());
2525 sf.setValue(keyValue.getKey(), keyValue.getValue());
2530 al.getSequenceAt(i).getDatasetSequence().addSequenceFeature(sf);
2533 if (vamsasSeq[i].getDBRefCount() > 0)
2535 addDBRefs(al.getSequenceAt(i).getDatasetSequence(), vamsasSeq[i]);
2537 if (jseqs[i].getPdbidsCount() > 0)
2539 Pdbids[] ids = jseqs[i].getPdbids();
2540 for (int p = 0; p < ids.length; p++)
2542 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
2543 entry.setId(ids[p].getId());
2544 entry.setType(ids[p].getType());
2545 if (ids[p].getFile() != null)
2547 if (!pdbloaded.containsKey(ids[p].getFile()))
2549 entry.setFile(loadPDBFile(jprovider, ids[p].getId()));
2553 entry.setFile(pdbloaded.get(ids[p].getId()).toString());
2556 StructureSelectionManager.getStructureSelectionManager(
2557 Desktop.instance).registerPDBEntry(entry);
2558 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
2562 } // end !multipleview
2564 // ///////////////////////////////
2565 // LOAD SEQUENCE MAPPINGS
2567 if (vamsasSet.getAlcodonFrameCount() > 0)
2569 // TODO Potentially this should only be done once for all views of an
2571 AlcodonFrame[] alc = vamsasSet.getAlcodonFrame();
2572 for (int i = 0; i < alc.length; i++)
2574 AlignedCodonFrame cf = new AlignedCodonFrame();
2575 if (alc[i].getAlcodMapCount() > 0)
2577 AlcodMap[] maps = alc[i].getAlcodMap();
2578 for (int m = 0; m < maps.length; m++)
2580 SequenceI dnaseq = seqRefIds.get(maps[m].getDnasq());
2582 jalview.datamodel.Mapping mapping = null;
2583 // attach to dna sequence reference.
2584 if (maps[m].getMapping() != null)
2586 mapping = addMapping(maps[m].getMapping());
2590 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
2595 frefedSequence.add(new Object[]
2596 { maps[m].getDnasq(), cf, mapping });
2600 al.addCodonFrame(cf);
2604 // ////////////////////////////////
2606 List<JvAnnotRow> autoAlan = new ArrayList<JvAnnotRow>();
2608 * store any annotations which forward reference a group's ID
2610 Hashtable<String, ArrayList<jalview.datamodel.AlignmentAnnotation>> groupAnnotRefs = new Hashtable<String, ArrayList<jalview.datamodel.AlignmentAnnotation>>();
2612 if (vamsasSet.getAnnotationCount() > 0)
2614 Annotation[] an = vamsasSet.getAnnotation();
2616 for (int i = 0; i < an.length; i++)
2619 * test if annotation is automatically calculated for this view only
2621 boolean autoForView = false;
2622 if (an[i].getLabel().equals("Quality")
2623 || an[i].getLabel().equals("Conservation")
2624 || an[i].getLabel().equals("Consensus"))
2626 // Kludge for pre 2.5 projects which lacked the autocalculated flag
2628 if (!an[i].hasAutoCalculated())
2630 an[i].setAutoCalculated(true);
2634 || (an[i].hasAutoCalculated() && an[i].isAutoCalculated()))
2636 // remove ID - we don't recover annotation from other views for
2637 // view-specific annotation
2641 // set visiblity for other annotation in this view
2642 if (an[i].getId() != null
2643 && annotationIds.containsKey(an[i].getId()))
2645 AlignmentAnnotation jda = annotationIds.get(an[i].getId());
2646 // in principle Visible should always be true for annotation displayed
2647 // in multiple views
2648 if (an[i].hasVisible())
2650 jda.visible = an[i].getVisible();
2653 al.addAnnotation(jda);
2657 // Construct new annotation from model.
2658 AnnotationElement[] ae = an[i].getAnnotationElement();
2659 jalview.datamodel.Annotation[] anot = null;
2660 java.awt.Color firstColour = null;
2662 if (!an[i].getScoreOnly())
2664 anot = new jalview.datamodel.Annotation[al.getWidth()];
2665 for (int aa = 0; aa < ae.length && aa < anot.length; aa++)
2667 anpos = ae[aa].getPosition();
2669 if (anpos >= anot.length)
2674 anot[anpos] = new jalview.datamodel.Annotation(
2676 ae[aa].getDisplayCharacter(), ae[aa].getDescription(),
2677 (ae[aa].getSecondaryStructure() == null || ae[aa]
2678 .getSecondaryStructure().length() == 0) ? ' '
2679 : ae[aa].getSecondaryStructure().charAt(0),
2683 // JBPNote: Consider verifying dataflow for IO of secondary
2684 // structure annotation read from Stockholm files
2685 // this was added to try to ensure that
2686 // if (anot[ae[aa].getPosition()].secondaryStructure>' ')
2688 // anot[ae[aa].getPosition()].displayCharacter = "";
2690 anot[anpos].colour = new java.awt.Color(ae[aa].getColour());
2691 if (firstColour == null)
2693 firstColour = anot[anpos].colour;
2697 jalview.datamodel.AlignmentAnnotation jaa = null;
2699 if (an[i].getGraph())
2701 float llim = 0, hlim = 0;
2702 // if (autoForView || an[i].isAutoCalculated()) {
2705 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
2706 an[i].getDescription(), anot, llim, hlim,
2707 an[i].getGraphType());
2709 jaa.graphGroup = an[i].getGraphGroup();
2710 jaa._linecolour = firstColour;
2711 if (an[i].getThresholdLine() != null)
2713 jaa.setThreshold(new jalview.datamodel.GraphLine(an[i]
2714 .getThresholdLine().getValue(), an[i]
2715 .getThresholdLine().getLabel(), new java.awt.Color(
2716 an[i].getThresholdLine().getColour())));
2719 if (autoForView || an[i].isAutoCalculated())
2721 // Hardwire the symbol display line to ensure that labels for
2722 // histograms are displayed
2728 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
2729 an[i].getDescription(), anot);
2730 jaa._linecolour = firstColour;
2732 // register new annotation
2733 if (an[i].getId() != null)
2735 annotationIds.put(an[i].getId(), jaa);
2736 jaa.annotationId = an[i].getId();
2738 // recover sequence association
2739 if (an[i].getSequenceRef() != null)
2741 if (al.findName(an[i].getSequenceRef()) != null)
2743 jaa.createSequenceMapping(al.findName(an[i].getSequenceRef()),
2745 al.findName(an[i].getSequenceRef()).addAlignmentAnnotation(jaa);
2748 // and make a note of any group association
2749 if (an[i].getGroupRef() != null && an[i].getGroupRef().length() > 0)
2751 ArrayList<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
2752 .get(an[i].getGroupRef());
2755 aal = new ArrayList<jalview.datamodel.AlignmentAnnotation>();
2756 groupAnnotRefs.put(an[i].getGroupRef(), aal);
2761 if (an[i].hasScore())
2763 jaa.setScore(an[i].getScore());
2765 if (an[i].hasVisible())
2767 jaa.visible = an[i].getVisible();
2770 if (an[i].hasCentreColLabels())
2772 jaa.centreColLabels = an[i].getCentreColLabels();
2775 if (an[i].hasScaleColLabels())
2777 jaa.scaleColLabel = an[i].getScaleColLabels();
2779 if (an[i].hasAutoCalculated() && an[i].isAutoCalculated())
2781 // newer files have an 'autoCalculated' flag and store calculation
2782 // state in viewport properties
2783 jaa.autoCalculated = true; // means annotation will be marked for
2784 // update at end of load.
2786 if (an[i].hasGraphHeight())
2788 jaa.graphHeight = an[i].getGraphHeight();
2790 if (an[i].hasBelowAlignment())
2792 jaa.belowAlignment = an[i].isBelowAlignment();
2794 jaa.setCalcId(an[i].getCalcId());
2795 if (an[i].getPropertyCount() > 0)
2797 for (jalview.schemabinding.version2.Property prop : an[i]
2800 jaa.setProperty(prop.getName(), prop.getValue());
2803 if (jaa.autoCalculated)
2805 autoAlan.add(new JvAnnotRow(i, jaa));
2808 // if (!autoForView)
2810 // add autocalculated group annotation and any user created annotation
2812 al.addAnnotation(jaa);
2816 // ///////////////////////
2818 // Create alignment markup and styles for this view
2819 if (jms.getJGroupCount() > 0)
2821 JGroup[] groups = jms.getJGroup();
2822 boolean addAnnotSchemeGroup = false;
2823 for (int i = 0; i < groups.length; i++)
2825 ColourSchemeI cs = null;
2827 if (groups[i].getColour() != null)
2829 if (groups[i].getColour().startsWith("ucs"))
2831 cs = getUserColourScheme(jms, groups[i].getColour());
2833 else if (groups[i].getColour().equals("AnnotationColourGradient")
2834 && groups[i].getAnnotationColours() != null)
2836 addAnnotSchemeGroup = true;
2841 cs = ColourSchemeProperty.getColour(al, groups[i].getColour());
2846 cs.setThreshold(groups[i].getPidThreshold(), true);
2850 Vector seqs = new Vector();
2852 for (int s = 0; s < groups[i].getSeqCount(); s++)
2854 String seqId = groups[i].getSeq(s) + "";
2855 jalview.datamodel.SequenceI ts = seqRefIds.get(seqId);
2859 seqs.addElement(ts);
2863 if (seqs.size() < 1)
2868 jalview.datamodel.SequenceGroup sg = new jalview.datamodel.SequenceGroup(
2869 seqs, groups[i].getName(), cs, groups[i].getDisplayBoxes(),
2870 groups[i].getDisplayText(), groups[i].getColourText(),
2871 groups[i].getStart(), groups[i].getEnd());
2873 sg.setOutlineColour(new java.awt.Color(groups[i].getOutlineColour()));
2875 sg.textColour = new java.awt.Color(groups[i].getTextCol1());
2876 sg.textColour2 = new java.awt.Color(groups[i].getTextCol2());
2877 sg.setShowNonconserved(groups[i].hasShowUnconserved() ? groups[i]
2878 .isShowUnconserved() : false);
2879 sg.thresholdTextColour = groups[i].getTextColThreshold();
2880 if (groups[i].hasShowConsensusHistogram())
2882 sg.setShowConsensusHistogram(groups[i].isShowConsensusHistogram());
2885 if (groups[i].hasShowSequenceLogo())
2887 sg.setshowSequenceLogo(groups[i].isShowSequenceLogo());
2889 if (groups[i].hasNormaliseSequenceLogo())
2891 sg.setNormaliseSequenceLogo(groups[i].isNormaliseSequenceLogo());
2893 if (groups[i].hasIgnoreGapsinConsensus())
2895 sg.setIgnoreGapsConsensus(groups[i].getIgnoreGapsinConsensus());
2897 if (groups[i].getConsThreshold() != 0)
2899 jalview.analysis.Conservation c = new jalview.analysis.Conservation(
2900 "All", ResidueProperties.propHash, 3,
2901 sg.getSequences(null), 0, sg.getWidth() - 1);
2903 c.verdict(false, 25);
2904 sg.cs.setConservation(c);
2907 if (groups[i].getId() != null && groupAnnotRefs.size() > 0)
2909 // re-instate unique group/annotation row reference
2910 ArrayList<jalview.datamodel.AlignmentAnnotation> jaal = groupAnnotRefs
2911 .get(groups[i].getId());
2914 for (jalview.datamodel.AlignmentAnnotation jaa : jaal)
2917 if (jaa.autoCalculated)
2919 // match up and try to set group autocalc alignment row for this
2921 if (jaa.label.startsWith("Consensus for "))
2923 sg.setConsensus(jaa);
2925 // match up and try to set group autocalc alignment row for this
2927 if (jaa.label.startsWith("Conservation for "))
2929 sg.setConservationRow(jaa);
2936 if (addAnnotSchemeGroup)
2938 // reconstruct the annotation colourscheme
2939 sg.cs = constructAnnotationColour(
2940 groups[i].getAnnotationColours(), null, al, jms, false);
2946 // only dataset in this model, so just return.
2949 // ///////////////////////////////
2952 // If we just load in the same jar file again, the sequenceSetId
2953 // will be the same, and we end up with multiple references
2954 // to the same sequenceSet. We must modify this id on load
2955 // so that each load of the file gives a unique id
2956 String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
2957 String viewId = (view.getId() == null ? null : view.getId()
2959 AlignFrame af = null;
2960 AlignViewport av = null;
2961 // now check to see if we really need to create a new viewport.
2962 if (multipleView && viewportsAdded.size() == 0)
2964 // We recovered an alignment for which a viewport already exists.
2965 // TODO: fix up any settings necessary for overlaying stored state onto
2966 // state recovered from another document. (may not be necessary).
2967 // we may need a binding from a viewport in memory to one recovered from
2969 // and then recover its containing af to allow the settings to be applied.
2970 // TODO: fix for vamsas demo
2972 .println("About to recover a viewport for existing alignment: Sequence set ID is "
2974 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
2975 if (seqsetobj != null)
2977 if (seqsetobj instanceof String)
2979 uniqueSeqSetId = (String) seqsetobj;
2981 .println("Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
2987 .println("Warning : Collision between sequence set ID string and existing jalview object mapping.");
2993 * indicate that annotation colours are applied across all groups (pre
2994 * Jalview 2.8.1 behaviour)
2996 boolean doGroupAnnColour = isVersionStringLaterThan("2.8.1",
2997 object.getVersion());
2999 AlignmentPanel ap = null;
3000 boolean isnewview = true;
3003 // Check to see if this alignment already has a view id == viewId
3004 jalview.gui.AlignmentPanel views[] = Desktop
3005 .getAlignmentPanels(uniqueSeqSetId);
3006 if (views != null && views.length > 0)
3008 for (int v = 0; v < views.length; v++)
3010 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
3012 // recover the existing alignpanel, alignframe, viewport
3013 af = views[v].alignFrame;
3016 // TODO: could even skip resetting view settings if we don't want to
3017 // change the local settings from other jalview processes
3026 af = loadViewport(file, jseqs, hiddenSeqs, al, jms, view,
3027 uniqueSeqSetId, viewId, autoAlan);
3032 // /////////////////////////////////////
3033 if (loadTreesAndStructures && jms.getTreeCount() > 0)
3037 for (int t = 0; t < jms.getTreeCount(); t++)
3040 Tree tree = jms.getTree(t);
3042 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
3045 tp = af.ShowNewickTree(
3046 new jalview.io.NewickFile(tree.getNewick()),
3047 tree.getTitle(), tree.getWidth(), tree.getHeight(),
3048 tree.getXpos(), tree.getYpos());
3049 if (tree.getId() != null)
3051 // perhaps bind the tree id to something ?
3056 // update local tree attributes ?
3057 // TODO: should check if tp has been manipulated by user - if so its
3058 // settings shouldn't be modified
3059 tp.setTitle(tree.getTitle());
3060 tp.setBounds(new Rectangle(tree.getXpos(), tree.getYpos(), tree
3061 .getWidth(), tree.getHeight()));
3062 tp.av = av; // af.viewport; // TODO: verify 'associate with all
3065 tp.treeCanvas.av = av; // af.viewport;
3066 tp.treeCanvas.ap = ap; // af.alignPanel;
3071 warn("There was a problem recovering stored Newick tree: \n"
3072 + tree.getNewick());
3076 tp.fitToWindow.setState(tree.getFitToWindow());
3077 tp.fitToWindow_actionPerformed(null);
3079 if (tree.getFontName() != null)
3081 tp.setTreeFont(new java.awt.Font(tree.getFontName(), tree
3082 .getFontStyle(), tree.getFontSize()));
3086 tp.setTreeFont(new java.awt.Font(view.getFontName(), view
3087 .getFontStyle(), tree.getFontSize()));
3090 tp.showPlaceholders(tree.getMarkUnlinked());
3091 tp.showBootstrap(tree.getShowBootstrap());
3092 tp.showDistances(tree.getShowDistances());
3094 tp.treeCanvas.threshold = tree.getThreshold();
3096 if (tree.getCurrentTree())
3098 af.viewport.setCurrentTree(tp.getTree());
3102 } catch (Exception ex)
3104 ex.printStackTrace();
3108 // //LOAD STRUCTURES
3109 if (loadTreesAndStructures)
3111 loadStructures(jprovider, jseqs, af, ap);
3113 // and finally return.
3118 * Load and link any saved structure viewers.
3125 protected void loadStructures(jarInputStreamProvider jprovider,
3126 JSeq[] jseqs, AlignFrame af, AlignmentPanel ap)
3129 * Run through all PDB ids on the alignment, and collect mappings between
3130 * distinct view ids and all sequences referring to that view.
3132 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<String, StructureViewerModel>();
3134 for (int i = 0; i < jseqs.length; i++)
3136 if (jseqs[i].getPdbidsCount() > 0)
3138 Pdbids[] ids = jseqs[i].getPdbids();
3139 for (int p = 0; p < ids.length; p++)
3141 final int structureStateCount = ids[p].getStructureStateCount();
3142 for (int s = 0; s < structureStateCount; s++)
3144 // check to see if we haven't already created this structure view
3145 final StructureState structureState = ids[p]
3146 .getStructureState(s);
3147 String sviewid = (structureState.getViewId() == null) ? null
3148 : structureState.getViewId() + uniqueSetSuffix;
3149 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
3150 // Originally : ids[p].getFile()
3151 // : TODO: verify external PDB file recovery still works in normal
3152 // jalview project load
3153 jpdb.setFile(loadPDBFile(jprovider, ids[p].getId()));
3154 jpdb.setId(ids[p].getId());
3156 int x = structureState.getXpos();
3157 int y = structureState.getYpos();
3158 int width = structureState.getWidth();
3159 int height = structureState.getHeight();
3161 // Probably don't need to do this anymore...
3162 // Desktop.desktop.getComponentAt(x, y);
3163 // TODO: NOW: check that this recovers the PDB file correctly.
3164 String pdbFile = loadPDBFile(jprovider, ids[p].getId());
3165 jalview.datamodel.SequenceI seq = seqRefIds.get(jseqs[i]
3167 if (sviewid == null)
3169 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width
3172 if (!structureViewers.containsKey(sviewid))
3174 structureViewers.put(sviewid, new StructureViewerModel(x, y,
3175 width, height, false, false, true));
3176 // Legacy pre-2.7 conversion JAL-823 :
3177 // do not assume any view has to be linked for colour by
3181 // assemble String[] { pdb files }, String[] { id for each
3182 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
3183 // seqs_file 2}, boolean[] {
3184 // linkAlignPanel,superposeWithAlignpanel}} from hash
3185 StructureViewerModel jmoldat = structureViewers.get(sviewid);
3186 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
3187 | (structureState.hasAlignwithAlignPanel() ? structureState
3188 .getAlignwithAlignPanel() : false));
3191 * Default colour by linked panel to false if not specified (e.g.
3192 * for pre-2.7 projects)
3194 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
3195 colourWithAlignPanel |= (structureState
3196 .hasColourwithAlignPanel() ? structureState
3197 .getColourwithAlignPanel() : false);
3198 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
3201 * Default colour by viewer to true if not specified (e.g. for
3204 boolean colourByViewer = jmoldat.isColourByViewer();
3205 colourByViewer &= structureState.hasColourByJmol() ? structureState
3206 .getColourByJmol() : true;
3207 jmoldat.setColourByViewer(colourByViewer);
3209 if (jmoldat.getStateData().length() < structureState
3210 .getContent().length())
3213 jmoldat.setStateData(structureState.getContent());
3216 if (ids[p].getFile() != null)
3218 File mapkey = new File(ids[p].getFile());
3219 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
3220 if (seqstrmaps == null)
3222 jmoldat.getFileData().put(
3224 seqstrmaps = jmoldat.new StructureData(pdbFile,
3227 if (!seqstrmaps.getSeqList().contains(seq))
3229 seqstrmaps.getSeqList().add(seq);
3235 errorMessage = ("The Jmol views in this project were imported\nfrom an older version of Jalview.\nPlease review the sequence colour associations\nin the Colour by section of the Jmol View menu.\n\nIn the case of problems, see note at\nhttp://issues.jalview.org/browse/JAL-747");
3242 // Instantiate the associated structure views
3243 for (Entry<String, StructureViewerModel> entry : structureViewers
3246 createOrLinkStructureViewer(entry, af, ap);
3256 protected void createOrLinkStructureViewer(
3257 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
3260 final StructureViewerModel svattrib = viewerData.getValue();
3263 * Search for any viewer windows already open from other alignment views
3264 * that exactly match the stored structure state
3266 StructureViewerBase comp = findMatchingViewer(viewerData);
3270 linkStructureViewer(ap, comp, svattrib);
3275 * Pending an XML element for ViewerType, just check if stateData contains
3276 * "chimera" (part of the chimera session filename).
3278 if (svattrib.getStateData().indexOf("chimera") > -1)
3280 createChimeraViewer(viewerData, af);
3284 createJmolViewer(viewerData, af);
3289 * Create a new Chimera viewer.
3294 protected void createChimeraViewer(
3295 Entry<String, StructureViewerModel> viewerData, AlignFrame af)
3297 final StructureViewerModel data = viewerData.getValue();
3298 String chimeraSession = data.getStateData();
3300 if (new File(chimeraSession).exists())
3302 Set<Entry<File, StructureData>> fileData = data.getFileData()
3304 List<PDBEntry> pdbs = new ArrayList<PDBEntry>();
3305 List<SequenceI[]> allseqs = new ArrayList<SequenceI[]>();
3306 for (Entry<File, StructureData> pdb : fileData)
3308 String filePath = pdb.getValue().getFilePath();
3309 String pdbId = pdb.getValue().getPdbId();
3310 pdbs.add(new PDBEntry(filePath, pdbId));
3311 final List<SequenceI> seqList = pdb.getValue().getSeqList();
3312 SequenceI[] seqs = seqList.toArray(new SequenceI[seqList.size()]);
3316 boolean colourByChimera = data.isColourByViewer();
3317 boolean colourBySequence = data.isColourWithAlignPanel();
3319 // TODO can/should this be done via StructureViewer (like Jmol)?
3320 final PDBEntry[] pdbArray = pdbs.toArray(new PDBEntry[pdbs.size()]);
3321 final SequenceI[][] seqsArray = allseqs.toArray(new SequenceI[allseqs
3323 new ChimeraViewFrame(chimeraSession, af.alignPanel, pdbArray,
3324 seqsArray, colourByChimera, colourBySequence);
3328 Cache.log.error("Chimera session file " + chimeraSession
3334 * Create a new Jmol window. First parse the Jmol state to translate filenames
3335 * loaded into the view, and record the order in which files are shown in the
3336 * Jmol view, so we can add the sequence mappings in same order.
3341 protected void createJmolViewer(
3342 final Entry<String, StructureViewerModel> viewerData,
3345 final StructureViewerModel svattrib = viewerData.getValue();
3346 String state = svattrib.getStateData();
3347 List<String> pdbfilenames = new ArrayList<String>();
3348 List<SequenceI[]> seqmaps = new ArrayList<SequenceI[]>();
3349 List<String> pdbids = new ArrayList<String>();
3350 StringBuilder newFileLoc = new StringBuilder(64);
3351 int cp = 0, ncp, ecp;
3352 Map<File, StructureData> oldFiles = svattrib.getFileData();
3353 while ((ncp = state.indexOf("load ", cp)) > -1)
3357 // look for next filename in load statement
3358 newFileLoc.append(state.substring(cp,
3359 ncp = (state.indexOf("\"", ncp + 1) + 1)));
3360 String oldfilenam = state.substring(ncp,
3361 ecp = state.indexOf("\"", ncp));
3362 // recover the new mapping data for this old filename
3363 // have to normalize filename - since Jmol and jalview do
3365 // translation differently.
3366 StructureData filedat = oldFiles.get(new File(oldfilenam));
3367 newFileLoc.append(Platform.escapeString(filedat.getFilePath()));
3368 pdbfilenames.add(filedat.getFilePath());
3369 pdbids.add(filedat.getPdbId());
3370 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
3371 newFileLoc.append("\"");
3372 cp = ecp + 1; // advance beyond last \" and set cursor so we can
3373 // look for next file statement.
3374 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
3378 // just append rest of state
3379 newFileLoc.append(state.substring(cp));
3383 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
3384 newFileLoc = new StringBuilder(state);
3385 newFileLoc.append("; load append ");
3386 for (File id : oldFiles.keySet())
3388 // add this and any other pdb files that should be present in
3390 StructureData filedat = oldFiles.get(id);
3391 newFileLoc.append(filedat.getFilePath());
3392 pdbfilenames.add(filedat.getFilePath());
3393 pdbids.add(filedat.getPdbId());
3394 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
3395 newFileLoc.append(" \"");
3396 newFileLoc.append(filedat.getFilePath());
3397 newFileLoc.append("\"");
3400 newFileLoc.append(";");
3403 if (newFileLoc.length() > 0)
3405 int histbug = newFileLoc.indexOf("history = ");
3407 int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";", histbug);
3408 String val = (diff == -1) ? null : newFileLoc
3409 .substring(histbug, diff);
3410 if (val != null && val.length() >= 4)
3412 if (val.contains("e"))
3414 if (val.trim().equals("true"))
3422 newFileLoc.replace(histbug, diff, val);
3426 final String[] pdbf = pdbfilenames.toArray(new String[pdbfilenames
3428 final String[] id = pdbids.toArray(new String[pdbids.size()]);
3429 final SequenceI[][] sq = seqmaps
3430 .toArray(new SequenceI[seqmaps.size()][]);
3431 final String fileloc = newFileLoc.toString();
3432 final String sviewid = viewerData.getKey();
3433 final AlignFrame alf = af;
3434 final Rectangle rect = new Rectangle(svattrib.getX(),
3435 svattrib.getY(), svattrib.getWidth(), svattrib.getHeight());
3438 javax.swing.SwingUtilities.invokeAndWait(new Runnable()
3443 JalviewStructureDisplayI sview = null;
3446 // JAL-1333 note - we probably can't migrate Jmol views to UCSF
3448 sview = new StructureViewer(alf.alignPanel
3449 .getStructureSelectionManager()).createView(
3450 StructureViewer.ViewerType.JMOL, pdbf, id, sq,
3451 alf.alignPanel, svattrib, fileloc, rect, sviewid);
3452 addNewStructureViewer(sview);
3453 } catch (OutOfMemoryError ex)
3455 new OOMWarning("restoring structure view for PDB id " + id,
3456 (OutOfMemoryError) ex.getCause());
3457 if (sview != null && sview.isVisible())
3459 sview.closeViewer();
3460 sview.setVisible(false);
3466 } catch (InvocationTargetException ex)
3468 warn("Unexpected error when opening Jmol view.", ex);
3470 } catch (InterruptedException e)
3472 // e.printStackTrace();
3478 * Returns any open frame that matches given structure viewer data. The match
3479 * is based on the unique viewId, or (for older project versions) the frame's
3485 protected StructureViewerBase findMatchingViewer(
3486 Entry<String, StructureViewerModel> viewerData)
3488 final String sviewid = viewerData.getKey();
3489 final StructureViewerModel svattrib = viewerData.getValue();
3490 StructureViewerBase comp = null;
3491 JInternalFrame[] frames = getAllFrames();
3492 for (JInternalFrame frame : frames)
3494 if (frame instanceof StructureViewerBase)
3497 * Post jalview 2.4 schema includes structure view id
3500 && ((StructureViewerBase) frame).getViewId()
3503 comp = (AppJmol) frame;
3507 * Otherwise test for matching position and size of viewer frame
3509 else if (frame.getX() == svattrib.getX()
3510 && frame.getY() == svattrib.getY()
3511 && frame.getHeight() == svattrib.getHeight()
3512 && frame.getWidth() == svattrib.getWidth())
3514 comp = (AppJmol) frame;
3523 * Link an AlignmentPanel to an existing structure viewer.
3528 * @param useinViewerSuperpos
3529 * @param usetoColourbyseq
3530 * @param viewerColouring
3532 protected void linkStructureViewer(AlignmentPanel ap,
3533 StructureViewerBase viewer, StructureViewerModel svattrib)
3535 // NOTE: if the jalview project is part of a shared session then
3536 // view synchronization should/could be done here.
3538 final boolean useinViewerSuperpos = svattrib.isAlignWithPanel();
3539 final boolean usetoColourbyseq = svattrib.isColourWithAlignPanel();
3540 final boolean viewerColouring = svattrib.isColourByViewer();
3541 Map<File, StructureData> oldFiles = svattrib.getFileData();
3544 * Add mapping for sequences in this view to an already open viewer
3546 final AAStructureBindingModel binding = viewer.getBinding();
3547 for (File id : oldFiles.keySet())
3549 // add this and any other pdb files that should be present in the
3551 StructureData filedat = oldFiles.get(id);
3552 String pdbFile = filedat.getFilePath();
3553 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
3554 binding.getSsm().setMapping(seq, null, pdbFile,
3555 jalview.io.AppletFormatAdapter.FILE);
3556 binding.addSequenceForStructFile(pdbFile, seq);
3558 // and add the AlignmentPanel's reference to the view panel
3559 viewer.addAlignmentPanel(ap);
3560 if (useinViewerSuperpos)
3562 viewer.useAlignmentPanelForSuperposition(ap);
3566 viewer.excludeAlignmentPanelForSuperposition(ap);
3568 if (usetoColourbyseq)
3570 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
3574 viewer.excludeAlignmentPanelForColourbyseq(ap);
3579 * Get all frames within the Desktop.
3583 protected JInternalFrame[] getAllFrames()
3585 JInternalFrame[] frames = null;
3586 // TODO is this necessary - is it safe - risk of hanging?
3591 frames = Desktop.desktop.getAllFrames();
3592 } catch (ArrayIndexOutOfBoundsException e)
3594 // occasional No such child exceptions are thrown here...
3598 } catch (InterruptedException f)
3602 } while (frames == null);
3609 * - minimum version we are comparing against
3611 * - version of data being processsed.
3612 * @return true if version is development/null or evaluates to the same or
3613 * later X.Y.Z (where X,Y,Z are like [0-9]+b?[0-9]*)
3615 private boolean isVersionStringLaterThan(String supported, String version)
3617 if (version == null || version.equalsIgnoreCase("DEVELOPMENT BUILD")
3618 || version.equalsIgnoreCase("Test")
3619 || version.equalsIgnoreCase("AUTOMATED BUILD"))
3621 System.err.println("Assuming project file with "
3622 + (version == null ? "null" : version)
3623 + " is compatible with Jalview version " + supported);
3628 StringTokenizer currentV = new StringTokenizer(supported, "."), fileV = new StringTokenizer(
3630 while (currentV.hasMoreTokens() && fileV.hasMoreTokens())
3632 // convert b to decimal to catch bugfix releases within a series
3633 String curT = currentV.nextToken().toLowerCase().replace('b', '.');
3634 String fileT = fileV.nextToken().toLowerCase().replace('b', '.');
3637 if (Float.valueOf(curT) > Float.valueOf(fileT))
3639 // current version is newer than the version that wrote the file
3642 } catch (NumberFormatException nfe)
3645 .println("** WARNING: Version comparison failed for tokens ("
3649 + ")\n** Current: '"
3650 + supported + "' and Version: '" + version + "'");
3653 if (currentV.hasMoreElements())
3655 // fileV has no minor version but identical series to current
3662 Vector<JalviewStructureDisplayI> newStructureViewers = null;
3664 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
3666 if (newStructureViewers != null)
3668 sview.getBinding().setFinishedLoadingFromArchive(false);
3669 newStructureViewers.add(sview);
3673 protected void setLoadingFinishedForNewStructureViewers()
3675 if (newStructureViewers != null)
3677 for (JalviewStructureDisplayI sview : newStructureViewers)
3679 sview.getBinding().setFinishedLoadingFromArchive(true);
3681 newStructureViewers.clear();
3682 newStructureViewers = null;
3686 AlignFrame loadViewport(String file, JSeq[] JSEQ,
3687 List<SequenceI> hiddenSeqs, Alignment al,
3688 JalviewModelSequence jms, Viewport view, String uniqueSeqSetId,
3689 String viewId, List<JvAnnotRow> autoAlan)
3691 AlignFrame af = null;
3692 af = new AlignFrame(al, view.getWidth(), view.getHeight(),
3693 uniqueSeqSetId, viewId);
3695 af.setFileName(file, "Jalview");
3697 for (int i = 0; i < JSEQ.length; i++)
3699 af.viewport.setSequenceColour(af.viewport.getAlignment()
3700 .getSequenceAt(i), new java.awt.Color(JSEQ[i].getColour()));
3703 af.viewport.setGatherViewsHere(view.getGatheredViews());
3705 if (view.getSequenceSetId() != null)
3707 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
3709 af.viewport.setSequenceSetId(uniqueSeqSetId);
3712 // propagate shared settings to this new view
3713 af.viewport.setHistoryList(av.getHistoryList());
3714 af.viewport.setRedoList(av.getRedoList());
3718 viewportsAdded.put(uniqueSeqSetId, af.viewport);
3720 // TODO: check if this method can be called repeatedly without
3721 // side-effects if alignpanel already registered.
3722 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
3724 // apply Hidden regions to view.
3725 if (hiddenSeqs != null)
3727 for (int s = 0; s < JSEQ.length; s++)
3729 jalview.datamodel.SequenceGroup hidden = new jalview.datamodel.SequenceGroup();
3731 for (int r = 0; r < JSEQ[s].getHiddenSequencesCount(); r++)
3734 al.getSequenceAt(JSEQ[s].getHiddenSequences(r)), false);
3736 af.viewport.hideRepSequences(al.getSequenceAt(s), hidden);
3739 // jalview.datamodel.SequenceI[] hseqs = new
3740 // jalview.datamodel.SequenceI[hiddenSeqs
3743 // for (int s = 0; s < hiddenSeqs.size(); s++)
3745 // hseqs[s] = (jalview.datamodel.SequenceI) hiddenSeqs.elementAt(s);
3748 SequenceI[] hseqs = hiddenSeqs.toArray(new SequenceI[hiddenSeqs
3750 af.viewport.hideSequence(hseqs);
3753 // recover view properties and display parameters
3754 if (view.getViewName() != null)
3756 af.viewport.viewName = view.getViewName();
3757 af.setInitialTabVisible();
3759 af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(),
3762 af.viewport.setShowAnnotation(view.getShowAnnotation());
3763 af.viewport.setAbovePIDThreshold(view.getPidSelected());
3765 af.viewport.setColourText(view.getShowColourText());
3767 af.viewport.setConservationSelected(view.getConservationSelected());
3768 af.viewport.setShowJVSuffix(view.getShowFullId());
3769 af.viewport.setRightAlignIds(view.getRightAlignIds());
3770 af.viewport.setFont(
3771 new java.awt.Font(view.getFontName(), view.getFontStyle(), view
3772 .getFontSize()), true);
3773 // TODO: allow custom charWidth/Heights to be restored by updating them
3774 // after setting font - which means set above to false
3775 af.viewport.setRenderGaps(view.getRenderGaps());
3776 af.viewport.setWrapAlignment(view.getWrapAlignment());
3777 af.viewport.setShowAnnotation(view.getShowAnnotation());
3779 af.viewport.setShowBoxes(view.getShowBoxes());
3781 af.viewport.setShowText(view.getShowText());
3783 af.viewport.setTextColour(new java.awt.Color(view.getTextCol1()));
3784 af.viewport.setTextColour2(new java.awt.Color(view.getTextCol2()));
3785 af.viewport.setThresholdTextColour(view.getTextColThreshold());
3786 af.viewport.setShowUnconserved(view.hasShowUnconserved() ? view
3787 .isShowUnconserved() : false);
3788 af.viewport.setStartRes(view.getStartRes());
3789 af.viewport.setStartSeq(view.getStartSeq());
3790 af.alignPanel.updateLayout();
3791 ColourSchemeI cs = null;
3792 // apply colourschemes
3793 if (view.getBgColour() != null)
3795 if (view.getBgColour().startsWith("ucs"))
3797 cs = getUserColourScheme(jms, view.getBgColour());
3799 else if (view.getBgColour().startsWith("Annotation"))
3801 AnnotationColours viewAnnColour = view.getAnnotationColours();
3802 cs = constructAnnotationColour(viewAnnColour, af, al, jms, true);
3809 cs = ColourSchemeProperty.getColour(al, view.getBgColour());
3814 cs.setThreshold(view.getPidThreshold(), true);
3815 cs.setConsensus(af.viewport.getSequenceConsensusHash());
3819 af.viewport.setGlobalColourScheme(cs);
3820 af.viewport.setColourAppliesToAllGroups(false);
3822 if (view.getConservationSelected() && cs != null)
3824 cs.setConservationInc(view.getConsThreshold());
3827 af.changeColour(cs);
3829 af.viewport.setColourAppliesToAllGroups(true);
3831 af.viewport.setShowSequenceFeatures(view.getShowSequenceFeatures());
3833 if (view.hasCentreColumnLabels())
3835 af.viewport.setCentreColumnLabels(view.getCentreColumnLabels());
3837 if (view.hasIgnoreGapsinConsensus())
3839 af.viewport.setIgnoreGapsConsensus(view.getIgnoreGapsinConsensus(),
3842 if (view.hasFollowHighlight())
3844 af.viewport.followHighlight = view.getFollowHighlight();
3846 if (view.hasFollowSelection())
3848 af.viewport.followSelection = view.getFollowSelection();
3850 if (view.hasShowConsensusHistogram())
3852 af.viewport.setShowConsensusHistogram(view
3853 .getShowConsensusHistogram());
3857 af.viewport.setShowConsensusHistogram(true);
3859 if (view.hasShowSequenceLogo())
3861 af.viewport.setShowSequenceLogo(view.getShowSequenceLogo());
3865 af.viewport.setShowSequenceLogo(false);
3867 if (view.hasNormaliseSequenceLogo())
3869 af.viewport.setNormaliseSequenceLogo(view.getNormaliseSequenceLogo());
3871 if (view.hasShowDbRefTooltip())
3873 af.viewport.setShowDBRefs(view.getShowDbRefTooltip());
3875 if (view.hasShowNPfeatureTooltip())
3877 af.viewport.setShowNPFeats(view.hasShowNPfeatureTooltip());
3879 if (view.hasShowGroupConsensus())
3881 af.viewport.setShowGroupConsensus(view.getShowGroupConsensus());
3885 af.viewport.setShowGroupConsensus(false);
3887 if (view.hasShowGroupConservation())
3889 af.viewport.setShowGroupConservation(view.getShowGroupConservation());
3893 af.viewport.setShowGroupConservation(false);
3896 // recover featre settings
3897 if (jms.getFeatureSettings() != null)
3899 FeaturesDisplayed fdi;
3900 af.viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
3901 String[] renderOrder = new String[jms.getFeatureSettings()
3902 .getSettingCount()];
3903 Hashtable featureGroups = new Hashtable();
3904 Hashtable featureColours = new Hashtable();
3905 Hashtable featureOrder = new Hashtable();
3907 for (int fs = 0; fs < jms.getFeatureSettings().getSettingCount(); fs++)
3909 Setting setting = jms.getFeatureSettings().getSetting(fs);
3910 if (setting.hasMincolour())
3912 GraduatedColor gc = setting.hasMin() ? new GraduatedColor(
3913 new java.awt.Color(setting.getMincolour()),
3914 new java.awt.Color(setting.getColour()),
3915 setting.getMin(), setting.getMax()) : new GraduatedColor(
3916 new java.awt.Color(setting.getMincolour()),
3917 new java.awt.Color(setting.getColour()), 0, 1);
3918 if (setting.hasThreshold())
3920 gc.setThresh(setting.getThreshold());
3921 gc.setThreshType(setting.getThreshstate());
3923 gc.setAutoScaled(true); // default
3924 if (setting.hasAutoScale())
3926 gc.setAutoScaled(setting.getAutoScale());
3928 if (setting.hasColourByLabel())
3930 gc.setColourByLabel(setting.getColourByLabel());
3932 // and put in the feature colour table.
3933 featureColours.put(setting.getType(), gc);
3937 featureColours.put(setting.getType(),
3938 new java.awt.Color(setting.getColour()));
3940 renderOrder[fs] = setting.getType();
3941 if (setting.hasOrder())
3943 featureOrder.put(setting.getType(), setting.getOrder());
3947 featureOrder.put(setting.getType(), new Float(fs
3948 / jms.getFeatureSettings().getSettingCount()));
3950 if (setting.getDisplay())
3952 fdi.setVisible(setting.getType());
3955 Hashtable fgtable = new Hashtable();
3956 for (int gs = 0; gs < jms.getFeatureSettings().getGroupCount(); gs++)
3958 Group grp = jms.getFeatureSettings().getGroup(gs);
3959 fgtable.put(grp.getName(), new Boolean(grp.getDisplay()));
3961 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
3962 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
3963 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
3964 FeatureRendererSettings frs = new FeatureRendererSettings(
3965 renderOrder, fgtable, featureColours, 1.0f, featureOrder);
3966 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
3967 .transferSettings(frs);
3971 if (view.getHiddenColumnsCount() > 0)
3973 for (int c = 0; c < view.getHiddenColumnsCount(); c++)
3975 af.viewport.hideColumns(view.getHiddenColumns(c).getStart(), view
3976 .getHiddenColumns(c).getEnd() // +1
3980 if (view.getCalcIdParam() != null)
3982 for (CalcIdParam calcIdParam : view.getCalcIdParam())
3984 if (calcIdParam != null)
3986 if (recoverCalcIdParam(calcIdParam, af.viewport))
3991 warn("Couldn't recover parameters for "
3992 + calcIdParam.getCalcId());
3997 af.setMenusFromViewport(af.viewport);
3999 // TODO: we don't need to do this if the viewport is aready visible.
4001 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
4002 * has a 'cdna/protein complement' view, in which case save it in order to
4003 * populate a SplitFrame once all views have been read in.
4005 String complementaryViewId = view.getComplementId();
4006 if (complementaryViewId == null)
4008 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
4010 // recompute any autoannotation
4011 af.alignPanel.updateAnnotation(false, true);
4012 reorderAutoannotation(af, al, autoAlan);
4013 af.alignPanel.alignmentChanged();
4017 splitFrameCandidates.put(view, af);
4022 private ColourSchemeI constructAnnotationColour(
4023 AnnotationColours viewAnnColour, AlignFrame af, Alignment al,
4024 JalviewModelSequence jms, boolean checkGroupAnnColour)
4026 boolean propagateAnnColour = false;
4027 ColourSchemeI cs = null;
4028 AlignmentI annAlignment = af != null ? af.viewport.getAlignment() : al;
4029 if (checkGroupAnnColour && al.getGroups() != null
4030 && al.getGroups().size() > 0)
4032 // pre 2.8.1 behaviour
4033 // check to see if we should transfer annotation colours
4034 propagateAnnColour = true;
4035 for (jalview.datamodel.SequenceGroup sg : al.getGroups())
4037 if (sg.cs instanceof AnnotationColourGradient)
4039 propagateAnnColour = false;
4043 // int find annotation
4044 if (annAlignment.getAlignmentAnnotation() != null)
4046 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
4048 if (annAlignment.getAlignmentAnnotation()[i].label
4049 .equals(viewAnnColour.getAnnotation()))
4051 if (annAlignment.getAlignmentAnnotation()[i].getThreshold() == null)
4053 annAlignment.getAlignmentAnnotation()[i]
4054 .setThreshold(new jalview.datamodel.GraphLine(
4055 viewAnnColour.getThreshold(), "Threshold",
4056 java.awt.Color.black)
4061 if (viewAnnColour.getColourScheme().equals("None"))
4063 cs = new AnnotationColourGradient(
4064 annAlignment.getAlignmentAnnotation()[i],
4065 new java.awt.Color(viewAnnColour.getMinColour()),
4066 new java.awt.Color(viewAnnColour.getMaxColour()),
4067 viewAnnColour.getAboveThreshold());
4069 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
4071 cs = new AnnotationColourGradient(
4072 annAlignment.getAlignmentAnnotation()[i],
4073 getUserColourScheme(jms,
4074 viewAnnColour.getColourScheme()),
4075 viewAnnColour.getAboveThreshold());
4079 cs = new AnnotationColourGradient(
4080 annAlignment.getAlignmentAnnotation()[i],
4081 ColourSchemeProperty.getColour(al,
4082 viewAnnColour.getColourScheme()),
4083 viewAnnColour.getAboveThreshold());
4085 if (viewAnnColour.hasPerSequence())
4087 ((AnnotationColourGradient) cs).setSeqAssociated(viewAnnColour
4090 if (viewAnnColour.hasPredefinedColours())
4092 ((AnnotationColourGradient) cs)
4093 .setPredefinedColours(viewAnnColour
4094 .isPredefinedColours());
4096 if (propagateAnnColour && al.getGroups() != null)
4098 // Also use these settings for all the groups
4099 for (int g = 0; g < al.getGroups().size(); g++)
4101 jalview.datamodel.SequenceGroup sg = al.getGroups().get(g);
4109 * if (viewAnnColour.getColourScheme().equals("None" )) { sg.cs =
4110 * new AnnotationColourGradient(
4111 * annAlignment.getAlignmentAnnotation()[i], new
4112 * java.awt.Color(viewAnnColour. getMinColour()), new
4113 * java.awt.Color(viewAnnColour. getMaxColour()),
4114 * viewAnnColour.getAboveThreshold()); } else
4117 sg.cs = new AnnotationColourGradient(
4118 annAlignment.getAlignmentAnnotation()[i], sg.cs,
4119 viewAnnColour.getAboveThreshold());
4120 if (cs instanceof AnnotationColourGradient)
4122 if (viewAnnColour.hasPerSequence())
4124 ((AnnotationColourGradient) cs)
4125 .setSeqAssociated(viewAnnColour.isPerSequence());
4127 if (viewAnnColour.hasPredefinedColours())
4129 ((AnnotationColourGradient) cs)
4130 .setPredefinedColours(viewAnnColour
4131 .isPredefinedColours());
4147 private void reorderAutoannotation(AlignFrame af, Alignment al,
4148 List<JvAnnotRow> autoAlan)
4150 // copy over visualization settings for autocalculated annotation in the
4152 if (al.getAlignmentAnnotation() != null)
4155 * Kludge for magic autoannotation names (see JAL-811)
4157 String[] magicNames = new String[]
4158 { "Consensus", "Quality", "Conservation" };
4159 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
4160 Hashtable<String, JvAnnotRow> visan = new Hashtable<String, JvAnnotRow>();
4161 for (String nm : magicNames)
4163 visan.put(nm, nullAnnot);
4165 for (JvAnnotRow auan : autoAlan)
4167 visan.put(auan.template.label
4168 + (auan.template.getCalcId() == null ? "" : "\t"
4169 + auan.template.getCalcId()), auan);
4171 int hSize = al.getAlignmentAnnotation().length;
4172 List<JvAnnotRow> reorder = new ArrayList<JvAnnotRow>();
4173 // work through any autoCalculated annotation already on the view
4174 // removing it if it should be placed in a different location on the
4175 // annotation panel.
4176 List<String> remains = new ArrayList<String>(visan.keySet());
4177 for (int h = 0; h < hSize; h++)
4179 jalview.datamodel.AlignmentAnnotation jalan = al
4180 .getAlignmentAnnotation()[h];
4181 if (jalan.autoCalculated)
4184 JvAnnotRow valan = visan.get(k = jalan.label);
4185 if (jalan.getCalcId() != null)
4187 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
4192 // delete the auto calculated row from the alignment
4193 al.deleteAnnotation(jalan, false);
4197 if (valan != nullAnnot)
4199 if (jalan != valan.template)
4201 // newly created autoannotation row instance
4202 // so keep a reference to the visible annotation row
4203 // and copy over all relevant attributes
4204 if (valan.template.graphHeight >= 0)
4207 jalan.graphHeight = valan.template.graphHeight;
4209 jalan.visible = valan.template.visible;
4211 reorder.add(new JvAnnotRow(valan.order, jalan));
4216 // Add any (possibly stale) autocalculated rows that were not appended to
4217 // the view during construction
4218 for (String other : remains)
4220 JvAnnotRow othera = visan.get(other);
4221 if (othera != nullAnnot && othera.template.getCalcId() != null
4222 && othera.template.getCalcId().length() > 0)
4224 reorder.add(othera);
4227 // now put the automatic annotation in its correct place
4228 int s = 0, srt[] = new int[reorder.size()];
4229 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
4230 for (JvAnnotRow jvar : reorder)
4233 srt[s++] = jvar.order;
4236 jalview.util.QuickSort.sort(srt, rws);
4237 // and re-insert the annotation at its correct position
4238 for (JvAnnotRow jvar : rws)
4240 al.addAnnotation(jvar.template, jvar.order);
4242 af.alignPanel.adjustAnnotationHeight();
4246 Hashtable skipList = null;
4249 * TODO remove this method
4252 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
4253 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
4254 * throw new Error("Implementation Error. No skipList defined for this
4255 * Jalview2XML instance."); } return (AlignFrame)
4256 * skipList.get(view.getSequenceSetId()); }
4260 * Check if the Jalview view contained in object should be skipped or not.
4263 * @return true if view's sequenceSetId is a key in skipList
4265 private boolean skipViewport(JalviewModel object)
4267 if (skipList == null)
4272 if (skipList.containsKey(id = object.getJalviewModelSequence()
4273 .getViewport()[0].getSequenceSetId()))
4275 if (Cache.log != null && Cache.log.isDebugEnabled())
4277 Cache.log.debug("Skipping seuqence set id " + id);
4284 public void addToSkipList(AlignFrame af)
4286 if (skipList == null)
4288 skipList = new Hashtable();
4290 skipList.put(af.getViewport().getSequenceSetId(), af);
4293 public void clearSkipList()
4295 if (skipList != null)
4302 private void recoverDatasetFor(SequenceSet vamsasSet, Alignment al,
4303 boolean ignoreUnrefed)
4305 jalview.datamodel.Alignment ds = getDatasetFor(vamsasSet.getDatasetId());
4306 Vector dseqs = null;
4309 // create a list of new dataset sequences
4310 dseqs = new Vector();
4312 for (int i = 0, iSize = vamsasSet.getSequenceCount(); i < iSize; i++)
4314 Sequence vamsasSeq = vamsasSet.getSequence(i);
4315 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed);
4317 // create a new dataset
4320 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
4321 dseqs.copyInto(dsseqs);
4322 ds = new jalview.datamodel.Alignment(dsseqs);
4323 debug("Created new dataset " + vamsasSet.getDatasetId()
4324 + " for alignment " + System.identityHashCode(al));
4325 addDatasetRef(vamsasSet.getDatasetId(), ds);
4327 // set the dataset for the newly imported alignment.
4328 if (al.getDataset() == null && !ignoreUnrefed)
4337 * sequence definition to create/merge dataset sequence for
4341 * vector to add new dataset sequence to
4343 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
4344 AlignmentI ds, Vector dseqs, boolean ignoreUnrefed)
4346 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
4348 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
4349 SequenceI dsq = null;
4350 if (sq != null && sq.getDatasetSequence() != null)
4352 dsq = sq.getDatasetSequence();
4354 if (sq == null && ignoreUnrefed)
4358 String sqid = vamsasSeq.getDsseqid();
4361 // need to create or add a new dataset sequence reference to this sequence
4364 dsq = seqRefIds.get(sqid);
4369 // make a new dataset sequence
4370 dsq = sq.createDatasetSequence();
4373 // make up a new dataset reference for this sequence
4374 sqid = seqHash(dsq);
4376 dsq.setVamsasId(uniqueSetSuffix + sqid);
4377 seqRefIds.put(sqid, dsq);
4382 dseqs.addElement(dsq);
4387 ds.addSequence(dsq);
4393 { // make this dataset sequence sq's dataset sequence
4394 sq.setDatasetSequence(dsq);
4395 // and update the current dataset alignment
4400 if (!dseqs.contains(dsq))
4407 if (ds.findIndex(dsq) < 0)
4409 ds.addSequence(dsq);
4416 // TODO: refactor this as a merge dataset sequence function
4417 // now check that sq (the dataset sequence) sequence really is the union of
4418 // all references to it
4419 // boolean pre = sq.getStart() < dsq.getStart();
4420 // boolean post = sq.getEnd() > dsq.getEnd();
4424 // StringBuffer sb = new StringBuffer();
4425 String newres = jalview.analysis.AlignSeq.extractGaps(
4426 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
4427 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
4428 && newres.length() > dsq.getLength())
4430 // Update with the longer sequence.
4434 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
4435 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
4436 * sb.append(newres.substring(newres.length() - sq.getEnd() -
4437 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
4439 dsq.setSequence(newres);
4441 // TODO: merges will never happen if we 'know' we have the real dataset
4442 // sequence - this should be detected when id==dssid
4444 .println("DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
4445 // + (pre ? "prepended" : "") + " "
4446 // + (post ? "appended" : ""));
4451 java.util.Hashtable datasetIds = null;
4453 java.util.IdentityHashMap dataset2Ids = null;
4455 private Alignment getDatasetFor(String datasetId)
4457 if (datasetIds == null)
4459 datasetIds = new Hashtable();
4462 if (datasetIds.containsKey(datasetId))
4464 return (Alignment) datasetIds.get(datasetId);
4469 private void addDatasetRef(String datasetId, Alignment dataset)
4471 if (datasetIds == null)
4473 datasetIds = new Hashtable();
4475 datasetIds.put(datasetId, dataset);
4479 * make a new dataset ID for this jalview dataset alignment
4484 private String getDatasetIdRef(jalview.datamodel.Alignment dataset)
4486 if (dataset.getDataset() != null)
4488 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
4490 String datasetId = makeHashCode(dataset, null);
4491 if (datasetId == null)
4493 // make a new datasetId and record it
4494 if (dataset2Ids == null)
4496 dataset2Ids = new IdentityHashMap();
4500 datasetId = (String) dataset2Ids.get(dataset);
4502 if (datasetId == null)
4504 datasetId = "ds" + dataset2Ids.size() + 1;
4505 dataset2Ids.put(dataset, datasetId);
4511 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
4513 for (int d = 0; d < sequence.getDBRefCount(); d++)
4515 DBRef dr = sequence.getDBRef(d);
4516 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
4517 sequence.getDBRef(d).getSource(), sequence.getDBRef(d)
4518 .getVersion(), sequence.getDBRef(d).getAccessionId());
4519 if (dr.getMapping() != null)
4521 entry.setMap(addMapping(dr.getMapping()));
4523 datasetSequence.addDBRef(entry);
4527 private jalview.datamodel.Mapping addMapping(Mapping m)
4529 SequenceI dsto = null;
4530 // Mapping m = dr.getMapping();
4531 int fr[] = new int[m.getMapListFromCount() * 2];
4532 Enumeration f = m.enumerateMapListFrom();
4533 for (int _i = 0; f.hasMoreElements(); _i += 2)
4535 MapListFrom mf = (MapListFrom) f.nextElement();
4536 fr[_i] = mf.getStart();
4537 fr[_i + 1] = mf.getEnd();
4539 int fto[] = new int[m.getMapListToCount() * 2];
4540 f = m.enumerateMapListTo();
4541 for (int _i = 0; f.hasMoreElements(); _i += 2)
4543 MapListTo mf = (MapListTo) f.nextElement();
4544 fto[_i] = mf.getStart();
4545 fto[_i + 1] = mf.getEnd();
4547 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto,
4548 fr, fto, (int) m.getMapFromUnit(), (int) m.getMapToUnit());
4549 if (m.getMappingChoice() != null)
4551 MappingChoice mc = m.getMappingChoice();
4552 if (mc.getDseqFor() != null)
4554 String dsfor = "" + mc.getDseqFor();
4555 if (seqRefIds.containsKey(dsfor))
4560 jmap.setTo(seqRefIds.get(dsfor));
4564 frefedSequence.add(new Object[]
4571 * local sequence definition
4573 Sequence ms = mc.getSequence();
4574 SequenceI djs = null;
4575 String sqid = ms.getDsseqid();
4576 if (sqid != null && sqid.length() > 0)
4579 * recover dataset sequence
4581 djs = seqRefIds.get(sqid);
4586 .println("Warning - making up dataset sequence id for DbRef sequence map reference");
4587 sqid = ((Object) ms).toString(); // make up a new hascode for
4588 // undefined dataset sequence hash
4589 // (unlikely to happen)
4595 * make a new dataset sequence and add it to refIds hash
4597 djs = new jalview.datamodel.Sequence(ms.getName(),
4599 djs.setStart(jmap.getMap().getToLowest());
4600 djs.setEnd(jmap.getMap().getToHighest());
4601 djs.setVamsasId(uniqueSetSuffix + sqid);
4603 seqRefIds.put(sqid, djs);
4606 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
4615 public jalview.gui.AlignmentPanel copyAlignPanel(AlignmentPanel ap,
4616 boolean keepSeqRefs)
4619 jalview.schemabinding.version2.JalviewModel jm = saveState(ap, null,
4625 jm.getJalviewModelSequence().getViewport(0).setSequenceSetId(null);
4629 uniqueSetSuffix = "";
4630 jm.getJalviewModelSequence().getViewport(0).setId(null); // we don't
4635 if (this.frefedSequence == null)
4637 frefedSequence = new Vector();
4640 viewportsAdded.clear();
4642 AlignFrame af = loadFromObject(jm, null, false, null);
4643 af.alignPanels.clear();
4644 af.closeMenuItem_actionPerformed(true);
4647 * if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
4648 * i<ap.av.getAlignment().getAlignmentAnnotation().length; i++) {
4649 * if(!ap.av.getAlignment().getAlignmentAnnotation()[i].autoCalculated) {
4650 * af.alignPanel.av.getAlignment().getAlignmentAnnotation()[i] =
4651 * ap.av.getAlignment().getAlignmentAnnotation()[i]; } } }
4654 return af.alignPanel;
4658 * flag indicating if hashtables should be cleared on finalization TODO this
4659 * flag may not be necessary
4661 private final boolean _cleartables = true;
4663 private Hashtable jvids2vobj;
4668 * @see java.lang.Object#finalize()
4671 protected void finalize() throws Throwable
4673 // really make sure we have no buried refs left.
4678 this.seqRefIds = null;
4679 this.seqsToIds = null;
4683 private void warn(String msg)
4688 private void warn(String msg, Exception e)
4690 if (Cache.log != null)
4694 Cache.log.warn(msg, e);
4698 Cache.log.warn(msg);
4703 System.err.println("Warning: " + msg);
4706 e.printStackTrace();
4711 private void debug(String string)
4713 debug(string, null);
4716 private void debug(String msg, Exception e)
4718 if (Cache.log != null)
4722 Cache.log.debug(msg, e);
4726 Cache.log.debug(msg);
4731 System.err.println("Warning: " + msg);
4734 e.printStackTrace();
4740 * set the object to ID mapping tables used to write/recover objects and XML
4741 * ID strings for the jalview project. If external tables are provided then
4742 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
4743 * object goes out of scope. - also populates the datasetIds hashtable with
4744 * alignment objects containing dataset sequences
4747 * Map from ID strings to jalview datamodel
4749 * Map from jalview datamodel to ID strings
4753 public void setObjectMappingTables(Hashtable vobj2jv,
4754 IdentityHashMap jv2vobj)
4756 this.jv2vobj = jv2vobj;
4757 this.vobj2jv = vobj2jv;
4758 Iterator ds = jv2vobj.keySet().iterator();
4760 while (ds.hasNext())
4762 Object jvobj = ds.next();
4763 id = jv2vobj.get(jvobj).toString();
4764 if (jvobj instanceof jalview.datamodel.Alignment)
4766 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
4768 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
4771 else if (jvobj instanceof jalview.datamodel.Sequence)
4773 // register sequence object so the XML parser can recover it.
4774 if (seqRefIds == null)
4776 seqRefIds = new HashMap<String, SequenceI>();
4778 if (seqsToIds == null)
4780 seqsToIds = new IdentityHashMap<SequenceI, String>();
4782 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
4783 seqsToIds.put((SequenceI) jvobj, id);
4785 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
4788 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
4789 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
4790 if (jvann.annotationId == null)
4792 jvann.annotationId = anid;
4794 if (!jvann.annotationId.equals(anid))
4796 // TODO verify that this is the correct behaviour
4797 this.warn("Overriding Annotation ID for " + anid
4798 + " from different id : " + jvann.annotationId);
4799 jvann.annotationId = anid;
4802 else if (jvobj instanceof String)
4804 if (jvids2vobj == null)
4806 jvids2vobj = new Hashtable();
4807 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
4812 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
4818 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
4819 * objects created from the project archive. If string is null (default for
4820 * construction) then suffix will be set automatically.
4824 public void setUniqueSetSuffix(String string)
4826 uniqueSetSuffix = string;
4831 * uses skipList2 as the skipList for skipping views on sequence sets
4832 * associated with keys in the skipList
4836 public void setSkipList(Hashtable skipList2)
4838 skipList = skipList2;