2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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.FeatureColourI;
24 import jalview.api.ViewStyleI;
25 import jalview.api.structures.JalviewStructureDisplayI;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignedCodonFrame;
28 import jalview.datamodel.Alignment;
29 import jalview.datamodel.AlignmentAnnotation;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.RnaViewerModel;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.datamodel.StructureViewerModel;
36 import jalview.datamodel.StructureViewerModel.StructureData;
37 import jalview.ext.varna.RnaModel;
38 import jalview.gui.StructureViewer.ViewerType;
39 import jalview.schemabinding.version2.AlcodMap;
40 import jalview.schemabinding.version2.AlcodonFrame;
41 import jalview.schemabinding.version2.Annotation;
42 import jalview.schemabinding.version2.AnnotationColours;
43 import jalview.schemabinding.version2.AnnotationElement;
44 import jalview.schemabinding.version2.CalcIdParam;
45 import jalview.schemabinding.version2.DBRef;
46 import jalview.schemabinding.version2.Features;
47 import jalview.schemabinding.version2.Group;
48 import jalview.schemabinding.version2.HiddenColumns;
49 import jalview.schemabinding.version2.JGroup;
50 import jalview.schemabinding.version2.JSeq;
51 import jalview.schemabinding.version2.JalviewModel;
52 import jalview.schemabinding.version2.JalviewModelSequence;
53 import jalview.schemabinding.version2.MapListFrom;
54 import jalview.schemabinding.version2.MapListTo;
55 import jalview.schemabinding.version2.Mapping;
56 import jalview.schemabinding.version2.MappingChoice;
57 import jalview.schemabinding.version2.OtherData;
58 import jalview.schemabinding.version2.PdbentryItem;
59 import jalview.schemabinding.version2.Pdbids;
60 import jalview.schemabinding.version2.Property;
61 import jalview.schemabinding.version2.RnaViewer;
62 import jalview.schemabinding.version2.SecondaryStructure;
63 import jalview.schemabinding.version2.Sequence;
64 import jalview.schemabinding.version2.SequenceSet;
65 import jalview.schemabinding.version2.SequenceSetProperties;
66 import jalview.schemabinding.version2.Setting;
67 import jalview.schemabinding.version2.StructureState;
68 import jalview.schemabinding.version2.ThresholdLine;
69 import jalview.schemabinding.version2.Tree;
70 import jalview.schemabinding.version2.UserColours;
71 import jalview.schemabinding.version2.Viewport;
72 import jalview.schemes.AnnotationColourGradient;
73 import jalview.schemes.ColourSchemeI;
74 import jalview.schemes.ColourSchemeProperty;
75 import jalview.schemes.FeatureColour;
76 import jalview.schemes.ResidueColourScheme;
77 import jalview.schemes.ResidueProperties;
78 import jalview.schemes.UserColourScheme;
79 import jalview.structure.StructureSelectionManager;
80 import jalview.structures.models.AAStructureBindingModel;
81 import jalview.util.MessageManager;
82 import jalview.util.Platform;
83 import jalview.util.StringUtils;
84 import jalview.util.jarInputStreamProvider;
85 import jalview.viewmodel.AlignmentViewport;
86 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
87 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
88 import jalview.ws.jws2.Jws2Discoverer;
89 import jalview.ws.jws2.dm.AAConSettings;
90 import jalview.ws.jws2.jabaws2.Jws2Instance;
91 import jalview.ws.params.ArgumentI;
92 import jalview.ws.params.AutoCalcSetting;
93 import jalview.ws.params.WsParamSetI;
95 import java.awt.Color;
96 import java.awt.Rectangle;
97 import java.io.BufferedReader;
98 import java.io.DataInputStream;
99 import java.io.DataOutputStream;
101 import java.io.FileInputStream;
102 import java.io.FileOutputStream;
103 import java.io.IOException;
104 import java.io.InputStreamReader;
105 import java.io.OutputStreamWriter;
106 import java.io.PrintWriter;
107 import java.lang.reflect.InvocationTargetException;
108 import java.net.MalformedURLException;
110 import java.util.ArrayList;
111 import java.util.Arrays;
112 import java.util.Enumeration;
113 import java.util.HashMap;
114 import java.util.HashSet;
115 import java.util.Hashtable;
116 import java.util.IdentityHashMap;
117 import java.util.Iterator;
118 import java.util.LinkedHashMap;
119 import java.util.List;
120 import java.util.Map;
121 import java.util.Map.Entry;
122 import java.util.Set;
123 import java.util.Vector;
124 import java.util.jar.JarEntry;
125 import java.util.jar.JarInputStream;
126 import java.util.jar.JarOutputStream;
128 import javax.swing.JInternalFrame;
129 import javax.swing.JOptionPane;
130 import javax.swing.SwingUtilities;
132 import org.exolab.castor.xml.Marshaller;
133 import org.exolab.castor.xml.Unmarshaller;
136 * Write out the current jalview desktop state as a Jalview XML stream.
138 * Note: the vamsas objects referred to here are primitive versions of the
139 * VAMSAS project schema elements - they are not the same and most likely never
143 * @version $Revision: 1.134 $
145 public class Jalview2XML
147 private static final String VIEWER_PREFIX = "viewer_";
149 private static final String RNA_PREFIX = "rna_";
151 private static final String UTF_8 = "UTF-8";
153 // use this with nextCounter() to make unique names for entities
154 private int counter = 0;
157 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
158 * of sequence objects are created.
160 IdentityHashMap<SequenceI, String> seqsToIds = null;
163 * jalview XML Sequence ID to jalview sequence object reference (both dataset
164 * and alignment sequences. Populated as XML reps of sequence objects are
167 Map<String, SequenceI> seqRefIds = null;
169 Map<String, SequenceI> incompleteSeqs = null;
171 List<SeqFref> frefedSequence = null;
173 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
176 * Map of reconstructed AlignFrame objects that appear to have come from
177 * SplitFrame objects (have a dna/protein complement view).
179 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<Viewport, AlignFrame>();
182 * Map from displayed rna structure models to their saved session state jar
185 private Map<RnaModel, String> rnaSessions = new HashMap<RnaModel, String>();
188 * create/return unique hash string for sq
191 * @return new or existing unique string for sq
193 String seqHash(SequenceI sq)
195 if (seqsToIds == null)
199 if (seqsToIds.containsKey(sq))
201 return seqsToIds.get(sq);
205 // create sequential key
206 String key = "sq" + (seqsToIds.size() + 1);
207 key = makeHashCode(sq, key); // check we don't have an external reference
209 seqsToIds.put(sq, key);
218 if (seqRefIds != null)
222 if (seqsToIds != null)
226 if (incompleteSeqs != null)
228 incompleteSeqs.clear();
236 warn("clearSeqRefs called when _cleartables was not set. Doing nothing.");
237 // seqRefIds = new Hashtable();
238 // seqsToIds = new IdentityHashMap();
244 if (seqsToIds == null)
246 seqsToIds = new IdentityHashMap<SequenceI, String>();
248 if (seqRefIds == null)
250 seqRefIds = new HashMap<String, SequenceI>();
252 if (incompleteSeqs == null)
254 incompleteSeqs = new HashMap<String, SequenceI>();
256 if (frefedSequence == null)
258 frefedSequence = new ArrayList<SeqFref>();
266 public Jalview2XML(boolean raiseGUI)
268 this.raiseGUI = raiseGUI;
272 * base class for resolving forward references to sequences by their ID
277 abstract class SeqFref
283 public SeqFref(String _sref, String type)
289 public String getSref()
294 public SequenceI getSrefSeq()
296 return seqRefIds.get(sref);
299 public boolean isResolvable()
301 return seqRefIds.get(sref) != null;
304 public SequenceI getSrefDatasetSeq()
306 SequenceI sq = seqRefIds.get(sref);
309 while (sq.getDatasetSequence() != null)
311 sq = sq.getDatasetSequence();
317 * @return true if the forward reference was fully resolved
319 abstract boolean resolve();
322 public String toString()
324 return type + " reference to " + sref;
329 * create forward reference for a mapping
335 public SeqFref newMappingRef(final String sref,
336 final jalview.datamodel.Mapping _jmap)
338 SeqFref fref = new SeqFref(sref, "Mapping")
340 public jalview.datamodel.Mapping jmap = _jmap;
345 SequenceI seq = getSrefDatasetSeq();
357 public SeqFref newAlcodMapRef(final String sref,
358 final AlignedCodonFrame _cf, final jalview.datamodel.Mapping _jmap)
361 SeqFref fref = new SeqFref(sref, "Codon Frame")
363 AlignedCodonFrame cf = _cf;
365 public jalview.datamodel.Mapping mp = _jmap;
368 public boolean isResolvable()
370 return super.isResolvable() && mp.getTo() != null;
376 SequenceI seq = getSrefDatasetSeq();
381 cf.addMap(seq, mp.getTo(), mp.getMap());
388 public void resolveFrefedSequences()
390 Iterator<SeqFref> nextFref=frefedSequence.iterator();
391 int toresolve=frefedSequence.size();
392 int unresolved=0,failedtoresolve=0;
393 while (nextFref.hasNext()) {
394 SeqFref ref = nextFref.next();
395 if (ref.isResolvable())
404 } catch (Exception x) {
405 System.err.println("IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "+ref.getSref());
415 System.err.println("Jalview Project Import: There were " + unresolved
416 + " forward references left unresolved on the stack.");
418 if (failedtoresolve>0)
420 System.err.println("SERIOUS! " + failedtoresolve
421 + " resolvable forward references failed to resolve.");
423 if (incompleteSeqs != null && incompleteSeqs.size() > 0)
425 System.err.println("Jalview Project Import: There are "
426 + incompleteSeqs.size()
427 + " sequences which may have incomplete metadata.");
428 if (incompleteSeqs.size() < 10)
430 for (SequenceI s : incompleteSeqs.values())
432 System.err.println(s.toString());
438 .println("Too many to report. Skipping output of incomplete sequences.");
444 * This maintains a map of viewports, the key being the seqSetId. Important to
445 * set historyItem and redoList for multiple views
447 Map<String, AlignViewport> viewportsAdded = new HashMap<String, AlignViewport>();
449 Map<String, AlignmentAnnotation> annotationIds = new HashMap<String, AlignmentAnnotation>();
451 String uniqueSetSuffix = "";
454 * List of pdbfiles added to Jar
456 List<String> pdbfiles = null;
458 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
459 public void saveState(File statefile)
461 FileOutputStream fos = null;
464 fos = new FileOutputStream(statefile);
465 JarOutputStream jout = new JarOutputStream(fos);
468 } catch (Exception e)
470 // TODO: inform user of the problem - they need to know if their data was
472 if (errorMessage == null)
474 errorMessage = "Couldn't write Jalview Archive to output file '"
475 + statefile + "' - See console error log for details";
479 errorMessage += "(output file was '" + statefile + "')";
489 } catch (IOException e)
499 * Writes a jalview project archive to the given Jar output stream.
503 public void saveState(JarOutputStream jout)
505 AlignFrame[] frames = Desktop.getAlignFrames();
511 saveAllFrames(Arrays.asList(frames), jout);
515 * core method for storing state for a set of AlignFrames.
518 * - frames involving all data to be exported (including containing
521 * - project output stream
523 private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
525 Hashtable<String, AlignFrame> dsses = new Hashtable<String, AlignFrame>();
528 * ensure cached data is clear before starting
530 // todo tidy up seqRefIds, seqsToIds initialisation / reset
532 splitFrameCandidates.clear();
537 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
538 // //////////////////////////////////////////////////
540 List<String> shortNames = new ArrayList<String>();
541 List<String> viewIds = new ArrayList<String>();
544 for (int i = frames.size() - 1; i > -1; i--)
546 AlignFrame af = frames.get(i);
550 .containsKey(af.getViewport().getSequenceSetId()))
555 String shortName = makeFilename(af, shortNames);
557 int ap, apSize = af.alignPanels.size();
559 for (ap = 0; ap < apSize; ap++)
561 AlignmentPanel apanel = af.alignPanels.get(ap);
562 String fileName = apSize == 1 ? shortName : ap + shortName;
563 if (!fileName.endsWith(".xml"))
565 fileName = fileName + ".xml";
568 saveState(apanel, fileName, jout, viewIds);
570 String dssid = getDatasetIdRef(af.getViewport().getAlignment()
572 if (!dsses.containsKey(dssid))
574 dsses.put(dssid, af);
579 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
585 } catch (Exception foo)
590 } catch (Exception ex)
592 // TODO: inform user of the problem - they need to know if their data was
594 if (errorMessage == null)
596 errorMessage = "Couldn't write Jalview Archive - see error output for details";
598 ex.printStackTrace();
603 * Generates a distinct file name, based on the title of the AlignFrame, by
604 * appending _n for increasing n until an unused name is generated. The new
605 * name (without its extension) is added to the list.
609 * @return the generated name, with .xml extension
611 protected String makeFilename(AlignFrame af, List<String> namesUsed)
613 String shortName = af.getTitle();
615 if (shortName.indexOf(File.separatorChar) > -1)
617 shortName = shortName.substring(shortName
618 .lastIndexOf(File.separatorChar) + 1);
623 while (namesUsed.contains(shortName))
625 if (shortName.endsWith("_" + (count - 1)))
627 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
630 shortName = shortName.concat("_" + count);
634 namesUsed.add(shortName);
636 if (!shortName.endsWith(".xml"))
638 shortName = shortName + ".xml";
643 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
644 public boolean saveAlignment(AlignFrame af, String jarFile,
649 FileOutputStream fos = new FileOutputStream(jarFile);
650 JarOutputStream jout = new JarOutputStream(fos);
651 List<AlignFrame> frames = new ArrayList<AlignFrame>();
653 // resolve splitframes
654 if (af.getViewport().getCodingComplement() != null)
656 frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
662 saveAllFrames(frames, jout);
666 } catch (Exception foo)
672 } catch (Exception ex)
674 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
675 ex.printStackTrace();
680 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
681 String fileName, JarOutputStream jout)
684 for (String dssids : dsses.keySet())
686 AlignFrame _af = dsses.get(dssids);
687 String jfileName = fileName + " Dataset for " + _af.getTitle();
688 if (!jfileName.endsWith(".xml"))
690 jfileName = jfileName + ".xml";
692 saveState(_af.alignPanel, jfileName, true, jout, null);
697 * create a JalviewModel from an alignment view and marshall it to a
701 * panel to create jalview model for
703 * name of alignment panel written to output stream
710 public JalviewModel saveState(AlignmentPanel ap, String fileName,
711 JarOutputStream jout, List<String> viewIds)
713 return saveState(ap, fileName, false, jout, viewIds);
717 * create a JalviewModel from an alignment view and marshall it to a
721 * panel to create jalview model for
723 * name of alignment panel written to output stream
725 * when true, only write the dataset for the alignment, not the data
726 * associated with the view.
732 public JalviewModel saveState(AlignmentPanel ap, String fileName,
733 boolean storeDS, JarOutputStream jout, List<String> viewIds)
737 viewIds = new ArrayList<String>();
742 List<UserColourScheme> userColours = new ArrayList<UserColourScheme>();
744 AlignViewport av = ap.av;
746 JalviewModel object = new JalviewModel();
747 object.setVamsasModel(new jalview.schemabinding.version2.VamsasModel());
749 object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
750 object.setVersion(jalview.bin.Cache.getDefault("VERSION",
751 "Development Build"));
754 * rjal is full height alignment, jal is actual alignment with full metadata
755 * but excludes hidden sequences.
757 jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
759 if (av.hasHiddenRows())
761 rjal = jal.getHiddenSequences().getFullAlignment();
764 SequenceSet vamsasSet = new SequenceSet();
766 JalviewModelSequence jms = new JalviewModelSequence();
768 vamsasSet.setGapChar(jal.getGapCharacter() + "");
770 if (jal.getDataset() != null)
772 // dataset id is the dataset's hashcode
773 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
776 // switch jal and the dataset
777 jal = jal.getDataset();
781 if (jal.getProperties() != null)
783 Enumeration en = jal.getProperties().keys();
784 while (en.hasMoreElements())
786 String key = en.nextElement().toString();
787 SequenceSetProperties ssp = new SequenceSetProperties();
789 ssp.setValue(jal.getProperties().get(key).toString());
790 vamsasSet.addSequenceSetProperties(ssp);
795 Set<String> calcIdSet = new HashSet<String>();
796 // record the set of vamsas sequence XML POJO we create.
797 HashMap<String,Sequence> vamsasSetIds = new HashMap<String,Sequence>();
799 for (final SequenceI jds : rjal.getSequences())
801 final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
802 : jds.getDatasetSequence();
803 String id = seqHash(jds);
804 if (vamsasSetIds.get(id) == null)
806 if (seqRefIds.get(id) != null && !storeDS)
808 // This happens for two reasons: 1. multiple views are being
810 // 2. the hashCode has collided with another sequence's code. This
812 // HAPPEN! (PF00072.15.stk does this)
813 // JBPNote: Uncomment to debug writing out of files that do not read
814 // back in due to ArrayOutOfBoundExceptions.
815 // System.err.println("vamsasSeq backref: "+id+"");
816 // System.err.println(jds.getName()+"
817 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
818 // System.err.println("Hashcode: "+seqHash(jds));
819 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
820 // System.err.println(rsq.getName()+"
821 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
822 // System.err.println("Hashcode: "+seqHash(rsq));
826 vamsasSeq = createVamsasSequence(id, jds);
827 vamsasSet.addSequence(vamsasSeq);
828 vamsasSetIds.put(id, vamsasSeq);
829 seqRefIds.put(id, jds);
833 jseq.setStart(jds.getStart());
834 jseq.setEnd(jds.getEnd());
835 jseq.setColour(av.getSequenceColour(jds).getRGB());
837 jseq.setId(id); // jseq id should be a string not a number
840 // Store any sequences this sequence represents
841 if (av.hasHiddenRows())
843 // use rjal, contains the full height alignment
844 jseq.setHidden(av.getAlignment().getHiddenSequences()
847 if (av.isHiddenRepSequence(jds))
849 jalview.datamodel.SequenceI[] reps = av
850 .getRepresentedSequences(jds)
851 .getSequencesInOrder(rjal);
853 for (int h = 0; h < reps.length; h++)
857 jseq.addHiddenSequences(rjal.findIndex(reps[h]));
862 // mark sequence as reference - if it is the reference for this view
865 jseq.setViewreference(jds == jal.getSeqrep());
869 // TODO: omit sequence features from each alignment view's XML dump if we
870 // are storing dataset
871 if (jds.getSequenceFeatures() != null)
873 jalview.datamodel.SequenceFeature[] sf = jds.getSequenceFeatures();
875 while (index < sf.length)
877 Features features = new Features();
879 features.setBegin(sf[index].getBegin());
880 features.setEnd(sf[index].getEnd());
881 features.setDescription(sf[index].getDescription());
882 features.setType(sf[index].getType());
883 features.setFeatureGroup(sf[index].getFeatureGroup());
884 features.setScore(sf[index].getScore());
885 if (sf[index].links != null)
887 for (int l = 0; l < sf[index].links.size(); l++)
889 OtherData keyValue = new OtherData();
890 keyValue.setKey("LINK_" + l);
891 keyValue.setValue(sf[index].links.elementAt(l).toString());
892 features.addOtherData(keyValue);
895 if (sf[index].otherDetails != null)
898 Iterator<String> keys = sf[index].otherDetails.keySet()
900 while (keys.hasNext())
903 OtherData keyValue = new OtherData();
904 keyValue.setKey(key);
905 keyValue.setValue(sf[index].otherDetails.get(key).toString());
906 features.addOtherData(keyValue);
910 jseq.addFeatures(features);
915 if (jdatasq.getAllPDBEntries() != null)
917 Enumeration en = jdatasq.getAllPDBEntries().elements();
918 while (en.hasMoreElements())
920 Pdbids pdb = new Pdbids();
921 jalview.datamodel.PDBEntry entry = (jalview.datamodel.PDBEntry) en
924 String pdbId = entry.getId();
926 pdb.setType(entry.getType());
929 * Store any structure views associated with this sequence. This
930 * section copes with duplicate entries in the project, so a dataset
931 * only view *should* be coped with sensibly.
933 // This must have been loaded, is it still visible?
934 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
935 String matchedFile = null;
936 for (int f = frames.length - 1; f > -1; f--)
938 if (frames[f] instanceof StructureViewerBase)
940 StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
941 matchedFile = saveStructureState(ap, jds, pdb, entry,
942 viewIds, matchedFile, viewFrame);
944 * Only store each structure viewer's state once in the project
945 * jar. First time through only (storeDS==false)
947 String viewId = viewFrame.getViewId();
948 if (!storeDS && !viewIds.contains(viewId))
953 String viewerState = viewFrame.getStateInfo();
954 writeJarEntry(jout, getViewerJarEntryName(viewId),
955 viewerState.getBytes());
956 } catch (IOException e)
958 System.err.println("Error saving viewer state: "
965 if (matchedFile != null || entry.getFile() != null)
967 if (entry.getFile() != null)
970 matchedFile = entry.getFile();
972 pdb.setFile(matchedFile); // entry.getFile());
973 if (pdbfiles == null)
975 pdbfiles = new ArrayList<String>();
978 if (!pdbfiles.contains(pdbId))
981 copyFileToJar(jout, matchedFile, pdbId);
985 if (entry.getProperty() != null && !entry.getProperty().isEmpty())
987 PdbentryItem item = new PdbentryItem();
988 Hashtable properties = entry.getProperty();
989 Enumeration en2 = properties.keys();
990 while (en2.hasMoreElements())
992 Property prop = new Property();
993 String key = en2.nextElement().toString();
995 prop.setValue(properties.get(key).toString());
996 item.addProperty(prop);
998 pdb.addPdbentryItem(item);
1001 jseq.addPdbids(pdb);
1005 saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
1010 if (!storeDS && av.hasHiddenRows())
1012 jal = av.getAlignment();
1016 if (storeDS && jal.getCodonFrames() != null)
1018 List<AlignedCodonFrame> jac = jal.getCodonFrames();
1019 for (AlignedCodonFrame acf : jac)
1021 AlcodonFrame alc = new AlcodonFrame();
1022 if (acf.getProtMappings() != null
1023 && acf.getProtMappings().length > 0)
1025 boolean hasMap = false;
1026 SequenceI[] dnas = acf.getdnaSeqs();
1027 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1028 for (int m = 0; m < pmaps.length; m++)
1030 AlcodMap alcmap = new AlcodMap();
1031 alcmap.setDnasq(seqHash(dnas[m]));
1032 alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1034 alc.addAlcodMap(alcmap);
1039 vamsasSet.addAlcodonFrame(alc);
1042 // TODO: delete this ? dead code from 2.8.3->2.9 ?
1044 // AlcodonFrame alc = new AlcodonFrame();
1045 // vamsasSet.addAlcodonFrame(alc);
1046 // for (int p = 0; p < acf.aaWidth; p++)
1048 // Alcodon cmap = new Alcodon();
1049 // if (acf.codons[p] != null)
1051 // // Null codons indicate a gapped column in the translated peptide
1053 // cmap.setPos1(acf.codons[p][0]);
1054 // cmap.setPos2(acf.codons[p][1]);
1055 // cmap.setPos3(acf.codons[p][2]);
1057 // alc.addAlcodon(cmap);
1059 // if (acf.getProtMappings() != null
1060 // && acf.getProtMappings().length > 0)
1062 // SequenceI[] dnas = acf.getdnaSeqs();
1063 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1064 // for (int m = 0; m < pmaps.length; m++)
1066 // AlcodMap alcmap = new AlcodMap();
1067 // alcmap.setDnasq(seqHash(dnas[m]));
1068 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1070 // alc.addAlcodMap(alcmap);
1077 // /////////////////////////////////
1078 if (!storeDS && av.currentTree != null)
1080 // FIND ANY ASSOCIATED TREES
1081 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
1082 if (Desktop.desktop != null)
1084 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1086 for (int t = 0; t < frames.length; t++)
1088 if (frames[t] instanceof TreePanel)
1090 TreePanel tp = (TreePanel) frames[t];
1092 if (tp.treeCanvas.av.getAlignment() == jal)
1094 Tree tree = new Tree();
1095 tree.setTitle(tp.getTitle());
1096 tree.setCurrentTree((av.currentTree == tp.getTree()));
1097 tree.setNewick(tp.getTree().toString());
1098 tree.setThreshold(tp.treeCanvas.threshold);
1100 tree.setFitToWindow(tp.fitToWindow.getState());
1101 tree.setFontName(tp.getTreeFont().getName());
1102 tree.setFontSize(tp.getTreeFont().getSize());
1103 tree.setFontStyle(tp.getTreeFont().getStyle());
1104 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
1106 tree.setShowBootstrap(tp.bootstrapMenu.getState());
1107 tree.setShowDistances(tp.distanceMenu.getState());
1109 tree.setHeight(tp.getHeight());
1110 tree.setWidth(tp.getWidth());
1111 tree.setXpos(tp.getX());
1112 tree.setYpos(tp.getY());
1113 tree.setId(makeHashCode(tp, null));
1123 * store forward refs from an annotationRow to any groups
1125 IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<SequenceGroup, String>();
1128 for (SequenceI sq : jal.getSequences())
1130 // Store annotation on dataset sequences only
1131 AlignmentAnnotation[] aa = sq.getAnnotation();
1132 if (aa != null && aa.length > 0)
1134 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1141 if (jal.getAlignmentAnnotation() != null)
1143 // Store the annotation shown on the alignment.
1144 AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
1145 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1150 if (jal.getGroups() != null)
1152 JGroup[] groups = new JGroup[jal.getGroups().size()];
1154 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
1156 JGroup jGroup = new JGroup();
1157 groups[++i] = jGroup;
1159 jGroup.setStart(sg.getStartRes());
1160 jGroup.setEnd(sg.getEndRes());
1161 jGroup.setName(sg.getName());
1162 if (groupRefs.containsKey(sg))
1164 // group has references so set its ID field
1165 jGroup.setId(groupRefs.get(sg));
1169 if (sg.cs.conservationApplied())
1171 jGroup.setConsThreshold(sg.cs.getConservationInc());
1173 if (sg.cs instanceof jalview.schemes.UserColourScheme)
1175 jGroup.setColour(setUserColourScheme(sg.cs, userColours, jms));
1179 jGroup.setColour(ColourSchemeProperty.getColourName(sg.cs));
1182 else if (sg.cs instanceof jalview.schemes.AnnotationColourGradient)
1184 jGroup.setColour("AnnotationColourGradient");
1185 jGroup.setAnnotationColours(constructAnnotationColours(
1186 (jalview.schemes.AnnotationColourGradient) sg.cs,
1189 else if (sg.cs instanceof jalview.schemes.UserColourScheme)
1191 jGroup.setColour(setUserColourScheme(sg.cs, userColours, jms));
1195 jGroup.setColour(ColourSchemeProperty.getColourName(sg.cs));
1198 jGroup.setPidThreshold(sg.cs.getThreshold());
1201 jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
1202 jGroup.setDisplayBoxes(sg.getDisplayBoxes());
1203 jGroup.setDisplayText(sg.getDisplayText());
1204 jGroup.setColourText(sg.getColourText());
1205 jGroup.setTextCol1(sg.textColour.getRGB());
1206 jGroup.setTextCol2(sg.textColour2.getRGB());
1207 jGroup.setTextColThreshold(sg.thresholdTextColour);
1208 jGroup.setShowUnconserved(sg.getShowNonconserved());
1209 jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1210 jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
1211 jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
1212 jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1213 for (SequenceI seq : sg.getSequences())
1215 jGroup.addSeq(seqHash(seq));
1219 jms.setJGroup(groups);
1223 // /////////SAVE VIEWPORT
1224 Viewport view = new Viewport();
1225 view.setTitle(ap.alignFrame.getTitle());
1226 view.setSequenceSetId(makeHashCode(av.getSequenceSetId(),
1227 av.getSequenceSetId()));
1228 view.setId(av.getViewId());
1229 if (av.getCodingComplement() != null)
1231 view.setComplementId(av.getCodingComplement().getViewId());
1233 view.setViewName(av.viewName);
1234 view.setGatheredViews(av.isGatherViewsHere());
1236 Rectangle size = ap.av.getExplodedGeometry();
1237 Rectangle position = size;
1240 size = ap.alignFrame.getBounds();
1241 if (av.getCodingComplement() != null)
1243 position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
1251 view.setXpos(position.x);
1252 view.setYpos(position.y);
1254 view.setWidth(size.width);
1255 view.setHeight(size.height);
1257 view.setStartRes(av.startRes);
1258 view.setStartSeq(av.startSeq);
1260 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1262 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1265 else if (av.getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1267 AnnotationColours ac = constructAnnotationColours(
1268 (jalview.schemes.AnnotationColourGradient) av
1269 .getGlobalColourScheme(),
1272 view.setAnnotationColours(ac);
1273 view.setBgColour("AnnotationColourGradient");
1277 view.setBgColour(ColourSchemeProperty.getColourName(av
1278 .getGlobalColourScheme()));
1281 ColourSchemeI cs = av.getGlobalColourScheme();
1285 if (cs.conservationApplied())
1287 view.setConsThreshold(cs.getConservationInc());
1288 if (cs instanceof jalview.schemes.UserColourScheme)
1290 view.setBgColour(setUserColourScheme(cs, userColours, jms));
1294 if (cs instanceof ResidueColourScheme)
1296 view.setPidThreshold(cs.getThreshold());
1300 view.setConservationSelected(av.getConservationSelected());
1301 view.setPidSelected(av.getAbovePIDThreshold());
1302 view.setFontName(av.font.getName());
1303 view.setFontSize(av.font.getSize());
1304 view.setFontStyle(av.font.getStyle());
1305 view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
1306 view.setRenderGaps(av.isRenderGaps());
1307 view.setShowAnnotation(av.isShowAnnotation());
1308 view.setShowBoxes(av.getShowBoxes());
1309 view.setShowColourText(av.getColourText());
1310 view.setShowFullId(av.getShowJVSuffix());
1311 view.setRightAlignIds(av.isRightAlignIds());
1312 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1313 view.setShowText(av.getShowText());
1314 view.setShowUnconserved(av.getShowUnconserved());
1315 view.setWrapAlignment(av.getWrapAlignment());
1316 view.setTextCol1(av.getTextColour().getRGB());
1317 view.setTextCol2(av.getTextColour2().getRGB());
1318 view.setTextColThreshold(av.getThresholdTextColour());
1319 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1320 view.setShowSequenceLogo(av.isShowSequenceLogo());
1321 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1322 view.setShowGroupConsensus(av.isShowGroupConsensus());
1323 view.setShowGroupConservation(av.isShowGroupConservation());
1324 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1325 view.setShowDbRefTooltip(av.isShowDBRefs());
1326 view.setFollowHighlight(av.isFollowHighlight());
1327 view.setFollowSelection(av.followSelection);
1328 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1329 if (av.getFeaturesDisplayed() != null)
1331 jalview.schemabinding.version2.FeatureSettings fs = new jalview.schemabinding.version2.FeatureSettings();
1333 String[] renderOrder = ap.getSeqPanel().seqCanvas
1334 .getFeatureRenderer().getRenderOrder()
1335 .toArray(new String[0]);
1337 Vector<String> settingsAdded = new Vector<String>();
1338 if (renderOrder != null)
1340 for (String featureType : renderOrder)
1342 FeatureColourI fcol = ap.getSeqPanel().seqCanvas
1343 .getFeatureRenderer()
1344 .getFeatureStyle(featureType);
1345 Setting setting = new Setting();
1346 setting.setType(featureType);
1347 if (!fcol.isSimpleColour())
1349 setting.setColour(fcol.getMaxColour().getRGB());
1350 setting.setMincolour(fcol.getMinColour().getRGB());
1351 setting.setMin(fcol.getMin());
1352 setting.setMax(fcol.getMax());
1353 setting.setColourByLabel(fcol.isColourByLabel());
1354 setting.setAutoScale(fcol.isAutoScaled());
1355 setting.setThreshold(fcol.getThreshold());
1356 // -1 = No threshold, 0 = Below, 1 = Above
1357 setting.setThreshstate(fcol.isAboveThreshold() ? 1
1358 : (fcol.isBelowThreshold() ? 0 : -1));
1362 setting.setColour(fcol.getColour().getRGB());
1365 setting.setDisplay(av.getFeaturesDisplayed().isVisible(
1367 float rorder = ap.getSeqPanel().seqCanvas.getFeatureRenderer()
1368 .getOrder(featureType);
1371 setting.setOrder(rorder);
1373 fs.addSetting(setting);
1374 settingsAdded.addElement(featureType);
1378 // is groups actually supposed to be a map here ?
1379 Iterator<String> en = ap.getSeqPanel().seqCanvas
1380 .getFeatureRenderer()
1381 .getFeatureGroups().iterator();
1382 Vector<String> groupsAdded = new Vector<String>();
1383 while (en.hasNext())
1385 String grp = en.next();
1386 if (groupsAdded.contains(grp))
1390 Group g = new Group();
1392 g.setDisplay(((Boolean) ap.getSeqPanel().seqCanvas
1393 .getFeatureRenderer().checkGroupVisibility(grp, false))
1396 groupsAdded.addElement(grp);
1398 jms.setFeatureSettings(fs);
1401 if (av.hasHiddenColumns())
1403 if (av.getColumnSelection() == null
1404 || av.getColumnSelection().getHiddenColumns() == null)
1406 warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1410 for (int c = 0; c < av.getColumnSelection().getHiddenColumns()
1413 int[] region = av.getColumnSelection().getHiddenColumns()
1415 HiddenColumns hc = new HiddenColumns();
1416 hc.setStart(region[0]);
1417 hc.setEnd(region[1]);
1418 view.addHiddenColumns(hc);
1422 if (calcIdSet.size() > 0)
1424 for (String calcId : calcIdSet)
1426 if (calcId.trim().length() > 0)
1428 CalcIdParam cidp = createCalcIdParam(calcId, av);
1429 // Some calcIds have no parameters.
1432 view.addCalcIdParam(cidp);
1438 jms.addViewport(view);
1440 object.setJalviewModelSequence(jms);
1441 object.getVamsasModel().addSequenceSet(vamsasSet);
1443 if (jout != null && fileName != null)
1445 // We may not want to write the object to disk,
1446 // eg we can copy the alignViewport to a new view object
1447 // using save and then load
1450 System.out.println("Writing jar entry " + fileName);
1451 JarEntry entry = new JarEntry(fileName);
1452 jout.putNextEntry(entry);
1453 PrintWriter pout = new PrintWriter(new OutputStreamWriter(jout,
1455 Marshaller marshaller = new Marshaller(pout);
1456 marshaller.marshal(object);
1459 } catch (Exception ex)
1461 // TODO: raise error in GUI if marshalling failed.
1462 ex.printStackTrace();
1469 * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
1470 * for each viewer, with
1472 * <li>viewer geometry (position, size, split pane divider location)</li>
1473 * <li>index of the selected structure in the viewer (currently shows gapped
1475 * <li>the id of the annotation holding RNA secondary structure</li>
1476 * <li>(currently only one SS is shown per viewer, may be more in future)</li>
1478 * Varna viewer state is also written out (in native Varna XML) to separate
1479 * project jar entries. A separate entry is written for each RNA structure
1480 * displayed, with the naming convention
1482 * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
1490 * @param storeDataset
1492 protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
1493 final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
1494 boolean storeDataset)
1496 if (Desktop.desktop == null)
1500 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1501 for (int f = frames.length - 1; f > -1; f--)
1503 if (frames[f] instanceof AppVarna)
1505 AppVarna varna = (AppVarna) frames[f];
1507 * link the sequence to every viewer that is showing it and is linked to
1508 * its alignment panel
1510 if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
1512 String viewId = varna.getViewId();
1513 RnaViewer rna = new RnaViewer();
1514 rna.setViewId(viewId);
1515 rna.setTitle(varna.getTitle());
1516 rna.setXpos(varna.getX());
1517 rna.setYpos(varna.getY());
1518 rna.setWidth(varna.getWidth());
1519 rna.setHeight(varna.getHeight());
1520 rna.setDividerLocation(varna.getDividerLocation());
1521 rna.setSelectedRna(varna.getSelectedIndex());
1522 jseq.addRnaViewer(rna);
1525 * Store each Varna panel's state once in the project per sequence.
1526 * First time through only (storeDataset==false)
1528 // boolean storeSessions = false;
1529 // String sequenceViewId = viewId + seqsToIds.get(jds);
1530 // if (!storeDataset && !viewIds.contains(sequenceViewId))
1532 // viewIds.add(sequenceViewId);
1533 // storeSessions = true;
1535 for (RnaModel model : varna.getModels())
1537 if (model.seq == jds)
1540 * VARNA saves each view (sequence or alignment secondary
1541 * structure, gapped or trimmed) as a separate XML file
1543 String jarEntryName = rnaSessions.get(model);
1544 if (jarEntryName == null)
1547 String varnaStateFile = varna.getStateInfo(model.rna);
1548 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
1549 copyFileToJar(jout, varnaStateFile, jarEntryName);
1550 rnaSessions.put(model, jarEntryName);
1552 SecondaryStructure ss = new SecondaryStructure();
1553 String annotationId = varna.getAnnotation(jds).annotationId;
1554 ss.setAnnotationId(annotationId);
1555 ss.setViewerState(jarEntryName);
1556 ss.setGapped(model.gapped);
1557 ss.setTitle(model.title);
1558 rna.addSecondaryStructure(ss);
1567 * Copy the contents of a file to a new entry added to the output jar
1571 * @param jarEntryName
1573 protected void copyFileToJar(JarOutputStream jout, String infilePath,
1574 String jarEntryName)
1576 DataInputStream dis = null;
1579 File file = new File(infilePath);
1580 if (file.exists() && jout != null)
1582 dis = new DataInputStream(new FileInputStream(file));
1583 byte[] data = new byte[(int) file.length()];
1584 dis.readFully(data);
1585 writeJarEntry(jout, jarEntryName, data);
1587 } catch (Exception ex)
1589 ex.printStackTrace();
1597 } catch (IOException e)
1606 * Write the data to a new entry of given name in the output jar file
1609 * @param jarEntryName
1611 * @throws IOException
1613 protected void writeJarEntry(JarOutputStream jout, String jarEntryName,
1614 byte[] data) throws IOException
1618 System.out.println("Writing jar entry " + jarEntryName);
1619 jout.putNextEntry(new JarEntry(jarEntryName));
1620 DataOutputStream dout = new DataOutputStream(jout);
1621 dout.write(data, 0, data.length);
1628 * Save the state of a structure viewer
1633 * the archive XML element under which to save the state
1636 * @param matchedFile
1640 protected String saveStructureState(AlignmentPanel ap, SequenceI jds,
1641 Pdbids pdb, PDBEntry entry, List<String> viewIds,
1642 String matchedFile, StructureViewerBase viewFrame)
1644 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
1647 * Look for any bindings for this viewer to the PDB file of interest
1648 * (including part matches excluding chain id)
1650 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
1652 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
1653 final String pdbId = pdbentry.getId();
1654 if (!pdbId.equals(entry.getId())
1655 && !(entry.getId().length() > 4 && entry.getId()
1656 .toLowerCase().startsWith(pdbId.toLowerCase())))
1659 * not interested in a binding to a different PDB entry here
1663 if (matchedFile == null)
1665 matchedFile = pdbentry.getFile();
1667 else if (!matchedFile.equals(pdbentry.getFile()))
1670 .warn("Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
1671 + pdbentry.getFile());
1675 // can get at it if the ID
1676 // match is ambiguous (e.g.
1679 for (int smap = 0; smap < viewFrame.getBinding().getSequence()[peid].length; smap++)
1681 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
1682 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
1684 StructureState state = new StructureState();
1685 state.setVisible(true);
1686 state.setXpos(viewFrame.getX());
1687 state.setYpos(viewFrame.getY());
1688 state.setWidth(viewFrame.getWidth());
1689 state.setHeight(viewFrame.getHeight());
1690 final String viewId = viewFrame.getViewId();
1691 state.setViewId(viewId);
1692 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
1693 state.setColourwithAlignPanel(viewFrame.isUsedforcolourby(ap));
1694 state.setColourByJmol(viewFrame.isColouredByViewer());
1695 state.setType(viewFrame.getViewerType().toString());
1696 pdb.addStructureState(state);
1703 private AnnotationColours constructAnnotationColours(
1704 AnnotationColourGradient acg, List<UserColourScheme> userColours,
1705 JalviewModelSequence jms)
1707 AnnotationColours ac = new AnnotationColours();
1708 ac.setAboveThreshold(acg.getAboveThreshold());
1709 ac.setThreshold(acg.getAnnotationThreshold());
1710 ac.setAnnotation(acg.getAnnotation());
1711 if (acg.getBaseColour() instanceof jalview.schemes.UserColourScheme)
1713 ac.setColourScheme(setUserColourScheme(acg.getBaseColour(),
1718 ac.setColourScheme(ColourSchemeProperty.getColourName(acg
1722 ac.setMaxColour(acg.getMaxColour().getRGB());
1723 ac.setMinColour(acg.getMinColour().getRGB());
1724 ac.setPerSequence(acg.isSeqAssociated());
1725 ac.setPredefinedColours(acg.isPredefinedColours());
1729 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
1730 IdentityHashMap<SequenceGroup, String> groupRefs,
1731 AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
1732 SequenceSet vamsasSet)
1735 for (int i = 0; i < aa.length; i++)
1737 Annotation an = new Annotation();
1739 AlignmentAnnotation annotation = aa[i];
1740 if (annotation.annotationId != null)
1742 annotationIds.put(annotation.annotationId, annotation);
1745 an.setId(annotation.annotationId);
1747 an.setVisible(annotation.visible);
1749 an.setDescription(annotation.description);
1751 if (annotation.sequenceRef != null)
1753 // 2.9 JAL-1781 xref on sequence id rather than name
1754 an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
1756 if (annotation.groupRef != null)
1758 String groupIdr = groupRefs.get(annotation.groupRef);
1759 if (groupIdr == null)
1761 // make a locally unique String
1763 annotation.groupRef,
1764 groupIdr = ("" + System.currentTimeMillis()
1765 + annotation.groupRef.getName() + groupRefs
1768 an.setGroupRef(groupIdr.toString());
1771 // store all visualization attributes for annotation
1772 an.setGraphHeight(annotation.graphHeight);
1773 an.setCentreColLabels(annotation.centreColLabels);
1774 an.setScaleColLabels(annotation.scaleColLabel);
1775 an.setShowAllColLabels(annotation.showAllColLabels);
1776 an.setBelowAlignment(annotation.belowAlignment);
1778 if (annotation.graph > 0)
1781 an.setGraphType(annotation.graph);
1782 an.setGraphGroup(annotation.graphGroup);
1783 if (annotation.getThreshold() != null)
1785 ThresholdLine line = new ThresholdLine();
1786 line.setLabel(annotation.getThreshold().label);
1787 line.setValue(annotation.getThreshold().value);
1788 line.setColour(annotation.getThreshold().colour.getRGB());
1789 an.setThresholdLine(line);
1797 an.setLabel(annotation.label);
1799 if (annotation == av.getAlignmentQualityAnnot()
1800 || annotation == av.getAlignmentConservationAnnotation()
1801 || annotation == av.getAlignmentConsensusAnnotation()
1802 || annotation.autoCalculated)
1804 // new way of indicating autocalculated annotation -
1805 an.setAutoCalculated(annotation.autoCalculated);
1807 if (annotation.hasScore())
1809 an.setScore(annotation.getScore());
1812 if (annotation.getCalcId() != null)
1814 calcIdSet.add(annotation.getCalcId());
1815 an.setCalcId(annotation.getCalcId());
1817 if (annotation.hasProperties())
1819 for (String pr : annotation.getProperties())
1821 Property prop = new Property();
1823 prop.setValue(annotation.getProperty(pr));
1824 an.addProperty(prop);
1828 AnnotationElement ae;
1829 if (annotation.annotations != null)
1831 an.setScoreOnly(false);
1832 for (int a = 0; a < annotation.annotations.length; a++)
1834 if ((annotation == null) || (annotation.annotations[a] == null))
1839 ae = new AnnotationElement();
1840 if (annotation.annotations[a].description != null)
1842 ae.setDescription(annotation.annotations[a].description);
1844 if (annotation.annotations[a].displayCharacter != null)
1846 ae.setDisplayCharacter(annotation.annotations[a].displayCharacter);
1849 if (!Float.isNaN(annotation.annotations[a].value))
1851 ae.setValue(annotation.annotations[a].value);
1855 if (annotation.annotations[a].secondaryStructure > ' ')
1857 ae.setSecondaryStructure(annotation.annotations[a].secondaryStructure
1861 if (annotation.annotations[a].colour != null
1862 && annotation.annotations[a].colour != java.awt.Color.black)
1864 ae.setColour(annotation.annotations[a].colour.getRGB());
1867 an.addAnnotationElement(ae);
1868 if (annotation.autoCalculated)
1870 // only write one non-null entry into the annotation row -
1871 // sufficient to get the visualization attributes necessary to
1879 an.setScoreOnly(true);
1881 if (!storeDS || (storeDS && !annotation.autoCalculated))
1883 // skip autocalculated annotation - these are only provided for
1885 vamsasSet.addAnnotation(an);
1891 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
1893 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
1894 if (settings != null)
1896 CalcIdParam vCalcIdParam = new CalcIdParam();
1897 vCalcIdParam.setCalcId(calcId);
1898 vCalcIdParam.addServiceURL(settings.getServiceURI());
1899 // generic URI allowing a third party to resolve another instance of the
1900 // service used for this calculation
1901 for (String urls : settings.getServiceURLs())
1903 vCalcIdParam.addServiceURL(urls);
1905 vCalcIdParam.setVersion("1.0");
1906 if (settings.getPreset() != null)
1908 WsParamSetI setting = settings.getPreset();
1909 vCalcIdParam.setName(setting.getName());
1910 vCalcIdParam.setDescription(setting.getDescription());
1914 vCalcIdParam.setName("");
1915 vCalcIdParam.setDescription("Last used parameters");
1917 // need to be able to recover 1) settings 2) user-defined presets or
1918 // recreate settings from preset 3) predefined settings provided by
1919 // service - or settings that can be transferred (or discarded)
1920 vCalcIdParam.setParameters(settings.getWsParamFile().replace("\n",
1922 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
1923 // todo - decide if updateImmediately is needed for any projects.
1925 return vCalcIdParam;
1930 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
1933 if (calcIdParam.getVersion().equals("1.0"))
1935 Jws2Instance service = Jws2Discoverer.getDiscoverer()
1936 .getPreferredServiceFor(calcIdParam.getServiceURL());
1937 if (service != null)
1939 WsParamSetI parmSet = null;
1942 parmSet = service.getParamStore().parseServiceParameterFile(
1943 calcIdParam.getName(), calcIdParam.getDescription(),
1944 calcIdParam.getServiceURL(),
1945 calcIdParam.getParameters().replace("|\\n|", "\n"));
1946 } catch (IOException x)
1948 warn("Couldn't parse parameter data for "
1949 + calcIdParam.getCalcId(), x);
1952 List<ArgumentI> argList = null;
1953 if (calcIdParam.getName().length() > 0)
1955 parmSet = service.getParamStore()
1956 .getPreset(calcIdParam.getName());
1957 if (parmSet != null)
1959 // TODO : check we have a good match with settings in AACon -
1960 // otherwise we'll need to create a new preset
1965 argList = parmSet.getArguments();
1968 AAConSettings settings = new AAConSettings(
1969 calcIdParam.isAutoUpdate(), service, parmSet, argList);
1970 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
1971 calcIdParam.isNeedsUpdate());
1976 warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
1980 throw new Error(MessageManager.formatMessage(
1981 "error.unsupported_version_calcIdparam",
1982 new Object[] { calcIdParam.toString() }));
1986 * External mapping between jalview objects and objects yielding a valid and
1987 * unique object ID string. This is null for normal Jalview project IO, but
1988 * non-null when a jalview project is being read or written as part of a
1991 IdentityHashMap jv2vobj = null;
1994 * Construct a unique ID for jvobj using either existing bindings or if none
1995 * exist, the result of the hashcode call for the object.
1998 * jalview data object
1999 * @return unique ID for referring to jvobj
2001 private String makeHashCode(Object jvobj, String altCode)
2003 if (jv2vobj != null)
2005 Object id = jv2vobj.get(jvobj);
2008 return id.toString();
2010 // check string ID mappings
2011 if (jvids2vobj != null && jvobj instanceof String)
2013 id = jvids2vobj.get(jvobj);
2017 return id.toString();
2019 // give up and warn that something has gone wrong
2020 warn("Cannot find ID for object in external mapping : " + jvobj);
2026 * return local jalview object mapped to ID, if it exists
2030 * @return null or object bound to idcode
2032 private Object retrieveExistingObj(String idcode)
2034 if (idcode != null && vobj2jv != null)
2036 return vobj2jv.get(idcode);
2042 * binding from ID strings from external mapping table to jalview data model
2045 private Hashtable vobj2jv;
2047 private Sequence createVamsasSequence(String id, SequenceI jds)
2049 return createVamsasSequence(true, id, jds, null);
2052 private Sequence createVamsasSequence(boolean recurse, String id,
2053 SequenceI jds, SequenceI parentseq)
2055 Sequence vamsasSeq = new Sequence();
2056 vamsasSeq.setId(id);
2057 vamsasSeq.setName(jds.getName());
2058 vamsasSeq.setSequence(jds.getSequenceAsString());
2059 vamsasSeq.setDescription(jds.getDescription());
2060 jalview.datamodel.DBRefEntry[] dbrefs = null;
2061 if (jds.getDatasetSequence() != null)
2063 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
2067 // seqId==dsseqid so we can tell which sequences really are
2068 // dataset sequences only
2069 vamsasSeq.setDsseqid(id);
2070 dbrefs = jds.getDBRefs();
2071 if (parentseq == null)
2078 for (int d = 0; d < dbrefs.length; d++)
2080 DBRef dbref = new DBRef();
2081 dbref.setSource(dbrefs[d].getSource());
2082 dbref.setVersion(dbrefs[d].getVersion());
2083 dbref.setAccessionId(dbrefs[d].getAccessionId());
2084 if (dbrefs[d].hasMap())
2086 Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
2088 dbref.setMapping(mp);
2090 vamsasSeq.addDBRef(dbref);
2096 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
2097 SequenceI parentseq, SequenceI jds, boolean recurse)
2100 if (jmp.getMap() != null)
2104 jalview.util.MapList mlst = jmp.getMap();
2105 List<int[]> r = mlst.getFromRanges();
2106 for (int[] range : r)
2108 MapListFrom mfrom = new MapListFrom();
2109 mfrom.setStart(range[0]);
2110 mfrom.setEnd(range[1]);
2111 mp.addMapListFrom(mfrom);
2113 r = mlst.getToRanges();
2114 for (int[] range : r)
2116 MapListTo mto = new MapListTo();
2117 mto.setStart(range[0]);
2118 mto.setEnd(range[1]);
2119 mp.addMapListTo(mto);
2121 mp.setMapFromUnit(mlst.getFromRatio());
2122 mp.setMapToUnit(mlst.getToRatio());
2123 if (jmp.getTo() != null)
2125 MappingChoice mpc = new MappingChoice();
2127 // check/create ID for the sequence referenced by getTo()
2130 SequenceI ps = null;
2131 if (parentseq != jmp.getTo()
2132 && parentseq.getDatasetSequence() != jmp.getTo())
2134 // chaining dbref rather than a handshaking one
2135 jmpid = seqHash(ps = jmp.getTo());
2139 jmpid = seqHash(ps = parentseq);
2141 mpc.setDseqFor(jmpid);
2142 if (!seqRefIds.containsKey(mpc.getDseqFor()))
2144 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
2145 seqRefIds.put(mpc.getDseqFor(), ps);
2149 jalview.bin.Cache.log.debug("reusing DseqFor ID");
2152 mp.setMappingChoice(mpc);
2158 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
2159 List<UserColourScheme> userColours, JalviewModelSequence jms)
2162 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
2163 boolean newucs = false;
2164 if (!userColours.contains(ucs))
2166 userColours.add(ucs);
2169 id = "ucs" + userColours.indexOf(ucs);
2172 // actually create the scheme's entry in the XML model
2173 java.awt.Color[] colours = ucs.getColours();
2174 jalview.schemabinding.version2.UserColours uc = new jalview.schemabinding.version2.UserColours();
2175 jalview.schemabinding.version2.UserColourScheme jbucs = new jalview.schemabinding.version2.UserColourScheme();
2177 for (int i = 0; i < colours.length; i++)
2179 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
2180 col.setName(ResidueProperties.aa[i]);
2181 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2182 jbucs.addColour(col);
2184 if (ucs.getLowerCaseColours() != null)
2186 colours = ucs.getLowerCaseColours();
2187 for (int i = 0; i < colours.length; i++)
2189 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
2190 col.setName(ResidueProperties.aa[i].toLowerCase());
2191 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2192 jbucs.addColour(col);
2197 uc.setUserColourScheme(jbucs);
2198 jms.addUserColours(uc);
2204 jalview.schemes.UserColourScheme getUserColourScheme(
2205 JalviewModelSequence jms, String id)
2207 UserColours[] uc = jms.getUserColours();
2208 UserColours colours = null;
2210 for (int i = 0; i < uc.length; i++)
2212 if (uc[i].getId().equals(id))
2220 java.awt.Color[] newColours = new java.awt.Color[24];
2222 for (int i = 0; i < 24; i++)
2224 newColours[i] = new java.awt.Color(Integer.parseInt(colours
2225 .getUserColourScheme().getColour(i).getRGB(), 16));
2228 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
2231 if (colours.getUserColourScheme().getColourCount() > 24)
2233 newColours = new java.awt.Color[23];
2234 for (int i = 0; i < 23; i++)
2236 newColours[i] = new java.awt.Color(Integer.parseInt(colours
2237 .getUserColourScheme().getColour(i + 24).getRGB(), 16));
2239 ucs.setLowerCaseColours(newColours);
2246 * contains last error message (if any) encountered by XML loader.
2248 String errorMessage = null;
2251 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
2252 * exceptions are raised during project XML parsing
2254 public boolean attemptversion1parse = true;
2257 * Load a jalview project archive from a jar file
2260 * - HTTP URL or filename
2262 public AlignFrame loadJalviewAlign(final String file)
2265 jalview.gui.AlignFrame af = null;
2269 // create list to store references for any new Jmol viewers created
2270 newStructureViewers = new Vector<JalviewStructureDisplayI>();
2271 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
2272 // Workaround is to make sure caller implements the JarInputStreamProvider
2274 // so we can re-open the jar input stream for each entry.
2276 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
2277 af = loadJalviewAlign(jprovider);
2279 } catch (MalformedURLException e)
2281 errorMessage = "Invalid URL format for '" + file + "'";
2287 SwingUtilities.invokeAndWait(new Runnable()
2292 setLoadingFinishedForNewStructureViewers();
2295 } catch (Exception x)
2297 System.err.println("Error loading alignment: " + x.getMessage());
2303 private jarInputStreamProvider createjarInputStreamProvider(
2304 final String file) throws MalformedURLException
2307 errorMessage = null;
2308 uniqueSetSuffix = null;
2310 viewportsAdded.clear();
2311 frefedSequence = null;
2313 if (file.startsWith("http://"))
2315 url = new URL(file);
2317 final URL _url = url;
2318 return new jarInputStreamProvider()
2322 public JarInputStream getJarInputStream() throws IOException
2326 return new JarInputStream(_url.openStream());
2330 return new JarInputStream(new FileInputStream(file));
2335 public String getFilename()
2343 * Recover jalview session from a jalview project archive. Caller may
2344 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
2345 * themselves. Any null fields will be initialised with default values,
2346 * non-null fields are left alone.
2351 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
2353 errorMessage = null;
2354 if (uniqueSetSuffix == null)
2356 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
2358 if (seqRefIds == null)
2362 AlignFrame af = null, _af = null;
2363 IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<AlignmentI, AlignmentI>();
2364 Map<String, AlignFrame> gatherToThisFrame = new HashMap<String, AlignFrame>();
2365 final String file = jprovider.getFilename();
2368 JarInputStream jin = null;
2369 JarEntry jarentry = null;
2374 jin = jprovider.getJarInputStream();
2375 for (int i = 0; i < entryCount; i++)
2377 jarentry = jin.getNextJarEntry();
2380 if (jarentry != null && jarentry.getName().endsWith(".xml"))
2382 InputStreamReader in = new InputStreamReader(jin, UTF_8);
2383 JalviewModel object = new JalviewModel();
2385 Unmarshaller unmar = new Unmarshaller(object);
2386 unmar.setValidation(false);
2387 object = (JalviewModel) unmar.unmarshal(in);
2388 if (true) // !skipViewport(object))
2390 _af = loadFromObject(object, file, true, jprovider);
2392 && object.getJalviewModelSequence().getViewportCount() > 0)
2396 // store a reference to the first view
2399 if (_af.viewport.isGatherViewsHere())
2401 // if this is a gathered view, keep its reference since
2402 // after gathering views, only this frame will remain
2404 gatherToThisFrame.put(_af.viewport.getSequenceSetId(), _af);
2406 // Save dataset to register mappings once all resolved
2407 importedDatasets.put(af.viewport.getAlignment().getDataset(),
2408 af.viewport.getAlignment().getDataset());
2413 else if (jarentry != null)
2415 // Some other file here.
2418 } while (jarentry != null);
2419 resolveFrefedSequences();
2420 } catch (IOException ex)
2422 ex.printStackTrace();
2423 errorMessage = "Couldn't locate Jalview XML file : " + file;
2424 System.err.println("Exception whilst loading jalview XML file : "
2426 } catch (Exception ex)
2428 System.err.println("Parsing as Jalview Version 2 file failed.");
2429 ex.printStackTrace(System.err);
2430 if (attemptversion1parse)
2432 // Is Version 1 Jar file?
2435 af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
2436 } catch (Exception ex2)
2438 System.err.println("Exception whilst loading as jalviewXMLV1:");
2439 ex2.printStackTrace();
2443 if (Desktop.instance != null)
2445 Desktop.instance.stopLoading();
2449 System.out.println("Successfully loaded archive file");
2452 ex.printStackTrace();
2454 System.err.println("Exception whilst loading jalview XML file : "
2456 } catch (OutOfMemoryError e)
2458 // Don't use the OOM Window here
2459 errorMessage = "Out of memory loading jalview XML file";
2460 System.err.println("Out of memory whilst loading jalview XML file");
2461 e.printStackTrace();
2465 * Regather multiple views (with the same sequence set id) to the frame (if
2466 * any) that is flagged as the one to gather to, i.e. convert them to tabbed
2467 * views instead of separate frames. Note this doesn't restore a state where
2468 * some expanded views in turn have tabbed views - the last "first tab" read
2469 * in will play the role of gatherer for all.
2471 for (AlignFrame fr : gatherToThisFrame.values())
2473 Desktop.instance.gatherViews(fr);
2476 restoreSplitFrames();
2477 for (AlignmentI ds : importedDatasets.keySet())
2479 if (ds.getCodonFrames() != null)
2481 StructureSelectionManager.getStructureSelectionManager(
2482 Desktop.instance).registerMappings(ds.getCodonFrames());
2485 if (errorMessage != null)
2490 if (Desktop.instance != null)
2492 Desktop.instance.stopLoading();
2499 * Try to reconstruct and display SplitFrame windows, where each contains
2500 * complementary dna and protein alignments. Done by pairing up AlignFrame
2501 * objects (created earlier) which have complementary viewport ids associated.
2503 protected void restoreSplitFrames()
2505 List<SplitFrame> gatherTo = new ArrayList<SplitFrame>();
2506 List<AlignFrame> addedToSplitFrames = new ArrayList<AlignFrame>();
2507 Map<String, AlignFrame> dna = new HashMap<String, AlignFrame>();
2510 * Identify the DNA alignments
2512 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2515 AlignFrame af = candidate.getValue();
2516 if (af.getViewport().getAlignment().isNucleotide())
2518 dna.put(candidate.getKey().getId(), af);
2523 * Try to match up the protein complements
2525 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2528 AlignFrame af = candidate.getValue();
2529 if (!af.getViewport().getAlignment().isNucleotide())
2531 String complementId = candidate.getKey().getComplementId();
2532 // only non-null complements should be in the Map
2533 if (complementId != null && dna.containsKey(complementId))
2535 final AlignFrame dnaFrame = dna.get(complementId);
2536 SplitFrame sf = createSplitFrame(dnaFrame, af);
2537 addedToSplitFrames.add(dnaFrame);
2538 addedToSplitFrames.add(af);
2539 if (af.viewport.isGatherViewsHere())
2548 * Open any that we failed to pair up (which shouldn't happen!) as
2549 * standalone AlignFrame's.
2551 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2554 AlignFrame af = candidate.getValue();
2555 if (!addedToSplitFrames.contains(af))
2557 Viewport view = candidate.getKey();
2558 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
2560 System.err.println("Failed to restore view " + view.getTitle()
2561 + " to split frame");
2566 * Gather back into tabbed views as flagged.
2568 for (SplitFrame sf : gatherTo)
2570 Desktop.instance.gatherViews(sf);
2573 splitFrameCandidates.clear();
2577 * Construct and display one SplitFrame holding DNA and protein alignments.
2580 * @param proteinFrame
2583 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
2584 AlignFrame proteinFrame)
2586 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
2587 String title = MessageManager.getString("label.linked_view_title");
2588 int width = (int) dnaFrame.getBounds().getWidth();
2589 int height = (int) (dnaFrame.getBounds().getHeight()
2590 + proteinFrame.getBounds().getHeight() + 50);
2593 * SplitFrame location is saved to both enclosed frames
2595 splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
2596 Desktop.addInternalFrame(splitFrame, title, width, height);
2599 * And compute cDNA consensus (couldn't do earlier with consensus as
2600 * mappings were not yet present)
2602 proteinFrame.viewport.alignmentChanged(proteinFrame.alignPanel);
2608 * check errorMessage for a valid error message and raise an error box in the
2609 * GUI or write the current errorMessage to stderr and then clear the error
2612 protected void reportErrors()
2614 reportErrors(false);
2617 protected void reportErrors(final boolean saving)
2619 if (errorMessage != null)
2621 final String finalErrorMessage = errorMessage;
2624 javax.swing.SwingUtilities.invokeLater(new Runnable()
2629 JOptionPane.showInternalMessageDialog(Desktop.desktop,
2630 finalErrorMessage, "Error "
2631 + (saving ? "saving" : "loading")
2632 + " Jalview file", JOptionPane.WARNING_MESSAGE);
2638 System.err.println("Problem loading Jalview file: " + errorMessage);
2641 errorMessage = null;
2644 Map<String, String> alreadyLoadedPDB = new HashMap<String, String>();
2647 * when set, local views will be updated from view stored in JalviewXML
2648 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
2649 * sync if this is set to true.
2651 private final boolean updateLocalViews = false;
2654 * Returns the path to a temporary file holding the PDB file for the given PDB
2655 * id. The first time of asking, searches for a file of that name in the
2656 * Jalview project jar, and copies it to a new temporary file. Any repeat
2657 * requests just return the path to the file previously created.
2663 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
2666 if (alreadyLoadedPDB.containsKey(pdbId))
2668 return alreadyLoadedPDB.get(pdbId).toString();
2671 String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
2673 if (tempFile != null)
2675 alreadyLoadedPDB.put(pdbId, tempFile);
2681 * Copies the jar entry of given name to a new temporary file and returns the
2682 * path to the file, or null if the entry is not found.
2685 * @param jarEntryName
2687 * a prefix for the temporary file name, must be at least three
2690 * null or original file - so new file can be given the same suffix
2694 protected String copyJarEntry(jarInputStreamProvider jprovider,
2695 String jarEntryName, String prefix, String origFile)
2697 BufferedReader in = null;
2698 PrintWriter out = null;
2699 String suffix = ".tmp";
2700 if (origFile == null)
2702 origFile = jarEntryName;
2704 int sfpos = origFile.lastIndexOf(".");
2705 if (sfpos > -1 && sfpos < (origFile.length() - 3))
2707 suffix = "." + origFile.substring(sfpos + 1);
2711 JarInputStream jin = jprovider.getJarInputStream();
2713 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
2714 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
2715 * FileInputStream(jprovider)); }
2718 JarEntry entry = null;
2721 entry = jin.getNextJarEntry();
2722 } while (entry != null && !entry.getName().equals(jarEntryName));
2725 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
2726 File outFile = File.createTempFile(prefix, suffix);
2727 outFile.deleteOnExit();
2728 out = new PrintWriter(new FileOutputStream(outFile));
2731 while ((data = in.readLine()) != null)
2736 String t = outFile.getAbsolutePath();
2741 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
2743 } catch (Exception ex)
2745 ex.printStackTrace();
2753 } catch (IOException e)
2767 private class JvAnnotRow
2769 public JvAnnotRow(int i, AlignmentAnnotation jaa)
2776 * persisted version of annotation row from which to take vis properties
2778 public jalview.datamodel.AlignmentAnnotation template;
2781 * original position of the annotation row in the alignment
2787 * Load alignment frame from jalview XML DOM object
2792 * filename source string
2793 * @param loadTreesAndStructures
2794 * when false only create Viewport
2796 * data source provider
2797 * @return alignment frame created from view stored in DOM
2799 AlignFrame loadFromObject(JalviewModel object, String file,
2800 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
2802 SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
2803 Sequence[] vamsasSeq = vamsasSet.getSequence();
2805 JalviewModelSequence jms = object.getJalviewModelSequence();
2807 Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
2810 // ////////////////////////////////
2813 List<SequenceI> hiddenSeqs = null;
2816 List<SequenceI> tmpseqs = new ArrayList<SequenceI>();
2818 boolean multipleView = false;
2819 SequenceI referenceseqForView = null;
2820 JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
2821 int vi = 0; // counter in vamsasSeq array
2822 for (int i = 0; i < jseqs.length; i++)
2824 String seqId = jseqs[i].getId();
2826 SequenceI tmpSeq = seqRefIds.get(seqId);
2829 if (!incompleteSeqs.containsKey(seqId))
2831 // may not need this check, but keep it for at least 2.9,1 release
2832 if (tmpSeq.getStart()!=jseqs[i].getStart() || tmpSeq.getEnd()!=jseqs[i].getEnd())
2835 .println("Warning JAL-2154 regression: updating start/end for sequence "
2836 + tmpSeq.toString() + " to " + jseqs[i]);
2839 incompleteSeqs.remove(seqId);
2841 if (vamsasSeq.length > vi && vamsasSeq[vi].getId().equals(seqId))
2843 // most likely we are reading a dataset XML document so
2844 // update from vamsasSeq section of XML for this sequence
2845 tmpSeq.setName(vamsasSeq[vi].getName());
2846 tmpSeq.setDescription(vamsasSeq[vi].getDescription());
2847 tmpSeq.setSequence(vamsasSeq[vi].getSequence());
2852 // reading multiple views, so vamsasSeq set is a subset of JSeq
2853 multipleView = true;
2855 tmpSeq.setStart(jseqs[i].getStart());
2856 tmpSeq.setEnd(jseqs[i].getEnd());
2857 tmpseqs.add(tmpSeq);
2861 tmpSeq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
2862 vamsasSeq[vi].getSequence());
2863 tmpSeq.setDescription(vamsasSeq[vi].getDescription());
2864 tmpSeq.setStart(jseqs[i].getStart());
2865 tmpSeq.setEnd(jseqs[i].getEnd());
2866 tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
2867 seqRefIds.put(vamsasSeq[vi].getId(), tmpSeq);
2868 tmpseqs.add(tmpSeq);
2872 if (jseqs[i].hasViewreference() && jseqs[i].getViewreference())
2874 referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
2877 if (jseqs[i].getHidden())
2879 if (hiddenSeqs == null)
2881 hiddenSeqs = new ArrayList<SequenceI>();
2884 hiddenSeqs.add(tmpSeq);
2889 // Create the alignment object from the sequence set
2890 // ///////////////////////////////
2891 SequenceI[] orderedSeqs = tmpseqs
2892 .toArray(new SequenceI[tmpseqs.size()]);
2894 AlignmentI al = null;
2895 // so we must create or recover the dataset alignment before going further
2896 // ///////////////////////////////
2897 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
2899 // older jalview projects do not have a dataset - so creat alignment and
2901 al = new Alignment(orderedSeqs);
2902 al.setDataset(null);
2906 boolean isdsal = object.getJalviewModelSequence().getViewportCount() == 0;
2909 // we are importing a dataset record, so
2910 // recover reference to an alignment already materialsed as dataset
2911 al = getDatasetFor(vamsasSet.getDatasetId());
2915 // materialse the alignment
2916 al = new Alignment(orderedSeqs);
2920 addDatasetRef(vamsasSet.getDatasetId(), al);
2923 // finally, verify all data in vamsasSet is actually present in al
2924 // passing on flag indicating if it is actually a stored dataset
2925 recoverDatasetFor(vamsasSet, al, isdsal);
2928 if (referenceseqForView != null)
2930 al.setSeqrep(referenceseqForView);
2932 // / Add the alignment properties
2933 for (int i = 0; i < vamsasSet.getSequenceSetPropertiesCount(); i++)
2935 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties(i);
2936 al.setProperty(ssp.getKey(), ssp.getValue());
2939 // ///////////////////////////////
2941 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
2944 // load sequence features, database references and any associated PDB
2945 // structures for the alignment
2947 // prior to 2.10, this part would only be executed the first time a
2948 // sequence was encountered, but not afterwards.
2949 // now, for 2.10 projects, this is also done if the xml doc includes
2950 // dataset sequences not actually present in any particular view.
2952 for (int i = 0; i < vamsasSeq.length; i++)
2954 if (jseqs[i].getFeaturesCount() > 0)
2956 Features[] features = jseqs[i].getFeatures();
2957 for (int f = 0; f < features.length; f++)
2959 jalview.datamodel.SequenceFeature sf = new jalview.datamodel.SequenceFeature(
2960 features[f].getType(), features[f].getDescription(),
2961 features[f].getStatus(), features[f].getBegin(),
2962 features[f].getEnd(), features[f].getFeatureGroup());
2964 sf.setScore(features[f].getScore());
2965 for (int od = 0; od < features[f].getOtherDataCount(); od++)
2967 OtherData keyValue = features[f].getOtherData(od);
2968 if (keyValue.getKey().startsWith("LINK"))
2970 sf.addLink(keyValue.getValue());
2974 sf.setValue(keyValue.getKey(), keyValue.getValue());
2978 // adds feature to datasequence's feature set (since Jalview 2.10)
2979 al.getSequenceAt(i).addSequenceFeature(sf);
2982 if (vamsasSeq[i].getDBRefCount() > 0)
2984 // adds dbrefs to datasequence's set (since Jalview 2.10)
2986 al.getSequenceAt(i).getDatasetSequence() == null ? al.getSequenceAt(i)
2987 : al.getSequenceAt(i).getDatasetSequence(),
2990 if (jseqs[i].getPdbidsCount() > 0)
2992 Pdbids[] ids = jseqs[i].getPdbids();
2993 for (int p = 0; p < ids.length; p++)
2995 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
2996 entry.setId(ids[p].getId());
2997 if (ids[p].getType() != null)
2999 if (PDBEntry.Type.getType(ids[p].getType()) != null)
3001 entry.setType(PDBEntry.Type.getType(ids[p].getType()));
3005 entry.setType(PDBEntry.Type.FILE);
3008 if (ids[p].getFile() != null)
3010 if (!pdbloaded.containsKey(ids[p].getFile()))
3012 entry.setFile(loadPDBFile(jprovider, ids[p].getId(),
3017 entry.setFile(pdbloaded.get(ids[p].getId()).toString());
3020 if (ids[p].getPdbentryItem() != null)
3022 entry.setProperty(new Hashtable());
3023 for (PdbentryItem item : ids[p].getPdbentryItem())
3025 for (Property pr : item.getProperty())
3027 entry.getProperty().put(pr.getName(), pr.getValue());
3031 StructureSelectionManager.getStructureSelectionManager(
3032 Desktop.instance).registerPDBEntry(entry);
3033 // adds PDBEntry to datasequence's set (since Jalview 2.10)
3034 if (al.getSequenceAt(i).getDatasetSequence() != null)
3036 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
3040 al.getSequenceAt(i).addPDBId(entry);
3045 } // end !multipleview
3047 // ///////////////////////////////
3048 // LOAD SEQUENCE MAPPINGS
3050 if (vamsasSet.getAlcodonFrameCount() > 0)
3052 // TODO Potentially this should only be done once for all views of an
3054 AlcodonFrame[] alc = vamsasSet.getAlcodonFrame();
3055 for (int i = 0; i < alc.length; i++)
3057 AlignedCodonFrame cf = new AlignedCodonFrame();
3058 if (alc[i].getAlcodMapCount() > 0)
3060 AlcodMap[] maps = alc[i].getAlcodMap();
3061 for (int m = 0; m < maps.length; m++)
3063 SequenceI dnaseq = seqRefIds.get(maps[m].getDnasq());
3065 jalview.datamodel.Mapping mapping = null;
3066 // attach to dna sequence reference.
3067 if (maps[m].getMapping() != null)
3069 mapping = addMapping(maps[m].getMapping());
3070 if (dnaseq != null && mapping.getTo() != null)
3072 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
3077 frefedSequence.add(newAlcodMapRef(maps[m].getDnasq(), cf,
3082 al.addCodonFrame(cf);
3087 // ////////////////////////////////
3089 List<JvAnnotRow> autoAlan = new ArrayList<JvAnnotRow>();
3092 * store any annotations which forward reference a group's ID
3094 Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<String, List<AlignmentAnnotation>>();
3096 if (vamsasSet.getAnnotationCount() > 0)
3098 Annotation[] an = vamsasSet.getAnnotation();
3100 for (int i = 0; i < an.length; i++)
3102 Annotation annotation = an[i];
3105 * test if annotation is automatically calculated for this view only
3107 boolean autoForView = false;
3108 if (annotation.getLabel().equals("Quality")
3109 || annotation.getLabel().equals("Conservation")
3110 || annotation.getLabel().equals("Consensus"))
3112 // Kludge for pre 2.5 projects which lacked the autocalculated flag
3114 if (!annotation.hasAutoCalculated())
3116 annotation.setAutoCalculated(true);
3120 || (annotation.hasAutoCalculated() && annotation
3121 .isAutoCalculated()))
3123 // remove ID - we don't recover annotation from other views for
3124 // view-specific annotation
3125 annotation.setId(null);
3128 // set visiblity for other annotation in this view
3129 String annotationId = annotation.getId();
3130 if (annotationId != null && annotationIds.containsKey(annotationId))
3132 AlignmentAnnotation jda = annotationIds.get(annotationId);
3133 // in principle Visible should always be true for annotation displayed
3134 // in multiple views
3135 if (annotation.hasVisible())
3137 jda.visible = annotation.getVisible();
3140 al.addAnnotation(jda);
3144 // Construct new annotation from model.
3145 AnnotationElement[] ae = annotation.getAnnotationElement();
3146 jalview.datamodel.Annotation[] anot = null;
3147 java.awt.Color firstColour = null;
3149 if (!annotation.getScoreOnly())
3151 anot = new jalview.datamodel.Annotation[al.getWidth()];
3152 for (int aa = 0; aa < ae.length && aa < anot.length; aa++)
3154 anpos = ae[aa].getPosition();
3156 if (anpos >= anot.length)
3161 anot[anpos] = new jalview.datamodel.Annotation(
3163 ae[aa].getDisplayCharacter(), ae[aa].getDescription(),
3164 (ae[aa].getSecondaryStructure() == null || ae[aa]
3165 .getSecondaryStructure().length() == 0) ? ' '
3166 : ae[aa].getSecondaryStructure().charAt(0),
3170 // JBPNote: Consider verifying dataflow for IO of secondary
3171 // structure annotation read from Stockholm files
3172 // this was added to try to ensure that
3173 // if (anot[ae[aa].getPosition()].secondaryStructure>' ')
3175 // anot[ae[aa].getPosition()].displayCharacter = "";
3177 anot[anpos].colour = new java.awt.Color(ae[aa].getColour());
3178 if (firstColour == null)
3180 firstColour = anot[anpos].colour;
3184 jalview.datamodel.AlignmentAnnotation jaa = null;
3186 if (annotation.getGraph())
3188 float llim = 0, hlim = 0;
3189 // if (autoForView || an[i].isAutoCalculated()) {
3192 jaa = new jalview.datamodel.AlignmentAnnotation(
3193 annotation.getLabel(), annotation.getDescription(), anot,
3194 llim, hlim, annotation.getGraphType());
3196 jaa.graphGroup = annotation.getGraphGroup();
3197 jaa._linecolour = firstColour;
3198 if (annotation.getThresholdLine() != null)
3200 jaa.setThreshold(new jalview.datamodel.GraphLine(annotation
3201 .getThresholdLine().getValue(), annotation
3202 .getThresholdLine().getLabel(), new java.awt.Color(
3203 annotation.getThresholdLine().getColour())));
3206 if (autoForView || annotation.isAutoCalculated())
3208 // Hardwire the symbol display line to ensure that labels for
3209 // histograms are displayed
3215 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
3216 an[i].getDescription(), anot);
3217 jaa._linecolour = firstColour;
3219 // register new annotation
3220 if (an[i].getId() != null)
3222 annotationIds.put(an[i].getId(), jaa);
3223 jaa.annotationId = an[i].getId();
3225 // recover sequence association
3226 String sequenceRef = an[i].getSequenceRef();
3227 if (sequenceRef != null)
3229 // from 2.9 sequenceRef is to sequence id (JAL-1781)
3230 SequenceI sequence = seqRefIds.get(sequenceRef);
3231 if (sequence == null)
3233 // in pre-2.9 projects sequence ref is to sequence name
3234 sequence = al.findName(sequenceRef);
3236 if (sequence != null)
3238 jaa.createSequenceMapping(sequence, 1, true);
3239 sequence.addAlignmentAnnotation(jaa);
3242 // and make a note of any group association
3243 if (an[i].getGroupRef() != null && an[i].getGroupRef().length() > 0)
3245 List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
3246 .get(an[i].getGroupRef());
3249 aal = new ArrayList<jalview.datamodel.AlignmentAnnotation>();
3250 groupAnnotRefs.put(an[i].getGroupRef(), aal);
3255 if (an[i].hasScore())
3257 jaa.setScore(an[i].getScore());
3259 if (an[i].hasVisible())
3261 jaa.visible = an[i].getVisible();
3264 if (an[i].hasCentreColLabels())
3266 jaa.centreColLabels = an[i].getCentreColLabels();
3269 if (an[i].hasScaleColLabels())
3271 jaa.scaleColLabel = an[i].getScaleColLabels();
3273 if (an[i].hasAutoCalculated() && an[i].isAutoCalculated())
3275 // newer files have an 'autoCalculated' flag and store calculation
3276 // state in viewport properties
3277 jaa.autoCalculated = true; // means annotation will be marked for
3278 // update at end of load.
3280 if (an[i].hasGraphHeight())
3282 jaa.graphHeight = an[i].getGraphHeight();
3284 if (an[i].hasBelowAlignment())
3286 jaa.belowAlignment = an[i].isBelowAlignment();
3288 jaa.setCalcId(an[i].getCalcId());
3289 if (an[i].getPropertyCount() > 0)
3291 for (jalview.schemabinding.version2.Property prop : an[i]
3294 jaa.setProperty(prop.getName(), prop.getValue());
3297 if (jaa.autoCalculated)
3299 autoAlan.add(new JvAnnotRow(i, jaa));
3302 // if (!autoForView)
3304 // add autocalculated group annotation and any user created annotation
3306 al.addAnnotation(jaa);
3310 // ///////////////////////
3312 // Create alignment markup and styles for this view
3313 if (jms.getJGroupCount() > 0)
3315 JGroup[] groups = jms.getJGroup();
3316 boolean addAnnotSchemeGroup = false;
3317 for (int i = 0; i < groups.length; i++)
3319 JGroup jGroup = groups[i];
3320 ColourSchemeI cs = null;
3321 if (jGroup.getColour() != null)
3323 if (jGroup.getColour().startsWith("ucs"))
3325 cs = getUserColourScheme(jms, jGroup.getColour());
3327 else if (jGroup.getColour().equals("AnnotationColourGradient")
3328 && jGroup.getAnnotationColours() != null)
3330 addAnnotSchemeGroup = true;
3335 cs = ColourSchemeProperty.getColour(al, jGroup.getColour());
3340 cs.setThreshold(jGroup.getPidThreshold(), true);
3344 Vector<SequenceI> seqs = new Vector<SequenceI>();
3346 for (int s = 0; s < jGroup.getSeqCount(); s++)
3348 String seqId = jGroup.getSeq(s) + "";
3349 SequenceI ts = seqRefIds.get(seqId);
3353 seqs.addElement(ts);
3357 if (seqs.size() < 1)
3362 SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
3363 jGroup.getDisplayBoxes(), jGroup.getDisplayText(),
3364 jGroup.getColourText(), jGroup.getStart(), jGroup.getEnd());
3366 sg.setOutlineColour(new java.awt.Color(jGroup.getOutlineColour()));
3368 sg.textColour = new java.awt.Color(jGroup.getTextCol1());
3369 sg.textColour2 = new java.awt.Color(jGroup.getTextCol2());
3370 sg.setShowNonconserved(jGroup.hasShowUnconserved() ? jGroup
3371 .isShowUnconserved() : false);
3372 sg.thresholdTextColour = jGroup.getTextColThreshold();
3373 if (jGroup.hasShowConsensusHistogram())
3375 sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
3378 if (jGroup.hasShowSequenceLogo())
3380 sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
3382 if (jGroup.hasNormaliseSequenceLogo())
3384 sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
3386 if (jGroup.hasIgnoreGapsinConsensus())
3388 sg.setIgnoreGapsConsensus(jGroup.getIgnoreGapsinConsensus());
3390 if (jGroup.getConsThreshold() != 0)
3392 jalview.analysis.Conservation c = new jalview.analysis.Conservation(
3393 "All", ResidueProperties.propHash, 3,
3394 sg.getSequences(null), 0, sg.getWidth() - 1);
3396 c.verdict(false, 25);
3397 sg.cs.setConservation(c);
3400 if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
3402 // re-instate unique group/annotation row reference
3403 List<AlignmentAnnotation> jaal = groupAnnotRefs.get(jGroup
3407 for (AlignmentAnnotation jaa : jaal)
3410 if (jaa.autoCalculated)
3412 // match up and try to set group autocalc alignment row for this
3414 if (jaa.label.startsWith("Consensus for "))
3416 sg.setConsensus(jaa);
3418 // match up and try to set group autocalc alignment row for this
3420 if (jaa.label.startsWith("Conservation for "))
3422 sg.setConservationRow(jaa);
3429 if (addAnnotSchemeGroup)
3431 // reconstruct the annotation colourscheme
3432 sg.cs = constructAnnotationColour(jGroup.getAnnotationColours(),
3433 null, al, jms, false);
3439 // only dataset in this model, so just return.
3442 // ///////////////////////////////
3445 // If we just load in the same jar file again, the sequenceSetId
3446 // will be the same, and we end up with multiple references
3447 // to the same sequenceSet. We must modify this id on load
3448 // so that each load of the file gives a unique id
3449 String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
3450 String viewId = (view.getId() == null ? null : view.getId()
3452 AlignFrame af = null;
3453 AlignViewport av = null;
3454 // now check to see if we really need to create a new viewport.
3455 if (multipleView && viewportsAdded.size() == 0)
3457 // We recovered an alignment for which a viewport already exists.
3458 // TODO: fix up any settings necessary for overlaying stored state onto
3459 // state recovered from another document. (may not be necessary).
3460 // we may need a binding from a viewport in memory to one recovered from
3462 // and then recover its containing af to allow the settings to be applied.
3463 // TODO: fix for vamsas demo
3465 .println("About to recover a viewport for existing alignment: Sequence set ID is "
3467 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
3468 if (seqsetobj != null)
3470 if (seqsetobj instanceof String)
3472 uniqueSeqSetId = (String) seqsetobj;
3474 .println("Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
3480 .println("Warning : Collision between sequence set ID string and existing jalview object mapping.");
3486 * indicate that annotation colours are applied across all groups (pre
3487 * Jalview 2.8.1 behaviour)
3489 boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan(
3490 "2.8.1", object.getVersion());
3492 AlignmentPanel ap = null;
3493 boolean isnewview = true;
3496 // Check to see if this alignment already has a view id == viewId
3497 jalview.gui.AlignmentPanel views[] = Desktop
3498 .getAlignmentPanels(uniqueSeqSetId);
3499 if (views != null && views.length > 0)
3501 for (int v = 0; v < views.length; v++)
3503 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
3505 // recover the existing alignpanel, alignframe, viewport
3506 af = views[v].alignFrame;
3509 // TODO: could even skip resetting view settings if we don't want to
3510 // change the local settings from other jalview processes
3519 af = loadViewport(file, jseqs, hiddenSeqs, al, jms, view,
3520 uniqueSeqSetId, viewId, autoAlan);
3526 * Load any trees, PDB structures and viewers
3528 * Not done if flag is false (when this method is used for New View)
3530 if (loadTreesAndStructures)
3532 loadTrees(jms, view, af, av, ap);
3533 loadPDBStructures(jprovider, jseqs, af, ap);
3534 loadRnaViewers(jprovider, jseqs, ap);
3536 // and finally return.
3541 * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
3542 * panel is restored from separate jar entries, two (gapped and trimmed) per
3543 * sequence and secondary structure.
3545 * Currently each viewer shows just one sequence and structure (gapped and
3546 * trimmed), however this method is designed to support multiple sequences or
3547 * structures in viewers if wanted in future.
3553 private void loadRnaViewers(jarInputStreamProvider jprovider,
3554 JSeq[] jseqs, AlignmentPanel ap)
3557 * scan the sequences for references to viewers; create each one the first
3558 * time it is referenced, add Rna models to existing viewers
3560 for (JSeq jseq : jseqs)
3562 for (int i = 0; i < jseq.getRnaViewerCount(); i++)
3564 RnaViewer viewer = jseq.getRnaViewer(i);
3565 AppVarna appVarna = findOrCreateVarnaViewer(viewer,
3566 uniqueSetSuffix, ap);
3568 for (int j = 0; j < viewer.getSecondaryStructureCount(); j++)
3570 SecondaryStructure ss = viewer.getSecondaryStructure(j);
3571 SequenceI seq = seqRefIds.get(jseq.getId());
3572 AlignmentAnnotation ann = this.annotationIds.get(ss
3573 .getAnnotationId());
3576 * add the structure to the Varna display (with session state copied
3577 * from the jar to a temporary file)
3579 boolean gapped = ss.isGapped();
3580 String rnaTitle = ss.getTitle();
3581 String sessionState = ss.getViewerState();
3582 String tempStateFile = copyJarEntry(jprovider, sessionState,
3584 RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
3585 appVarna.addModelSession(rna, rnaTitle, tempStateFile);
3587 appVarna.setInitialSelection(viewer.getSelectedRna());
3593 * Locate and return an already instantiated matching AppVarna, or create one
3597 * @param viewIdSuffix
3601 protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
3602 String viewIdSuffix, AlignmentPanel ap)
3605 * on each load a suffix is appended to the saved viewId, to avoid conflicts
3606 * if load is repeated
3608 String postLoadId = viewer.getViewId() + viewIdSuffix;
3609 for (JInternalFrame frame : getAllFrames())
3611 if (frame instanceof AppVarna)
3613 AppVarna varna = (AppVarna) frame;
3614 if (postLoadId.equals(varna.getViewId()))
3616 // this viewer is already instantiated
3617 // could in future here add ap as another 'parent' of the
3618 // AppVarna window; currently just 1-to-many
3625 * viewer not found - make it
3627 RnaViewerModel model = new RnaViewerModel(postLoadId,
3628 viewer.getTitle(), viewer.getXpos(), viewer.getYpos(),
3629 viewer.getWidth(), viewer.getHeight(),
3630 viewer.getDividerLocation());
3631 AppVarna varna = new AppVarna(model, ap);
3637 * Load any saved trees
3645 protected void loadTrees(JalviewModelSequence jms, Viewport view,
3646 AlignFrame af, AlignViewport av, AlignmentPanel ap)
3648 // TODO result of automated refactoring - are all these parameters needed?
3651 for (int t = 0; t < jms.getTreeCount(); t++)
3654 Tree tree = jms.getTree(t);
3656 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
3659 tp = af.ShowNewickTree(
3660 new jalview.io.NewickFile(tree.getNewick()),
3661 tree.getTitle(), tree.getWidth(), tree.getHeight(),
3662 tree.getXpos(), tree.getYpos());
3663 if (tree.getId() != null)
3665 // perhaps bind the tree id to something ?
3670 // update local tree attributes ?
3671 // TODO: should check if tp has been manipulated by user - if so its
3672 // settings shouldn't be modified
3673 tp.setTitle(tree.getTitle());
3674 tp.setBounds(new Rectangle(tree.getXpos(), tree.getYpos(), tree
3675 .getWidth(), tree.getHeight()));
3676 tp.av = av; // af.viewport; // TODO: verify 'associate with all
3679 tp.treeCanvas.av = av; // af.viewport;
3680 tp.treeCanvas.ap = ap; // af.alignPanel;
3685 warn("There was a problem recovering stored Newick tree: \n"
3686 + tree.getNewick());
3690 tp.fitToWindow.setState(tree.getFitToWindow());
3691 tp.fitToWindow_actionPerformed(null);
3693 if (tree.getFontName() != null)
3695 tp.setTreeFont(new java.awt.Font(tree.getFontName(), tree
3696 .getFontStyle(), tree.getFontSize()));
3700 tp.setTreeFont(new java.awt.Font(view.getFontName(), view
3701 .getFontStyle(), tree.getFontSize()));
3704 tp.showPlaceholders(tree.getMarkUnlinked());
3705 tp.showBootstrap(tree.getShowBootstrap());
3706 tp.showDistances(tree.getShowDistances());
3708 tp.treeCanvas.threshold = tree.getThreshold();
3710 if (tree.getCurrentTree())
3712 af.viewport.setCurrentTree(tp.getTree());
3716 } catch (Exception ex)
3718 ex.printStackTrace();
3723 * Load and link any saved structure viewers.
3730 protected void loadPDBStructures(jarInputStreamProvider jprovider,
3731 JSeq[] jseqs, AlignFrame af, AlignmentPanel ap)
3734 * Run through all PDB ids on the alignment, and collect mappings between
3735 * distinct view ids and all sequences referring to that view.
3737 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<String, StructureViewerModel>();
3739 for (int i = 0; i < jseqs.length; i++)
3741 if (jseqs[i].getPdbidsCount() > 0)
3743 Pdbids[] ids = jseqs[i].getPdbids();
3744 for (int p = 0; p < ids.length; p++)
3746 final int structureStateCount = ids[p].getStructureStateCount();
3747 for (int s = 0; s < structureStateCount; s++)
3749 // check to see if we haven't already created this structure view
3750 final StructureState structureState = ids[p]
3751 .getStructureState(s);
3752 String sviewid = (structureState.getViewId() == null) ? null
3753 : structureState.getViewId() + uniqueSetSuffix;
3754 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
3755 // Originally : ids[p].getFile()
3756 // : TODO: verify external PDB file recovery still works in normal
3757 // jalview project load
3758 jpdb.setFile(loadPDBFile(jprovider, ids[p].getId(),
3760 jpdb.setId(ids[p].getId());
3762 int x = structureState.getXpos();
3763 int y = structureState.getYpos();
3764 int width = structureState.getWidth();
3765 int height = structureState.getHeight();
3767 // Probably don't need to do this anymore...
3768 // Desktop.desktop.getComponentAt(x, y);
3769 // TODO: NOW: check that this recovers the PDB file correctly.
3770 String pdbFile = loadPDBFile(jprovider, ids[p].getId(),
3772 jalview.datamodel.SequenceI seq = seqRefIds.get(jseqs[i]
3774 if (sviewid == null)
3776 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width
3779 if (!structureViewers.containsKey(sviewid))
3781 structureViewers.put(sviewid,
3782 new StructureViewerModel(x, y, width, height, false,
3783 false, true, structureState.getViewId(),
3784 structureState.getType()));
3785 // Legacy pre-2.7 conversion JAL-823 :
3786 // do not assume any view has to be linked for colour by
3790 // assemble String[] { pdb files }, String[] { id for each
3791 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
3792 // seqs_file 2}, boolean[] {
3793 // linkAlignPanel,superposeWithAlignpanel}} from hash
3794 StructureViewerModel jmoldat = structureViewers.get(sviewid);
3795 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
3796 | (structureState.hasAlignwithAlignPanel() ? structureState
3797 .getAlignwithAlignPanel() : false));
3800 * Default colour by linked panel to false if not specified (e.g.
3801 * for pre-2.7 projects)
3803 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
3804 colourWithAlignPanel |= (structureState
3805 .hasColourwithAlignPanel() ? structureState
3806 .getColourwithAlignPanel() : false);
3807 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
3810 * Default colour by viewer to true if not specified (e.g. for
3813 boolean colourByViewer = jmoldat.isColourByViewer();
3814 colourByViewer &= structureState.hasColourByJmol() ? structureState
3815 .getColourByJmol() : true;
3816 jmoldat.setColourByViewer(colourByViewer);
3818 if (jmoldat.getStateData().length() < structureState
3819 .getContent().length())
3822 jmoldat.setStateData(structureState.getContent());
3825 if (ids[p].getFile() != null)
3827 File mapkey = new File(ids[p].getFile());
3828 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
3829 if (seqstrmaps == null)
3831 jmoldat.getFileData().put(
3833 seqstrmaps = jmoldat.new StructureData(pdbFile,
3836 if (!seqstrmaps.getSeqList().contains(seq))
3838 seqstrmaps.getSeqList().add(seq);
3844 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");
3851 // Instantiate the associated structure views
3852 for (Entry<String, StructureViewerModel> entry : structureViewers
3857 createOrLinkStructureViewer(entry, af, ap, jprovider);
3858 } catch (Exception e)
3860 System.err.println("Error loading structure viewer: "
3862 // failed - try the next one
3874 protected void createOrLinkStructureViewer(
3875 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
3876 AlignmentPanel ap, jarInputStreamProvider jprovider)
3878 final StructureViewerModel stateData = viewerData.getValue();
3881 * Search for any viewer windows already open from other alignment views
3882 * that exactly match the stored structure state
3884 StructureViewerBase comp = findMatchingViewer(viewerData);
3888 linkStructureViewer(ap, comp, stateData);
3893 * From 2.9: stateData.type contains JMOL or CHIMERA, data is in jar entry
3894 * "viewer_"+stateData.viewId
3896 if (ViewerType.CHIMERA.toString().equals(stateData.getType()))
3898 createChimeraViewer(viewerData, af, jprovider);
3903 * else Jmol (if pre-2.9, stateData contains JMOL state string)
3905 createJmolViewer(viewerData, af, jprovider);
3910 * Create a new Chimera viewer.
3916 protected void createChimeraViewer(
3917 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
3918 jarInputStreamProvider jprovider)
3920 StructureViewerModel data = viewerData.getValue();
3921 String chimeraSessionFile = data.getStateData();
3924 * Copy Chimera session from jar entry "viewer_"+viewId to a temporary file
3926 * NB this is the 'saved' viewId as in the project file XML, _not_ the
3927 * 'uniquified' sviewid used to reconstruct the viewer here
3929 String viewerJarEntryName = getViewerJarEntryName(data.getViewId());
3930 chimeraSessionFile = copyJarEntry(jprovider, viewerJarEntryName,
3933 Set<Entry<File, StructureData>> fileData = data.getFileData()
3935 List<PDBEntry> pdbs = new ArrayList<PDBEntry>();
3936 List<SequenceI[]> allseqs = new ArrayList<SequenceI[]>();
3937 for (Entry<File, StructureData> pdb : fileData)
3939 String filePath = pdb.getValue().getFilePath();
3940 String pdbId = pdb.getValue().getPdbId();
3941 // pdbs.add(new PDBEntry(filePath, pdbId));
3942 pdbs.add(new PDBEntry(pdbId, null, PDBEntry.Type.PDB, filePath));
3943 final List<SequenceI> seqList = pdb.getValue().getSeqList();
3944 SequenceI[] seqs = seqList.toArray(new SequenceI[seqList.size()]);
3948 boolean colourByChimera = data.isColourByViewer();
3949 boolean colourBySequence = data.isColourWithAlignPanel();
3951 // TODO use StructureViewer as a factory here, see JAL-1761
3952 final PDBEntry[] pdbArray = pdbs.toArray(new PDBEntry[pdbs.size()]);
3953 final SequenceI[][] seqsArray = allseqs.toArray(new SequenceI[allseqs
3955 String newViewId = viewerData.getKey();
3957 ChimeraViewFrame cvf = new ChimeraViewFrame(chimeraSessionFile,
3958 af.alignPanel, pdbArray, seqsArray, colourByChimera,
3959 colourBySequence, newViewId);
3960 cvf.setSize(data.getWidth(), data.getHeight());
3961 cvf.setLocation(data.getX(), data.getY());
3965 * Create a new Jmol window. First parse the Jmol state to translate filenames
3966 * loaded into the view, and record the order in which files are shown in the
3967 * Jmol view, so we can add the sequence mappings in same order.
3973 protected void createJmolViewer(
3974 final Entry<String, StructureViewerModel> viewerData,
3975 AlignFrame af, jarInputStreamProvider jprovider)
3977 final StructureViewerModel svattrib = viewerData.getValue();
3978 String state = svattrib.getStateData();
3981 * Pre-2.9: state element value is the Jmol state string
3983 * 2.9+: @type is "JMOL", state data is in a Jar file member named "viewer_"
3986 if (ViewerType.JMOL.toString().equals(svattrib.getType()))
3988 state = readJarEntry(jprovider,
3989 getViewerJarEntryName(svattrib.getViewId()));
3992 List<String> pdbfilenames = new ArrayList<String>();
3993 List<SequenceI[]> seqmaps = new ArrayList<SequenceI[]>();
3994 List<String> pdbids = new ArrayList<String>();
3995 StringBuilder newFileLoc = new StringBuilder(64);
3996 int cp = 0, ncp, ecp;
3997 Map<File, StructureData> oldFiles = svattrib.getFileData();
3998 while ((ncp = state.indexOf("load ", cp)) > -1)
4002 // look for next filename in load statement
4003 newFileLoc.append(state.substring(cp,
4004 ncp = (state.indexOf("\"", ncp + 1) + 1)));
4005 String oldfilenam = state.substring(ncp,
4006 ecp = state.indexOf("\"", ncp));
4007 // recover the new mapping data for this old filename
4008 // have to normalize filename - since Jmol and jalview do
4010 // translation differently.
4011 StructureData filedat = oldFiles.get(new File(oldfilenam));
4012 if (filedat == null)
4014 String reformatedOldFilename = oldfilenam.replaceAll("/",
4016 filedat = oldFiles.get(new File(reformatedOldFilename));
4018 newFileLoc.append(Platform.escapeString(filedat.getFilePath()));
4019 pdbfilenames.add(filedat.getFilePath());
4020 pdbids.add(filedat.getPdbId());
4021 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4022 newFileLoc.append("\"");
4023 cp = ecp + 1; // advance beyond last \" and set cursor so we can
4024 // look for next file statement.
4025 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
4029 // just append rest of state
4030 newFileLoc.append(state.substring(cp));
4034 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
4035 newFileLoc = new StringBuilder(state);
4036 newFileLoc.append("; load append ");
4037 for (File id : oldFiles.keySet())
4039 // add this and any other pdb files that should be present in
4041 StructureData filedat = oldFiles.get(id);
4042 newFileLoc.append(filedat.getFilePath());
4043 pdbfilenames.add(filedat.getFilePath());
4044 pdbids.add(filedat.getPdbId());
4045 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4046 newFileLoc.append(" \"");
4047 newFileLoc.append(filedat.getFilePath());
4048 newFileLoc.append("\"");
4051 newFileLoc.append(";");
4054 if (newFileLoc.length() == 0)
4058 int histbug = newFileLoc.indexOf("history = ");
4062 * change "history = [true|false];" to "history = [1|0];"
4065 int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";", histbug);
4066 String val = (diff == -1) ? null : newFileLoc
4067 .substring(histbug, diff);
4068 if (val != null && val.length() >= 4)
4070 if (val.contains("e")) // eh? what can it be?
4072 if (val.trim().equals("true"))
4080 newFileLoc.replace(histbug, diff, val);
4085 final String[] pdbf = pdbfilenames.toArray(new String[pdbfilenames
4087 final String[] id = pdbids.toArray(new String[pdbids.size()]);
4088 final SequenceI[][] sq = seqmaps
4089 .toArray(new SequenceI[seqmaps.size()][]);
4090 final String fileloc = newFileLoc.toString();
4091 final String sviewid = viewerData.getKey();
4092 final AlignFrame alf = af;
4093 final Rectangle rect = new Rectangle(svattrib.getX(), svattrib.getY(),
4094 svattrib.getWidth(), svattrib.getHeight());
4097 javax.swing.SwingUtilities.invokeAndWait(new Runnable()
4102 JalviewStructureDisplayI sview = null;
4105 sview = new StructureViewer(alf.alignPanel
4106 .getStructureSelectionManager()).createView(
4107 StructureViewer.ViewerType.JMOL, pdbf, id, sq,
4108 alf.alignPanel, svattrib, fileloc, rect, sviewid);
4109 addNewStructureViewer(sview);
4110 } catch (OutOfMemoryError ex)
4112 new OOMWarning("restoring structure view for PDB id " + id,
4113 (OutOfMemoryError) ex.getCause());
4114 if (sview != null && sview.isVisible())
4116 sview.closeViewer(false);
4117 sview.setVisible(false);
4123 } catch (InvocationTargetException ex)
4125 warn("Unexpected error when opening Jmol view.", ex);
4127 } catch (InterruptedException e)
4129 // e.printStackTrace();
4135 * Generates a name for the entry in the project jar file to hold state
4136 * information for a structure viewer
4141 protected String getViewerJarEntryName(String viewId)
4143 return VIEWER_PREFIX + viewId;
4147 * Returns any open frame that matches given structure viewer data. The match
4148 * is based on the unique viewId, or (for older project versions) the frame's
4154 protected StructureViewerBase findMatchingViewer(
4155 Entry<String, StructureViewerModel> viewerData)
4157 final String sviewid = viewerData.getKey();
4158 final StructureViewerModel svattrib = viewerData.getValue();
4159 StructureViewerBase comp = null;
4160 JInternalFrame[] frames = getAllFrames();
4161 for (JInternalFrame frame : frames)
4163 if (frame instanceof StructureViewerBase)
4166 * Post jalview 2.4 schema includes structure view id
4169 && ((StructureViewerBase) frame).getViewId()
4172 comp = (StructureViewerBase) frame;
4173 break; // break added in 2.9
4176 * Otherwise test for matching position and size of viewer frame
4178 else if (frame.getX() == svattrib.getX()
4179 && frame.getY() == svattrib.getY()
4180 && frame.getHeight() == svattrib.getHeight()
4181 && frame.getWidth() == svattrib.getWidth())
4183 comp = (StructureViewerBase) frame;
4184 // no break in faint hope of an exact match on viewId
4192 * Link an AlignmentPanel to an existing structure viewer.
4197 * @param useinViewerSuperpos
4198 * @param usetoColourbyseq
4199 * @param viewerColouring
4201 protected void linkStructureViewer(AlignmentPanel ap,
4202 StructureViewerBase viewer, StructureViewerModel stateData)
4204 // NOTE: if the jalview project is part of a shared session then
4205 // view synchronization should/could be done here.
4207 final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
4208 final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
4209 final boolean viewerColouring = stateData.isColourByViewer();
4210 Map<File, StructureData> oldFiles = stateData.getFileData();
4213 * Add mapping for sequences in this view to an already open viewer
4215 final AAStructureBindingModel binding = viewer.getBinding();
4216 for (File id : oldFiles.keySet())
4218 // add this and any other pdb files that should be present in the
4220 StructureData filedat = oldFiles.get(id);
4221 String pdbFile = filedat.getFilePath();
4222 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
4223 binding.getSsm().setMapping(seq, null, pdbFile,
4224 jalview.io.AppletFormatAdapter.FILE);
4225 binding.addSequenceForStructFile(pdbFile, seq);
4227 // and add the AlignmentPanel's reference to the view panel
4228 viewer.addAlignmentPanel(ap);
4229 if (useinViewerSuperpos)
4231 viewer.useAlignmentPanelForSuperposition(ap);
4235 viewer.excludeAlignmentPanelForSuperposition(ap);
4237 if (usetoColourbyseq)
4239 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
4243 viewer.excludeAlignmentPanelForColourbyseq(ap);
4248 * Get all frames within the Desktop.
4252 protected JInternalFrame[] getAllFrames()
4254 JInternalFrame[] frames = null;
4255 // TODO is this necessary - is it safe - risk of hanging?
4260 frames = Desktop.desktop.getAllFrames();
4261 } catch (ArrayIndexOutOfBoundsException e)
4263 // occasional No such child exceptions are thrown here...
4267 } catch (InterruptedException f)
4271 } while (frames == null);
4276 * Answers true if 'version' is equal to or later than 'supported', where each
4277 * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
4278 * changes. Development and test values for 'version' are leniently treated
4282 * - minimum version we are comparing against
4284 * - version of data being processsed
4287 public static boolean isVersionStringLaterThan(String supported,
4290 if (supported == null || version == null
4291 || version.equalsIgnoreCase("DEVELOPMENT BUILD")
4292 || version.equalsIgnoreCase("Test")
4293 || version.equalsIgnoreCase("AUTOMATED BUILD"))
4295 System.err.println("Assuming project file with "
4296 + (version == null ? "null" : version)
4297 + " is compatible with Jalview version " + supported);
4302 return StringUtils.compareVersions(version, supported, "b") >= 0;
4306 Vector<JalviewStructureDisplayI> newStructureViewers = null;
4308 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
4310 if (newStructureViewers != null)
4312 sview.getBinding().setFinishedLoadingFromArchive(false);
4313 newStructureViewers.add(sview);
4317 protected void setLoadingFinishedForNewStructureViewers()
4319 if (newStructureViewers != null)
4321 for (JalviewStructureDisplayI sview : newStructureViewers)
4323 sview.getBinding().setFinishedLoadingFromArchive(true);
4325 newStructureViewers.clear();
4326 newStructureViewers = null;
4330 AlignFrame loadViewport(String file, JSeq[] JSEQ,
4331 List<SequenceI> hiddenSeqs, AlignmentI al,
4332 JalviewModelSequence jms, Viewport view, String uniqueSeqSetId,
4333 String viewId, List<JvAnnotRow> autoAlan)
4335 AlignFrame af = null;
4336 af = new AlignFrame(al, view.getWidth(), view.getHeight(),
4337 uniqueSeqSetId, viewId);
4339 af.setFileName(file, "Jalview");
4341 for (int i = 0; i < JSEQ.length; i++)
4343 af.viewport.setSequenceColour(af.viewport.getAlignment()
4344 .getSequenceAt(i), new java.awt.Color(JSEQ[i].getColour()));
4349 af.getViewport().setColourByReferenceSeq(true);
4350 af.getViewport().setDisplayReferenceSeq(true);
4353 af.viewport.setGatherViewsHere(view.getGatheredViews());
4355 if (view.getSequenceSetId() != null)
4357 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
4359 af.viewport.setSequenceSetId(uniqueSeqSetId);
4362 // propagate shared settings to this new view
4363 af.viewport.setHistoryList(av.getHistoryList());
4364 af.viewport.setRedoList(av.getRedoList());
4368 viewportsAdded.put(uniqueSeqSetId, af.viewport);
4370 // TODO: check if this method can be called repeatedly without
4371 // side-effects if alignpanel already registered.
4372 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
4374 // apply Hidden regions to view.
4375 if (hiddenSeqs != null)
4377 for (int s = 0; s < JSEQ.length; s++)
4379 SequenceGroup hidden = new SequenceGroup();
4380 boolean isRepresentative = false;
4381 for (int r = 0; r < JSEQ[s].getHiddenSequencesCount(); r++)
4383 isRepresentative = true;
4384 SequenceI sequenceToHide = al.getSequenceAt(JSEQ[s]
4385 .getHiddenSequences(r));
4386 hidden.addSequence(sequenceToHide, false);
4387 // remove from hiddenSeqs list so we don't try to hide it twice
4388 hiddenSeqs.remove(sequenceToHide);
4390 if (isRepresentative)
4392 SequenceI representativeSequence = al.getSequenceAt(s);
4393 hidden.addSequence(representativeSequence, false);
4394 af.viewport.hideRepSequences(representativeSequence, hidden);
4398 SequenceI[] hseqs = hiddenSeqs.toArray(new SequenceI[hiddenSeqs
4400 af.viewport.hideSequence(hseqs);
4403 // recover view properties and display parameters
4404 if (view.getViewName() != null)
4406 af.viewport.viewName = view.getViewName();
4407 af.setInitialTabVisible();
4409 af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(),
4412 af.viewport.setShowAnnotation(view.getShowAnnotation());
4413 af.viewport.setAbovePIDThreshold(view.getPidSelected());
4415 af.viewport.setColourText(view.getShowColourText());
4417 af.viewport.setConservationSelected(view.getConservationSelected());
4418 af.viewport.setShowJVSuffix(view.getShowFullId());
4419 af.viewport.setRightAlignIds(view.getRightAlignIds());
4420 af.viewport.setFont(
4421 new java.awt.Font(view.getFontName(), view.getFontStyle(), view
4422 .getFontSize()), true);
4423 ViewStyleI vs = af.viewport.getViewStyle();
4424 vs.setScaleProteinAsCdna(view.isScaleProteinAsCdna());
4425 af.viewport.setViewStyle(vs);
4426 // TODO: allow custom charWidth/Heights to be restored by updating them
4427 // after setting font - which means set above to false
4428 af.viewport.setRenderGaps(view.getRenderGaps());
4429 af.viewport.setWrapAlignment(view.getWrapAlignment());
4430 af.viewport.setShowAnnotation(view.getShowAnnotation());
4432 af.viewport.setShowBoxes(view.getShowBoxes());
4434 af.viewport.setShowText(view.getShowText());
4436 af.viewport.setTextColour(new java.awt.Color(view.getTextCol1()));
4437 af.viewport.setTextColour2(new java.awt.Color(view.getTextCol2()));
4438 af.viewport.setThresholdTextColour(view.getTextColThreshold());
4439 af.viewport.setShowUnconserved(view.hasShowUnconserved() ? view
4440 .isShowUnconserved() : false);
4441 af.viewport.setStartRes(view.getStartRes());
4442 af.viewport.setStartSeq(view.getStartSeq());
4443 af.alignPanel.updateLayout();
4444 ColourSchemeI cs = null;
4445 // apply colourschemes
4446 if (view.getBgColour() != null)
4448 if (view.getBgColour().startsWith("ucs"))
4450 cs = getUserColourScheme(jms, view.getBgColour());
4452 else if (view.getBgColour().startsWith("Annotation"))
4454 AnnotationColours viewAnnColour = view.getAnnotationColours();
4455 cs = constructAnnotationColour(viewAnnColour, af, al, jms, true);
4462 cs = ColourSchemeProperty.getColour(al, view.getBgColour());
4467 cs.setThreshold(view.getPidThreshold(), true);
4468 cs.setConsensus(af.viewport.getSequenceConsensusHash());
4472 af.viewport.setGlobalColourScheme(cs);
4473 af.viewport.setColourAppliesToAllGroups(false);
4475 if (view.getConservationSelected() && cs != null)
4477 cs.setConservationInc(view.getConsThreshold());
4480 af.changeColour(cs);
4482 af.viewport.setColourAppliesToAllGroups(true);
4484 af.viewport.setShowSequenceFeatures(view.getShowSequenceFeatures());
4486 if (view.hasCentreColumnLabels())
4488 af.viewport.setCentreColumnLabels(view.getCentreColumnLabels());
4490 if (view.hasIgnoreGapsinConsensus())
4492 af.viewport.setIgnoreGapsConsensus(view.getIgnoreGapsinConsensus(),
4495 if (view.hasFollowHighlight())
4497 af.viewport.setFollowHighlight(view.getFollowHighlight());
4499 if (view.hasFollowSelection())
4501 af.viewport.followSelection = view.getFollowSelection();
4503 if (view.hasShowConsensusHistogram())
4505 af.viewport.setShowConsensusHistogram(view
4506 .getShowConsensusHistogram());
4510 af.viewport.setShowConsensusHistogram(true);
4512 if (view.hasShowSequenceLogo())
4514 af.viewport.setShowSequenceLogo(view.getShowSequenceLogo());
4518 af.viewport.setShowSequenceLogo(false);
4520 if (view.hasNormaliseSequenceLogo())
4522 af.viewport.setNormaliseSequenceLogo(view.getNormaliseSequenceLogo());
4524 if (view.hasShowDbRefTooltip())
4526 af.viewport.setShowDBRefs(view.getShowDbRefTooltip());
4528 if (view.hasShowNPfeatureTooltip())
4530 af.viewport.setShowNPFeats(view.hasShowNPfeatureTooltip());
4532 if (view.hasShowGroupConsensus())
4534 af.viewport.setShowGroupConsensus(view.getShowGroupConsensus());
4538 af.viewport.setShowGroupConsensus(false);
4540 if (view.hasShowGroupConservation())
4542 af.viewport.setShowGroupConservation(view.getShowGroupConservation());
4546 af.viewport.setShowGroupConservation(false);
4549 // recover featre settings
4550 if (jms.getFeatureSettings() != null)
4552 FeaturesDisplayed fdi;
4553 af.viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
4554 String[] renderOrder = new String[jms.getFeatureSettings()
4555 .getSettingCount()];
4556 Map<String, FeatureColourI> featureColours = new Hashtable<String, FeatureColourI>();
4557 Map<String, Float> featureOrder = new Hashtable<String, Float>();
4559 for (int fs = 0; fs < jms.getFeatureSettings().getSettingCount(); fs++)
4561 Setting setting = jms.getFeatureSettings().getSetting(fs);
4562 if (setting.hasMincolour())
4564 FeatureColourI gc = setting.hasMin() ? new FeatureColour(
4565 new Color(setting.getMincolour()), new Color(
4566 setting.getColour()), setting.getMin(),
4567 setting.getMax()) : new FeatureColour(new Color(
4568 setting.getMincolour()), new Color(setting.getColour()),
4570 if (setting.hasThreshold())
4572 gc.setThreshold(setting.getThreshold());
4573 int threshstate = setting.getThreshstate();
4574 // -1 = None, 0 = Below, 1 = Above threshold
4575 if (threshstate == 0)
4577 gc.setBelowThreshold(true);
4579 else if (threshstate == 1)
4581 gc.setAboveThreshold(true);
4584 gc.setAutoScaled(true); // default
4585 if (setting.hasAutoScale())
4587 gc.setAutoScaled(setting.getAutoScale());
4589 if (setting.hasColourByLabel())
4591 gc.setColourByLabel(setting.getColourByLabel());
4593 // and put in the feature colour table.
4594 featureColours.put(setting.getType(), gc);
4598 featureColours.put(setting.getType(), new FeatureColour(
4599 new Color(setting.getColour())));
4601 renderOrder[fs] = setting.getType();
4602 if (setting.hasOrder())
4604 featureOrder.put(setting.getType(), setting.getOrder());
4608 featureOrder.put(setting.getType(), new Float(fs
4609 / jms.getFeatureSettings().getSettingCount()));
4611 if (setting.getDisplay())
4613 fdi.setVisible(setting.getType());
4616 Map<String, Boolean> fgtable = new Hashtable<String, Boolean>();
4617 for (int gs = 0; gs < jms.getFeatureSettings().getGroupCount(); gs++)
4619 Group grp = jms.getFeatureSettings().getGroup(gs);
4620 fgtable.put(grp.getName(), new Boolean(grp.getDisplay()));
4622 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
4623 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
4624 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
4625 FeatureRendererSettings frs = new FeatureRendererSettings(
4626 renderOrder, fgtable, featureColours, 1.0f, featureOrder);
4627 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
4628 .transferSettings(frs);
4632 if (view.getHiddenColumnsCount() > 0)
4634 for (int c = 0; c < view.getHiddenColumnsCount(); c++)
4636 af.viewport.hideColumns(view.getHiddenColumns(c).getStart(), view
4637 .getHiddenColumns(c).getEnd() // +1
4641 if (view.getCalcIdParam() != null)
4643 for (CalcIdParam calcIdParam : view.getCalcIdParam())
4645 if (calcIdParam != null)
4647 if (recoverCalcIdParam(calcIdParam, af.viewport))
4652 warn("Couldn't recover parameters for "
4653 + calcIdParam.getCalcId());
4658 af.setMenusFromViewport(af.viewport);
4659 af.setTitle(view.getTitle());
4660 // TODO: we don't need to do this if the viewport is aready visible.
4662 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
4663 * has a 'cdna/protein complement' view, in which case save it in order to
4664 * populate a SplitFrame once all views have been read in.
4666 String complementaryViewId = view.getComplementId();
4667 if (complementaryViewId == null)
4669 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
4671 // recompute any autoannotation
4672 af.alignPanel.updateAnnotation(false, true);
4673 reorderAutoannotation(af, al, autoAlan);
4674 af.alignPanel.alignmentChanged();
4678 splitFrameCandidates.put(view, af);
4683 private ColourSchemeI constructAnnotationColour(
4684 AnnotationColours viewAnnColour, AlignFrame af, AlignmentI al,
4685 JalviewModelSequence jms, boolean checkGroupAnnColour)
4687 boolean propagateAnnColour = false;
4688 ColourSchemeI cs = null;
4689 AlignmentI annAlignment = af != null ? af.viewport.getAlignment() : al;
4690 if (checkGroupAnnColour && al.getGroups() != null
4691 && al.getGroups().size() > 0)
4693 // pre 2.8.1 behaviour
4694 // check to see if we should transfer annotation colours
4695 propagateAnnColour = true;
4696 for (jalview.datamodel.SequenceGroup sg : al.getGroups())
4698 if (sg.cs instanceof AnnotationColourGradient)
4700 propagateAnnColour = false;
4704 // int find annotation
4705 if (annAlignment.getAlignmentAnnotation() != null)
4707 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
4709 if (annAlignment.getAlignmentAnnotation()[i].label
4710 .equals(viewAnnColour.getAnnotation()))
4712 if (annAlignment.getAlignmentAnnotation()[i].getThreshold() == null)
4714 annAlignment.getAlignmentAnnotation()[i]
4715 .setThreshold(new jalview.datamodel.GraphLine(
4716 viewAnnColour.getThreshold(), "Threshold",
4717 java.awt.Color.black)
4722 if (viewAnnColour.getColourScheme().equals("None"))
4724 cs = new AnnotationColourGradient(
4725 annAlignment.getAlignmentAnnotation()[i],
4726 new java.awt.Color(viewAnnColour.getMinColour()),
4727 new java.awt.Color(viewAnnColour.getMaxColour()),
4728 viewAnnColour.getAboveThreshold());
4730 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
4732 cs = new AnnotationColourGradient(
4733 annAlignment.getAlignmentAnnotation()[i],
4734 getUserColourScheme(jms,
4735 viewAnnColour.getColourScheme()),
4736 viewAnnColour.getAboveThreshold());
4740 cs = new AnnotationColourGradient(
4741 annAlignment.getAlignmentAnnotation()[i],
4742 ColourSchemeProperty.getColour(al,
4743 viewAnnColour.getColourScheme()),
4744 viewAnnColour.getAboveThreshold());
4746 if (viewAnnColour.hasPerSequence())
4748 ((AnnotationColourGradient) cs).setSeqAssociated(viewAnnColour
4751 if (viewAnnColour.hasPredefinedColours())
4753 ((AnnotationColourGradient) cs)
4754 .setPredefinedColours(viewAnnColour
4755 .isPredefinedColours());
4757 if (propagateAnnColour && al.getGroups() != null)
4759 // Also use these settings for all the groups
4760 for (int g = 0; g < al.getGroups().size(); g++)
4762 jalview.datamodel.SequenceGroup sg = al.getGroups().get(g);
4770 * if (viewAnnColour.getColourScheme().equals("None" )) { sg.cs =
4771 * new AnnotationColourGradient(
4772 * annAlignment.getAlignmentAnnotation()[i], new
4773 * java.awt.Color(viewAnnColour. getMinColour()), new
4774 * java.awt.Color(viewAnnColour. getMaxColour()),
4775 * viewAnnColour.getAboveThreshold()); } else
4778 sg.cs = new AnnotationColourGradient(
4779 annAlignment.getAlignmentAnnotation()[i], sg.cs,
4780 viewAnnColour.getAboveThreshold());
4781 if (cs instanceof AnnotationColourGradient)
4783 if (viewAnnColour.hasPerSequence())
4785 ((AnnotationColourGradient) cs)
4786 .setSeqAssociated(viewAnnColour.isPerSequence());
4788 if (viewAnnColour.hasPredefinedColours())
4790 ((AnnotationColourGradient) cs)
4791 .setPredefinedColours(viewAnnColour
4792 .isPredefinedColours());
4808 private void reorderAutoannotation(AlignFrame af, AlignmentI al,
4809 List<JvAnnotRow> autoAlan)
4811 // copy over visualization settings for autocalculated annotation in the
4813 if (al.getAlignmentAnnotation() != null)
4816 * Kludge for magic autoannotation names (see JAL-811)
4818 String[] magicNames = new String[] { "Consensus", "Quality",
4820 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
4821 Hashtable<String, JvAnnotRow> visan = new Hashtable<String, JvAnnotRow>();
4822 for (String nm : magicNames)
4824 visan.put(nm, nullAnnot);
4826 for (JvAnnotRow auan : autoAlan)
4828 visan.put(auan.template.label
4829 + (auan.template.getCalcId() == null ? "" : "\t"
4830 + auan.template.getCalcId()), auan);
4832 int hSize = al.getAlignmentAnnotation().length;
4833 List<JvAnnotRow> reorder = new ArrayList<JvAnnotRow>();
4834 // work through any autoCalculated annotation already on the view
4835 // removing it if it should be placed in a different location on the
4836 // annotation panel.
4837 List<String> remains = new ArrayList<String>(visan.keySet());
4838 for (int h = 0; h < hSize; h++)
4840 jalview.datamodel.AlignmentAnnotation jalan = al
4841 .getAlignmentAnnotation()[h];
4842 if (jalan.autoCalculated)
4845 JvAnnotRow valan = visan.get(k = jalan.label);
4846 if (jalan.getCalcId() != null)
4848 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
4853 // delete the auto calculated row from the alignment
4854 al.deleteAnnotation(jalan, false);
4858 if (valan != nullAnnot)
4860 if (jalan != valan.template)
4862 // newly created autoannotation row instance
4863 // so keep a reference to the visible annotation row
4864 // and copy over all relevant attributes
4865 if (valan.template.graphHeight >= 0)
4868 jalan.graphHeight = valan.template.graphHeight;
4870 jalan.visible = valan.template.visible;
4872 reorder.add(new JvAnnotRow(valan.order, jalan));
4877 // Add any (possibly stale) autocalculated rows that were not appended to
4878 // the view during construction
4879 for (String other : remains)
4881 JvAnnotRow othera = visan.get(other);
4882 if (othera != nullAnnot && othera.template.getCalcId() != null
4883 && othera.template.getCalcId().length() > 0)
4885 reorder.add(othera);
4888 // now put the automatic annotation in its correct place
4889 int s = 0, srt[] = new int[reorder.size()];
4890 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
4891 for (JvAnnotRow jvar : reorder)
4894 srt[s++] = jvar.order;
4897 jalview.util.QuickSort.sort(srt, rws);
4898 // and re-insert the annotation at its correct position
4899 for (JvAnnotRow jvar : rws)
4901 al.addAnnotation(jvar.template, jvar.order);
4903 af.alignPanel.adjustAnnotationHeight();
4907 Hashtable skipList = null;
4910 * TODO remove this method
4913 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
4914 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
4915 * throw new Error("Implementation Error. No skipList defined for this
4916 * Jalview2XML instance."); } return (AlignFrame)
4917 * skipList.get(view.getSequenceSetId()); }
4921 * Check if the Jalview view contained in object should be skipped or not.
4924 * @return true if view's sequenceSetId is a key in skipList
4926 private boolean skipViewport(JalviewModel object)
4928 if (skipList == null)
4933 if (skipList.containsKey(id = object.getJalviewModelSequence()
4934 .getViewport()[0].getSequenceSetId()))
4936 if (Cache.log != null && Cache.log.isDebugEnabled())
4938 Cache.log.debug("Skipping seuqence set id " + id);
4945 public void addToSkipList(AlignFrame af)
4947 if (skipList == null)
4949 skipList = new Hashtable();
4951 skipList.put(af.getViewport().getSequenceSetId(), af);
4954 public void clearSkipList()
4956 if (skipList != null)
4963 private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
4964 boolean ignoreUnrefed)
4966 jalview.datamodel.AlignmentI ds = getDatasetFor(vamsasSet
4968 Vector dseqs = null;
4971 // create a list of new dataset sequences
4972 dseqs = new Vector();
4974 for (int i = 0, iSize = vamsasSet.getSequenceCount(); i < iSize; i++)
4976 Sequence vamsasSeq = vamsasSet.getSequence(i);
4977 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed, i);
4979 // create a new dataset
4982 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
4983 dseqs.copyInto(dsseqs);
4984 ds = new jalview.datamodel.Alignment(dsseqs);
4985 debug("Created new dataset " + vamsasSet.getDatasetId()
4986 + " for alignment " + System.identityHashCode(al));
4987 addDatasetRef(vamsasSet.getDatasetId(), ds);
4989 // set the dataset for the newly imported alignment.
4990 if (al.getDataset() == null && !ignoreUnrefed)
4999 * sequence definition to create/merge dataset sequence for
5003 * vector to add new dataset sequence to
5004 * @param ignoreUnrefed
5005 * - when true, don't create new sequences from vamsasSeq if it's id
5006 * doesn't already have an asssociated Jalview sequence.
5008 * - used to reorder the sequence in the alignment according to the
5009 * vamsasSeq array ordering, to preserve ordering of dataset
5011 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
5012 AlignmentI ds, Vector dseqs, boolean ignoreUnrefed, int vseqpos)
5014 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
5016 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
5017 boolean reorder = false;
5018 SequenceI dsq = null;
5019 if (sq != null && sq.getDatasetSequence() != null)
5021 dsq = sq.getDatasetSequence();
5027 if (sq == null && ignoreUnrefed)
5031 String sqid = vamsasSeq.getDsseqid();
5034 // need to create or add a new dataset sequence reference to this sequence
5037 dsq = seqRefIds.get(sqid);
5042 // make a new dataset sequence
5043 dsq = sq.createDatasetSequence();
5046 // make up a new dataset reference for this sequence
5047 sqid = seqHash(dsq);
5049 dsq.setVamsasId(uniqueSetSuffix + sqid);
5050 seqRefIds.put(sqid, dsq);
5055 dseqs.addElement(dsq);
5060 ds.addSequence(dsq);
5066 { // make this dataset sequence sq's dataset sequence
5067 sq.setDatasetSequence(dsq);
5068 // and update the current dataset alignment
5073 if (!dseqs.contains(dsq))
5080 if (ds.findIndex(dsq) < 0)
5082 ds.addSequence(dsq);
5089 // TODO: refactor this as a merge dataset sequence function
5090 // now check that sq (the dataset sequence) sequence really is the union of
5091 // all references to it
5092 // boolean pre = sq.getStart() < dsq.getStart();
5093 // boolean post = sq.getEnd() > dsq.getEnd();
5097 // StringBuffer sb = new StringBuffer();
5098 String newres = jalview.analysis.AlignSeq.extractGaps(
5099 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
5100 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
5101 && newres.length() > dsq.getLength())
5103 // Update with the longer sequence.
5107 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
5108 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
5109 * sb.append(newres.substring(newres.length() - sq.getEnd() -
5110 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
5112 dsq.setSequence(newres);
5114 // TODO: merges will never happen if we 'know' we have the real dataset
5115 // sequence - this should be detected when id==dssid
5117 .println("DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
5118 // + (pre ? "prepended" : "") + " "
5119 // + (post ? "appended" : ""));
5124 // sequence refs are identical. We may need to update the existing dataset
5125 // alignment with this one, though.
5126 if (ds != null && dseqs == null)
5128 int opos = ds.findIndex(dsq);
5129 SequenceI tseq = null;
5130 if (opos != -1 && vseqpos != opos)
5132 // remove from old position
5133 ds.deleteSequence(dsq);
5135 if (vseqpos < ds.getHeight())
5137 if (vseqpos != opos)
5139 // save sequence at destination position
5140 tseq = ds.getSequenceAt(vseqpos);
5141 ds.replaceSequenceAt(vseqpos, dsq);
5142 ds.addSequence(tseq);
5147 ds.addSequence(dsq);
5154 * TODO use AlignmentI here and in related methods - needs
5155 * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
5157 Hashtable<String, AlignmentI> datasetIds = null;
5159 IdentityHashMap<AlignmentI, String> dataset2Ids = null;
5161 private AlignmentI getDatasetFor(String datasetId)
5163 if (datasetIds == null)
5165 datasetIds = new Hashtable<String, AlignmentI>();
5168 if (datasetIds.containsKey(datasetId))
5170 return datasetIds.get(datasetId);
5175 private void addDatasetRef(String datasetId, AlignmentI dataset)
5177 if (datasetIds == null)
5179 datasetIds = new Hashtable<String, AlignmentI>();
5181 datasetIds.put(datasetId, dataset);
5185 * make a new dataset ID for this jalview dataset alignment
5190 private String getDatasetIdRef(AlignmentI dataset)
5192 if (dataset.getDataset() != null)
5194 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
5196 String datasetId = makeHashCode(dataset, null);
5197 if (datasetId == null)
5199 // make a new datasetId and record it
5200 if (dataset2Ids == null)
5202 dataset2Ids = new IdentityHashMap<AlignmentI, String>();
5206 datasetId = dataset2Ids.get(dataset);
5208 if (datasetId == null)
5210 datasetId = "ds" + dataset2Ids.size() + 1;
5211 dataset2Ids.put(dataset, datasetId);
5217 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
5219 for (int d = 0; d < sequence.getDBRefCount(); d++)
5221 DBRef dr = sequence.getDBRef(d);
5222 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
5223 sequence.getDBRef(d).getSource(), sequence.getDBRef(d)
5224 .getVersion(), sequence.getDBRef(d).getAccessionId());
5225 if (dr.getMapping() != null)
5227 entry.setMap(addMapping(dr.getMapping()));
5229 datasetSequence.addDBRef(entry);
5233 private jalview.datamodel.Mapping addMapping(Mapping m)
5235 SequenceI dsto = null;
5236 // Mapping m = dr.getMapping();
5237 int fr[] = new int[m.getMapListFromCount() * 2];
5238 Enumeration f = m.enumerateMapListFrom();
5239 for (int _i = 0; f.hasMoreElements(); _i += 2)
5241 MapListFrom mf = (MapListFrom) f.nextElement();
5242 fr[_i] = mf.getStart();
5243 fr[_i + 1] = mf.getEnd();
5245 int fto[] = new int[m.getMapListToCount() * 2];
5246 f = m.enumerateMapListTo();
5247 for (int _i = 0; f.hasMoreElements(); _i += 2)
5249 MapListTo mf = (MapListTo) f.nextElement();
5250 fto[_i] = mf.getStart();
5251 fto[_i + 1] = mf.getEnd();
5253 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto,
5254 fr, fto, (int) m.getMapFromUnit(), (int) m.getMapToUnit());
5255 if (m.getMappingChoice() != null)
5257 MappingChoice mc = m.getMappingChoice();
5258 if (mc.getDseqFor() != null)
5260 String dsfor = "" + mc.getDseqFor();
5261 if (seqRefIds.containsKey(dsfor))
5266 jmap.setTo(seqRefIds.get(dsfor));
5270 frefedSequence.add(newMappingRef(dsfor, jmap));
5276 * local sequence definition
5278 Sequence ms = mc.getSequence();
5279 SequenceI djs = null;
5280 String sqid = ms.getDsseqid();
5281 if (sqid != null && sqid.length() > 0)
5284 * recover dataset sequence
5286 djs = seqRefIds.get(sqid);
5291 .println("Warning - making up dataset sequence id for DbRef sequence map reference");
5292 sqid = ((Object) ms).toString(); // make up a new hascode for
5293 // undefined dataset sequence hash
5294 // (unlikely to happen)
5300 * make a new dataset sequence and add it to refIds hash
5302 djs = new jalview.datamodel.Sequence(ms.getName(),
5304 djs.setStart(jmap.getMap().getToLowest());
5305 djs.setEnd(jmap.getMap().getToHighest());
5306 djs.setVamsasId(uniqueSetSuffix + sqid);
5308 incompleteSeqs.put(sqid, djs);
5309 seqRefIds.put(sqid, djs);
5312 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
5321 public jalview.gui.AlignmentPanel copyAlignPanel(AlignmentPanel ap,
5322 boolean keepSeqRefs)
5325 JalviewModel jm = saveState(ap, null, null, null);
5330 jm.getJalviewModelSequence().getViewport(0).setSequenceSetId(null);
5334 uniqueSetSuffix = "";
5335 jm.getJalviewModelSequence().getViewport(0).setId(null); // we don't
5340 if (this.frefedSequence == null)
5342 frefedSequence = new Vector();
5345 viewportsAdded.clear();
5347 AlignFrame af = loadFromObject(jm, null, false, null);
5348 af.alignPanels.clear();
5349 af.closeMenuItem_actionPerformed(true);
5352 * if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
5353 * i<ap.av.getAlignment().getAlignmentAnnotation().length; i++) {
5354 * if(!ap.av.getAlignment().getAlignmentAnnotation()[i].autoCalculated) {
5355 * af.alignPanel.av.getAlignment().getAlignmentAnnotation()[i] =
5356 * ap.av.getAlignment().getAlignmentAnnotation()[i]; } } }
5359 return af.alignPanel;
5363 * flag indicating if hashtables should be cleared on finalization TODO this
5364 * flag may not be necessary
5366 private final boolean _cleartables = true;
5368 private Hashtable jvids2vobj;
5373 * @see java.lang.Object#finalize()
5376 protected void finalize() throws Throwable
5378 // really make sure we have no buried refs left.
5383 this.seqRefIds = null;
5384 this.seqsToIds = null;
5388 private void warn(String msg)
5393 private void warn(String msg, Exception e)
5395 if (Cache.log != null)
5399 Cache.log.warn(msg, e);
5403 Cache.log.warn(msg);
5408 System.err.println("Warning: " + msg);
5411 e.printStackTrace();
5416 private void debug(String string)
5418 debug(string, null);
5421 private void debug(String msg, Exception e)
5423 if (Cache.log != null)
5427 Cache.log.debug(msg, e);
5431 Cache.log.debug(msg);
5436 System.err.println("Warning: " + msg);
5439 e.printStackTrace();
5445 * set the object to ID mapping tables used to write/recover objects and XML
5446 * ID strings for the jalview project. If external tables are provided then
5447 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
5448 * object goes out of scope. - also populates the datasetIds hashtable with
5449 * alignment objects containing dataset sequences
5452 * Map from ID strings to jalview datamodel
5454 * Map from jalview datamodel to ID strings
5458 public void setObjectMappingTables(Hashtable vobj2jv,
5459 IdentityHashMap jv2vobj)
5461 this.jv2vobj = jv2vobj;
5462 this.vobj2jv = vobj2jv;
5463 Iterator ds = jv2vobj.keySet().iterator();
5465 while (ds.hasNext())
5467 Object jvobj = ds.next();
5468 id = jv2vobj.get(jvobj).toString();
5469 if (jvobj instanceof jalview.datamodel.Alignment)
5471 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
5473 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
5476 else if (jvobj instanceof jalview.datamodel.Sequence)
5478 // register sequence object so the XML parser can recover it.
5479 if (seqRefIds == null)
5481 seqRefIds = new HashMap<String, SequenceI>();
5483 if (seqsToIds == null)
5485 seqsToIds = new IdentityHashMap<SequenceI, String>();
5487 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
5488 seqsToIds.put((SequenceI) jvobj, id);
5490 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
5493 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
5494 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
5495 if (jvann.annotationId == null)
5497 jvann.annotationId = anid;
5499 if (!jvann.annotationId.equals(anid))
5501 // TODO verify that this is the correct behaviour
5502 this.warn("Overriding Annotation ID for " + anid
5503 + " from different id : " + jvann.annotationId);
5504 jvann.annotationId = anid;
5507 else if (jvobj instanceof String)
5509 if (jvids2vobj == null)
5511 jvids2vobj = new Hashtable();
5512 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
5517 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
5523 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
5524 * objects created from the project archive. If string is null (default for
5525 * construction) then suffix will be set automatically.
5529 public void setUniqueSetSuffix(String string)
5531 uniqueSetSuffix = string;
5536 * uses skipList2 as the skipList for skipping views on sequence sets
5537 * associated with keys in the skipList
5541 public void setSkipList(Hashtable skipList2)
5543 skipList = skipList2;
5547 * Reads the jar entry of given name and returns its contents, or null if the
5548 * entry is not found.
5551 * @param jarEntryName
5554 protected String readJarEntry(jarInputStreamProvider jprovider,
5555 String jarEntryName)
5557 String result = null;
5558 BufferedReader in = null;
5563 * Reopen the jar input stream and traverse its entries to find a matching
5566 JarInputStream jin = jprovider.getJarInputStream();
5567 JarEntry entry = null;
5570 entry = jin.getNextJarEntry();
5571 } while (entry != null && !entry.getName().equals(jarEntryName));
5575 StringBuilder out = new StringBuilder(256);
5576 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
5579 while ((data = in.readLine()) != null)
5583 result = out.toString();
5587 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
5589 } catch (Exception ex)
5591 ex.printStackTrace();
5599 } catch (IOException e)
5610 * Returns an incrementing counter (0, 1, 2...)
5614 private synchronized int nextCounter()