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 static jalview.math.RotatableMatrix.Axis.X;
24 import static jalview.math.RotatableMatrix.Axis.Y;
25 import static jalview.math.RotatableMatrix.Axis.Z;
27 import jalview.analysis.Conservation;
28 import jalview.analysis.PCA;
29 import jalview.analysis.scoremodels.ScoreModels;
30 import jalview.analysis.scoremodels.SimilarityParams;
31 import jalview.api.FeatureColourI;
32 import jalview.api.ViewStyleI;
33 import jalview.api.analysis.ScoreModelI;
34 import jalview.api.analysis.SimilarityParamsI;
35 import jalview.api.structures.JalviewStructureDisplayI;
36 import jalview.bin.Cache;
37 import jalview.datamodel.AlignedCodonFrame;
38 import jalview.datamodel.Alignment;
39 import jalview.datamodel.AlignmentAnnotation;
40 import jalview.datamodel.AlignmentI;
41 import jalview.datamodel.GraphLine;
42 import jalview.datamodel.PDBEntry;
43 import jalview.datamodel.Point;
44 import jalview.datamodel.RnaViewerModel;
45 import jalview.datamodel.SequenceFeature;
46 import jalview.datamodel.SequenceGroup;
47 import jalview.datamodel.SequenceI;
48 import jalview.datamodel.StructureViewerModel;
49 import jalview.datamodel.StructureViewerModel.StructureData;
50 import jalview.datamodel.features.FeatureMatcher;
51 import jalview.datamodel.features.FeatureMatcherI;
52 import jalview.datamodel.features.FeatureMatcherSet;
53 import jalview.datamodel.features.FeatureMatcherSetI;
54 import jalview.ext.varna.RnaModel;
55 import jalview.gui.StructureViewer.ViewerType;
56 import jalview.io.DataSourceType;
57 import jalview.io.FileFormat;
58 import jalview.math.Matrix;
59 import jalview.math.MatrixI;
60 import jalview.renderer.ResidueShaderI;
61 import jalview.schemabinding.version2.AlcodMap;
62 import jalview.schemabinding.version2.AlcodonFrame;
63 import jalview.schemabinding.version2.Annotation;
64 import jalview.schemabinding.version2.AnnotationColours;
65 import jalview.schemabinding.version2.AnnotationElement;
66 import jalview.schemabinding.version2.Axis;
67 import jalview.schemabinding.version2.CalcIdParam;
68 import jalview.schemabinding.version2.CompoundMatcher;
69 import jalview.schemabinding.version2.D;
70 import jalview.schemabinding.version2.DBRef;
71 import jalview.schemabinding.version2.DoubleMatrix;
72 import jalview.schemabinding.version2.E;
73 import jalview.schemabinding.version2.EigenMatrix;
74 import jalview.schemabinding.version2.Features;
75 import jalview.schemabinding.version2.Group;
76 import jalview.schemabinding.version2.HiddenColumns;
77 import jalview.schemabinding.version2.JGroup;
78 import jalview.schemabinding.version2.JSeq;
79 import jalview.schemabinding.version2.JalviewModel;
80 import jalview.schemabinding.version2.JalviewModelSequence;
81 import jalview.schemabinding.version2.MapListFrom;
82 import jalview.schemabinding.version2.MapListTo;
83 import jalview.schemabinding.version2.Mapping;
84 import jalview.schemabinding.version2.MappingChoice;
85 import jalview.schemabinding.version2.MatchCondition;
86 import jalview.schemabinding.version2.MatcherSet;
87 import jalview.schemabinding.version2.OtherData;
88 import jalview.schemabinding.version2.PairwiseMatrix;
89 import jalview.schemabinding.version2.PcaData;
90 import jalview.schemabinding.version2.PcaViewer;
91 import jalview.schemabinding.version2.PdbentryItem;
92 import jalview.schemabinding.version2.Pdbids;
93 import jalview.schemabinding.version2.Property;
94 import jalview.schemabinding.version2.RnaViewer;
95 import jalview.schemabinding.version2.Row;
96 import jalview.schemabinding.version2.SecondaryStructure;
97 import jalview.schemabinding.version2.SeqPointMax;
98 import jalview.schemabinding.version2.SeqPointMin;
99 import jalview.schemabinding.version2.Sequence;
100 import jalview.schemabinding.version2.SequencePoint;
101 import jalview.schemabinding.version2.SequenceSet;
102 import jalview.schemabinding.version2.SequenceSetProperties;
103 import jalview.schemabinding.version2.Setting;
104 import jalview.schemabinding.version2.StructureState;
105 import jalview.schemabinding.version2.ThresholdLine;
106 import jalview.schemabinding.version2.Tree;
107 import jalview.schemabinding.version2.TridiagonalMatrix;
108 import jalview.schemabinding.version2.UserColours;
109 import jalview.schemabinding.version2.Viewport;
110 import jalview.schemabinding.version2.types.ColourThreshTypeType;
111 import jalview.schemabinding.version2.types.FeatureMatcherByType;
112 import jalview.schemabinding.version2.types.NoValueColour;
113 import jalview.schemes.AnnotationColourGradient;
114 import jalview.schemes.ColourSchemeI;
115 import jalview.schemes.ColourSchemeProperty;
116 import jalview.schemes.FeatureColour;
117 import jalview.schemes.ResidueProperties;
118 import jalview.schemes.UserColourScheme;
119 import jalview.structure.StructureSelectionManager;
120 import jalview.structures.models.AAStructureBindingModel;
121 import jalview.util.Format;
122 import jalview.util.MessageManager;
123 import jalview.util.Platform;
124 import jalview.util.StringUtils;
125 import jalview.util.jarInputStreamProvider;
126 import jalview.util.matcher.Condition;
127 import jalview.viewmodel.AlignmentViewport;
128 import jalview.viewmodel.PCAModel;
129 import jalview.viewmodel.ViewportRanges;
130 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
131 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
132 import jalview.ws.jws2.Jws2Discoverer;
133 import jalview.ws.jws2.dm.AAConSettings;
134 import jalview.ws.jws2.jabaws2.Jws2Instance;
135 import jalview.ws.params.ArgumentI;
136 import jalview.ws.params.AutoCalcSetting;
137 import jalview.ws.params.WsParamSetI;
139 import java.awt.Color;
140 import java.awt.Rectangle;
141 import java.io.BufferedReader;
142 import java.io.DataInputStream;
143 import java.io.DataOutputStream;
145 import java.io.FileInputStream;
146 import java.io.FileOutputStream;
147 import java.io.IOException;
148 import java.io.InputStreamReader;
149 import java.io.OutputStreamWriter;
150 import java.io.PrintWriter;
151 import java.lang.reflect.InvocationTargetException;
152 import java.net.MalformedURLException;
154 import java.util.ArrayList;
155 import java.util.Arrays;
156 import java.util.Collections;
157 import java.util.Enumeration;
158 import java.util.HashMap;
159 import java.util.HashSet;
160 import java.util.Hashtable;
161 import java.util.IdentityHashMap;
162 import java.util.Iterator;
163 import java.util.LinkedHashMap;
164 import java.util.List;
165 import java.util.Map;
166 import java.util.Map.Entry;
167 import java.util.Set;
168 import java.util.Vector;
169 import java.util.jar.JarEntry;
170 import java.util.jar.JarInputStream;
171 import java.util.jar.JarOutputStream;
173 import javax.swing.JInternalFrame;
174 import javax.swing.SwingUtilities;
176 import org.exolab.castor.xml.Marshaller;
177 import org.exolab.castor.xml.Unmarshaller;
180 * Write out the current jalview desktop state as a Jalview XML stream.
182 * Note: the vamsas objects referred to here are primitive versions of the
183 * VAMSAS project schema elements - they are not the same and most likely never
187 * @version $Revision: 1.134 $
189 public class Jalview2XML
191 private static final String VIEWER_PREFIX = "viewer_";
193 private static final String RNA_PREFIX = "rna_";
195 private static final String UTF_8 = "UTF-8";
197 // use this with nextCounter() to make unique names for entities
198 private int counter = 0;
201 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
202 * of sequence objects are created.
204 IdentityHashMap<SequenceI, String> seqsToIds = null;
207 * jalview XML Sequence ID to jalview sequence object reference (both dataset
208 * and alignment sequences. Populated as XML reps of sequence objects are
211 Map<String, SequenceI> seqRefIds = null;
213 Map<String, SequenceI> incompleteSeqs = null;
215 List<SeqFref> frefedSequence = null;
217 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
220 * Map of reconstructed AlignFrame objects that appear to have come from
221 * SplitFrame objects (have a dna/protein complement view).
223 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
226 * Map from displayed rna structure models to their saved session state jar
229 private Map<RnaModel, String> rnaSessions = new HashMap<>();
232 * create/return unique hash string for sq
235 * @return new or existing unique string for sq
237 String seqHash(SequenceI sq)
239 if (seqsToIds == null)
243 if (seqsToIds.containsKey(sq))
245 return seqsToIds.get(sq);
249 // create sequential key
250 String key = "sq" + (seqsToIds.size() + 1);
251 key = makeHashCode(sq, key); // check we don't have an external reference
253 seqsToIds.put(sq, key);
260 if (seqsToIds == null)
262 seqsToIds = new IdentityHashMap<>();
264 if (seqRefIds == null)
266 seqRefIds = new HashMap<>();
268 if (incompleteSeqs == null)
270 incompleteSeqs = new HashMap<>();
272 if (frefedSequence == null)
274 frefedSequence = new ArrayList<>();
282 public Jalview2XML(boolean raiseGUI)
284 this.raiseGUI = raiseGUI;
288 * base class for resolving forward references to sequences by their ID
293 abstract class SeqFref
299 public SeqFref(String _sref, String type)
305 public String getSref()
310 public SequenceI getSrefSeq()
312 return seqRefIds.get(sref);
315 public boolean isResolvable()
317 return seqRefIds.get(sref) != null;
320 public SequenceI getSrefDatasetSeq()
322 SequenceI sq = seqRefIds.get(sref);
325 while (sq.getDatasetSequence() != null)
327 sq = sq.getDatasetSequence();
334 * @return true if the forward reference was fully resolved
336 abstract boolean resolve();
339 public String toString()
341 return type + " reference to " + sref;
346 * create forward reference for a mapping
352 public SeqFref newMappingRef(final String sref,
353 final jalview.datamodel.Mapping _jmap)
355 SeqFref fref = new SeqFref(sref, "Mapping")
357 public jalview.datamodel.Mapping jmap = _jmap;
362 SequenceI seq = getSrefDatasetSeq();
374 public SeqFref newAlcodMapRef(final String sref,
375 final AlignedCodonFrame _cf,
376 final jalview.datamodel.Mapping _jmap)
379 SeqFref fref = new SeqFref(sref, "Codon Frame")
381 AlignedCodonFrame cf = _cf;
383 public jalview.datamodel.Mapping mp = _jmap;
386 public boolean isResolvable()
388 return super.isResolvable() && mp.getTo() != null;
394 SequenceI seq = getSrefDatasetSeq();
399 cf.addMap(seq, mp.getTo(), mp.getMap());
406 public void resolveFrefedSequences()
408 Iterator<SeqFref> nextFref = frefedSequence.iterator();
409 int toresolve = frefedSequence.size();
410 int unresolved = 0, failedtoresolve = 0;
411 while (nextFref.hasNext())
413 SeqFref ref = nextFref.next();
414 if (ref.isResolvable())
426 } catch (Exception x)
429 "IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
442 System.err.println("Jalview Project Import: There were " + unresolved
443 + " forward references left unresolved on the stack.");
445 if (failedtoresolve > 0)
447 System.err.println("SERIOUS! " + failedtoresolve
448 + " resolvable forward references failed to resolve.");
450 if (incompleteSeqs != null && incompleteSeqs.size() > 0)
453 "Jalview Project Import: There are " + incompleteSeqs.size()
454 + " sequences which may have incomplete metadata.");
455 if (incompleteSeqs.size() < 10)
457 for (SequenceI s : incompleteSeqs.values())
459 System.err.println(s.toString());
465 "Too many to report. Skipping output of incomplete sequences.");
471 * This maintains a map of viewports, the key being the seqSetId. Important to
472 * set historyItem and redoList for multiple views
474 Map<String, AlignViewport> viewportsAdded = new HashMap<>();
476 Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
478 String uniqueSetSuffix = "";
481 * List of pdbfiles added to Jar
483 List<String> pdbfiles = null;
485 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
486 public void saveState(File statefile)
488 FileOutputStream fos = null;
491 fos = new FileOutputStream(statefile);
492 JarOutputStream jout = new JarOutputStream(fos);
495 } catch (Exception e)
497 // TODO: inform user of the problem - they need to know if their data was
499 if (errorMessage == null)
501 errorMessage = "Couldn't write Jalview Archive to output file '"
502 + statefile + "' - See console error log for details";
506 errorMessage += "(output file was '" + statefile + "')";
516 } catch (IOException e)
526 * Writes a jalview project archive to the given Jar output stream.
530 public void saveState(JarOutputStream jout)
532 AlignFrame[] frames = Desktop.getAlignFrames();
538 saveAllFrames(Arrays.asList(frames), jout);
542 * core method for storing state for a set of AlignFrames.
545 * - frames involving all data to be exported (including containing
548 * - project output stream
550 private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
552 Hashtable<String, AlignFrame> dsses = new Hashtable<>();
555 * ensure cached data is clear before starting
557 // todo tidy up seqRefIds, seqsToIds initialisation / reset
559 splitFrameCandidates.clear();
564 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
565 // //////////////////////////////////////////////////
567 List<String> shortNames = new ArrayList<>();
568 List<String> viewIds = new ArrayList<>();
571 for (int i = frames.size() - 1; i > -1; i--)
573 AlignFrame af = frames.get(i);
575 if (skipList != null && skipList
576 .containsKey(af.getViewport().getSequenceSetId()))
581 String shortName = makeFilename(af, shortNames);
583 int ap, apSize = af.alignPanels.size();
585 for (ap = 0; ap < apSize; ap++)
587 AlignmentPanel apanel = af.alignPanels.get(ap);
588 String fileName = apSize == 1 ? shortName : ap + shortName;
589 if (!fileName.endsWith(".xml"))
591 fileName = fileName + ".xml";
594 saveState(apanel, fileName, jout, viewIds);
596 String dssid = getDatasetIdRef(
597 af.getViewport().getAlignment().getDataset());
598 if (!dsses.containsKey(dssid))
600 dsses.put(dssid, af);
605 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
611 } catch (Exception foo)
616 } catch (Exception ex)
618 // TODO: inform user of the problem - they need to know if their data was
620 if (errorMessage == null)
622 errorMessage = "Couldn't write Jalview Archive - see error output for details";
624 ex.printStackTrace();
629 * Generates a distinct file name, based on the title of the AlignFrame, by
630 * appending _n for increasing n until an unused name is generated. The new
631 * name (without its extension) is added to the list.
635 * @return the generated name, with .xml extension
637 protected String makeFilename(AlignFrame af, List<String> namesUsed)
639 String shortName = af.getTitle();
641 if (shortName.indexOf(File.separatorChar) > -1)
643 shortName = shortName
644 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
649 while (namesUsed.contains(shortName))
651 if (shortName.endsWith("_" + (count - 1)))
653 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
656 shortName = shortName.concat("_" + count);
660 namesUsed.add(shortName);
662 if (!shortName.endsWith(".xml"))
664 shortName = shortName + ".xml";
669 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
670 public boolean saveAlignment(AlignFrame af, String jarFile,
675 FileOutputStream fos = new FileOutputStream(jarFile);
676 JarOutputStream jout = new JarOutputStream(fos);
677 List<AlignFrame> frames = new ArrayList<>();
679 // resolve splitframes
680 if (af.getViewport().getCodingComplement() != null)
682 frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
688 saveAllFrames(frames, jout);
692 } catch (Exception foo)
698 } catch (Exception ex)
700 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
701 ex.printStackTrace();
706 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
707 String fileName, JarOutputStream jout)
710 for (String dssids : dsses.keySet())
712 AlignFrame _af = dsses.get(dssids);
713 String jfileName = fileName + " Dataset for " + _af.getTitle();
714 if (!jfileName.endsWith(".xml"))
716 jfileName = jfileName + ".xml";
718 saveState(_af.alignPanel, jfileName, true, jout, null);
723 * create a JalviewModel from an alignment view and marshall it to a
727 * panel to create jalview model for
729 * name of alignment panel written to output stream
736 public JalviewModel saveState(AlignmentPanel ap, String fileName,
737 JarOutputStream jout, List<String> viewIds)
739 return saveState(ap, fileName, false, jout, viewIds);
743 * create a JalviewModel from an alignment view and marshall it to a
747 * panel to create jalview model for
749 * name of alignment panel written to output stream
751 * when true, only write the dataset for the alignment, not the data
752 * associated with the view.
758 public JalviewModel saveState(AlignmentPanel ap, String fileName,
759 boolean storeDS, JarOutputStream jout, List<String> viewIds)
763 viewIds = new ArrayList<>();
768 List<UserColourScheme> userColours = new ArrayList<>();
770 AlignViewport av = ap.av;
771 ViewportRanges vpRanges = av.getRanges();
773 JalviewModel object = new JalviewModel();
774 object.setVamsasModel(new jalview.schemabinding.version2.VamsasModel());
776 object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
778 jalview.bin.Cache.getDefault("VERSION", "Development Build"));
781 * rjal is full height alignment, jal is actual alignment with full metadata
782 * but excludes hidden sequences.
784 jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
786 if (av.hasHiddenRows())
788 rjal = jal.getHiddenSequences().getFullAlignment();
791 SequenceSet vamsasSet = new SequenceSet();
793 JalviewModelSequence jms = new JalviewModelSequence();
795 vamsasSet.setGapChar(jal.getGapCharacter() + "");
797 if (jal.getDataset() != null)
799 // dataset id is the dataset's hashcode
800 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
803 // switch jal and the dataset
804 jal = jal.getDataset();
808 if (jal.getProperties() != null)
810 Enumeration en = jal.getProperties().keys();
811 while (en.hasMoreElements())
813 String key = en.nextElement().toString();
814 SequenceSetProperties ssp = new SequenceSetProperties();
816 ssp.setValue(jal.getProperties().get(key).toString());
817 vamsasSet.addSequenceSetProperties(ssp);
822 Set<String> calcIdSet = new HashSet<>();
823 // record the set of vamsas sequence XML POJO we create.
824 HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
826 for (final SequenceI jds : rjal.getSequences())
828 final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
829 : jds.getDatasetSequence();
830 String id = seqHash(jds);
831 if (vamsasSetIds.get(id) == null)
833 if (seqRefIds.get(id) != null && !storeDS)
835 // This happens for two reasons: 1. multiple views are being
837 // 2. the hashCode has collided with another sequence's code. This
839 // HAPPEN! (PF00072.15.stk does this)
840 // JBPNote: Uncomment to debug writing out of files that do not read
841 // back in due to ArrayOutOfBoundExceptions.
842 // System.err.println("vamsasSeq backref: "+id+"");
843 // System.err.println(jds.getName()+"
844 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
845 // System.err.println("Hashcode: "+seqHash(jds));
846 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
847 // System.err.println(rsq.getName()+"
848 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
849 // System.err.println("Hashcode: "+seqHash(rsq));
853 vamsasSeq = createVamsasSequence(id, jds);
854 vamsasSet.addSequence(vamsasSeq);
855 vamsasSetIds.put(id, vamsasSeq);
856 seqRefIds.put(id, jds);
860 jseq.setStart(jds.getStart());
861 jseq.setEnd(jds.getEnd());
862 jseq.setColour(av.getSequenceColour(jds).getRGB());
864 jseq.setId(id); // jseq id should be a string not a number
867 // Store any sequences this sequence represents
868 if (av.hasHiddenRows())
870 // use rjal, contains the full height alignment
872 av.getAlignment().getHiddenSequences().isHidden(jds));
874 if (av.isHiddenRepSequence(jds))
876 jalview.datamodel.SequenceI[] reps = av
877 .getRepresentedSequences(jds).getSequencesInOrder(rjal);
879 for (int h = 0; h < reps.length; h++)
883 jseq.addHiddenSequences(rjal.findIndex(reps[h]));
888 // mark sequence as reference - if it is the reference for this view
891 jseq.setViewreference(jds == jal.getSeqrep());
895 // TODO: omit sequence features from each alignment view's XML dump if we
896 // are storing dataset
897 List<jalview.datamodel.SequenceFeature> sfs = jds
898 .getSequenceFeatures();
899 for (SequenceFeature sf : sfs)
901 Features features = new Features();
903 features.setBegin(sf.getBegin());
904 features.setEnd(sf.getEnd());
905 features.setDescription(sf.getDescription());
906 features.setType(sf.getType());
907 features.setFeatureGroup(sf.getFeatureGroup());
908 features.setScore(sf.getScore());
909 if (sf.links != null)
911 for (int l = 0; l < sf.links.size(); l++)
913 OtherData keyValue = new OtherData();
914 keyValue.setKey("LINK_" + l);
915 keyValue.setValue(sf.links.elementAt(l).toString());
916 features.addOtherData(keyValue);
919 if (sf.otherDetails != null)
922 * save feature attributes, which may be simple strings or
923 * map valued (have sub-attributes)
925 for (Entry<String, Object> entry : sf.otherDetails.entrySet())
927 String key = entry.getKey();
928 Object value = entry.getValue();
929 if (value instanceof Map<?, ?>)
931 for (Entry<String, Object> subAttribute : ((Map<String, Object>) value)
934 OtherData otherData = new OtherData();
935 otherData.setKey(key);
936 otherData.setKey2(subAttribute.getKey());
937 otherData.setValue(subAttribute.getValue().toString());
938 features.addOtherData(otherData);
943 OtherData otherData = new OtherData();
944 otherData.setKey(key);
945 otherData.setValue(value.toString());
946 features.addOtherData(otherData);
951 jseq.addFeatures(features);
954 if (jdatasq.getAllPDBEntries() != null)
956 Enumeration en = jdatasq.getAllPDBEntries().elements();
957 while (en.hasMoreElements())
959 Pdbids pdb = new Pdbids();
960 jalview.datamodel.PDBEntry entry = (jalview.datamodel.PDBEntry) en
963 String pdbId = entry.getId();
965 pdb.setType(entry.getType());
968 * Store any structure views associated with this sequence. This
969 * section copes with duplicate entries in the project, so a dataset
970 * only view *should* be coped with sensibly.
972 // This must have been loaded, is it still visible?
973 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
974 String matchedFile = null;
975 for (int f = frames.length - 1; f > -1; f--)
977 if (frames[f] instanceof StructureViewerBase)
979 StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
980 matchedFile = saveStructureState(ap, jds, pdb, entry, viewIds,
981 matchedFile, viewFrame);
983 * Only store each structure viewer's state once in the project
984 * jar. First time through only (storeDS==false)
986 String viewId = viewFrame.getViewId();
987 if (!storeDS && !viewIds.contains(viewId))
992 String viewerState = viewFrame.getStateInfo();
993 writeJarEntry(jout, getViewerJarEntryName(viewId),
994 viewerState.getBytes());
995 } catch (IOException e)
998 "Error saving viewer state: " + e.getMessage());
1004 if (matchedFile != null || entry.getFile() != null)
1006 if (entry.getFile() != null)
1009 matchedFile = entry.getFile();
1011 pdb.setFile(matchedFile); // entry.getFile());
1012 if (pdbfiles == null)
1014 pdbfiles = new ArrayList<>();
1017 if (!pdbfiles.contains(pdbId))
1019 pdbfiles.add(pdbId);
1020 copyFileToJar(jout, matchedFile, pdbId);
1024 Enumeration<String> props = entry.getProperties();
1025 if (props.hasMoreElements())
1027 PdbentryItem item = new PdbentryItem();
1028 while (props.hasMoreElements())
1030 Property prop = new Property();
1031 String key = props.nextElement();
1033 prop.setValue(entry.getProperty(key).toString());
1034 item.addProperty(prop);
1036 pdb.addPdbentryItem(item);
1039 jseq.addPdbids(pdb);
1043 saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
1048 if (!storeDS && av.hasHiddenRows())
1050 jal = av.getAlignment();
1054 if (storeDS && jal.getCodonFrames() != null)
1056 List<AlignedCodonFrame> jac = jal.getCodonFrames();
1057 for (AlignedCodonFrame acf : jac)
1059 AlcodonFrame alc = new AlcodonFrame();
1060 if (acf.getProtMappings() != null
1061 && acf.getProtMappings().length > 0)
1063 boolean hasMap = false;
1064 SequenceI[] dnas = acf.getdnaSeqs();
1065 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1066 for (int m = 0; m < pmaps.length; m++)
1068 AlcodMap alcmap = new AlcodMap();
1069 alcmap.setDnasq(seqHash(dnas[m]));
1071 createVamsasMapping(pmaps[m], dnas[m], null, false));
1072 alc.addAlcodMap(alcmap);
1077 vamsasSet.addAlcodonFrame(alc);
1080 // TODO: delete this ? dead code from 2.8.3->2.9 ?
1082 // AlcodonFrame alc = new AlcodonFrame();
1083 // vamsasSet.addAlcodonFrame(alc);
1084 // for (int p = 0; p < acf.aaWidth; p++)
1086 // Alcodon cmap = new Alcodon();
1087 // if (acf.codons[p] != null)
1089 // // Null codons indicate a gapped column in the translated peptide
1091 // cmap.setPos1(acf.codons[p][0]);
1092 // cmap.setPos2(acf.codons[p][1]);
1093 // cmap.setPos3(acf.codons[p][2]);
1095 // alc.addAlcodon(cmap);
1097 // if (acf.getProtMappings() != null
1098 // && acf.getProtMappings().length > 0)
1100 // SequenceI[] dnas = acf.getdnaSeqs();
1101 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1102 // for (int m = 0; m < pmaps.length; m++)
1104 // AlcodMap alcmap = new AlcodMap();
1105 // alcmap.setDnasq(seqHash(dnas[m]));
1106 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1108 // alc.addAlcodMap(alcmap);
1115 // /////////////////////////////////
1116 if (!storeDS && av.getCurrentTree() != null)
1118 // FIND ANY ASSOCIATED TREES
1119 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
1120 if (Desktop.desktop != null)
1122 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1124 for (int t = 0; t < frames.length; t++)
1126 if (frames[t] instanceof TreePanel)
1128 TreePanel tp = (TreePanel) frames[t];
1130 if (tp.treeCanvas.av.getAlignment() == jal)
1132 Tree tree = new Tree();
1133 tree.setTitle(tp.getTitle());
1134 tree.setCurrentTree((av.getCurrentTree() == tp.getTree()));
1135 tree.setNewick(tp.getTree().print());
1136 tree.setThreshold(tp.treeCanvas.threshold);
1138 tree.setFitToWindow(tp.fitToWindow.getState());
1139 tree.setFontName(tp.getTreeFont().getName());
1140 tree.setFontSize(tp.getTreeFont().getSize());
1141 tree.setFontStyle(tp.getTreeFont().getStyle());
1142 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
1144 tree.setShowBootstrap(tp.bootstrapMenu.getState());
1145 tree.setShowDistances(tp.distanceMenu.getState());
1147 tree.setHeight(tp.getHeight());
1148 tree.setWidth(tp.getWidth());
1149 tree.setXpos(tp.getX());
1150 tree.setYpos(tp.getY());
1151 tree.setId(makeHashCode(tp, null));
1152 tree.setLinkToAllViews(tp.treeCanvas.applyToAllViews);
1163 if (!storeDS && Desktop.desktop != null)
1165 for (JInternalFrame frame : Desktop.desktop.getAllFrames())
1167 if (frame instanceof PCAPanel)
1169 PCAPanel panel = (PCAPanel) frame;
1170 if (panel.av.getAlignment() == jal)
1172 savePCA(panel, jms);
1180 * store forward refs from an annotationRow to any groups
1182 IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
1185 for (SequenceI sq : jal.getSequences())
1187 // Store annotation on dataset sequences only
1188 AlignmentAnnotation[] aa = sq.getAnnotation();
1189 if (aa != null && aa.length > 0)
1191 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1198 if (jal.getAlignmentAnnotation() != null)
1200 // Store the annotation shown on the alignment.
1201 AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
1202 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1207 if (jal.getGroups() != null)
1209 JGroup[] groups = new JGroup[jal.getGroups().size()];
1211 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
1213 JGroup jGroup = new JGroup();
1214 groups[++i] = jGroup;
1216 jGroup.setStart(sg.getStartRes());
1217 jGroup.setEnd(sg.getEndRes());
1218 jGroup.setName(sg.getName());
1219 if (groupRefs.containsKey(sg))
1221 // group has references so set its ID field
1222 jGroup.setId(groupRefs.get(sg));
1224 ColourSchemeI colourScheme = sg.getColourScheme();
1225 if (colourScheme != null)
1227 ResidueShaderI groupColourScheme = sg.getGroupColourScheme();
1228 if (groupColourScheme.conservationApplied())
1230 jGroup.setConsThreshold(groupColourScheme.getConservationInc());
1232 if (colourScheme instanceof jalview.schemes.UserColourScheme)
1235 setUserColourScheme(colourScheme, userColours, jms));
1239 jGroup.setColour(colourScheme.getSchemeName());
1242 else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
1244 jGroup.setColour("AnnotationColourGradient");
1245 jGroup.setAnnotationColours(constructAnnotationColours(
1246 (jalview.schemes.AnnotationColourGradient) colourScheme,
1249 else if (colourScheme instanceof jalview.schemes.UserColourScheme)
1252 setUserColourScheme(colourScheme, userColours, jms));
1256 jGroup.setColour(colourScheme.getSchemeName());
1259 jGroup.setPidThreshold(groupColourScheme.getThreshold());
1262 jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
1263 jGroup.setDisplayBoxes(sg.getDisplayBoxes());
1264 jGroup.setDisplayText(sg.getDisplayText());
1265 jGroup.setColourText(sg.getColourText());
1266 jGroup.setTextCol1(sg.textColour.getRGB());
1267 jGroup.setTextCol2(sg.textColour2.getRGB());
1268 jGroup.setTextColThreshold(sg.thresholdTextColour);
1269 jGroup.setShowUnconserved(sg.getShowNonconserved());
1270 jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1271 jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
1272 jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
1273 jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1274 for (SequenceI seq : sg.getSequences())
1276 jGroup.addSeq(seqHash(seq));
1280 jms.setJGroup(groups);
1284 // /////////SAVE VIEWPORT
1285 Viewport view = new Viewport();
1286 view.setTitle(ap.alignFrame.getTitle());
1287 view.setSequenceSetId(
1288 makeHashCode(av.getSequenceSetId(), av.getSequenceSetId()));
1289 view.setId(av.getViewId());
1290 if (av.getCodingComplement() != null)
1292 view.setComplementId(av.getCodingComplement().getViewId());
1294 view.setViewName(av.viewName);
1295 view.setGatheredViews(av.isGatherViewsHere());
1297 Rectangle size = ap.av.getExplodedGeometry();
1298 Rectangle position = size;
1301 size = ap.alignFrame.getBounds();
1302 if (av.getCodingComplement() != null)
1304 position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
1312 view.setXpos(position.x);
1313 view.setYpos(position.y);
1315 view.setWidth(size.width);
1316 view.setHeight(size.height);
1318 view.setStartRes(vpRanges.getStartRes());
1319 view.setStartSeq(vpRanges.getStartSeq());
1321 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1323 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1327 .getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1329 AnnotationColours ac = constructAnnotationColours(
1330 (jalview.schemes.AnnotationColourGradient) av
1331 .getGlobalColourScheme(),
1334 view.setAnnotationColours(ac);
1335 view.setBgColour("AnnotationColourGradient");
1339 view.setBgColour(ColourSchemeProperty
1340 .getColourName(av.getGlobalColourScheme()));
1343 ResidueShaderI vcs = av.getResidueShading();
1344 ColourSchemeI cs = av.getGlobalColourScheme();
1348 if (vcs.conservationApplied())
1350 view.setConsThreshold(vcs.getConservationInc());
1351 if (cs instanceof jalview.schemes.UserColourScheme)
1353 view.setBgColour(setUserColourScheme(cs, userColours, jms));
1356 view.setPidThreshold(vcs.getThreshold());
1359 view.setConservationSelected(av.getConservationSelected());
1360 view.setPidSelected(av.getAbovePIDThreshold());
1361 view.setFontName(av.font.getName());
1362 view.setFontSize(av.font.getSize());
1363 view.setFontStyle(av.font.getStyle());
1364 view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
1365 view.setRenderGaps(av.isRenderGaps());
1366 view.setShowAnnotation(av.isShowAnnotation());
1367 view.setShowBoxes(av.getShowBoxes());
1368 view.setShowColourText(av.getColourText());
1369 view.setShowFullId(av.getShowJVSuffix());
1370 view.setRightAlignIds(av.isRightAlignIds());
1371 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1372 view.setShowText(av.getShowText());
1373 view.setShowUnconserved(av.getShowUnconserved());
1374 view.setWrapAlignment(av.getWrapAlignment());
1375 view.setTextCol1(av.getTextColour().getRGB());
1376 view.setTextCol2(av.getTextColour2().getRGB());
1377 view.setTextColThreshold(av.getThresholdTextColour());
1378 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1379 view.setShowSequenceLogo(av.isShowSequenceLogo());
1380 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1381 view.setShowGroupConsensus(av.isShowGroupConsensus());
1382 view.setShowGroupConservation(av.isShowGroupConservation());
1383 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1384 view.setShowDbRefTooltip(av.isShowDBRefs());
1385 view.setFollowHighlight(av.isFollowHighlight());
1386 view.setFollowSelection(av.followSelection);
1387 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1388 if (av.getFeaturesDisplayed() != null)
1390 jalview.schemabinding.version2.FeatureSettings fs = new jalview.schemabinding.version2.FeatureSettings();
1392 FeatureRenderer fr = ap.getSeqPanel().seqCanvas
1393 .getFeatureRenderer();
1394 String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
1396 Vector<String> settingsAdded = new Vector<>();
1397 if (renderOrder != null)
1399 for (String featureType : renderOrder)
1401 Setting setting = new Setting();
1402 setting.setType(featureType);
1405 * save any filter for the feature type
1407 FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
1408 if (filter != null) {
1409 Iterator<FeatureMatcherI> filters = filter.getMatchers().iterator();
1410 FeatureMatcherI firstFilter = filters.next();
1411 setting.setMatcherSet(Jalview2XML.marshalFilter(
1412 firstFilter, filters, filter.isAnded()));
1416 * save colour scheme for the feature type
1418 FeatureColourI fcol = fr.getFeatureStyle(featureType);
1419 if (!fcol.isSimpleColour())
1421 setting.setColour(fcol.getMaxColour().getRGB());
1422 setting.setMincolour(fcol.getMinColour().getRGB());
1423 setting.setMin(fcol.getMin());
1424 setting.setMax(fcol.getMax());
1425 setting.setColourByLabel(fcol.isColourByLabel());
1426 if (fcol.isColourByAttribute())
1428 setting.setAttributeName(fcol.getAttributeName());
1430 setting.setAutoScale(fcol.isAutoScaled());
1431 setting.setThreshold(fcol.getThreshold());
1432 Color noColour = fcol.getNoColour();
1433 if (noColour == null)
1435 setting.setNoValueColour(NoValueColour.NONE);
1437 else if (noColour.equals(fcol.getMaxColour()))
1439 setting.setNoValueColour(NoValueColour.MAX);
1443 setting.setNoValueColour(NoValueColour.MIN);
1445 // -1 = No threshold, 0 = Below, 1 = Above
1446 setting.setThreshstate(fcol.isAboveThreshold() ? 1
1447 : (fcol.isBelowThreshold() ? 0 : -1));
1451 setting.setColour(fcol.getColour().getRGB());
1455 av.getFeaturesDisplayed().isVisible(featureType));
1457 .getOrder(featureType);
1460 setting.setOrder(rorder);
1462 fs.addSetting(setting);
1463 settingsAdded.addElement(featureType);
1467 // is groups actually supposed to be a map here ?
1468 Iterator<String> en = fr.getFeatureGroups().iterator();
1469 Vector<String> groupsAdded = new Vector<>();
1470 while (en.hasNext())
1472 String grp = en.next();
1473 if (groupsAdded.contains(grp))
1477 Group g = new Group();
1479 g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
1482 groupsAdded.addElement(grp);
1484 jms.setFeatureSettings(fs);
1487 if (av.hasHiddenColumns())
1489 jalview.datamodel.HiddenColumns hidden = av.getAlignment()
1490 .getHiddenColumns();
1493 warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1497 Iterator<int[]> hiddenRegions = hidden.iterator();
1498 while (hiddenRegions.hasNext())
1500 int[] region = hiddenRegions.next();
1501 HiddenColumns hc = new HiddenColumns();
1502 hc.setStart(region[0]);
1503 hc.setEnd(region[1]);
1504 view.addHiddenColumns(hc);
1508 if (calcIdSet.size() > 0)
1510 for (String calcId : calcIdSet)
1512 if (calcId.trim().length() > 0)
1514 CalcIdParam cidp = createCalcIdParam(calcId, av);
1515 // Some calcIds have no parameters.
1518 view.addCalcIdParam(cidp);
1524 jms.addViewport(view);
1526 object.setJalviewModelSequence(jms);
1527 object.getVamsasModel().addSequenceSet(vamsasSet);
1529 if (jout != null && fileName != null)
1531 // We may not want to write the object to disk,
1532 // eg we can copy the alignViewport to a new view object
1533 // using save and then load
1536 System.out.println("Writing jar entry " + fileName);
1537 JarEntry entry = new JarEntry(fileName);
1538 jout.putNextEntry(entry);
1539 PrintWriter pout = new PrintWriter(
1540 new OutputStreamWriter(jout, UTF_8));
1541 Marshaller marshaller = new Marshaller(pout);
1542 marshaller.marshal(object);
1545 } catch (Exception ex)
1547 // TODO: raise error in GUI if marshalling failed.
1548 ex.printStackTrace();
1555 * Writes PCA viewer attributes and computed values to an XML model object and adds it to the JalviewModel. Any exceptions are reported by logging.
1557 protected void savePCA(PCAPanel panel, JalviewModelSequence jms)
1561 PcaViewer viewer = new PcaViewer();
1562 viewer.setHeight(panel.getHeight());
1563 viewer.setWidth(panel.getWidth());
1564 viewer.setXpos(panel.getX());
1565 viewer.setYpos(panel.getY());
1566 viewer.setTitle(panel.getTitle());
1567 PCAModel pcaModel = panel.pcaModel;
1568 viewer.setScoreModelName(pcaModel.getScoreModelName());
1569 viewer.setXDim(panel.getSelectedDimensionIndex(X));
1570 viewer.setYDim(panel.getSelectedDimensionIndex(Y));
1571 viewer.setZDim(panel.getSelectedDimensionIndex(Z));
1572 viewer.setBgColour(panel.rc.getBackgroundColour().getRGB());
1573 viewer.setScaleFactor(panel.rc.scaleFactor);
1574 float[] spMin = panel.rc.getSeqMin();
1575 SeqPointMin spmin = new SeqPointMin();
1576 spmin.setXPos(spMin[0]);
1577 spmin.setYPos(spMin[1]);
1578 spmin.setZPos(spMin[2]);
1579 viewer.setSeqPointMin(spmin);
1580 float[] spMax = panel.rc.getSeqMax();
1581 SeqPointMax spmax = new SeqPointMax();
1582 spmax.setXPos(spMax[0]);
1583 spmax.setYPos(spMax[1]);
1584 spmax.setZPos(spMax[2]);
1585 viewer.setSeqPointMax(spmax);
1586 viewer.setShowLabels(panel.rc.showLabels);
1587 viewer.setLinkToAllViews(panel.rc.applyToAllViews);
1588 SimilarityParamsI sp = pcaModel.getSimilarityParameters();
1589 viewer.setIncludeGaps(sp.includeGaps());
1590 viewer.setMatchGaps(sp.matchGaps());
1591 viewer.setIncludeGappedColumns(sp.includeGappedColumns());
1592 viewer.setDenominateByShortestLength(sp.denominateByShortestLength());
1595 * sequence points on display
1597 for (jalview.datamodel.SequencePoint spt : pcaModel
1598 .getSequencePoints())
1600 SequencePoint point = new SequencePoint();
1601 point.setSequenceRef(seqHash(spt.getSequence()));
1602 point.setXPos(spt.coord.x);
1603 point.setYPos(spt.coord.y);
1604 point.setZPos(spt.coord.z);
1605 viewer.addSequencePoint(point);
1609 * (end points of) axes on display
1611 for (Point p : panel.rc.axisEndPoints)
1613 Axis axis = new Axis();
1617 viewer.addAxis(axis);
1621 * raw PCA data (note we are not restoring PCA inputs here -
1622 * alignment view, score model, similarity parameters)
1624 PcaData data = new PcaData();
1625 viewer.setPcaData(data);
1626 PCA pca = pcaModel.getPcaData();
1628 PairwiseMatrix pm = new PairwiseMatrix();
1629 saveDoubleMatrix(pca.getPairwiseScores(), pm);
1630 data.setPairwiseMatrix(pm);
1632 TridiagonalMatrix tm = new TridiagonalMatrix();
1633 saveDoubleMatrix(pca.getTridiagonal(), tm);
1634 data.setTridiagonalMatrix(tm);
1636 EigenMatrix eigenMatrix = new EigenMatrix();
1637 data.setEigenMatrix(eigenMatrix);
1638 saveDoubleMatrix(pca.getEigenmatrix(), eigenMatrix);
1640 jms.addPcaViewer(viewer);
1641 } catch (Throwable t)
1643 Cache.log.error("Error saving PCA: " + t.getMessage());
1648 * Stores values from a matrix into an XML element, including (if present) the
1653 * @see #loadDoubleMatrix(DoubleMatrix)
1655 protected void saveDoubleMatrix(MatrixI m, DoubleMatrix xmlMatrix)
1657 xmlMatrix.setRows(m.height());
1658 xmlMatrix.setColumns(m.width());
1659 for (int i = 0; i < m.height(); i++)
1661 Row row = new Row();
1662 for (int j = 0; j < m.width(); j++)
1664 row.addV(m.getValue(i, j));
1666 xmlMatrix.addRow(row);
1668 if (m.getD() != null)
1670 D dVector = new D();
1671 dVector.setV(m.getD());
1672 xmlMatrix.setD(dVector);
1674 if (m.getE() != null)
1676 E eVector = new E();
1677 eVector.setV(m.getE());
1678 xmlMatrix.setE(eVector);
1683 * Loads XML matrix data into a new Matrix object, including the D and/or E
1684 * vectors (if present)
1688 * @see Jalview2XML#saveDoubleMatrix(MatrixI, DoubleMatrix)
1690 protected MatrixI loadDoubleMatrix(DoubleMatrix mData)
1692 int rows = mData.getRows();
1693 double[][] vals = new double[rows][];
1695 for (int i = 0; i < rows; i++)
1697 vals[i] = mData.getRow(i).getV();
1700 MatrixI m = new Matrix(vals);
1702 if (mData.getD() != null) {
1703 m.setD(mData.getD().getV());
1705 if (mData.getE() != null)
1707 m.setE(mData.getE().getV());
1714 * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
1715 * for each viewer, with
1717 * <li>viewer geometry (position, size, split pane divider location)</li>
1718 * <li>index of the selected structure in the viewer (currently shows gapped
1720 * <li>the id of the annotation holding RNA secondary structure</li>
1721 * <li>(currently only one SS is shown per viewer, may be more in future)</li>
1723 * Varna viewer state is also written out (in native Varna XML) to separate
1724 * project jar entries. A separate entry is written for each RNA structure
1725 * displayed, with the naming convention
1727 * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
1735 * @param storeDataset
1737 protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
1738 final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
1739 boolean storeDataset)
1741 if (Desktop.desktop == null)
1745 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1746 for (int f = frames.length - 1; f > -1; f--)
1748 if (frames[f] instanceof AppVarna)
1750 AppVarna varna = (AppVarna) frames[f];
1752 * link the sequence to every viewer that is showing it and is linked to
1753 * its alignment panel
1755 if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
1757 String viewId = varna.getViewId();
1758 RnaViewer rna = new RnaViewer();
1759 rna.setViewId(viewId);
1760 rna.setTitle(varna.getTitle());
1761 rna.setXpos(varna.getX());
1762 rna.setYpos(varna.getY());
1763 rna.setWidth(varna.getWidth());
1764 rna.setHeight(varna.getHeight());
1765 rna.setDividerLocation(varna.getDividerLocation());
1766 rna.setSelectedRna(varna.getSelectedIndex());
1767 jseq.addRnaViewer(rna);
1770 * Store each Varna panel's state once in the project per sequence.
1771 * First time through only (storeDataset==false)
1773 // boolean storeSessions = false;
1774 // String sequenceViewId = viewId + seqsToIds.get(jds);
1775 // if (!storeDataset && !viewIds.contains(sequenceViewId))
1777 // viewIds.add(sequenceViewId);
1778 // storeSessions = true;
1780 for (RnaModel model : varna.getModels())
1782 if (model.seq == jds)
1785 * VARNA saves each view (sequence or alignment secondary
1786 * structure, gapped or trimmed) as a separate XML file
1788 String jarEntryName = rnaSessions.get(model);
1789 if (jarEntryName == null)
1792 String varnaStateFile = varna.getStateInfo(model.rna);
1793 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
1794 copyFileToJar(jout, varnaStateFile, jarEntryName);
1795 rnaSessions.put(model, jarEntryName);
1797 SecondaryStructure ss = new SecondaryStructure();
1798 String annotationId = varna.getAnnotation(jds).annotationId;
1799 ss.setAnnotationId(annotationId);
1800 ss.setViewerState(jarEntryName);
1801 ss.setGapped(model.gapped);
1802 ss.setTitle(model.title);
1803 rna.addSecondaryStructure(ss);
1812 * Copy the contents of a file to a new entry added to the output jar
1816 * @param jarEntryName
1818 protected void copyFileToJar(JarOutputStream jout, String infilePath,
1819 String jarEntryName)
1821 DataInputStream dis = null;
1824 File file = new File(infilePath);
1825 if (file.exists() && jout != null)
1827 dis = new DataInputStream(new FileInputStream(file));
1828 byte[] data = new byte[(int) file.length()];
1829 dis.readFully(data);
1830 writeJarEntry(jout, jarEntryName, data);
1832 } catch (Exception ex)
1834 ex.printStackTrace();
1842 } catch (IOException e)
1851 * Write the data to a new entry of given name in the output jar file
1854 * @param jarEntryName
1856 * @throws IOException
1858 protected void writeJarEntry(JarOutputStream jout, String jarEntryName,
1859 byte[] data) throws IOException
1863 System.out.println("Writing jar entry " + jarEntryName);
1864 jout.putNextEntry(new JarEntry(jarEntryName));
1865 DataOutputStream dout = new DataOutputStream(jout);
1866 dout.write(data, 0, data.length);
1873 * Save the state of a structure viewer
1878 * the archive XML element under which to save the state
1881 * @param matchedFile
1885 protected String saveStructureState(AlignmentPanel ap, SequenceI jds,
1886 Pdbids pdb, PDBEntry entry, List<String> viewIds,
1887 String matchedFile, StructureViewerBase viewFrame)
1889 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
1892 * Look for any bindings for this viewer to the PDB file of interest
1893 * (including part matches excluding chain id)
1895 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
1897 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
1898 final String pdbId = pdbentry.getId();
1899 if (!pdbId.equals(entry.getId())
1900 && !(entry.getId().length() > 4 && entry.getId().toLowerCase()
1901 .startsWith(pdbId.toLowerCase())))
1904 * not interested in a binding to a different PDB entry here
1908 if (matchedFile == null)
1910 matchedFile = pdbentry.getFile();
1912 else if (!matchedFile.equals(pdbentry.getFile()))
1915 "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
1916 + pdbentry.getFile());
1920 // can get at it if the ID
1921 // match is ambiguous (e.g.
1924 for (int smap = 0; smap < viewFrame.getBinding()
1925 .getSequence()[peid].length; smap++)
1927 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
1928 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
1930 StructureState state = new StructureState();
1931 state.setVisible(true);
1932 state.setXpos(viewFrame.getX());
1933 state.setYpos(viewFrame.getY());
1934 state.setWidth(viewFrame.getWidth());
1935 state.setHeight(viewFrame.getHeight());
1936 final String viewId = viewFrame.getViewId();
1937 state.setViewId(viewId);
1938 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
1939 state.setColourwithAlignPanel(viewFrame.isUsedforcolourby(ap));
1940 state.setColourByJmol(viewFrame.isColouredByViewer());
1941 state.setType(viewFrame.getViewerType().toString());
1942 pdb.addStructureState(state);
1950 * Populates the AnnotationColours xml for save. This captures the settings of
1951 * the options in the 'Colour by Annotation' dialog.
1954 * @param userColours
1958 private AnnotationColours constructAnnotationColours(
1959 AnnotationColourGradient acg, List<UserColourScheme> userColours,
1960 JalviewModelSequence jms)
1962 AnnotationColours ac = new AnnotationColours();
1963 ac.setAboveThreshold(acg.getAboveThreshold());
1964 ac.setThreshold(acg.getAnnotationThreshold());
1965 // 2.10.2 save annotationId (unique) not annotation label
1966 ac.setAnnotation(acg.getAnnotation().annotationId);
1967 if (acg.getBaseColour() instanceof UserColourScheme)
1970 setUserColourScheme(acg.getBaseColour(), userColours, jms));
1975 ColourSchemeProperty.getColourName(acg.getBaseColour()));
1978 ac.setMaxColour(acg.getMaxColour().getRGB());
1979 ac.setMinColour(acg.getMinColour().getRGB());
1980 ac.setPerSequence(acg.isSeqAssociated());
1981 ac.setPredefinedColours(acg.isPredefinedColours());
1985 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
1986 IdentityHashMap<SequenceGroup, String> groupRefs,
1987 AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
1988 SequenceSet vamsasSet)
1991 for (int i = 0; i < aa.length; i++)
1993 Annotation an = new Annotation();
1995 AlignmentAnnotation annotation = aa[i];
1996 if (annotation.annotationId != null)
1998 annotationIds.put(annotation.annotationId, annotation);
2001 an.setId(annotation.annotationId);
2003 an.setVisible(annotation.visible);
2005 an.setDescription(annotation.description);
2007 if (annotation.sequenceRef != null)
2009 // 2.9 JAL-1781 xref on sequence id rather than name
2010 an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
2012 if (annotation.groupRef != null)
2014 String groupIdr = groupRefs.get(annotation.groupRef);
2015 if (groupIdr == null)
2017 // make a locally unique String
2018 groupRefs.put(annotation.groupRef,
2019 groupIdr = ("" + System.currentTimeMillis()
2020 + annotation.groupRef.getName()
2021 + groupRefs.size()));
2023 an.setGroupRef(groupIdr.toString());
2026 // store all visualization attributes for annotation
2027 an.setGraphHeight(annotation.graphHeight);
2028 an.setCentreColLabels(annotation.centreColLabels);
2029 an.setScaleColLabels(annotation.scaleColLabel);
2030 an.setShowAllColLabels(annotation.showAllColLabels);
2031 an.setBelowAlignment(annotation.belowAlignment);
2033 if (annotation.graph > 0)
2036 an.setGraphType(annotation.graph);
2037 an.setGraphGroup(annotation.graphGroup);
2038 if (annotation.getThreshold() != null)
2040 ThresholdLine line = new ThresholdLine();
2041 line.setLabel(annotation.getThreshold().label);
2042 line.setValue(annotation.getThreshold().value);
2043 line.setColour(annotation.getThreshold().colour.getRGB());
2044 an.setThresholdLine(line);
2052 an.setLabel(annotation.label);
2054 if (annotation == av.getAlignmentQualityAnnot()
2055 || annotation == av.getAlignmentConservationAnnotation()
2056 || annotation == av.getAlignmentConsensusAnnotation()
2057 || annotation.autoCalculated)
2059 // new way of indicating autocalculated annotation -
2060 an.setAutoCalculated(annotation.autoCalculated);
2062 if (annotation.hasScore())
2064 an.setScore(annotation.getScore());
2067 if (annotation.getCalcId() != null)
2069 calcIdSet.add(annotation.getCalcId());
2070 an.setCalcId(annotation.getCalcId());
2072 if (annotation.hasProperties())
2074 for (String pr : annotation.getProperties())
2076 Property prop = new Property();
2078 prop.setValue(annotation.getProperty(pr));
2079 an.addProperty(prop);
2083 AnnotationElement ae;
2084 if (annotation.annotations != null)
2086 an.setScoreOnly(false);
2087 for (int a = 0; a < annotation.annotations.length; a++)
2089 if ((annotation == null) || (annotation.annotations[a] == null))
2094 ae = new AnnotationElement();
2095 if (annotation.annotations[a].description != null)
2097 ae.setDescription(annotation.annotations[a].description);
2099 if (annotation.annotations[a].displayCharacter != null)
2101 ae.setDisplayCharacter(
2102 annotation.annotations[a].displayCharacter);
2105 if (!Float.isNaN(annotation.annotations[a].value))
2107 ae.setValue(annotation.annotations[a].value);
2111 if (annotation.annotations[a].secondaryStructure > ' ')
2113 ae.setSecondaryStructure(
2114 annotation.annotations[a].secondaryStructure + "");
2117 if (annotation.annotations[a].colour != null
2118 && annotation.annotations[a].colour != java.awt.Color.black)
2120 ae.setColour(annotation.annotations[a].colour.getRGB());
2123 an.addAnnotationElement(ae);
2124 if (annotation.autoCalculated)
2126 // only write one non-null entry into the annotation row -
2127 // sufficient to get the visualization attributes necessary to
2135 an.setScoreOnly(true);
2137 if (!storeDS || (storeDS && !annotation.autoCalculated))
2139 // skip autocalculated annotation - these are only provided for
2141 vamsasSet.addAnnotation(an);
2147 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
2149 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
2150 if (settings != null)
2152 CalcIdParam vCalcIdParam = new CalcIdParam();
2153 vCalcIdParam.setCalcId(calcId);
2154 vCalcIdParam.addServiceURL(settings.getServiceURI());
2155 // generic URI allowing a third party to resolve another instance of the
2156 // service used for this calculation
2157 for (String urls : settings.getServiceURLs())
2159 vCalcIdParam.addServiceURL(urls);
2161 vCalcIdParam.setVersion("1.0");
2162 if (settings.getPreset() != null)
2164 WsParamSetI setting = settings.getPreset();
2165 vCalcIdParam.setName(setting.getName());
2166 vCalcIdParam.setDescription(setting.getDescription());
2170 vCalcIdParam.setName("");
2171 vCalcIdParam.setDescription("Last used parameters");
2173 // need to be able to recover 1) settings 2) user-defined presets or
2174 // recreate settings from preset 3) predefined settings provided by
2175 // service - or settings that can be transferred (or discarded)
2176 vCalcIdParam.setParameters(
2177 settings.getWsParamFile().replace("\n", "|\\n|"));
2178 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
2179 // todo - decide if updateImmediately is needed for any projects.
2181 return vCalcIdParam;
2186 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
2189 if (calcIdParam.getVersion().equals("1.0"))
2191 Jws2Instance service = Jws2Discoverer.getDiscoverer()
2192 .getPreferredServiceFor(calcIdParam.getServiceURL());
2193 if (service != null)
2195 WsParamSetI parmSet = null;
2198 parmSet = service.getParamStore().parseServiceParameterFile(
2199 calcIdParam.getName(), calcIdParam.getDescription(),
2200 calcIdParam.getServiceURL(),
2201 calcIdParam.getParameters().replace("|\\n|", "\n"));
2202 } catch (IOException x)
2204 warn("Couldn't parse parameter data for "
2205 + calcIdParam.getCalcId(), x);
2208 List<ArgumentI> argList = null;
2209 if (calcIdParam.getName().length() > 0)
2211 parmSet = service.getParamStore()
2212 .getPreset(calcIdParam.getName());
2213 if (parmSet != null)
2215 // TODO : check we have a good match with settings in AACon -
2216 // otherwise we'll need to create a new preset
2221 argList = parmSet.getArguments();
2224 AAConSettings settings = new AAConSettings(
2225 calcIdParam.isAutoUpdate(), service, parmSet, argList);
2226 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
2227 calcIdParam.isNeedsUpdate());
2232 warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
2236 throw new Error(MessageManager.formatMessage(
2237 "error.unsupported_version_calcIdparam", new Object[]
2238 { calcIdParam.toString() }));
2242 * External mapping between jalview objects and objects yielding a valid and
2243 * unique object ID string. This is null for normal Jalview project IO, but
2244 * non-null when a jalview project is being read or written as part of a
2247 IdentityHashMap jv2vobj = null;
2250 * Construct a unique ID for jvobj using either existing bindings or if none
2251 * exist, the result of the hashcode call for the object.
2254 * jalview data object
2255 * @return unique ID for referring to jvobj
2257 private String makeHashCode(Object jvobj, String altCode)
2259 if (jv2vobj != null)
2261 Object id = jv2vobj.get(jvobj);
2264 return id.toString();
2266 // check string ID mappings
2267 if (jvids2vobj != null && jvobj instanceof String)
2269 id = jvids2vobj.get(jvobj);
2273 return id.toString();
2275 // give up and warn that something has gone wrong
2276 warn("Cannot find ID for object in external mapping : " + jvobj);
2282 * return local jalview object mapped to ID, if it exists
2286 * @return null or object bound to idcode
2288 private Object retrieveExistingObj(String idcode)
2290 if (idcode != null && vobj2jv != null)
2292 return vobj2jv.get(idcode);
2298 * binding from ID strings from external mapping table to jalview data model
2301 private Hashtable vobj2jv;
2303 private Sequence createVamsasSequence(String id, SequenceI jds)
2305 return createVamsasSequence(true, id, jds, null);
2308 private Sequence createVamsasSequence(boolean recurse, String id,
2309 SequenceI jds, SequenceI parentseq)
2311 Sequence vamsasSeq = new Sequence();
2312 vamsasSeq.setId(id);
2313 vamsasSeq.setName(jds.getName());
2314 vamsasSeq.setSequence(jds.getSequenceAsString());
2315 vamsasSeq.setDescription(jds.getDescription());
2316 jalview.datamodel.DBRefEntry[] dbrefs = null;
2317 if (jds.getDatasetSequence() != null)
2319 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
2323 // seqId==dsseqid so we can tell which sequences really are
2324 // dataset sequences only
2325 vamsasSeq.setDsseqid(id);
2326 dbrefs = jds.getDBRefs();
2327 if (parentseq == null)
2334 for (int d = 0; d < dbrefs.length; d++)
2336 DBRef dbref = new DBRef();
2337 dbref.setSource(dbrefs[d].getSource());
2338 dbref.setVersion(dbrefs[d].getVersion());
2339 dbref.setAccessionId(dbrefs[d].getAccessionId());
2340 if (dbrefs[d].hasMap())
2342 Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
2344 dbref.setMapping(mp);
2346 vamsasSeq.addDBRef(dbref);
2352 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
2353 SequenceI parentseq, SequenceI jds, boolean recurse)
2356 if (jmp.getMap() != null)
2360 jalview.util.MapList mlst = jmp.getMap();
2361 List<int[]> r = mlst.getFromRanges();
2362 for (int[] range : r)
2364 MapListFrom mfrom = new MapListFrom();
2365 mfrom.setStart(range[0]);
2366 mfrom.setEnd(range[1]);
2367 mp.addMapListFrom(mfrom);
2369 r = mlst.getToRanges();
2370 for (int[] range : r)
2372 MapListTo mto = new MapListTo();
2373 mto.setStart(range[0]);
2374 mto.setEnd(range[1]);
2375 mp.addMapListTo(mto);
2377 mp.setMapFromUnit(mlst.getFromRatio());
2378 mp.setMapToUnit(mlst.getToRatio());
2379 if (jmp.getTo() != null)
2381 MappingChoice mpc = new MappingChoice();
2383 // check/create ID for the sequence referenced by getTo()
2386 SequenceI ps = null;
2387 if (parentseq != jmp.getTo()
2388 && parentseq.getDatasetSequence() != jmp.getTo())
2390 // chaining dbref rather than a handshaking one
2391 jmpid = seqHash(ps = jmp.getTo());
2395 jmpid = seqHash(ps = parentseq);
2397 mpc.setDseqFor(jmpid);
2398 if (!seqRefIds.containsKey(mpc.getDseqFor()))
2400 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
2401 seqRefIds.put(mpc.getDseqFor(), ps);
2405 jalview.bin.Cache.log.debug("reusing DseqFor ID");
2408 mp.setMappingChoice(mpc);
2414 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
2415 List<UserColourScheme> userColours, JalviewModelSequence jms)
2418 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
2419 boolean newucs = false;
2420 if (!userColours.contains(ucs))
2422 userColours.add(ucs);
2425 id = "ucs" + userColours.indexOf(ucs);
2428 // actually create the scheme's entry in the XML model
2429 java.awt.Color[] colours = ucs.getColours();
2430 jalview.schemabinding.version2.UserColours uc = new jalview.schemabinding.version2.UserColours();
2431 jalview.schemabinding.version2.UserColourScheme jbucs = new jalview.schemabinding.version2.UserColourScheme();
2433 for (int i = 0; i < colours.length; i++)
2435 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
2436 col.setName(ResidueProperties.aa[i]);
2437 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2438 jbucs.addColour(col);
2440 if (ucs.getLowerCaseColours() != null)
2442 colours = ucs.getLowerCaseColours();
2443 for (int i = 0; i < colours.length; i++)
2445 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
2446 col.setName(ResidueProperties.aa[i].toLowerCase());
2447 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2448 jbucs.addColour(col);
2453 uc.setUserColourScheme(jbucs);
2454 jms.addUserColours(uc);
2460 jalview.schemes.UserColourScheme getUserColourScheme(
2461 JalviewModelSequence jms, String id)
2463 UserColours[] uc = jms.getUserColours();
2464 UserColours colours = null;
2466 for (int i = 0; i < uc.length; i++)
2468 if (uc[i].getId().equals(id))
2476 java.awt.Color[] newColours = new java.awt.Color[24];
2478 for (int i = 0; i < 24; i++)
2480 newColours[i] = new java.awt.Color(Integer.parseInt(
2481 colours.getUserColourScheme().getColour(i).getRGB(), 16));
2484 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
2487 if (colours.getUserColourScheme().getColourCount() > 24)
2489 newColours = new java.awt.Color[23];
2490 for (int i = 0; i < 23; i++)
2492 newColours[i] = new java.awt.Color(Integer.parseInt(
2493 colours.getUserColourScheme().getColour(i + 24).getRGB(),
2496 ucs.setLowerCaseColours(newColours);
2503 * contains last error message (if any) encountered by XML loader.
2505 String errorMessage = null;
2508 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
2509 * exceptions are raised during project XML parsing
2511 public boolean attemptversion1parse = true;
2514 * Load a jalview project archive from a jar file
2517 * - HTTP URL or filename
2519 public AlignFrame loadJalviewAlign(final String file)
2522 jalview.gui.AlignFrame af = null;
2526 // create list to store references for any new Jmol viewers created
2527 newStructureViewers = new Vector<>();
2528 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
2529 // Workaround is to make sure caller implements the JarInputStreamProvider
2531 // so we can re-open the jar input stream for each entry.
2533 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
2534 af = loadJalviewAlign(jprovider);
2535 af.setMenusForViewport();
2537 } catch (MalformedURLException e)
2539 errorMessage = "Invalid URL format for '" + file + "'";
2545 SwingUtilities.invokeAndWait(new Runnable()
2550 setLoadingFinishedForNewStructureViewers();
2553 } catch (Exception x)
2555 System.err.println("Error loading alignment: " + x.getMessage());
2561 private jarInputStreamProvider createjarInputStreamProvider(
2562 final String file) throws MalformedURLException
2565 errorMessage = null;
2566 uniqueSetSuffix = null;
2568 viewportsAdded.clear();
2569 frefedSequence = null;
2571 if (file.startsWith("http://"))
2573 url = new URL(file);
2575 final URL _url = url;
2576 return new jarInputStreamProvider()
2580 public JarInputStream getJarInputStream() throws IOException
2584 return new JarInputStream(_url.openStream());
2588 return new JarInputStream(new FileInputStream(file));
2593 public String getFilename()
2601 * Recover jalview session from a jalview project archive. Caller may
2602 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
2603 * themselves. Any null fields will be initialised with default values,
2604 * non-null fields are left alone.
2609 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
2611 errorMessage = null;
2612 if (uniqueSetSuffix == null)
2614 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
2616 if (seqRefIds == null)
2620 AlignFrame af = null, _af = null;
2621 IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
2622 Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
2623 final String file = jprovider.getFilename();
2626 JarInputStream jin = null;
2627 JarEntry jarentry = null;
2632 jin = jprovider.getJarInputStream();
2633 for (int i = 0; i < entryCount; i++)
2635 jarentry = jin.getNextJarEntry();
2638 if (jarentry != null && jarentry.getName().endsWith(".xml"))
2640 InputStreamReader in = new InputStreamReader(jin, UTF_8);
2641 JalviewModel object = new JalviewModel();
2643 Unmarshaller unmar = new Unmarshaller(object);
2644 unmar.setValidation(false);
2645 object = (JalviewModel) unmar.unmarshal(in);
2646 if (true) // !skipViewport(object))
2648 _af = loadFromObject(object, file, true, jprovider);
2649 if (_af != null && object.getJalviewModelSequence()
2650 .getViewportCount() > 0)
2654 // store a reference to the first view
2657 if (_af.viewport.isGatherViewsHere())
2659 // if this is a gathered view, keep its reference since
2660 // after gathering views, only this frame will remain
2662 gatherToThisFrame.put(_af.viewport.getSequenceSetId(), _af);
2664 // Save dataset to register mappings once all resolved
2665 importedDatasets.put(af.viewport.getAlignment().getDataset(),
2666 af.viewport.getAlignment().getDataset());
2671 else if (jarentry != null)
2673 // Some other file here.
2676 } while (jarentry != null);
2677 resolveFrefedSequences();
2678 } catch (IOException ex)
2680 ex.printStackTrace();
2681 errorMessage = "Couldn't locate Jalview XML file : " + file;
2683 "Exception whilst loading jalview XML file : " + ex + "\n");
2684 } catch (Exception ex)
2686 System.err.println("Parsing as Jalview Version 2 file failed.");
2687 ex.printStackTrace(System.err);
2688 if (attemptversion1parse)
2690 // Is Version 1 Jar file?
2693 af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
2694 } catch (Exception ex2)
2696 System.err.println("Exception whilst loading as jalviewXMLV1:");
2697 ex2.printStackTrace();
2701 if (Desktop.instance != null)
2703 Desktop.instance.stopLoading();
2707 System.out.println("Successfully loaded archive file");
2710 ex.printStackTrace();
2713 "Exception whilst loading jalview XML file : " + ex + "\n");
2714 } catch (OutOfMemoryError e)
2716 // Don't use the OOM Window here
2717 errorMessage = "Out of memory loading jalview XML file";
2718 System.err.println("Out of memory whilst loading jalview XML file");
2719 e.printStackTrace();
2723 * Regather multiple views (with the same sequence set id) to the frame (if
2724 * any) that is flagged as the one to gather to, i.e. convert them to tabbed
2725 * views instead of separate frames. Note this doesn't restore a state where
2726 * some expanded views in turn have tabbed views - the last "first tab" read
2727 * in will play the role of gatherer for all.
2729 for (AlignFrame fr : gatherToThisFrame.values())
2731 Desktop.instance.gatherViews(fr);
2734 restoreSplitFrames();
2735 for (AlignmentI ds : importedDatasets.keySet())
2737 if (ds.getCodonFrames() != null)
2739 StructureSelectionManager
2740 .getStructureSelectionManager(Desktop.instance)
2741 .registerMappings(ds.getCodonFrames());
2744 if (errorMessage != null)
2749 if (Desktop.instance != null)
2751 Desktop.instance.stopLoading();
2758 * Try to reconstruct and display SplitFrame windows, where each contains
2759 * complementary dna and protein alignments. Done by pairing up AlignFrame
2760 * objects (created earlier) which have complementary viewport ids associated.
2762 protected void restoreSplitFrames()
2764 List<SplitFrame> gatherTo = new ArrayList<>();
2765 List<AlignFrame> addedToSplitFrames = new ArrayList<>();
2766 Map<String, AlignFrame> dna = new HashMap<>();
2769 * Identify the DNA alignments
2771 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2774 AlignFrame af = candidate.getValue();
2775 if (af.getViewport().getAlignment().isNucleotide())
2777 dna.put(candidate.getKey().getId(), af);
2782 * Try to match up the protein complements
2784 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2787 AlignFrame af = candidate.getValue();
2788 if (!af.getViewport().getAlignment().isNucleotide())
2790 String complementId = candidate.getKey().getComplementId();
2791 // only non-null complements should be in the Map
2792 if (complementId != null && dna.containsKey(complementId))
2794 final AlignFrame dnaFrame = dna.get(complementId);
2795 SplitFrame sf = createSplitFrame(dnaFrame, af);
2796 addedToSplitFrames.add(dnaFrame);
2797 addedToSplitFrames.add(af);
2798 dnaFrame.setMenusForViewport();
2799 af.setMenusForViewport();
2800 if (af.viewport.isGatherViewsHere())
2809 * Open any that we failed to pair up (which shouldn't happen!) as
2810 * standalone AlignFrame's.
2812 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2815 AlignFrame af = candidate.getValue();
2816 if (!addedToSplitFrames.contains(af))
2818 Viewport view = candidate.getKey();
2819 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
2821 af.setMenusForViewport();
2822 System.err.println("Failed to restore view " + view.getTitle()
2823 + " to split frame");
2828 * Gather back into tabbed views as flagged.
2830 for (SplitFrame sf : gatherTo)
2832 Desktop.instance.gatherViews(sf);
2835 splitFrameCandidates.clear();
2839 * Construct and display one SplitFrame holding DNA and protein alignments.
2842 * @param proteinFrame
2845 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
2846 AlignFrame proteinFrame)
2848 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
2849 String title = MessageManager.getString("label.linked_view_title");
2850 int width = (int) dnaFrame.getBounds().getWidth();
2851 int height = (int) (dnaFrame.getBounds().getHeight()
2852 + proteinFrame.getBounds().getHeight() + 50);
2855 * SplitFrame location is saved to both enclosed frames
2857 splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
2858 Desktop.addInternalFrame(splitFrame, title, width, height);
2861 * And compute cDNA consensus (couldn't do earlier with consensus as
2862 * mappings were not yet present)
2864 proteinFrame.viewport.alignmentChanged(proteinFrame.alignPanel);
2870 * check errorMessage for a valid error message and raise an error box in the
2871 * GUI or write the current errorMessage to stderr and then clear the error
2874 protected void reportErrors()
2876 reportErrors(false);
2879 protected void reportErrors(final boolean saving)
2881 if (errorMessage != null)
2883 final String finalErrorMessage = errorMessage;
2886 javax.swing.SwingUtilities.invokeLater(new Runnable()
2891 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2893 "Error " + (saving ? "saving" : "loading")
2895 JvOptionPane.WARNING_MESSAGE);
2901 System.err.println("Problem loading Jalview file: " + errorMessage);
2904 errorMessage = null;
2907 Map<String, String> alreadyLoadedPDB = new HashMap<>();
2910 * when set, local views will be updated from view stored in JalviewXML
2911 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
2912 * sync if this is set to true.
2914 private final boolean updateLocalViews = false;
2917 * Returns the path to a temporary file holding the PDB file for the given PDB
2918 * id. The first time of asking, searches for a file of that name in the
2919 * Jalview project jar, and copies it to a new temporary file. Any repeat
2920 * requests just return the path to the file previously created.
2926 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
2929 if (alreadyLoadedPDB.containsKey(pdbId))
2931 return alreadyLoadedPDB.get(pdbId).toString();
2934 String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
2936 if (tempFile != null)
2938 alreadyLoadedPDB.put(pdbId, tempFile);
2944 * Copies the jar entry of given name to a new temporary file and returns the
2945 * path to the file, or null if the entry is not found.
2948 * @param jarEntryName
2950 * a prefix for the temporary file name, must be at least three
2953 * null or original file - so new file can be given the same suffix
2957 protected String copyJarEntry(jarInputStreamProvider jprovider,
2958 String jarEntryName, String prefix, String origFile)
2960 BufferedReader in = null;
2961 PrintWriter out = null;
2962 String suffix = ".tmp";
2963 if (origFile == null)
2965 origFile = jarEntryName;
2967 int sfpos = origFile.lastIndexOf(".");
2968 if (sfpos > -1 && sfpos < (origFile.length() - 3))
2970 suffix = "." + origFile.substring(sfpos + 1);
2974 JarInputStream jin = jprovider.getJarInputStream();
2976 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
2977 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
2978 * FileInputStream(jprovider)); }
2981 JarEntry entry = null;
2984 entry = jin.getNextJarEntry();
2985 } while (entry != null && !entry.getName().equals(jarEntryName));
2988 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
2989 File outFile = File.createTempFile(prefix, suffix);
2990 outFile.deleteOnExit();
2991 out = new PrintWriter(new FileOutputStream(outFile));
2994 while ((data = in.readLine()) != null)
2999 String t = outFile.getAbsolutePath();
3004 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
3006 } catch (Exception ex)
3008 ex.printStackTrace();
3016 } catch (IOException e)
3030 private class JvAnnotRow
3032 public JvAnnotRow(int i, AlignmentAnnotation jaa)
3039 * persisted version of annotation row from which to take vis properties
3041 public jalview.datamodel.AlignmentAnnotation template;
3044 * original position of the annotation row in the alignment
3050 * Load alignment frame from jalview XML DOM object
3055 * filename source string
3056 * @param loadTreesAndStructures
3057 * when false only create Viewport
3059 * data source provider
3060 * @return alignment frame created from view stored in DOM
3062 AlignFrame loadFromObject(JalviewModel object, String file,
3063 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
3065 SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
3066 Sequence[] vamsasSeq = vamsasSet.getSequence();
3068 JalviewModelSequence jms = object.getJalviewModelSequence();
3070 Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
3073 // ////////////////////////////////
3076 List<SequenceI> hiddenSeqs = null;
3078 List<SequenceI> tmpseqs = new ArrayList<>();
3080 boolean multipleView = false;
3081 SequenceI referenceseqForView = null;
3082 JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
3083 int vi = 0; // counter in vamsasSeq array
3084 for (int i = 0; i < jseqs.length; i++)
3086 String seqId = jseqs[i].getId();
3088 SequenceI tmpSeq = seqRefIds.get(seqId);
3091 if (!incompleteSeqs.containsKey(seqId))
3093 // may not need this check, but keep it for at least 2.9,1 release
3094 if (tmpSeq.getStart() != jseqs[i].getStart()
3095 || tmpSeq.getEnd() != jseqs[i].getEnd())
3098 "Warning JAL-2154 regression: updating start/end for sequence "
3099 + tmpSeq.toString() + " to " + jseqs[i]);
3104 incompleteSeqs.remove(seqId);
3106 if (vamsasSeq.length > vi && vamsasSeq[vi].getId().equals(seqId))
3108 // most likely we are reading a dataset XML document so
3109 // update from vamsasSeq section of XML for this sequence
3110 tmpSeq.setName(vamsasSeq[vi].getName());
3111 tmpSeq.setDescription(vamsasSeq[vi].getDescription());
3112 tmpSeq.setSequence(vamsasSeq[vi].getSequence());
3117 // reading multiple views, so vamsasSeq set is a subset of JSeq
3118 multipleView = true;
3120 tmpSeq.setStart(jseqs[i].getStart());
3121 tmpSeq.setEnd(jseqs[i].getEnd());
3122 tmpseqs.add(tmpSeq);
3126 tmpSeq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
3127 vamsasSeq[vi].getSequence());
3128 tmpSeq.setDescription(vamsasSeq[vi].getDescription());
3129 tmpSeq.setStart(jseqs[i].getStart());
3130 tmpSeq.setEnd(jseqs[i].getEnd());
3131 tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
3132 seqRefIds.put(vamsasSeq[vi].getId(), tmpSeq);
3133 tmpseqs.add(tmpSeq);
3137 if (jseqs[i].hasViewreference() && jseqs[i].getViewreference())
3139 referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
3142 if (jseqs[i].getHidden())
3144 if (hiddenSeqs == null)
3146 hiddenSeqs = new ArrayList<>();
3149 hiddenSeqs.add(tmpSeq);
3154 // Create the alignment object from the sequence set
3155 // ///////////////////////////////
3156 SequenceI[] orderedSeqs = tmpseqs
3157 .toArray(new SequenceI[tmpseqs.size()]);
3159 AlignmentI al = null;
3160 // so we must create or recover the dataset alignment before going further
3161 // ///////////////////////////////
3162 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
3164 // older jalview projects do not have a dataset - so creat alignment and
3166 al = new Alignment(orderedSeqs);
3167 al.setDataset(null);
3171 boolean isdsal = object.getJalviewModelSequence()
3172 .getViewportCount() == 0;
3175 // we are importing a dataset record, so
3176 // recover reference to an alignment already materialsed as dataset
3177 al = getDatasetFor(vamsasSet.getDatasetId());
3181 // materialse the alignment
3182 al = new Alignment(orderedSeqs);
3186 addDatasetRef(vamsasSet.getDatasetId(), al);
3189 // finally, verify all data in vamsasSet is actually present in al
3190 // passing on flag indicating if it is actually a stored dataset
3191 recoverDatasetFor(vamsasSet, al, isdsal);
3194 if (referenceseqForView != null)
3196 al.setSeqrep(referenceseqForView);
3198 // / Add the alignment properties
3199 for (int i = 0; i < vamsasSet.getSequenceSetPropertiesCount(); i++)
3201 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties(i);
3202 al.setProperty(ssp.getKey(), ssp.getValue());
3205 // ///////////////////////////////
3207 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
3210 // load sequence features, database references and any associated PDB
3211 // structures for the alignment
3213 // prior to 2.10, this part would only be executed the first time a
3214 // sequence was encountered, but not afterwards.
3215 // now, for 2.10 projects, this is also done if the xml doc includes
3216 // dataset sequences not actually present in any particular view.
3218 for (int i = 0; i < vamsasSeq.length; i++)
3220 if (jseqs[i].getFeaturesCount() > 0)
3222 Features[] features = jseqs[i].getFeatures();
3223 for (int f = 0; f < features.length; f++)
3225 SequenceFeature sf = new SequenceFeature(features[f].getType(),
3226 features[f].getDescription(), features[f].getBegin(),
3227 features[f].getEnd(), features[f].getScore(),
3228 features[f].getFeatureGroup());
3229 sf.setStatus(features[f].getStatus());
3232 * load any feature attributes - include map-valued attributes
3234 Map<String, Map<String, String>> mapAttributes = new HashMap<>();
3235 for (int od = 0; od < features[f].getOtherDataCount(); od++)
3237 OtherData keyValue = features[f].getOtherData(od);
3238 String attributeName = keyValue.getKey();
3239 String attributeValue = keyValue.getValue();
3240 if (attributeName.startsWith("LINK"))
3242 sf.addLink(attributeValue);
3246 String subAttribute = keyValue.getKey2();
3247 if (subAttribute == null)
3249 // simple string-valued attribute
3250 sf.setValue(attributeName, attributeValue);
3254 // attribute 'key' has sub-attribute 'key2'
3255 if (!mapAttributes.containsKey(attributeName))
3257 mapAttributes.put(attributeName, new HashMap<>());
3259 mapAttributes.get(attributeName).put(subAttribute,
3264 for (Entry<String, Map<String, String>> mapAttribute : mapAttributes
3267 sf.setValue(mapAttribute.getKey(), mapAttribute.getValue());
3270 // adds feature to datasequence's feature set (since Jalview 2.10)
3271 al.getSequenceAt(i).addSequenceFeature(sf);
3274 if (vamsasSeq[i].getDBRefCount() > 0)
3276 // adds dbrefs to datasequence's set (since Jalview 2.10)
3278 al.getSequenceAt(i).getDatasetSequence() == null
3279 ? al.getSequenceAt(i)
3280 : al.getSequenceAt(i).getDatasetSequence(),
3283 if (jseqs[i].getPdbidsCount() > 0)
3285 Pdbids[] ids = jseqs[i].getPdbids();
3286 for (int p = 0; p < ids.length; p++)
3288 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
3289 entry.setId(ids[p].getId());
3290 if (ids[p].getType() != null)
3292 if (PDBEntry.Type.getType(ids[p].getType()) != null)
3294 entry.setType(PDBEntry.Type.getType(ids[p].getType()));
3298 entry.setType(PDBEntry.Type.FILE);
3301 // jprovider is null when executing 'New View'
3302 if (ids[p].getFile() != null && jprovider != null)
3304 if (!pdbloaded.containsKey(ids[p].getFile()))
3306 entry.setFile(loadPDBFile(jprovider, ids[p].getId(),
3311 entry.setFile(pdbloaded.get(ids[p].getId()).toString());
3314 if (ids[p].getPdbentryItem() != null)
3316 for (PdbentryItem item : ids[p].getPdbentryItem())
3318 for (Property pr : item.getProperty())
3320 entry.setProperty(pr.getName(), pr.getValue());
3324 StructureSelectionManager
3325 .getStructureSelectionManager(Desktop.instance)
3326 .registerPDBEntry(entry);
3327 // adds PDBEntry to datasequence's set (since Jalview 2.10)
3328 if (al.getSequenceAt(i).getDatasetSequence() != null)
3330 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
3334 al.getSequenceAt(i).addPDBId(entry);
3339 } // end !multipleview
3341 // ///////////////////////////////
3342 // LOAD SEQUENCE MAPPINGS
3344 if (vamsasSet.getAlcodonFrameCount() > 0)
3346 // TODO Potentially this should only be done once for all views of an
3348 AlcodonFrame[] alc = vamsasSet.getAlcodonFrame();
3349 for (int i = 0; i < alc.length; i++)
3351 AlignedCodonFrame cf = new AlignedCodonFrame();
3352 if (alc[i].getAlcodMapCount() > 0)
3354 AlcodMap[] maps = alc[i].getAlcodMap();
3355 for (int m = 0; m < maps.length; m++)
3357 SequenceI dnaseq = seqRefIds.get(maps[m].getDnasq());
3359 jalview.datamodel.Mapping mapping = null;
3360 // attach to dna sequence reference.
3361 if (maps[m].getMapping() != null)
3363 mapping = addMapping(maps[m].getMapping());
3364 if (dnaseq != null && mapping.getTo() != null)
3366 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
3372 newAlcodMapRef(maps[m].getDnasq(), cf, mapping));
3376 al.addCodonFrame(cf);
3381 // ////////////////////////////////
3383 List<JvAnnotRow> autoAlan = new ArrayList<>();
3386 * store any annotations which forward reference a group's ID
3388 Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
3390 if (vamsasSet.getAnnotationCount() > 0)
3392 Annotation[] an = vamsasSet.getAnnotation();
3394 for (int i = 0; i < an.length; i++)
3396 Annotation annotation = an[i];
3399 * test if annotation is automatically calculated for this view only
3401 boolean autoForView = false;
3402 if (annotation.getLabel().equals("Quality")
3403 || annotation.getLabel().equals("Conservation")
3404 || annotation.getLabel().equals("Consensus"))
3406 // Kludge for pre 2.5 projects which lacked the autocalculated flag
3408 if (!annotation.hasAutoCalculated())
3410 annotation.setAutoCalculated(true);
3413 if (autoForView || (annotation.hasAutoCalculated()
3414 && annotation.isAutoCalculated()))
3416 // remove ID - we don't recover annotation from other views for
3417 // view-specific annotation
3418 annotation.setId(null);
3421 // set visiblity for other annotation in this view
3422 String annotationId = annotation.getId();
3423 if (annotationId != null && annotationIds.containsKey(annotationId))
3425 AlignmentAnnotation jda = annotationIds.get(annotationId);
3426 // in principle Visible should always be true for annotation displayed
3427 // in multiple views
3428 if (annotation.hasVisible())
3430 jda.visible = annotation.getVisible();
3433 al.addAnnotation(jda);
3437 // Construct new annotation from model.
3438 AnnotationElement[] ae = annotation.getAnnotationElement();
3439 jalview.datamodel.Annotation[] anot = null;
3440 java.awt.Color firstColour = null;
3442 if (!annotation.getScoreOnly())
3444 anot = new jalview.datamodel.Annotation[al.getWidth()];
3445 for (int aa = 0; aa < ae.length && aa < anot.length; aa++)
3447 anpos = ae[aa].getPosition();
3449 if (anpos >= anot.length)
3454 anot[anpos] = new jalview.datamodel.Annotation(
3456 ae[aa].getDisplayCharacter(), ae[aa].getDescription(),
3457 (ae[aa].getSecondaryStructure() == null
3458 || ae[aa].getSecondaryStructure().length() == 0)
3460 : ae[aa].getSecondaryStructure()
3465 // JBPNote: Consider verifying dataflow for IO of secondary
3466 // structure annotation read from Stockholm files
3467 // this was added to try to ensure that
3468 // if (anot[ae[aa].getPosition()].secondaryStructure>' ')
3470 // anot[ae[aa].getPosition()].displayCharacter = "";
3472 anot[anpos].colour = new java.awt.Color(ae[aa].getColour());
3473 if (firstColour == null)
3475 firstColour = anot[anpos].colour;
3479 jalview.datamodel.AlignmentAnnotation jaa = null;
3481 if (annotation.getGraph())
3483 float llim = 0, hlim = 0;
3484 // if (autoForView || an[i].isAutoCalculated()) {
3487 jaa = new jalview.datamodel.AlignmentAnnotation(
3488 annotation.getLabel(), annotation.getDescription(), anot,
3489 llim, hlim, annotation.getGraphType());
3491 jaa.graphGroup = annotation.getGraphGroup();
3492 jaa._linecolour = firstColour;
3493 if (annotation.getThresholdLine() != null)
3495 jaa.setThreshold(new jalview.datamodel.GraphLine(
3496 annotation.getThresholdLine().getValue(),
3497 annotation.getThresholdLine().getLabel(),
3499 annotation.getThresholdLine().getColour())));
3502 if (autoForView || annotation.isAutoCalculated())
3504 // Hardwire the symbol display line to ensure that labels for
3505 // histograms are displayed
3511 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
3512 an[i].getDescription(), anot);
3513 jaa._linecolour = firstColour;
3515 // register new annotation
3516 if (an[i].getId() != null)
3518 annotationIds.put(an[i].getId(), jaa);
3519 jaa.annotationId = an[i].getId();
3521 // recover sequence association
3522 String sequenceRef = an[i].getSequenceRef();
3523 if (sequenceRef != null)
3525 // from 2.9 sequenceRef is to sequence id (JAL-1781)
3526 SequenceI sequence = seqRefIds.get(sequenceRef);
3527 if (sequence == null)
3529 // in pre-2.9 projects sequence ref is to sequence name
3530 sequence = al.findName(sequenceRef);
3532 if (sequence != null)
3534 jaa.createSequenceMapping(sequence, 1, true);
3535 sequence.addAlignmentAnnotation(jaa);
3538 // and make a note of any group association
3539 if (an[i].getGroupRef() != null && an[i].getGroupRef().length() > 0)
3541 List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
3542 .get(an[i].getGroupRef());
3545 aal = new ArrayList<>();
3546 groupAnnotRefs.put(an[i].getGroupRef(), aal);
3551 if (an[i].hasScore())
3553 jaa.setScore(an[i].getScore());
3555 if (an[i].hasVisible())
3557 jaa.visible = an[i].getVisible();
3560 if (an[i].hasCentreColLabels())
3562 jaa.centreColLabels = an[i].getCentreColLabels();
3565 if (an[i].hasScaleColLabels())
3567 jaa.scaleColLabel = an[i].getScaleColLabels();
3569 if (an[i].hasAutoCalculated() && an[i].isAutoCalculated())
3571 // newer files have an 'autoCalculated' flag and store calculation
3572 // state in viewport properties
3573 jaa.autoCalculated = true; // means annotation will be marked for
3574 // update at end of load.
3576 if (an[i].hasGraphHeight())
3578 jaa.graphHeight = an[i].getGraphHeight();
3580 if (an[i].hasBelowAlignment())
3582 jaa.belowAlignment = an[i].isBelowAlignment();
3584 jaa.setCalcId(an[i].getCalcId());
3585 if (an[i].getPropertyCount() > 0)
3587 for (jalview.schemabinding.version2.Property prop : an[i]
3590 jaa.setProperty(prop.getName(), prop.getValue());
3593 if (jaa.autoCalculated)
3595 autoAlan.add(new JvAnnotRow(i, jaa));
3598 // if (!autoForView)
3600 // add autocalculated group annotation and any user created annotation
3602 al.addAnnotation(jaa);
3606 // ///////////////////////
3608 // Create alignment markup and styles for this view
3609 if (jms.getJGroupCount() > 0)
3611 JGroup[] groups = jms.getJGroup();
3612 boolean addAnnotSchemeGroup = false;
3613 for (int i = 0; i < groups.length; i++)
3615 JGroup jGroup = groups[i];
3616 ColourSchemeI cs = null;
3617 if (jGroup.getColour() != null)
3619 if (jGroup.getColour().startsWith("ucs"))
3621 cs = getUserColourScheme(jms, jGroup.getColour());
3623 else if (jGroup.getColour().equals("AnnotationColourGradient")
3624 && jGroup.getAnnotationColours() != null)
3626 addAnnotSchemeGroup = true;
3630 cs = ColourSchemeProperty.getColourScheme(al,
3631 jGroup.getColour());
3634 int pidThreshold = jGroup.getPidThreshold();
3636 Vector<SequenceI> seqs = new Vector<>();
3638 for (int s = 0; s < jGroup.getSeqCount(); s++)
3640 String seqId = jGroup.getSeq(s) + "";
3641 SequenceI ts = seqRefIds.get(seqId);
3645 seqs.addElement(ts);
3649 if (seqs.size() < 1)
3654 SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
3655 jGroup.getDisplayBoxes(), jGroup.getDisplayText(),
3656 jGroup.getColourText(), jGroup.getStart(), jGroup.getEnd());
3657 sg.getGroupColourScheme().setThreshold(pidThreshold, true);
3658 sg.getGroupColourScheme()
3659 .setConservationInc(jGroup.getConsThreshold());
3660 sg.setOutlineColour(new java.awt.Color(jGroup.getOutlineColour()));
3662 sg.textColour = new java.awt.Color(jGroup.getTextCol1());
3663 sg.textColour2 = new java.awt.Color(jGroup.getTextCol2());
3664 sg.setShowNonconserved(
3665 jGroup.hasShowUnconserved() ? jGroup.isShowUnconserved()
3667 sg.thresholdTextColour = jGroup.getTextColThreshold();
3668 if (jGroup.hasShowConsensusHistogram())
3670 sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
3673 if (jGroup.hasShowSequenceLogo())
3675 sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
3677 if (jGroup.hasNormaliseSequenceLogo())
3679 sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
3681 if (jGroup.hasIgnoreGapsinConsensus())
3683 sg.setIgnoreGapsConsensus(jGroup.getIgnoreGapsinConsensus());
3685 if (jGroup.getConsThreshold() != 0)
3687 Conservation c = new Conservation("All", sg.getSequences(null), 0,
3690 c.verdict(false, 25);
3691 sg.cs.setConservation(c);
3694 if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
3696 // re-instate unique group/annotation row reference
3697 List<AlignmentAnnotation> jaal = groupAnnotRefs
3698 .get(jGroup.getId());
3701 for (AlignmentAnnotation jaa : jaal)
3704 if (jaa.autoCalculated)
3706 // match up and try to set group autocalc alignment row for this
3708 if (jaa.label.startsWith("Consensus for "))
3710 sg.setConsensus(jaa);
3712 // match up and try to set group autocalc alignment row for this
3714 if (jaa.label.startsWith("Conservation for "))
3716 sg.setConservationRow(jaa);
3723 if (addAnnotSchemeGroup)
3725 // reconstruct the annotation colourscheme
3726 sg.setColourScheme(constructAnnotationColour(
3727 jGroup.getAnnotationColours(), null, al, jms, false));
3733 // only dataset in this model, so just return.
3736 // ///////////////////////////////
3739 // If we just load in the same jar file again, the sequenceSetId
3740 // will be the same, and we end up with multiple references
3741 // to the same sequenceSet. We must modify this id on load
3742 // so that each load of the file gives a unique id
3743 String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
3744 String viewId = (view.getId() == null ? null
3745 : view.getId() + uniqueSetSuffix);
3746 AlignFrame af = null;
3747 AlignViewport av = null;
3748 // now check to see if we really need to create a new viewport.
3749 if (multipleView && viewportsAdded.size() == 0)
3751 // We recovered an alignment for which a viewport already exists.
3752 // TODO: fix up any settings necessary for overlaying stored state onto
3753 // state recovered from another document. (may not be necessary).
3754 // we may need a binding from a viewport in memory to one recovered from
3756 // and then recover its containing af to allow the settings to be applied.
3757 // TODO: fix for vamsas demo
3759 "About to recover a viewport for existing alignment: Sequence set ID is "
3761 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
3762 if (seqsetobj != null)
3764 if (seqsetobj instanceof String)
3766 uniqueSeqSetId = (String) seqsetobj;
3768 "Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
3774 "Warning : Collision between sequence set ID string and existing jalview object mapping.");
3780 * indicate that annotation colours are applied across all groups (pre
3781 * Jalview 2.8.1 behaviour)
3783 boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan("2.8.1",
3784 object.getVersion());
3786 AlignmentPanel ap = null;
3787 boolean isnewview = true;
3790 // Check to see if this alignment already has a view id == viewId
3791 jalview.gui.AlignmentPanel views[] = Desktop
3792 .getAlignmentPanels(uniqueSeqSetId);
3793 if (views != null && views.length > 0)
3795 for (int v = 0; v < views.length; v++)
3797 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
3799 // recover the existing alignpanel, alignframe, viewport
3800 af = views[v].alignFrame;
3803 // TODO: could even skip resetting view settings if we don't want to
3804 // change the local settings from other jalview processes
3813 af = loadViewport(file, jseqs, hiddenSeqs, al, jms, view,
3814 uniqueSeqSetId, viewId, autoAlan);
3820 * Load any trees, PDB structures and viewers
3822 * Not done if flag is false (when this method is used for New View)
3824 if (loadTreesAndStructures)
3826 loadTrees(jms, view, af, av, ap);
3827 loadPCAViewers(jms, ap);
3828 loadPDBStructures(jprovider, jseqs, af, ap);
3829 loadRnaViewers(jprovider, jseqs, ap);
3831 // and finally return.
3836 * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
3837 * panel is restored from separate jar entries, two (gapped and trimmed) per
3838 * sequence and secondary structure.
3840 * Currently each viewer shows just one sequence and structure (gapped and
3841 * trimmed), however this method is designed to support multiple sequences or
3842 * structures in viewers if wanted in future.
3848 private void loadRnaViewers(jarInputStreamProvider jprovider,
3849 JSeq[] jseqs, AlignmentPanel ap)
3852 * scan the sequences for references to viewers; create each one the first
3853 * time it is referenced, add Rna models to existing viewers
3855 for (JSeq jseq : jseqs)
3857 for (int i = 0; i < jseq.getRnaViewerCount(); i++)
3859 RnaViewer viewer = jseq.getRnaViewer(i);
3860 AppVarna appVarna = findOrCreateVarnaViewer(viewer, uniqueSetSuffix,
3863 for (int j = 0; j < viewer.getSecondaryStructureCount(); j++)
3865 SecondaryStructure ss = viewer.getSecondaryStructure(j);
3866 SequenceI seq = seqRefIds.get(jseq.getId());
3867 AlignmentAnnotation ann = this.annotationIds
3868 .get(ss.getAnnotationId());
3871 * add the structure to the Varna display (with session state copied
3872 * from the jar to a temporary file)
3874 boolean gapped = ss.isGapped();
3875 String rnaTitle = ss.getTitle();
3876 String sessionState = ss.getViewerState();
3877 String tempStateFile = copyJarEntry(jprovider, sessionState,
3879 RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
3880 appVarna.addModelSession(rna, rnaTitle, tempStateFile);
3882 appVarna.setInitialSelection(viewer.getSelectedRna());
3888 * Locate and return an already instantiated matching AppVarna, or create one
3892 * @param viewIdSuffix
3896 protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
3897 String viewIdSuffix, AlignmentPanel ap)
3900 * on each load a suffix is appended to the saved viewId, to avoid conflicts
3901 * if load is repeated
3903 String postLoadId = viewer.getViewId() + viewIdSuffix;
3904 for (JInternalFrame frame : getAllFrames())
3906 if (frame instanceof AppVarna)
3908 AppVarna varna = (AppVarna) frame;
3909 if (postLoadId.equals(varna.getViewId()))
3911 // this viewer is already instantiated
3912 // could in future here add ap as another 'parent' of the
3913 // AppVarna window; currently just 1-to-many
3920 * viewer not found - make it
3922 RnaViewerModel model = new RnaViewerModel(postLoadId, viewer.getTitle(),
3923 viewer.getXpos(), viewer.getYpos(), viewer.getWidth(),
3924 viewer.getHeight(), viewer.getDividerLocation());
3925 AppVarna varna = new AppVarna(model, ap);
3931 * Load any saved trees
3939 protected void loadTrees(JalviewModelSequence jms, Viewport view,
3940 AlignFrame af, AlignViewport av, AlignmentPanel ap)
3942 // TODO result of automated refactoring - are all these parameters needed?
3945 for (int t = 0; t < jms.getTreeCount(); t++)
3948 Tree tree = jms.getTree(t);
3950 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
3953 tp = af.showNewickTree(
3954 new jalview.io.NewickFile(tree.getNewick()),
3955 tree.getTitle(), tree.getWidth(), tree.getHeight(),
3956 tree.getXpos(), tree.getYpos());
3957 if (tree.getId() != null)
3959 // perhaps bind the tree id to something ?
3964 // update local tree attributes ?
3965 // TODO: should check if tp has been manipulated by user - if so its
3966 // settings shouldn't be modified
3967 tp.setTitle(tree.getTitle());
3968 tp.setBounds(new Rectangle(tree.getXpos(), tree.getYpos(),
3969 tree.getWidth(), tree.getHeight()));
3971 tp.treeCanvas.av = av; // af.viewport;
3972 tp.treeCanvas.ap = ap; // af.alignPanel;
3977 warn("There was a problem recovering stored Newick tree: \n"
3978 + tree.getNewick());
3982 tp.fitToWindow.setState(tree.getFitToWindow());
3983 tp.fitToWindow_actionPerformed(null);
3985 if (tree.getFontName() != null)
3987 tp.setTreeFont(new java.awt.Font(tree.getFontName(),
3988 tree.getFontStyle(), tree.getFontSize()));
3992 tp.setTreeFont(new java.awt.Font(view.getFontName(),
3993 view.getFontStyle(), tree.getFontSize()));
3996 tp.showPlaceholders(tree.getMarkUnlinked());
3997 tp.showBootstrap(tree.getShowBootstrap());
3998 tp.showDistances(tree.getShowDistances());
4000 tp.treeCanvas.threshold = tree.getThreshold();
4001 tp.treeCanvas.applyToAllViews = tree.isLinkToAllViews();
4003 if (tree.getCurrentTree())
4005 af.viewport.setCurrentTree(tp.getTree());
4009 } catch (Exception ex)
4011 ex.printStackTrace();
4016 * Load and link any saved structure viewers.
4023 protected void loadPDBStructures(jarInputStreamProvider jprovider,
4024 JSeq[] jseqs, AlignFrame af, AlignmentPanel ap)
4027 * Run through all PDB ids on the alignment, and collect mappings between
4028 * distinct view ids and all sequences referring to that view.
4030 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
4032 for (int i = 0; i < jseqs.length; i++)
4034 if (jseqs[i].getPdbidsCount() > 0)
4036 Pdbids[] ids = jseqs[i].getPdbids();
4037 for (int p = 0; p < ids.length; p++)
4039 final int structureStateCount = ids[p].getStructureStateCount();
4040 for (int s = 0; s < structureStateCount; s++)
4042 // check to see if we haven't already created this structure view
4043 final StructureState structureState = ids[p]
4044 .getStructureState(s);
4045 String sviewid = (structureState.getViewId() == null) ? null
4046 : structureState.getViewId() + uniqueSetSuffix;
4047 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
4048 // Originally : ids[p].getFile()
4049 // : TODO: verify external PDB file recovery still works in normal
4050 // jalview project load
4051 jpdb.setFile(loadPDBFile(jprovider, ids[p].getId(),
4053 jpdb.setId(ids[p].getId());
4055 int x = structureState.getXpos();
4056 int y = structureState.getYpos();
4057 int width = structureState.getWidth();
4058 int height = structureState.getHeight();
4060 // Probably don't need to do this anymore...
4061 // Desktop.desktop.getComponentAt(x, y);
4062 // TODO: NOW: check that this recovers the PDB file correctly.
4063 String pdbFile = loadPDBFile(jprovider, ids[p].getId(),
4065 jalview.datamodel.SequenceI seq = seqRefIds
4066 .get(jseqs[i].getId() + "");
4067 if (sviewid == null)
4069 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width + ","
4072 if (!structureViewers.containsKey(sviewid))
4074 structureViewers.put(sviewid,
4075 new StructureViewerModel(x, y, width, height, false,
4076 false, true, structureState.getViewId(),
4077 structureState.getType()));
4078 // Legacy pre-2.7 conversion JAL-823 :
4079 // do not assume any view has to be linked for colour by
4083 // assemble String[] { pdb files }, String[] { id for each
4084 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
4085 // seqs_file 2}, boolean[] {
4086 // linkAlignPanel,superposeWithAlignpanel}} from hash
4087 StructureViewerModel jmoldat = structureViewers.get(sviewid);
4088 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
4089 | (structureState.hasAlignwithAlignPanel()
4090 ? structureState.getAlignwithAlignPanel()
4094 * Default colour by linked panel to false if not specified (e.g.
4095 * for pre-2.7 projects)
4097 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
4098 colourWithAlignPanel |= (structureState
4099 .hasColourwithAlignPanel()
4100 ? structureState.getColourwithAlignPanel()
4102 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
4105 * Default colour by viewer to true if not specified (e.g. for
4108 boolean colourByViewer = jmoldat.isColourByViewer();
4109 colourByViewer &= structureState.hasColourByJmol()
4110 ? structureState.getColourByJmol()
4112 jmoldat.setColourByViewer(colourByViewer);
4114 if (jmoldat.getStateData().length() < structureState
4115 .getContent().length())
4118 jmoldat.setStateData(structureState.getContent());
4121 if (ids[p].getFile() != null)
4123 File mapkey = new File(ids[p].getFile());
4124 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
4125 if (seqstrmaps == null)
4127 jmoldat.getFileData().put(mapkey,
4128 seqstrmaps = jmoldat.new StructureData(pdbFile,
4131 if (!seqstrmaps.getSeqList().contains(seq))
4133 seqstrmaps.getSeqList().add(seq);
4139 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");
4146 // Instantiate the associated structure views
4147 for (Entry<String, StructureViewerModel> entry : structureViewers
4152 createOrLinkStructureViewer(entry, af, ap, jprovider);
4153 } catch (Exception e)
4156 "Error loading structure viewer: " + e.getMessage());
4157 // failed - try the next one
4169 protected void createOrLinkStructureViewer(
4170 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
4171 AlignmentPanel ap, jarInputStreamProvider jprovider)
4173 final StructureViewerModel stateData = viewerData.getValue();
4176 * Search for any viewer windows already open from other alignment views
4177 * that exactly match the stored structure state
4179 StructureViewerBase comp = findMatchingViewer(viewerData);
4183 linkStructureViewer(ap, comp, stateData);
4188 * From 2.9: stateData.type contains JMOL or CHIMERA, data is in jar entry
4189 * "viewer_"+stateData.viewId
4191 if (ViewerType.CHIMERA.toString().equals(stateData.getType()))
4193 createChimeraViewer(viewerData, af, jprovider);
4198 * else Jmol (if pre-2.9, stateData contains JMOL state string)
4200 createJmolViewer(viewerData, af, jprovider);
4205 * Create a new Chimera viewer.
4211 protected void createChimeraViewer(
4212 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
4213 jarInputStreamProvider jprovider)
4215 StructureViewerModel data = viewerData.getValue();
4216 String chimeraSessionFile = data.getStateData();
4219 * Copy Chimera session from jar entry "viewer_"+viewId to a temporary file
4221 * NB this is the 'saved' viewId as in the project file XML, _not_ the
4222 * 'uniquified' sviewid used to reconstruct the viewer here
4224 String viewerJarEntryName = getViewerJarEntryName(data.getViewId());
4225 chimeraSessionFile = copyJarEntry(jprovider, viewerJarEntryName,
4228 Set<Entry<File, StructureData>> fileData = data.getFileData()
4230 List<PDBEntry> pdbs = new ArrayList<>();
4231 List<SequenceI[]> allseqs = new ArrayList<>();
4232 for (Entry<File, StructureData> pdb : fileData)
4234 String filePath = pdb.getValue().getFilePath();
4235 String pdbId = pdb.getValue().getPdbId();
4236 // pdbs.add(new PDBEntry(filePath, pdbId));
4237 pdbs.add(new PDBEntry(pdbId, null, PDBEntry.Type.PDB, filePath));
4238 final List<SequenceI> seqList = pdb.getValue().getSeqList();
4239 SequenceI[] seqs = seqList.toArray(new SequenceI[seqList.size()]);
4243 boolean colourByChimera = data.isColourByViewer();
4244 boolean colourBySequence = data.isColourWithAlignPanel();
4246 // TODO use StructureViewer as a factory here, see JAL-1761
4247 final PDBEntry[] pdbArray = pdbs.toArray(new PDBEntry[pdbs.size()]);
4248 final SequenceI[][] seqsArray = allseqs
4249 .toArray(new SequenceI[allseqs.size()][]);
4250 String newViewId = viewerData.getKey();
4252 ChimeraViewFrame cvf = new ChimeraViewFrame(chimeraSessionFile,
4253 af.alignPanel, pdbArray, seqsArray, colourByChimera,
4254 colourBySequence, newViewId);
4255 cvf.setSize(data.getWidth(), data.getHeight());
4256 cvf.setLocation(data.getX(), data.getY());
4260 * Create a new Jmol window. First parse the Jmol state to translate filenames
4261 * loaded into the view, and record the order in which files are shown in the
4262 * Jmol view, so we can add the sequence mappings in same order.
4268 protected void createJmolViewer(
4269 final Entry<String, StructureViewerModel> viewerData,
4270 AlignFrame af, jarInputStreamProvider jprovider)
4272 final StructureViewerModel svattrib = viewerData.getValue();
4273 String state = svattrib.getStateData();
4276 * Pre-2.9: state element value is the Jmol state string
4278 * 2.9+: @type is "JMOL", state data is in a Jar file member named "viewer_"
4281 if (ViewerType.JMOL.toString().equals(svattrib.getType()))
4283 state = readJarEntry(jprovider,
4284 getViewerJarEntryName(svattrib.getViewId()));
4287 List<String> pdbfilenames = new ArrayList<>();
4288 List<SequenceI[]> seqmaps = new ArrayList<>();
4289 List<String> pdbids = new ArrayList<>();
4290 StringBuilder newFileLoc = new StringBuilder(64);
4291 int cp = 0, ncp, ecp;
4292 Map<File, StructureData> oldFiles = svattrib.getFileData();
4293 while ((ncp = state.indexOf("load ", cp)) > -1)
4297 // look for next filename in load statement
4298 newFileLoc.append(state.substring(cp,
4299 ncp = (state.indexOf("\"", ncp + 1) + 1)));
4300 String oldfilenam = state.substring(ncp,
4301 ecp = state.indexOf("\"", ncp));
4302 // recover the new mapping data for this old filename
4303 // have to normalize filename - since Jmol and jalview do
4305 // translation differently.
4306 StructureData filedat = oldFiles.get(new File(oldfilenam));
4307 if (filedat == null)
4309 String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
4310 filedat = oldFiles.get(new File(reformatedOldFilename));
4312 newFileLoc.append(Platform.escapeString(filedat.getFilePath()));
4313 pdbfilenames.add(filedat.getFilePath());
4314 pdbids.add(filedat.getPdbId());
4315 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4316 newFileLoc.append("\"");
4317 cp = ecp + 1; // advance beyond last \" and set cursor so we can
4318 // look for next file statement.
4319 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
4323 // just append rest of state
4324 newFileLoc.append(state.substring(cp));
4328 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
4329 newFileLoc = new StringBuilder(state);
4330 newFileLoc.append("; load append ");
4331 for (File id : oldFiles.keySet())
4333 // add this and any other pdb files that should be present in
4335 StructureData filedat = oldFiles.get(id);
4336 newFileLoc.append(filedat.getFilePath());
4337 pdbfilenames.add(filedat.getFilePath());
4338 pdbids.add(filedat.getPdbId());
4339 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4340 newFileLoc.append(" \"");
4341 newFileLoc.append(filedat.getFilePath());
4342 newFileLoc.append("\"");
4345 newFileLoc.append(";");
4348 if (newFileLoc.length() == 0)
4352 int histbug = newFileLoc.indexOf("history = ");
4356 * change "history = [true|false];" to "history = [1|0];"
4359 int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";", histbug);
4360 String val = (diff == -1) ? null
4361 : newFileLoc.substring(histbug, diff);
4362 if (val != null && val.length() >= 4)
4364 if (val.contains("e")) // eh? what can it be?
4366 if (val.trim().equals("true"))
4374 newFileLoc.replace(histbug, diff, val);
4379 final String[] pdbf = pdbfilenames
4380 .toArray(new String[pdbfilenames.size()]);
4381 final String[] id = pdbids.toArray(new String[pdbids.size()]);
4382 final SequenceI[][] sq = seqmaps
4383 .toArray(new SequenceI[seqmaps.size()][]);
4384 final String fileloc = newFileLoc.toString();
4385 final String sviewid = viewerData.getKey();
4386 final AlignFrame alf = af;
4387 final Rectangle rect = new Rectangle(svattrib.getX(), svattrib.getY(),
4388 svattrib.getWidth(), svattrib.getHeight());
4391 javax.swing.SwingUtilities.invokeAndWait(new Runnable()
4396 JalviewStructureDisplayI sview = null;
4399 sview = new StructureViewer(
4400 alf.alignPanel.getStructureSelectionManager())
4401 .createView(StructureViewer.ViewerType.JMOL,
4402 pdbf, id, sq, alf.alignPanel, svattrib,
4403 fileloc, rect, sviewid);
4404 addNewStructureViewer(sview);
4405 } catch (OutOfMemoryError ex)
4407 new OOMWarning("restoring structure view for PDB id " + id,
4408 (OutOfMemoryError) ex.getCause());
4409 if (sview != null && sview.isVisible())
4411 sview.closeViewer(false);
4412 sview.setVisible(false);
4418 } catch (InvocationTargetException ex)
4420 warn("Unexpected error when opening Jmol view.", ex);
4422 } catch (InterruptedException e)
4424 // e.printStackTrace();
4430 * Generates a name for the entry in the project jar file to hold state
4431 * information for a structure viewer
4436 protected String getViewerJarEntryName(String viewId)
4438 return VIEWER_PREFIX + viewId;
4442 * Returns any open frame that matches given structure viewer data. The match
4443 * is based on the unique viewId, or (for older project versions) the frame's
4449 protected StructureViewerBase findMatchingViewer(
4450 Entry<String, StructureViewerModel> viewerData)
4452 final String sviewid = viewerData.getKey();
4453 final StructureViewerModel svattrib = viewerData.getValue();
4454 StructureViewerBase comp = null;
4455 JInternalFrame[] frames = getAllFrames();
4456 for (JInternalFrame frame : frames)
4458 if (frame instanceof StructureViewerBase)
4461 * Post jalview 2.4 schema includes structure view id
4463 if (sviewid != null && ((StructureViewerBase) frame).getViewId()
4466 comp = (StructureViewerBase) frame;
4467 break; // break added in 2.9
4470 * Otherwise test for matching position and size of viewer frame
4472 else if (frame.getX() == svattrib.getX()
4473 && frame.getY() == svattrib.getY()
4474 && frame.getHeight() == svattrib.getHeight()
4475 && frame.getWidth() == svattrib.getWidth())
4477 comp = (StructureViewerBase) frame;
4478 // no break in faint hope of an exact match on viewId
4486 * Link an AlignmentPanel to an existing structure viewer.
4491 * @param useinViewerSuperpos
4492 * @param usetoColourbyseq
4493 * @param viewerColouring
4495 protected void linkStructureViewer(AlignmentPanel ap,
4496 StructureViewerBase viewer, StructureViewerModel stateData)
4498 // NOTE: if the jalview project is part of a shared session then
4499 // view synchronization should/could be done here.
4501 final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
4502 final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
4503 final boolean viewerColouring = stateData.isColourByViewer();
4504 Map<File, StructureData> oldFiles = stateData.getFileData();
4507 * Add mapping for sequences in this view to an already open viewer
4509 final AAStructureBindingModel binding = viewer.getBinding();
4510 for (File id : oldFiles.keySet())
4512 // add this and any other pdb files that should be present in the
4514 StructureData filedat = oldFiles.get(id);
4515 String pdbFile = filedat.getFilePath();
4516 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
4517 binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE,
4519 binding.addSequenceForStructFile(pdbFile, seq);
4521 // and add the AlignmentPanel's reference to the view panel
4522 viewer.addAlignmentPanel(ap);
4523 if (useinViewerSuperpos)
4525 viewer.useAlignmentPanelForSuperposition(ap);
4529 viewer.excludeAlignmentPanelForSuperposition(ap);
4531 if (usetoColourbyseq)
4533 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
4537 viewer.excludeAlignmentPanelForColourbyseq(ap);
4542 * Get all frames within the Desktop.
4546 protected JInternalFrame[] getAllFrames()
4548 JInternalFrame[] frames = null;
4549 // TODO is this necessary - is it safe - risk of hanging?
4554 frames = Desktop.desktop.getAllFrames();
4555 } catch (ArrayIndexOutOfBoundsException e)
4557 // occasional No such child exceptions are thrown here...
4561 } catch (InterruptedException f)
4565 } while (frames == null);
4570 * Answers true if 'version' is equal to or later than 'supported', where each
4571 * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
4572 * changes. Development and test values for 'version' are leniently treated
4576 * - minimum version we are comparing against
4578 * - version of data being processsed
4581 public static boolean isVersionStringLaterThan(String supported,
4584 if (supported == null || version == null
4585 || version.equalsIgnoreCase("DEVELOPMENT BUILD")
4586 || version.equalsIgnoreCase("Test")
4587 || version.equalsIgnoreCase("AUTOMATED BUILD"))
4589 System.err.println("Assuming project file with "
4590 + (version == null ? "null" : version)
4591 + " is compatible with Jalview version " + supported);
4596 return StringUtils.compareVersions(version, supported, "b") >= 0;
4600 Vector<JalviewStructureDisplayI> newStructureViewers = null;
4602 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
4604 if (newStructureViewers != null)
4606 sview.getBinding().setFinishedLoadingFromArchive(false);
4607 newStructureViewers.add(sview);
4611 protected void setLoadingFinishedForNewStructureViewers()
4613 if (newStructureViewers != null)
4615 for (JalviewStructureDisplayI sview : newStructureViewers)
4617 sview.getBinding().setFinishedLoadingFromArchive(true);
4619 newStructureViewers.clear();
4620 newStructureViewers = null;
4624 AlignFrame loadViewport(String file, JSeq[] JSEQ,
4625 List<SequenceI> hiddenSeqs, AlignmentI al,
4626 JalviewModelSequence jms, Viewport view, String uniqueSeqSetId,
4627 String viewId, List<JvAnnotRow> autoAlan)
4629 AlignFrame af = null;
4630 af = new AlignFrame(al, view.getWidth(), view.getHeight(),
4631 uniqueSeqSetId, viewId);
4633 af.setFileName(file, FileFormat.Jalview);
4635 for (int i = 0; i < JSEQ.length; i++)
4637 af.viewport.setSequenceColour(
4638 af.viewport.getAlignment().getSequenceAt(i),
4639 new java.awt.Color(JSEQ[i].getColour()));
4644 af.getViewport().setColourByReferenceSeq(true);
4645 af.getViewport().setDisplayReferenceSeq(true);
4648 af.viewport.setGatherViewsHere(view.getGatheredViews());
4650 if (view.getSequenceSetId() != null)
4652 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
4654 af.viewport.setSequenceSetId(uniqueSeqSetId);
4657 // propagate shared settings to this new view
4658 af.viewport.setHistoryList(av.getHistoryList());
4659 af.viewport.setRedoList(av.getRedoList());
4663 viewportsAdded.put(uniqueSeqSetId, af.viewport);
4665 // TODO: check if this method can be called repeatedly without
4666 // side-effects if alignpanel already registered.
4667 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
4669 // apply Hidden regions to view.
4670 if (hiddenSeqs != null)
4672 for (int s = 0; s < JSEQ.length; s++)
4674 SequenceGroup hidden = new SequenceGroup();
4675 boolean isRepresentative = false;
4676 for (int r = 0; r < JSEQ[s].getHiddenSequencesCount(); r++)
4678 isRepresentative = true;
4679 SequenceI sequenceToHide = al
4680 .getSequenceAt(JSEQ[s].getHiddenSequences(r));
4681 hidden.addSequence(sequenceToHide, false);
4682 // remove from hiddenSeqs list so we don't try to hide it twice
4683 hiddenSeqs.remove(sequenceToHide);
4685 if (isRepresentative)
4687 SequenceI representativeSequence = al.getSequenceAt(s);
4688 hidden.addSequence(representativeSequence, false);
4689 af.viewport.hideRepSequences(representativeSequence, hidden);
4693 SequenceI[] hseqs = hiddenSeqs
4694 .toArray(new SequenceI[hiddenSeqs.size()]);
4695 af.viewport.hideSequence(hseqs);
4698 // recover view properties and display parameters
4700 af.viewport.setShowAnnotation(view.getShowAnnotation());
4701 af.viewport.setAbovePIDThreshold(view.getPidSelected());
4702 af.viewport.setThreshold(view.getPidThreshold());
4704 af.viewport.setColourText(view.getShowColourText());
4706 af.viewport.setConservationSelected(view.getConservationSelected());
4707 af.viewport.setIncrement(view.getConsThreshold());
4708 af.viewport.setShowJVSuffix(view.getShowFullId());
4709 af.viewport.setRightAlignIds(view.getRightAlignIds());
4710 af.viewport.setFont(new java.awt.Font(view.getFontName(),
4711 view.getFontStyle(), view.getFontSize()), true);
4712 ViewStyleI vs = af.viewport.getViewStyle();
4713 vs.setScaleProteinAsCdna(view.isScaleProteinAsCdna());
4714 af.viewport.setViewStyle(vs);
4715 // TODO: allow custom charWidth/Heights to be restored by updating them
4716 // after setting font - which means set above to false
4717 af.viewport.setRenderGaps(view.getRenderGaps());
4718 af.viewport.setWrapAlignment(view.getWrapAlignment());
4719 af.viewport.setShowAnnotation(view.getShowAnnotation());
4721 af.viewport.setShowBoxes(view.getShowBoxes());
4723 af.viewport.setShowText(view.getShowText());
4725 af.viewport.setTextColour(new java.awt.Color(view.getTextCol1()));
4726 af.viewport.setTextColour2(new java.awt.Color(view.getTextCol2()));
4727 af.viewport.setThresholdTextColour(view.getTextColThreshold());
4728 af.viewport.setShowUnconserved(
4729 view.hasShowUnconserved() ? view.isShowUnconserved() : false);
4730 af.viewport.getRanges().setStartRes(view.getStartRes());
4732 if (view.getViewName() != null)
4734 af.viewport.viewName = view.getViewName();
4735 af.setInitialTabVisible();
4737 af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(),
4739 // startSeq set in af.alignPanel.updateLayout below
4740 af.alignPanel.updateLayout();
4741 ColourSchemeI cs = null;
4742 // apply colourschemes
4743 if (view.getBgColour() != null)
4745 if (view.getBgColour().startsWith("ucs"))
4747 cs = getUserColourScheme(jms, view.getBgColour());
4749 else if (view.getBgColour().startsWith("Annotation"))
4751 AnnotationColours viewAnnColour = view.getAnnotationColours();
4752 cs = constructAnnotationColour(viewAnnColour, af, al, jms, true);
4759 cs = ColourSchemeProperty.getColourScheme(al, view.getBgColour());
4763 af.viewport.setGlobalColourScheme(cs);
4764 af.viewport.getResidueShading().setThreshold(view.getPidThreshold(),
4765 view.getIgnoreGapsinConsensus());
4766 af.viewport.getResidueShading()
4767 .setConsensus(af.viewport.getSequenceConsensusHash());
4768 af.viewport.setColourAppliesToAllGroups(false);
4770 if (view.getConservationSelected() && cs != null)
4772 af.viewport.getResidueShading()
4773 .setConservationInc(view.getConsThreshold());
4776 af.changeColour(cs);
4778 af.viewport.setColourAppliesToAllGroups(true);
4780 af.viewport.setShowSequenceFeatures(view.getShowSequenceFeatures());
4782 if (view.hasCentreColumnLabels())
4784 af.viewport.setCentreColumnLabels(view.getCentreColumnLabels());
4786 if (view.hasIgnoreGapsinConsensus())
4788 af.viewport.setIgnoreGapsConsensus(view.getIgnoreGapsinConsensus(),
4791 if (view.hasFollowHighlight())
4793 af.viewport.setFollowHighlight(view.getFollowHighlight());
4795 if (view.hasFollowSelection())
4797 af.viewport.followSelection = view.getFollowSelection();
4799 if (view.hasShowConsensusHistogram())
4802 .setShowConsensusHistogram(view.getShowConsensusHistogram());
4806 af.viewport.setShowConsensusHistogram(true);
4808 if (view.hasShowSequenceLogo())
4810 af.viewport.setShowSequenceLogo(view.getShowSequenceLogo());
4814 af.viewport.setShowSequenceLogo(false);
4816 if (view.hasNormaliseSequenceLogo())
4818 af.viewport.setNormaliseSequenceLogo(view.getNormaliseSequenceLogo());
4820 if (view.hasShowDbRefTooltip())
4822 af.viewport.setShowDBRefs(view.getShowDbRefTooltip());
4824 if (view.hasShowNPfeatureTooltip())
4826 af.viewport.setShowNPFeats(view.hasShowNPfeatureTooltip());
4828 if (view.hasShowGroupConsensus())
4830 af.viewport.setShowGroupConsensus(view.getShowGroupConsensus());
4834 af.viewport.setShowGroupConsensus(false);
4836 if (view.hasShowGroupConservation())
4838 af.viewport.setShowGroupConservation(view.getShowGroupConservation());
4842 af.viewport.setShowGroupConservation(false);
4845 // recover feature settings
4846 if (jms.getFeatureSettings() != null)
4848 FeatureRenderer fr = af.alignPanel.getSeqPanel().seqCanvas
4849 .getFeatureRenderer();
4850 FeaturesDisplayed fdi;
4851 af.viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
4852 String[] renderOrder = new String[jms.getFeatureSettings()
4853 .getSettingCount()];
4854 Map<String, FeatureColourI> featureColours = new Hashtable<>();
4855 Map<String, Float> featureOrder = new Hashtable<>();
4857 for (int fs = 0; fs < jms.getFeatureSettings()
4858 .getSettingCount(); fs++)
4860 Setting setting = jms.getFeatureSettings().getSetting(fs);
4861 String featureType = setting.getType();
4864 * restore feature filters (if any)
4866 MatcherSet filters = setting.getMatcherSet();
4867 if (filters != null)
4869 FeatureMatcherSetI filter = Jalview2XML
4870 .unmarshalFilter(featureType, filters);
4871 if (!filter.isEmpty())
4873 fr.setFeatureFilter(featureType, filter);
4878 * restore feature colour scheme
4880 Color maxColour = new Color(setting.getColour());
4881 if (setting.hasMincolour())
4884 * minColour is always set unless a simple colour
4885 * (including for colour by label though it doesn't use it)
4887 Color minColour = new Color(setting.getMincolour());
4888 Color noValueColour = minColour;
4889 NoValueColour noColour = setting.getNoValueColour();
4890 if (noColour == NoValueColour.NONE)
4892 noValueColour = null;
4894 else if (noColour == NoValueColour.MAX)
4896 noValueColour = maxColour;
4898 float min = setting.hasMin() ? setting.getMin() : 0f;
4899 float max = setting.hasMin() ? setting.getMax() : 1f;
4900 FeatureColourI gc = new FeatureColour(minColour, maxColour,
4901 noValueColour, min, max);
4902 if (setting.getAttributeNameCount() > 0)
4904 gc.setAttributeName(setting.getAttributeName());
4906 if (setting.hasThreshold())
4908 gc.setThreshold(setting.getThreshold());
4909 int threshstate = setting.getThreshstate();
4910 // -1 = None, 0 = Below, 1 = Above threshold
4911 if (threshstate == 0)
4913 gc.setBelowThreshold(true);
4915 else if (threshstate == 1)
4917 gc.setAboveThreshold(true);
4920 gc.setAutoScaled(true); // default
4921 if (setting.hasAutoScale())
4923 gc.setAutoScaled(setting.getAutoScale());
4925 if (setting.hasColourByLabel())
4927 gc.setColourByLabel(setting.getColourByLabel());
4929 // and put in the feature colour table.
4930 featureColours.put(featureType, gc);
4934 featureColours.put(featureType,
4935 new FeatureColour(maxColour));
4937 renderOrder[fs] = featureType;
4938 if (setting.hasOrder())
4940 featureOrder.put(featureType, setting.getOrder());
4944 featureOrder.put(featureType, new Float(
4945 fs / jms.getFeatureSettings().getSettingCount()));
4947 if (setting.getDisplay())
4949 fdi.setVisible(featureType);
4952 Map<String, Boolean> fgtable = new Hashtable<>();
4953 for (int gs = 0; gs < jms.getFeatureSettings().getGroupCount(); gs++)
4955 Group grp = jms.getFeatureSettings().getGroup(gs);
4956 fgtable.put(grp.getName(), new Boolean(grp.getDisplay()));
4958 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
4959 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
4960 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
4961 FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
4962 fgtable, featureColours, 1.0f, featureOrder);
4963 fr.transferSettings(frs);
4966 if (view.getHiddenColumnsCount() > 0)
4968 for (int c = 0; c < view.getHiddenColumnsCount(); c++)
4970 af.viewport.hideColumns(view.getHiddenColumns(c).getStart(),
4971 view.getHiddenColumns(c).getEnd() // +1
4975 if (view.getCalcIdParam() != null)
4977 for (CalcIdParam calcIdParam : view.getCalcIdParam())
4979 if (calcIdParam != null)
4981 if (recoverCalcIdParam(calcIdParam, af.viewport))
4986 warn("Couldn't recover parameters for "
4987 + calcIdParam.getCalcId());
4992 af.setMenusFromViewport(af.viewport);
4993 af.setTitle(view.getTitle());
4994 // TODO: we don't need to do this if the viewport is aready visible.
4996 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
4997 * has a 'cdna/protein complement' view, in which case save it in order to
4998 * populate a SplitFrame once all views have been read in.
5000 String complementaryViewId = view.getComplementId();
5001 if (complementaryViewId == null)
5003 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
5005 // recompute any autoannotation
5006 af.alignPanel.updateAnnotation(false, true);
5007 reorderAutoannotation(af, al, autoAlan);
5008 af.alignPanel.alignmentChanged();
5012 splitFrameCandidates.put(view, af);
5018 * Reads saved data to restore Colour by Annotation settings
5020 * @param viewAnnColour
5024 * @param checkGroupAnnColour
5027 private ColourSchemeI constructAnnotationColour(
5028 AnnotationColours viewAnnColour, AlignFrame af, AlignmentI al,
5029 JalviewModelSequence jms, boolean checkGroupAnnColour)
5031 boolean propagateAnnColour = false;
5032 AlignmentI annAlignment = af != null ? af.viewport.getAlignment() : al;
5033 if (checkGroupAnnColour && al.getGroups() != null
5034 && al.getGroups().size() > 0)
5036 // pre 2.8.1 behaviour
5037 // check to see if we should transfer annotation colours
5038 propagateAnnColour = true;
5039 for (SequenceGroup sg : al.getGroups())
5041 if (sg.getColourScheme() instanceof AnnotationColourGradient)
5043 propagateAnnColour = false;
5049 * 2.10.2- : saved annotationId is AlignmentAnnotation.annotationId
5051 String annotationId = viewAnnColour.getAnnotation();
5052 AlignmentAnnotation matchedAnnotation = annotationIds.get(annotationId);
5055 * pre 2.10.2: saved annotationId is AlignmentAnnotation.label
5057 if (matchedAnnotation == null
5058 && annAlignment.getAlignmentAnnotation() != null)
5060 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
5063 .equals(annAlignment.getAlignmentAnnotation()[i].label))
5065 matchedAnnotation = annAlignment.getAlignmentAnnotation()[i];
5070 if (matchedAnnotation == null)
5072 System.err.println("Failed to match annotation colour scheme for "
5076 if (matchedAnnotation.getThreshold() == null)
5078 matchedAnnotation.setThreshold(new GraphLine(
5079 viewAnnColour.getThreshold(), "Threshold", Color.black));
5082 AnnotationColourGradient cs = null;
5083 if (viewAnnColour.getColourScheme().equals("None"))
5085 cs = new AnnotationColourGradient(matchedAnnotation,
5086 new Color(viewAnnColour.getMinColour()),
5087 new Color(viewAnnColour.getMaxColour()),
5088 viewAnnColour.getAboveThreshold());
5090 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
5092 cs = new AnnotationColourGradient(matchedAnnotation,
5093 getUserColourScheme(jms, viewAnnColour.getColourScheme()),
5094 viewAnnColour.getAboveThreshold());
5098 cs = new AnnotationColourGradient(matchedAnnotation,
5099 ColourSchemeProperty.getColourScheme(al,
5100 viewAnnColour.getColourScheme()),
5101 viewAnnColour.getAboveThreshold());
5104 boolean perSequenceOnly = viewAnnColour.isPerSequence();
5105 boolean useOriginalColours = viewAnnColour.isPredefinedColours();
5106 cs.setSeqAssociated(perSequenceOnly);
5107 cs.setPredefinedColours(useOriginalColours);
5109 if (propagateAnnColour && al.getGroups() != null)
5111 // Also use these settings for all the groups
5112 for (int g = 0; g < al.getGroups().size(); g++)
5114 SequenceGroup sg = al.getGroups().get(g);
5115 if (sg.getGroupColourScheme() == null)
5120 AnnotationColourGradient groupScheme = new AnnotationColourGradient(
5121 matchedAnnotation, sg.getColourScheme(),
5122 viewAnnColour.getAboveThreshold());
5123 sg.setColourScheme(groupScheme);
5124 groupScheme.setSeqAssociated(perSequenceOnly);
5125 groupScheme.setPredefinedColours(useOriginalColours);
5131 private void reorderAutoannotation(AlignFrame af, AlignmentI al,
5132 List<JvAnnotRow> autoAlan)
5134 // copy over visualization settings for autocalculated annotation in the
5136 if (al.getAlignmentAnnotation() != null)
5139 * Kludge for magic autoannotation names (see JAL-811)
5141 String[] magicNames = new String[] { "Consensus", "Quality",
5143 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
5144 Hashtable<String, JvAnnotRow> visan = new Hashtable<>();
5145 for (String nm : magicNames)
5147 visan.put(nm, nullAnnot);
5149 for (JvAnnotRow auan : autoAlan)
5151 visan.put(auan.template.label
5152 + (auan.template.getCalcId() == null ? ""
5153 : "\t" + auan.template.getCalcId()),
5156 int hSize = al.getAlignmentAnnotation().length;
5157 List<JvAnnotRow> reorder = new ArrayList<>();
5158 // work through any autoCalculated annotation already on the view
5159 // removing it if it should be placed in a different location on the
5160 // annotation panel.
5161 List<String> remains = new ArrayList<>(visan.keySet());
5162 for (int h = 0; h < hSize; h++)
5164 jalview.datamodel.AlignmentAnnotation jalan = al
5165 .getAlignmentAnnotation()[h];
5166 if (jalan.autoCalculated)
5169 JvAnnotRow valan = visan.get(k = jalan.label);
5170 if (jalan.getCalcId() != null)
5172 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
5177 // delete the auto calculated row from the alignment
5178 al.deleteAnnotation(jalan, false);
5182 if (valan != nullAnnot)
5184 if (jalan != valan.template)
5186 // newly created autoannotation row instance
5187 // so keep a reference to the visible annotation row
5188 // and copy over all relevant attributes
5189 if (valan.template.graphHeight >= 0)
5192 jalan.graphHeight = valan.template.graphHeight;
5194 jalan.visible = valan.template.visible;
5196 reorder.add(new JvAnnotRow(valan.order, jalan));
5201 // Add any (possibly stale) autocalculated rows that were not appended to
5202 // the view during construction
5203 for (String other : remains)
5205 JvAnnotRow othera = visan.get(other);
5206 if (othera != nullAnnot && othera.template.getCalcId() != null
5207 && othera.template.getCalcId().length() > 0)
5209 reorder.add(othera);
5212 // now put the automatic annotation in its correct place
5213 int s = 0, srt[] = new int[reorder.size()];
5214 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
5215 for (JvAnnotRow jvar : reorder)
5218 srt[s++] = jvar.order;
5221 jalview.util.QuickSort.sort(srt, rws);
5222 // and re-insert the annotation at its correct position
5223 for (JvAnnotRow jvar : rws)
5225 al.addAnnotation(jvar.template, jvar.order);
5227 af.alignPanel.adjustAnnotationHeight();
5231 Hashtable skipList = null;
5234 * TODO remove this method
5237 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
5238 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
5239 * throw new Error("Implementation Error. No skipList defined for this
5240 * Jalview2XML instance."); } return (AlignFrame)
5241 * skipList.get(view.getSequenceSetId()); }
5245 * Check if the Jalview view contained in object should be skipped or not.
5248 * @return true if view's sequenceSetId is a key in skipList
5250 private boolean skipViewport(JalviewModel object)
5252 if (skipList == null)
5257 if (skipList.containsKey(
5258 id = object.getJalviewModelSequence().getViewport()[0]
5259 .getSequenceSetId()))
5261 if (Cache.log != null && Cache.log.isDebugEnabled())
5263 Cache.log.debug("Skipping seuqence set id " + id);
5270 public void addToSkipList(AlignFrame af)
5272 if (skipList == null)
5274 skipList = new Hashtable();
5276 skipList.put(af.getViewport().getSequenceSetId(), af);
5279 public void clearSkipList()
5281 if (skipList != null)
5288 private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
5289 boolean ignoreUnrefed)
5291 jalview.datamodel.AlignmentI ds = getDatasetFor(
5292 vamsasSet.getDatasetId());
5293 Vector dseqs = null;
5296 // create a list of new dataset sequences
5297 dseqs = new Vector();
5299 for (int i = 0, iSize = vamsasSet.getSequenceCount(); i < iSize; i++)
5301 Sequence vamsasSeq = vamsasSet.getSequence(i);
5302 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed, i);
5304 // create a new dataset
5307 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
5308 dseqs.copyInto(dsseqs);
5309 ds = new jalview.datamodel.Alignment(dsseqs);
5310 debug("Created new dataset " + vamsasSet.getDatasetId()
5311 + " for alignment " + System.identityHashCode(al));
5312 addDatasetRef(vamsasSet.getDatasetId(), ds);
5314 // set the dataset for the newly imported alignment.
5315 if (al.getDataset() == null && !ignoreUnrefed)
5324 * sequence definition to create/merge dataset sequence for
5328 * vector to add new dataset sequence to
5329 * @param ignoreUnrefed
5330 * - when true, don't create new sequences from vamsasSeq if it's id
5331 * doesn't already have an asssociated Jalview sequence.
5333 * - used to reorder the sequence in the alignment according to the
5334 * vamsasSeq array ordering, to preserve ordering of dataset
5336 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
5337 AlignmentI ds, Vector dseqs, boolean ignoreUnrefed, int vseqpos)
5339 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
5341 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
5342 boolean reorder = false;
5343 SequenceI dsq = null;
5344 if (sq != null && sq.getDatasetSequence() != null)
5346 dsq = sq.getDatasetSequence();
5352 if (sq == null && ignoreUnrefed)
5356 String sqid = vamsasSeq.getDsseqid();
5359 // need to create or add a new dataset sequence reference to this sequence
5362 dsq = seqRefIds.get(sqid);
5367 // make a new dataset sequence
5368 dsq = sq.createDatasetSequence();
5371 // make up a new dataset reference for this sequence
5372 sqid = seqHash(dsq);
5374 dsq.setVamsasId(uniqueSetSuffix + sqid);
5375 seqRefIds.put(sqid, dsq);
5380 dseqs.addElement(dsq);
5385 ds.addSequence(dsq);
5391 { // make this dataset sequence sq's dataset sequence
5392 sq.setDatasetSequence(dsq);
5393 // and update the current dataset alignment
5398 if (!dseqs.contains(dsq))
5405 if (ds.findIndex(dsq) < 0)
5407 ds.addSequence(dsq);
5414 // TODO: refactor this as a merge dataset sequence function
5415 // now check that sq (the dataset sequence) sequence really is the union of
5416 // all references to it
5417 // boolean pre = sq.getStart() < dsq.getStart();
5418 // boolean post = sq.getEnd() > dsq.getEnd();
5422 // StringBuffer sb = new StringBuffer();
5423 String newres = jalview.analysis.AlignSeq.extractGaps(
5424 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
5425 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
5426 && newres.length() > dsq.getLength())
5428 // Update with the longer sequence.
5432 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
5433 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
5434 * sb.append(newres.substring(newres.length() - sq.getEnd() -
5435 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
5437 dsq.setSequence(newres);
5439 // TODO: merges will never happen if we 'know' we have the real dataset
5440 // sequence - this should be detected when id==dssid
5442 "DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
5443 // + (pre ? "prepended" : "") + " "
5444 // + (post ? "appended" : ""));
5449 // sequence refs are identical. We may need to update the existing dataset
5450 // alignment with this one, though.
5451 if (ds != null && dseqs == null)
5453 int opos = ds.findIndex(dsq);
5454 SequenceI tseq = null;
5455 if (opos != -1 && vseqpos != opos)
5457 // remove from old position
5458 ds.deleteSequence(dsq);
5460 if (vseqpos < ds.getHeight())
5462 if (vseqpos != opos)
5464 // save sequence at destination position
5465 tseq = ds.getSequenceAt(vseqpos);
5466 ds.replaceSequenceAt(vseqpos, dsq);
5467 ds.addSequence(tseq);
5472 ds.addSequence(dsq);
5479 * TODO use AlignmentI here and in related methods - needs
5480 * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
5482 Hashtable<String, AlignmentI> datasetIds = null;
5484 IdentityHashMap<AlignmentI, String> dataset2Ids = null;
5486 private AlignmentI getDatasetFor(String datasetId)
5488 if (datasetIds == null)
5490 datasetIds = new Hashtable<>();
5493 if (datasetIds.containsKey(datasetId))
5495 return datasetIds.get(datasetId);
5500 private void addDatasetRef(String datasetId, AlignmentI dataset)
5502 if (datasetIds == null)
5504 datasetIds = new Hashtable<>();
5506 datasetIds.put(datasetId, dataset);
5510 * make a new dataset ID for this jalview dataset alignment
5515 private String getDatasetIdRef(AlignmentI dataset)
5517 if (dataset.getDataset() != null)
5519 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
5521 String datasetId = makeHashCode(dataset, null);
5522 if (datasetId == null)
5524 // make a new datasetId and record it
5525 if (dataset2Ids == null)
5527 dataset2Ids = new IdentityHashMap<>();
5531 datasetId = dataset2Ids.get(dataset);
5533 if (datasetId == null)
5535 datasetId = "ds" + dataset2Ids.size() + 1;
5536 dataset2Ids.put(dataset, datasetId);
5542 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
5544 for (int d = 0; d < sequence.getDBRefCount(); d++)
5546 DBRef dr = sequence.getDBRef(d);
5547 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
5548 sequence.getDBRef(d).getSource(),
5549 sequence.getDBRef(d).getVersion(),
5550 sequence.getDBRef(d).getAccessionId());
5551 if (dr.getMapping() != null)
5553 entry.setMap(addMapping(dr.getMapping()));
5555 datasetSequence.addDBRef(entry);
5559 private jalview.datamodel.Mapping addMapping(Mapping m)
5561 SequenceI dsto = null;
5562 // Mapping m = dr.getMapping();
5563 int fr[] = new int[m.getMapListFromCount() * 2];
5564 Enumeration f = m.enumerateMapListFrom();
5565 for (int _i = 0; f.hasMoreElements(); _i += 2)
5567 MapListFrom mf = (MapListFrom) f.nextElement();
5568 fr[_i] = mf.getStart();
5569 fr[_i + 1] = mf.getEnd();
5571 int fto[] = new int[m.getMapListToCount() * 2];
5572 f = m.enumerateMapListTo();
5573 for (int _i = 0; f.hasMoreElements(); _i += 2)
5575 MapListTo mf = (MapListTo) f.nextElement();
5576 fto[_i] = mf.getStart();
5577 fto[_i + 1] = mf.getEnd();
5579 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto, fr,
5580 fto, (int) m.getMapFromUnit(), (int) m.getMapToUnit());
5581 if (m.getMappingChoice() != null)
5583 MappingChoice mc = m.getMappingChoice();
5584 if (mc.getDseqFor() != null)
5586 String dsfor = "" + mc.getDseqFor();
5587 if (seqRefIds.containsKey(dsfor))
5592 jmap.setTo(seqRefIds.get(dsfor));
5596 frefedSequence.add(newMappingRef(dsfor, jmap));
5602 * local sequence definition
5604 Sequence ms = mc.getSequence();
5605 SequenceI djs = null;
5606 String sqid = ms.getDsseqid();
5607 if (sqid != null && sqid.length() > 0)
5610 * recover dataset sequence
5612 djs = seqRefIds.get(sqid);
5617 "Warning - making up dataset sequence id for DbRef sequence map reference");
5618 sqid = ((Object) ms).toString(); // make up a new hascode for
5619 // undefined dataset sequence hash
5620 // (unlikely to happen)
5626 * make a new dataset sequence and add it to refIds hash
5628 djs = new jalview.datamodel.Sequence(ms.getName(),
5630 djs.setStart(jmap.getMap().getToLowest());
5631 djs.setEnd(jmap.getMap().getToHighest());
5632 djs.setVamsasId(uniqueSetSuffix + sqid);
5634 incompleteSeqs.put(sqid, djs);
5635 seqRefIds.put(sqid, djs);
5638 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
5648 * Provides a 'copy' of an alignment view (on action New View) by 'saving' the
5649 * view as XML (but not to file), and then reloading it
5654 public AlignmentPanel copyAlignPanel(AlignmentPanel ap)
5657 JalviewModel jm = saveState(ap, null, null, null);
5659 uniqueSetSuffix = "";
5660 jm.getJalviewModelSequence().getViewport(0).setId(null);
5661 // we don't overwrite the view we just copied
5663 if (this.frefedSequence == null)
5665 frefedSequence = new Vector<>();
5668 viewportsAdded.clear();
5670 AlignFrame af = loadFromObject(jm, null, false, null);
5671 af.alignPanels.clear();
5672 af.closeMenuItem_actionPerformed(true);
5675 * if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
5676 * i<ap.av.getAlignment().getAlignmentAnnotation().length; i++) {
5677 * if(!ap.av.getAlignment().getAlignmentAnnotation()[i].autoCalculated) {
5678 * af.alignPanel.av.getAlignment().getAlignmentAnnotation()[i] =
5679 * ap.av.getAlignment().getAlignmentAnnotation()[i]; } } }
5682 return af.alignPanel;
5685 private Hashtable jvids2vobj;
5687 private void warn(String msg)
5692 private void warn(String msg, Exception e)
5694 if (Cache.log != null)
5698 Cache.log.warn(msg, e);
5702 Cache.log.warn(msg);
5707 System.err.println("Warning: " + msg);
5710 e.printStackTrace();
5715 private void debug(String string)
5717 debug(string, null);
5720 private void debug(String msg, Exception e)
5722 if (Cache.log != null)
5726 Cache.log.debug(msg, e);
5730 Cache.log.debug(msg);
5735 System.err.println("Warning: " + msg);
5738 e.printStackTrace();
5744 * set the object to ID mapping tables used to write/recover objects and XML
5745 * ID strings for the jalview project. If external tables are provided then
5746 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
5747 * object goes out of scope. - also populates the datasetIds hashtable with
5748 * alignment objects containing dataset sequences
5751 * Map from ID strings to jalview datamodel
5753 * Map from jalview datamodel to ID strings
5757 public void setObjectMappingTables(Hashtable vobj2jv,
5758 IdentityHashMap jv2vobj)
5760 this.jv2vobj = jv2vobj;
5761 this.vobj2jv = vobj2jv;
5762 Iterator ds = jv2vobj.keySet().iterator();
5764 while (ds.hasNext())
5766 Object jvobj = ds.next();
5767 id = jv2vobj.get(jvobj).toString();
5768 if (jvobj instanceof jalview.datamodel.Alignment)
5770 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
5772 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
5775 else if (jvobj instanceof jalview.datamodel.Sequence)
5777 // register sequence object so the XML parser can recover it.
5778 if (seqRefIds == null)
5780 seqRefIds = new HashMap<>();
5782 if (seqsToIds == null)
5784 seqsToIds = new IdentityHashMap<>();
5786 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
5787 seqsToIds.put((SequenceI) jvobj, id);
5789 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
5792 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
5793 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
5794 if (jvann.annotationId == null)
5796 jvann.annotationId = anid;
5798 if (!jvann.annotationId.equals(anid))
5800 // TODO verify that this is the correct behaviour
5801 this.warn("Overriding Annotation ID for " + anid
5802 + " from different id : " + jvann.annotationId);
5803 jvann.annotationId = anid;
5806 else if (jvobj instanceof String)
5808 if (jvids2vobj == null)
5810 jvids2vobj = new Hashtable();
5811 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
5816 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
5822 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
5823 * objects created from the project archive. If string is null (default for
5824 * construction) then suffix will be set automatically.
5828 public void setUniqueSetSuffix(String string)
5830 uniqueSetSuffix = string;
5835 * uses skipList2 as the skipList for skipping views on sequence sets
5836 * associated with keys in the skipList
5840 public void setSkipList(Hashtable skipList2)
5842 skipList = skipList2;
5846 * Reads the jar entry of given name and returns its contents, or null if the
5847 * entry is not found.
5850 * @param jarEntryName
5853 protected String readJarEntry(jarInputStreamProvider jprovider,
5854 String jarEntryName)
5856 String result = null;
5857 BufferedReader in = null;
5862 * Reopen the jar input stream and traverse its entries to find a matching
5865 JarInputStream jin = jprovider.getJarInputStream();
5866 JarEntry entry = null;
5869 entry = jin.getNextJarEntry();
5870 } while (entry != null && !entry.getName().equals(jarEntryName));
5874 StringBuilder out = new StringBuilder(256);
5875 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
5878 while ((data = in.readLine()) != null)
5882 result = out.toString();
5886 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
5888 } catch (Exception ex)
5890 ex.printStackTrace();
5898 } catch (IOException e)
5909 * Returns an incrementing counter (0, 1, 2...)
5913 private synchronized int nextCounter()
5919 * Loads any saved PCA viewers
5924 protected void loadPCAViewers(JalviewModelSequence jms, AlignmentPanel ap)
5928 for (int t = 0; t < jms.getPcaViewerCount(); t++)
5930 PcaViewer viewer = jms.getPcaViewer(t);
5931 String modelName = viewer.getScoreModelName();
5932 SimilarityParamsI params = new SimilarityParams(
5933 viewer.isIncludeGappedColumns(),
5934 viewer.isMatchGaps(), viewer.isIncludeGaps(),
5935 viewer.isDenominateByShortestLength());
5938 * create the panel (without computing the PCA)
5940 PCAPanel panel = new PCAPanel(ap, modelName, params);
5942 panel.setTitle(viewer.getTitle());
5943 panel.setBounds(new Rectangle(viewer.getXpos(), viewer.getYpos(),
5944 viewer.getWidth(), viewer.getHeight()));
5946 boolean showLabels = viewer.isShowLabels();
5947 panel.setShowLabels(showLabels);
5948 panel.rc.showLabels = showLabels;
5949 panel.rc.bgColour = new Color(viewer.getBgColour());
5950 panel.rc.applyToAllViews = viewer.isLinkToAllViews();
5953 * load PCA output data
5955 ScoreModelI scoreModel = ScoreModels.getInstance()
5956 .getScoreModel(modelName, ap);
5957 PCA pca = new PCA(null, scoreModel, params);
5958 PcaData pcaData = viewer.getPcaData();
5960 MatrixI pairwise = loadDoubleMatrix(pcaData.getPairwiseMatrix());
5961 pca.setPairwiseScores(pairwise);
5963 MatrixI triDiag = loadDoubleMatrix(pcaData.getTridiagonalMatrix());
5964 pca.setTridiagonal(triDiag);
5966 MatrixI result = loadDoubleMatrix(pcaData.getEigenMatrix());
5967 pca.setEigenmatrix(result);
5969 panel.pcaModel.setPCA(pca);
5972 * we haven't saved the input data! (JAL-2647 to do)
5974 panel.setInputData(null);
5977 * add the sequence points for the PCA display
5979 List<jalview.datamodel.SequencePoint> seqPoints = new ArrayList<>();
5980 for (SequencePoint sp : viewer.getSequencePoint())
5982 String seqId = sp.getSequenceRef();
5983 SequenceI seq = seqRefIds.get(seqId);
5986 throw new IllegalStateException(
5987 "Unmatched seqref for PCA: " + seqId);
5989 Point pt = new Point(sp.getXPos(), sp.getYPos(), sp.getZPos());
5990 jalview.datamodel.SequencePoint seqPoint = new jalview.datamodel.SequencePoint(
5992 seqPoints.add(seqPoint);
5994 panel.rc.setPoints(seqPoints, seqPoints.size());
5997 * set min-max ranges and scale after setPoints (which recomputes them)
5999 panel.rc.scaleFactor = viewer.getScaleFactor();
6000 SeqPointMin spMin = viewer.getSeqPointMin();
6001 float[] min = new float[] { spMin.getXPos(), spMin.getYPos(),
6003 SeqPointMax spMax = viewer.getSeqPointMax();
6004 float[] max = new float[] { spMax.getXPos(), spMax.getYPos(),
6006 panel.rc.setSeqMinMax(min, max);
6008 // todo: hold points list in PCAModel only
6009 panel.pcaModel.setSequencePoints(seqPoints);
6011 panel.setSelectedDimensionIndex(viewer.getXDim(), X);
6012 panel.setSelectedDimensionIndex(viewer.getYDim(), Y);
6013 panel.setSelectedDimensionIndex(viewer.getZDim(), Z);
6015 // is this duplication needed?
6016 panel.top = seqPoints.size() - 1;
6017 panel.pcaModel.setTop(seqPoints.size() - 1);
6020 * add the axes' end points for the display
6022 for (int i = 0; i < 3; i++)
6024 Axis axis = viewer.getAxis(i);
6025 panel.rc.axisEndPoints[i] = new Point(axis.getXPos(),
6026 axis.getYPos(), axis.getZPos());
6029 Desktop.addInternalFrame(panel, MessageManager.formatMessage(
6030 "label.calc_title", "PCA", modelName), 475, 450);
6032 } catch (Exception ex)
6034 Cache.log.error("Error loading PCA: " + ex.toString());
6039 * Populates an XML model of the feature colour scheme for one feature type
6041 * @param featureType
6045 protected static jalview.schemabinding.version2.Colour marshalColour(
6046 String featureType, FeatureColourI fcol)
6048 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
6049 if (fcol.isSimpleColour())
6051 col.setRGB(Format.getHexString(fcol.getColour()));
6055 col.setRGB(Format.getHexString(fcol.getMaxColour()));
6056 col.setMin(fcol.getMin());
6057 col.setMax(fcol.getMax());
6058 col.setMinRGB(jalview.util.Format.getHexString(fcol.getMinColour()));
6059 col.setAutoScale(fcol.isAutoScaled());
6060 col.setThreshold(fcol.getThreshold());
6061 col.setColourByLabel(fcol.isColourByLabel());
6062 col.setThreshType(fcol.isAboveThreshold() ? ColourThreshTypeType.ABOVE
6063 : (fcol.isBelowThreshold() ? ColourThreshTypeType.BELOW
6064 : ColourThreshTypeType.NONE));
6065 if (fcol.isColourByAttribute())
6067 col.setAttributeName(fcol.getAttributeName());
6069 Color noColour = fcol.getNoColour();
6070 if (noColour == null)
6072 col.setNoValueColour(NoValueColour.NONE);
6074 else if (noColour == fcol.getMaxColour())
6076 col.setNoValueColour(NoValueColour.MAX);
6080 col.setNoValueColour(NoValueColour.MIN);
6083 col.setName(featureType);
6088 * Populates an XML model of the feature filter(s) for one feature type
6090 * @param firstMatcher
6091 * the first (or only) match condition)
6093 * remaining match conditions (if any)
6095 * if true, conditions are and-ed, else or-ed
6097 protected static MatcherSet marshalFilter(FeatureMatcherI firstMatcher,
6098 Iterator<FeatureMatcherI> filters, boolean and)
6100 MatcherSet result = new MatcherSet();
6102 if (filters.hasNext())
6107 CompoundMatcher compound = new CompoundMatcher();
6108 compound.setAnd(and);
6109 MatcherSet matcher1 = marshalFilter(firstMatcher,
6110 Collections.emptyIterator(), and);
6111 compound.addMatcherSet(matcher1);
6112 FeatureMatcherI nextMatcher = filters.next();
6113 MatcherSet matcher2 = marshalFilter(nextMatcher, filters, and);
6114 compound.addMatcherSet(matcher2);
6115 result.setCompoundMatcher(compound);
6120 * single condition matcher
6122 MatchCondition matcherModel = new MatchCondition();
6123 matcherModel.setCondition(
6124 firstMatcher.getMatcher().getCondition().getStableName());
6125 matcherModel.setValue(firstMatcher.getMatcher().getPattern());
6126 if (firstMatcher.isByAttribute())
6128 matcherModel.setBy(FeatureMatcherByType.BYATTRIBUTE);
6129 matcherModel.setAttributeName(firstMatcher.getAttribute());
6131 else if (firstMatcher.isByLabel())
6133 matcherModel.setBy(FeatureMatcherByType.BYLABEL);
6135 else if (firstMatcher.isByScore())
6137 matcherModel.setBy(FeatureMatcherByType.BYSCORE);
6139 result.setMatchCondition(matcherModel);
6146 * Loads one XML model of a feature filter to a Jalview object
6148 * @param featureType
6149 * @param matcherSetModel
6152 protected static FeatureMatcherSetI unmarshalFilter(
6153 String featureType, MatcherSet matcherSetModel)
6155 FeatureMatcherSetI result = new FeatureMatcherSet();
6158 unmarshalFilterConditions(result, matcherSetModel, true);
6159 } catch (IllegalStateException e)
6161 // mixing AND and OR conditions perhaps
6163 String.format("Error reading filter conditions for '%s': %s",
6164 featureType, e.getMessage()));
6165 // return as much as was parsed up to the error
6172 * Adds feature match conditions to matcherSet as unmarshalled from XML
6173 * (possibly recursively for compound conditions)
6176 * @param matcherSetModel
6178 * if true, multiple conditions are AND-ed, else they are OR-ed
6179 * @throws IllegalStateException
6180 * if AND and OR conditions are mixed
6182 protected static void unmarshalFilterConditions(
6183 FeatureMatcherSetI matcherSet, MatcherSet matcherSetModel,
6186 MatchCondition mc = matcherSetModel.getMatchCondition();
6192 FeatureMatcherByType filterBy = mc.getBy();
6193 Condition cond = Condition.fromString(mc.getCondition());
6194 String pattern = mc.getValue();
6195 FeatureMatcherI matchCondition = null;
6196 if (filterBy == FeatureMatcherByType.BYLABEL)
6198 matchCondition = FeatureMatcher.byLabel(cond, pattern);
6200 else if (filterBy == FeatureMatcherByType.BYSCORE)
6202 matchCondition = FeatureMatcher.byScore(cond, pattern);
6205 else if (filterBy == FeatureMatcherByType.BYATTRIBUTE)
6207 String[] attNames = mc.getAttributeName();
6208 matchCondition = FeatureMatcher.byAttribute(cond, pattern,
6213 * note this throws IllegalStateException if AND-ing to a
6214 * previously OR-ed compound condition, or vice versa
6218 matcherSet.and(matchCondition);
6222 matcherSet.or(matchCondition);
6228 * compound condition
6230 MatcherSet[] matchers = matcherSetModel.getCompoundMatcher()
6232 boolean anded = matcherSetModel.getCompoundMatcher().getAnd();
6233 if (matchers.length == 2)
6235 unmarshalFilterConditions(matcherSet, matchers[0], anded);
6236 unmarshalFilterConditions(matcherSet, matchers[1], anded);
6240 System.err.println("Malformed compound filter condition");
6246 * Loads one XML model of a feature colour to a Jalview object
6248 * @param colourModel
6251 protected static FeatureColourI unmarshalColour(
6252 jalview.schemabinding.version2.Colour colourModel)
6254 FeatureColourI colour = null;
6256 if (colourModel.hasMax())
6258 Color mincol = null;
6259 Color maxcol = null;
6260 Color noValueColour = null;
6264 mincol = new Color(Integer.parseInt(colourModel.getMinRGB(), 16));
6265 maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6266 } catch (Exception e)
6268 Cache.log.warn("Couldn't parse out graduated feature color.", e);
6271 NoValueColour noCol = colourModel.getNoValueColour();
6272 if (noCol == NoValueColour.MIN)
6274 noValueColour = mincol;
6276 else if (noCol == NoValueColour.MAX)
6278 noValueColour = maxcol;
6281 colour = new FeatureColour(mincol, maxcol, noValueColour,
6282 colourModel.getMin(),
6283 colourModel.getMax());
6284 String[] attributes = colourModel.getAttributeName();
6285 if (attributes != null && attributes.length > 0)
6287 colour.setAttributeName(attributes);
6289 if (colourModel.hasAutoScale())
6291 colour.setAutoScaled(colourModel.getAutoScale());
6293 if (colourModel.hasColourByLabel())
6295 colour.setColourByLabel(colourModel.getColourByLabel());
6297 if (colourModel.hasThreshold())
6299 colour.setThreshold(colourModel.getThreshold());
6301 ColourThreshTypeType ttyp = colourModel.getThreshType();
6304 if (ttyp == ColourThreshTypeType.ABOVE)
6306 colour.setAboveThreshold(true);
6308 else if (ttyp == ColourThreshTypeType.BELOW)
6310 colour.setBelowThreshold(true);
6316 Color color = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6317 colour = new FeatureColour(color);