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.
21 package jalview.project;
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.AlignmentViewPanel;
32 import jalview.api.FeatureColourI;
33 import jalview.api.ViewStyleI;
34 import jalview.api.analysis.ScoreModelI;
35 import jalview.api.analysis.SimilarityParamsI;
36 import jalview.api.structures.JalviewStructureDisplayI;
37 import jalview.bin.Cache;
38 import jalview.datamodel.AlignedCodonFrame;
39 import jalview.datamodel.Alignment;
40 import jalview.datamodel.AlignmentAnnotation;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.DBRefEntry;
43 import jalview.datamodel.GraphLine;
44 import jalview.datamodel.PDBEntry;
45 import jalview.datamodel.Point;
46 import jalview.datamodel.RnaViewerModel;
47 import jalview.datamodel.SequenceFeature;
48 import jalview.datamodel.SequenceGroup;
49 import jalview.datamodel.SequenceI;
50 import jalview.datamodel.StructureViewerModel;
51 import jalview.datamodel.StructureViewerModel.StructureData;
52 import jalview.datamodel.features.FeatureMatcher;
53 import jalview.datamodel.features.FeatureMatcherI;
54 import jalview.datamodel.features.FeatureMatcherSet;
55 import jalview.datamodel.features.FeatureMatcherSetI;
56 import jalview.ext.varna.RnaModel;
57 import jalview.gui.AlignFrame;
58 import jalview.gui.AlignViewport;
59 import jalview.gui.AlignmentPanel;
60 import jalview.gui.AppVarna;
61 import jalview.gui.ChimeraViewFrame;
62 import jalview.gui.Desktop;
63 import jalview.gui.FeatureRenderer;
64 import jalview.gui.JvOptionPane;
65 import jalview.gui.OOMWarning;
66 import jalview.gui.PCAPanel;
67 import jalview.gui.PaintRefresher;
68 import jalview.gui.SplitFrame;
69 import jalview.gui.StructureViewer;
70 import jalview.gui.StructureViewer.ViewerType;
71 import jalview.gui.StructureViewerBase;
72 import jalview.gui.TreePanel;
73 import jalview.io.BackupFiles;
74 import jalview.io.DataSourceType;
75 import jalview.io.FileFormat;
76 import jalview.io.NewickFile;
77 import jalview.math.Matrix;
78 import jalview.math.MatrixI;
79 import jalview.renderer.ResidueShaderI;
80 import jalview.schemes.AnnotationColourGradient;
81 import jalview.schemes.ColourSchemeI;
82 import jalview.schemes.ColourSchemeProperty;
83 import jalview.schemes.FeatureColour;
84 import jalview.schemes.ResidueProperties;
85 import jalview.schemes.UserColourScheme;
86 import jalview.structures.models.AAStructureBindingModel;
87 import jalview.util.Format;
88 import jalview.util.MessageManager;
89 import jalview.util.Platform;
90 import jalview.util.StringUtils;
91 import jalview.util.jarInputStreamProvider;
92 import jalview.util.matcher.Condition;
93 import jalview.viewmodel.AlignmentViewport;
94 import jalview.viewmodel.PCAModel;
95 import jalview.viewmodel.ViewportRanges;
96 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
97 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
98 import jalview.ws.jws2.Jws2Discoverer;
99 import jalview.ws.jws2.dm.AAConSettings;
100 import jalview.ws.jws2.jabaws2.Jws2Instance;
101 import jalview.ws.params.ArgumentI;
102 import jalview.ws.params.AutoCalcSetting;
103 import jalview.ws.params.WsParamSetI;
104 import jalview.xml.binding.jalview.AlcodonFrame;
105 import jalview.xml.binding.jalview.AlcodonFrame.AlcodMap;
106 import jalview.xml.binding.jalview.Annotation;
107 import jalview.xml.binding.jalview.Annotation.ThresholdLine;
108 import jalview.xml.binding.jalview.AnnotationColourScheme;
109 import jalview.xml.binding.jalview.AnnotationElement;
110 import jalview.xml.binding.jalview.DoubleMatrix;
111 import jalview.xml.binding.jalview.DoubleVector;
112 import jalview.xml.binding.jalview.Feature;
113 import jalview.xml.binding.jalview.Feature.OtherData;
114 import jalview.xml.binding.jalview.FeatureMatcherSet.CompoundMatcher;
115 import jalview.xml.binding.jalview.FilterBy;
116 import jalview.xml.binding.jalview.JalviewModel;
117 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings;
118 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Group;
119 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Setting;
120 import jalview.xml.binding.jalview.JalviewModel.JGroup;
121 import jalview.xml.binding.jalview.JalviewModel.JSeq;
122 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids;
123 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids.StructureState;
124 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer;
125 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer.SecondaryStructure;
126 import jalview.xml.binding.jalview.JalviewModel.PcaViewer;
127 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.Axis;
128 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SeqPointMax;
129 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SeqPointMin;
130 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SequencePoint;
131 import jalview.xml.binding.jalview.JalviewModel.Tree;
132 import jalview.xml.binding.jalview.JalviewModel.UserColours;
133 import jalview.xml.binding.jalview.JalviewModel.Viewport;
134 import jalview.xml.binding.jalview.JalviewModel.Viewport.CalcIdParam;
135 import jalview.xml.binding.jalview.JalviewModel.Viewport.HiddenColumns;
136 import jalview.xml.binding.jalview.JalviewUserColours;
137 import jalview.xml.binding.jalview.JalviewUserColours.Colour;
138 import jalview.xml.binding.jalview.MapListType.MapListFrom;
139 import jalview.xml.binding.jalview.MapListType.MapListTo;
140 import jalview.xml.binding.jalview.Mapping;
141 import jalview.xml.binding.jalview.NoValueColour;
142 import jalview.xml.binding.jalview.ObjectFactory;
143 import jalview.xml.binding.jalview.PcaDataType;
144 import jalview.xml.binding.jalview.Pdbentry.Property;
145 import jalview.xml.binding.jalview.Sequence;
146 import jalview.xml.binding.jalview.Sequence.DBRef;
147 import jalview.xml.binding.jalview.SequenceSet;
148 import jalview.xml.binding.jalview.SequenceSet.SequenceSetProperties;
149 import jalview.xml.binding.jalview.ThresholdType;
150 import jalview.xml.binding.jalview.VAMSAS;
152 import java.awt.Color;
153 import java.awt.Dimension;
154 import java.awt.Font;
155 import java.awt.Rectangle;
156 import java.io.BufferedReader;
157 import java.io.ByteArrayInputStream;
158 import java.io.DataInputStream;
159 import java.io.DataOutputStream;
161 import java.io.FileInputStream;
162 import java.io.FileOutputStream;
163 import java.io.IOException;
164 import java.io.InputStreamReader;
165 import java.io.OutputStreamWriter;
166 import java.io.PrintWriter;
167 import java.math.BigInteger;
168 import java.net.MalformedURLException;
170 import java.util.ArrayList;
171 import java.util.Arrays;
172 import java.util.Collections;
173 import java.util.Enumeration;
174 import java.util.GregorianCalendar;
175 import java.util.HashMap;
176 import java.util.HashSet;
177 import java.util.Hashtable;
178 import java.util.IdentityHashMap;
179 import java.util.Iterator;
180 import java.util.LinkedHashMap;
181 import java.util.List;
182 import java.util.Map;
183 import java.util.Map.Entry;
184 import java.util.Set;
185 import java.util.Vector;
186 import java.util.jar.JarEntry;
187 import java.util.jar.JarInputStream;
188 import java.util.jar.JarOutputStream;
190 import javax.swing.JInternalFrame;
191 import javax.swing.SwingUtilities;
192 import javax.xml.bind.JAXBContext;
193 import javax.xml.bind.JAXBElement;
194 import javax.xml.bind.Marshaller;
195 import javax.xml.datatype.DatatypeConfigurationException;
196 import javax.xml.datatype.DatatypeFactory;
197 import javax.xml.datatype.XMLGregorianCalendar;
198 import javax.xml.stream.XMLInputFactory;
199 import javax.xml.stream.XMLStreamReader;
202 * Write out the current jalview desktop state as a Jalview XML stream.
204 * Note: the vamsas objects referred to here are primitive versions of the
205 * VAMSAS project schema elements - they are not the same and most likely never
209 * @version $Revision: 1.134 $
211 public class Jalview2XML
214 // BH 2018 we add the .jvp binary extension to J2S so that
215 // it will declare that binary when we do the file save from the browser
219 Platform.addJ2SBinaryType(".jvp?");
222 private static final String VIEWER_PREFIX = "viewer_";
224 private static final String RNA_PREFIX = "rna_";
226 private static final String UTF_8 = "UTF-8";
229 * prefix for recovering datasets for alignments with multiple views where
230 * non-existent dataset IDs were written for some views
232 private static final String UNIQSEQSETID = "uniqueSeqSetId.";
234 // use this with nextCounter() to make unique names for entities
235 private int counter = 0;
238 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
239 * of sequence objects are created.
241 IdentityHashMap<SequenceI, String> seqsToIds = null;
244 * jalview XML Sequence ID to jalview sequence object reference (both dataset
245 * and alignment sequences. Populated as XML reps of sequence objects are
248 Map<String, SequenceI> seqRefIds = null;
250 Map<String, SequenceI> incompleteSeqs = null;
252 List<SeqFref> frefedSequence = null;
254 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
257 * Map of reconstructed AlignFrame objects that appear to have come from
258 * SplitFrame objects (have a dna/protein complement view).
260 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
263 * Map from displayed rna structure models to their saved session state jar
266 private Map<RnaModel, String> rnaSessions = new HashMap<>();
269 * A helper method for safely using the value of an optional attribute that
270 * may be null if not present in the XML. Answers the boolean value, or false
276 public static boolean safeBoolean(Boolean b)
278 return b == null ? false : b.booleanValue();
282 * A helper method for safely using the value of an optional attribute that
283 * may be null if not present in the XML. Answers the integer value, or zero
289 public static int safeInt(Integer i)
291 return i == null ? 0 : i.intValue();
295 * A helper method for safely using the value of an optional attribute that
296 * may be null if not present in the XML. Answers the float value, or zero if
302 public static float safeFloat(Float f)
304 return f == null ? 0f : f.floatValue();
308 * create/return unique hash string for sq
311 * @return new or existing unique string for sq
313 String seqHash(SequenceI sq)
315 if (seqsToIds == null)
319 if (seqsToIds.containsKey(sq))
321 return seqsToIds.get(sq);
325 // create sequential key
326 String key = "sq" + (seqsToIds.size() + 1);
327 key = makeHashCode(sq, key); // check we don't have an external reference
329 seqsToIds.put(sq, key);
336 if (seqsToIds == null)
338 seqsToIds = new IdentityHashMap<>();
340 if (seqRefIds == null)
342 seqRefIds = new HashMap<>();
344 if (incompleteSeqs == null)
346 incompleteSeqs = new HashMap<>();
348 if (frefedSequence == null)
350 frefedSequence = new ArrayList<>();
358 public Jalview2XML(boolean raiseGUI)
360 this.raiseGUI = raiseGUI;
364 * base class for resolving forward references to sequences by their ID
369 abstract class SeqFref
375 public SeqFref(String _sref, String type)
381 public String getSref()
386 public SequenceI getSrefSeq()
388 return seqRefIds.get(sref);
391 public boolean isResolvable()
393 return seqRefIds.get(sref) != null;
396 public SequenceI getSrefDatasetSeq()
398 SequenceI sq = seqRefIds.get(sref);
401 while (sq.getDatasetSequence() != null)
403 sq = sq.getDatasetSequence();
410 * @return true if the forward reference was fully resolved
412 abstract boolean resolve();
415 public String toString()
417 return type + " reference to " + sref;
422 * create forward reference for a mapping
428 public SeqFref newMappingRef(final String sref,
429 final jalview.datamodel.Mapping _jmap)
431 SeqFref fref = new SeqFref(sref, "Mapping")
433 public jalview.datamodel.Mapping jmap = _jmap;
438 SequenceI seq = getSrefDatasetSeq();
450 public SeqFref newAlcodMapRef(final String sref,
451 final AlignedCodonFrame _cf,
452 final jalview.datamodel.Mapping _jmap)
455 SeqFref fref = new SeqFref(sref, "Codon Frame")
457 AlignedCodonFrame cf = _cf;
459 public jalview.datamodel.Mapping mp = _jmap;
462 public boolean isResolvable()
464 return super.isResolvable() && mp.getTo() != null;
470 SequenceI seq = getSrefDatasetSeq();
475 cf.addMap(seq, mp.getTo(), mp.getMap());
482 public void resolveFrefedSequences()
484 Iterator<SeqFref> nextFref = frefedSequence.iterator();
485 int toresolve = frefedSequence.size();
486 int unresolved = 0, failedtoresolve = 0;
487 while (nextFref.hasNext())
489 SeqFref ref = nextFref.next();
490 if (ref.isResolvable())
502 } catch (Exception x)
505 "IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
518 System.err.println("Jalview Project Import: There were " + unresolved
519 + " forward references left unresolved on the stack.");
521 if (failedtoresolve > 0)
523 System.err.println("SERIOUS! " + failedtoresolve
524 + " resolvable forward references failed to resolve.");
526 if (incompleteSeqs != null && incompleteSeqs.size() > 0)
529 "Jalview Project Import: There are " + incompleteSeqs.size()
530 + " sequences which may have incomplete metadata.");
531 if (incompleteSeqs.size() < 10)
533 for (SequenceI s : incompleteSeqs.values())
535 System.err.println(s.toString());
541 "Too many to report. Skipping output of incomplete sequences.");
547 * This maintains a map of viewports, the key being the seqSetId. Important to
548 * set historyItem and redoList for multiple views
550 Map<String, AlignViewport> viewportsAdded = new HashMap<>();
552 Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
554 String uniqueSetSuffix = "";
557 * List of pdbfiles added to Jar
559 List<String> pdbfiles = null;
561 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
562 public void saveState(File statefile)
564 FileOutputStream fos = null;
569 fos = new FileOutputStream(statefile);
571 JarOutputStream jout = new JarOutputStream(fos);
575 } catch (Exception e)
577 Cache.log.error("Couln't write Jalview state to " + statefile, e);
578 // TODO: inform user of the problem - they need to know if their data was
580 if (errorMessage == null)
582 errorMessage = "Did't write Jalview Archive to output file '"
583 + statefile + "' - See console error log for details";
587 errorMessage += "(Didn't write Jalview Archive to output file '"
598 } catch (IOException e)
608 * Writes a jalview project archive to the given Jar output stream.
612 public void saveState(JarOutputStream jout)
614 AlignFrame[] frames = Desktop.getAlignFrames();
620 saveAllFrames(Arrays.asList(frames), jout);
624 * core method for storing state for a set of AlignFrames.
627 * - frames involving all data to be exported (including those
628 * contained in splitframes, though not the split frames themselves)
630 * - project output stream
632 private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
635 Hashtable<String, AlignFrame> dsses = new Hashtable<>();
638 * ensure cached data is clear before starting
640 // todo tidy up seqRefIds, seqsToIds initialisation / reset
642 splitFrameCandidates.clear();
647 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
648 // //////////////////////////////////////////////////
650 List<String> shortNames = new ArrayList<>();
651 List<String> viewIds = new ArrayList<>();
654 for (int i = frames.size() - 1; i > -1; i--)
656 AlignFrame af = frames.get(i);
657 AlignViewport vp = af.getViewport();
659 if (skipList != null && skipList
660 .containsKey(vp.getSequenceSetId()))
665 String shortName = makeFilename(af, shortNames);
667 AlignmentI alignment = vp.getAlignment();
668 List<? extends AlignmentViewPanel> panels = af.getAlignPanels();
669 int apSize = panels.size();
670 for (int ap = 0; ap < apSize; ap++)
672 AlignmentPanel apanel = (AlignmentPanel) panels.get(ap);
673 String fileName = apSize == 1 ? shortName : ap + shortName;
674 if (!fileName.endsWith(".xml"))
676 fileName = fileName + ".xml";
679 saveState(apanel, fileName, jout, viewIds);
683 // BH moved next bit out of inner loop, not that it really matters.
684 // so we are testing to make sure we actually have an alignment,
686 String dssid = getDatasetIdRef(alignment.getDataset());
687 if (!dsses.containsKey(dssid))
689 // We have not already covered this data by reference from another
691 dsses.put(dssid, af);
696 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
702 } catch (Exception foo)
706 } catch (Exception ex)
708 // TODO: inform user of the problem - they need to know if their data was
710 if (errorMessage == null)
712 errorMessage = "Couldn't write Jalview Archive - see error output for details";
714 ex.printStackTrace();
719 * Generates a distinct file name, based on the title of the AlignFrame, by
720 * appending _n for increasing n until an unused name is generated. The new
721 * name (without its extension) is added to the list.
725 * @return the generated name, with .xml extension
727 protected String makeFilename(AlignFrame af, List<String> namesUsed)
729 String shortName = af.getTitle();
731 if (shortName.indexOf(File.separatorChar) > -1)
733 shortName = shortName
734 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
739 while (namesUsed.contains(shortName))
741 if (shortName.endsWith("_" + (count - 1)))
743 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
746 shortName = shortName.concat("_" + count);
750 namesUsed.add(shortName);
752 if (!shortName.endsWith(".xml"))
754 shortName = shortName + ".xml";
759 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
760 public boolean saveAlignment(AlignFrame af, String jarFile,
765 // create backupfiles object and get new temp filename destination
766 boolean doBackup = BackupFiles.getEnabled();
767 BackupFiles backupfiles = doBackup ? new BackupFiles(jarFile) : null;
768 FileOutputStream fos = new FileOutputStream(doBackup ?
769 backupfiles.getTempFilePath() : jarFile);
771 JarOutputStream jout = new JarOutputStream(fos);
772 List<AlignFrame> frames = new ArrayList<>();
774 // resolve splitframes
775 if (af.getViewport().getCodingComplement() != null)
777 frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
783 saveAllFrames(frames, jout);
787 } catch (Exception foo)
791 boolean success = true;
795 backupfiles.setWriteSuccess(success);
796 success = backupfiles.rollBackupsAndRenameTempFile();
800 } catch (Exception ex)
802 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
803 ex.printStackTrace();
809 * Each AlignFrame has a single data set associated with it. Note that none of
810 * these frames are split frames, because Desktop.getAlignFrames() collects
811 * top and bottom separately here.
817 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
818 String fileName, JarOutputStream jout)
821 // Note that in saveAllFrames we have associated each specific dataset to
822 // ONE of its associated frames.
824 for (String dssids : dsses.keySet())
826 AlignFrame _af = dsses.get(dssids);
827 String jfileName = fileName + " Dataset for " + _af.getTitle();
828 if (!jfileName.endsWith(".xml"))
830 jfileName = jfileName + ".xml";
832 saveState(_af.alignPanel, jfileName, true, jout, null);
837 * create a JalviewModel from an alignment view and marshall it to a
841 * panel to create jalview model for
843 * name of alignment panel written to output stream
850 public JalviewModel saveState(AlignmentPanel ap, String fileName,
851 JarOutputStream jout, List<String> viewIds)
853 return saveState(ap, fileName, false, jout, viewIds);
857 * create a JalviewModel from an alignment view and marshall it to a
861 * panel to create jalview model for
863 * name of alignment panel written to output stream
865 * when true, only write the dataset for the alignment, not the data
866 * associated with the view.
872 public JalviewModel saveState(AlignmentPanel ap, String fileName,
873 boolean storeDS, JarOutputStream jout, List<String> viewIds)
877 viewIds = new ArrayList<>();
882 List<UserColourScheme> userColours = new ArrayList<>();
884 AlignViewport av = ap.av;
885 ViewportRanges vpRanges = av.getRanges();
887 final ObjectFactory objectFactory = new ObjectFactory();
888 JalviewModel object = objectFactory.createJalviewModel();
889 object.setVamsasModel(new VAMSAS());
891 // object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
894 GregorianCalendar c = new GregorianCalendar();
895 DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
896 XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(c);// gregorianCalendar);
897 object.setCreationDate(now);
898 } catch (DatatypeConfigurationException e)
900 System.err.println("error writing date: " + e.toString());
903 jalview.bin.Cache.getDefault("VERSION", "Development Build"));
906 * rjal is full height alignment, jal is actual alignment with full metadata
907 * but excludes hidden sequences.
909 jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
911 if (av.hasHiddenRows())
913 rjal = jal.getHiddenSequences().getFullAlignment();
916 SequenceSet vamsasSet = new SequenceSet();
918 // JalviewModelSequence jms = new JalviewModelSequence();
920 vamsasSet.setGapChar(jal.getGapCharacter() + "");
922 if (jal.getDataset() != null)
924 // dataset id is the dataset's hashcode
925 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
928 // switch jal and the dataset
929 jal = jal.getDataset();
933 if (jal.getProperties() != null)
935 Enumeration en = jal.getProperties().keys();
936 while (en.hasMoreElements())
938 String key = en.nextElement().toString();
939 SequenceSetProperties ssp = new SequenceSetProperties();
941 ssp.setValue(jal.getProperties().get(key).toString());
942 // vamsasSet.addSequenceSetProperties(ssp);
943 vamsasSet.getSequenceSetProperties().add(ssp);
948 Set<String> calcIdSet = new HashSet<>();
949 // record the set of vamsas sequence XML POJO we create.
950 HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
952 for (final SequenceI jds : rjal.getSequences())
954 final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
955 : jds.getDatasetSequence();
956 String id = seqHash(jds);
957 if (vamsasSetIds.get(id) == null)
959 if (seqRefIds.get(id) != null && !storeDS)
961 // This happens for two reasons: 1. multiple views are being
963 // 2. the hashCode has collided with another sequence's code. This
965 // HAPPEN! (PF00072.15.stk does this)
966 // JBPNote: Uncomment to debug writing out of files that do not read
967 // back in due to ArrayOutOfBoundExceptions.
968 // System.err.println("vamsasSeq backref: "+id+"");
969 // System.err.println(jds.getName()+"
970 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
971 // System.err.println("Hashcode: "+seqHash(jds));
972 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
973 // System.err.println(rsq.getName()+"
974 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
975 // System.err.println("Hashcode: "+seqHash(rsq));
979 vamsasSeq = createVamsasSequence(id, jds);
980 // vamsasSet.addSequence(vamsasSeq);
981 vamsasSet.getSequence().add(vamsasSeq);
982 vamsasSetIds.put(id, vamsasSeq);
983 seqRefIds.put(id, jds);
987 jseq.setStart(jds.getStart());
988 jseq.setEnd(jds.getEnd());
989 jseq.setColour(av.getSequenceColour(jds).getRGB());
991 jseq.setId(id); // jseq id should be a string not a number
994 // Store any sequences this sequence represents
995 if (av.hasHiddenRows())
997 // use rjal, contains the full height alignment
999 av.getAlignment().getHiddenSequences().isHidden(jds));
1001 if (av.isHiddenRepSequence(jds))
1003 jalview.datamodel.SequenceI[] reps = av
1004 .getRepresentedSequences(jds).getSequencesInOrder(rjal);
1006 for (int h = 0; h < reps.length; h++)
1010 // jseq.addHiddenSequences(rjal.findIndex(reps[h]));
1011 jseq.getHiddenSequences().add(rjal.findIndex(reps[h]));
1016 // mark sequence as reference - if it is the reference for this view
1017 if (jal.hasSeqrep())
1019 jseq.setViewreference(jds == jal.getSeqrep());
1023 // TODO: omit sequence features from each alignment view's XML dump if we
1024 // are storing dataset
1025 List<SequenceFeature> sfs = jds.getSequenceFeatures();
1026 for (SequenceFeature sf : sfs)
1028 // Features features = new Features();
1029 Feature features = new Feature();
1031 features.setBegin(sf.getBegin());
1032 features.setEnd(sf.getEnd());
1033 features.setDescription(sf.getDescription());
1034 features.setType(sf.getType());
1035 features.setFeatureGroup(sf.getFeatureGroup());
1036 features.setScore(sf.getScore());
1037 if (sf.links != null)
1039 for (int l = 0; l < sf.links.size(); l++)
1041 OtherData keyValue = new OtherData();
1042 keyValue.setKey("LINK_" + l);
1043 keyValue.setValue(sf.links.elementAt(l).toString());
1044 // features.addOtherData(keyValue);
1045 features.getOtherData().add(keyValue);
1048 if (sf.otherDetails != null)
1051 * save feature attributes, which may be simple strings or
1052 * map valued (have sub-attributes)
1054 for (Entry<String, Object> entry : sf.otherDetails.entrySet())
1056 String key = entry.getKey();
1057 Object value = entry.getValue();
1058 if (value instanceof Map<?, ?>)
1060 for (Entry<String, Object> subAttribute : ((Map<String, Object>) value)
1063 OtherData otherData = new OtherData();
1064 otherData.setKey(key);
1065 otherData.setKey2(subAttribute.getKey());
1066 otherData.setValue(subAttribute.getValue().toString());
1067 // features.addOtherData(otherData);
1068 features.getOtherData().add(otherData);
1073 OtherData otherData = new OtherData();
1074 otherData.setKey(key);
1075 otherData.setValue(value.toString());
1076 // features.addOtherData(otherData);
1077 features.getOtherData().add(otherData);
1082 // jseq.addFeatures(features);
1083 jseq.getFeatures().add(features);
1086 if (jdatasq.getAllPDBEntries() != null)
1088 Enumeration<PDBEntry> en = jdatasq.getAllPDBEntries().elements();
1089 while (en.hasMoreElements())
1091 Pdbids pdb = new Pdbids();
1092 jalview.datamodel.PDBEntry entry = en.nextElement();
1094 String pdbId = entry.getId();
1096 pdb.setType(entry.getType());
1099 * Store any structure views associated with this sequence. This
1100 * section copes with duplicate entries in the project, so a dataset
1101 * only view *should* be coped with sensibly.
1103 // This must have been loaded, is it still visible?
1104 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1105 String matchedFile = null;
1106 for (int f = frames.length - 1; f > -1; f--)
1108 if (frames[f] instanceof StructureViewerBase)
1110 StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
1111 matchedFile = saveStructureState(ap, jds, pdb, entry, viewIds,
1112 matchedFile, viewFrame);
1114 * Only store each structure viewer's state once in the project
1115 * jar. First time through only (storeDS==false)
1117 String viewId = viewFrame.getViewId();
1118 if (!storeDS && !viewIds.contains(viewId))
1120 viewIds.add(viewId);
1123 String viewerState = viewFrame.getStateInfo();
1124 writeJarEntry(jout, getViewerJarEntryName(viewId),
1125 viewerState.getBytes());
1126 } catch (IOException e)
1129 "Error saving viewer state: " + e.getMessage());
1135 if (matchedFile != null || entry.getFile() != null)
1137 if (entry.getFile() != null)
1140 matchedFile = entry.getFile();
1142 pdb.setFile(matchedFile); // entry.getFile());
1143 if (pdbfiles == null)
1145 pdbfiles = new ArrayList<>();
1148 if (!pdbfiles.contains(pdbId))
1150 pdbfiles.add(pdbId);
1151 copyFileToJar(jout, matchedFile, pdbId);
1155 Enumeration<String> props = entry.getProperties();
1156 if (props.hasMoreElements())
1158 // PdbentryItem item = new PdbentryItem();
1159 while (props.hasMoreElements())
1161 Property prop = new Property();
1162 String key = props.nextElement();
1164 prop.setValue(entry.getProperty(key).toString());
1165 // item.addProperty(prop);
1166 pdb.getProperty().add(prop);
1168 // pdb.addPdbentryItem(item);
1171 // jseq.addPdbids(pdb);
1172 jseq.getPdbids().add(pdb);
1176 saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
1178 // jms.addJSeq(jseq);
1179 object.getJSeq().add(jseq);
1182 if (!storeDS && av.hasHiddenRows())
1184 jal = av.getAlignment();
1188 if (storeDS && jal.getCodonFrames() != null)
1190 List<AlignedCodonFrame> jac = jal.getCodonFrames();
1191 for (AlignedCodonFrame acf : jac)
1193 AlcodonFrame alc = new AlcodonFrame();
1194 if (acf.getProtMappings() != null
1195 && acf.getProtMappings().length > 0)
1197 boolean hasMap = false;
1198 SequenceI[] dnas = acf.getdnaSeqs();
1199 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1200 for (int m = 0; m < pmaps.length; m++)
1202 AlcodMap alcmap = new AlcodMap();
1203 alcmap.setDnasq(seqHash(dnas[m]));
1205 createVamsasMapping(pmaps[m], dnas[m], null, false));
1206 // alc.addAlcodMap(alcmap);
1207 alc.getAlcodMap().add(alcmap);
1212 // vamsasSet.addAlcodonFrame(alc);
1213 vamsasSet.getAlcodonFrame().add(alc);
1216 // TODO: delete this ? dead code from 2.8.3->2.9 ?
1218 // AlcodonFrame alc = new AlcodonFrame();
1219 // vamsasSet.addAlcodonFrame(alc);
1220 // for (int p = 0; p < acf.aaWidth; p++)
1222 // Alcodon cmap = new Alcodon();
1223 // if (acf.codons[p] != null)
1225 // // Null codons indicate a gapped column in the translated peptide
1227 // cmap.setPos1(acf.codons[p][0]);
1228 // cmap.setPos2(acf.codons[p][1]);
1229 // cmap.setPos3(acf.codons[p][2]);
1231 // alc.addAlcodon(cmap);
1233 // if (acf.getProtMappings() != null
1234 // && acf.getProtMappings().length > 0)
1236 // SequenceI[] dnas = acf.getdnaSeqs();
1237 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1238 // for (int m = 0; m < pmaps.length; m++)
1240 // AlcodMap alcmap = new AlcodMap();
1241 // alcmap.setDnasq(seqHash(dnas[m]));
1242 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1244 // alc.addAlcodMap(alcmap);
1251 // /////////////////////////////////
1252 if (!storeDS && av.getCurrentTree() != null)
1254 // FIND ANY ASSOCIATED TREES
1255 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
1256 if (Desktop.getDesktopPane() != null)
1258 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1260 for (int t = 0; t < frames.length; t++)
1262 if (frames[t] instanceof TreePanel)
1264 TreePanel tp = (TreePanel) frames[t];
1266 if (tp.getTreeCanvas().getViewport().getAlignment() == jal)
1268 JalviewModel.Tree tree = new JalviewModel.Tree();
1269 tree.setTitle(tp.getTitle());
1270 tree.setCurrentTree((av.getCurrentTree() == tp.getTree()));
1271 tree.setNewick(tp.getTree().print());
1272 tree.setThreshold(tp.getTreeCanvas().getThreshold());
1274 tree.setFitToWindow(tp.fitToWindow.getState());
1275 tree.setFontName(tp.getTreeFont().getName());
1276 tree.setFontSize(tp.getTreeFont().getSize());
1277 tree.setFontStyle(tp.getTreeFont().getStyle());
1278 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
1280 tree.setShowBootstrap(tp.bootstrapMenu.getState());
1281 tree.setShowDistances(tp.distanceMenu.getState());
1283 tree.setHeight(tp.getHeight());
1284 tree.setWidth(tp.getWidth());
1285 tree.setXpos(tp.getX());
1286 tree.setYpos(tp.getY());
1287 tree.setId(makeHashCode(tp, null));
1288 tree.setLinkToAllViews(
1289 tp.getTreeCanvas().isApplyToAllViews());
1291 // jms.addTree(tree);
1292 object.getTree().add(tree);
1302 if (!storeDS && Desktop.getDesktopPane() != null)
1304 for (JInternalFrame frame : Desktop.getDesktopPane().getAllFrames())
1306 if (frame instanceof PCAPanel)
1308 PCAPanel panel = (PCAPanel) frame;
1309 if (panel.getAlignViewport().getAlignment() == jal)
1311 savePCA(panel, object);
1319 * store forward refs from an annotationRow to any groups
1321 IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
1324 for (SequenceI sq : jal.getSequences())
1326 // Store annotation on dataset sequences only
1327 AlignmentAnnotation[] aa = sq.getAnnotation();
1328 if (aa != null && aa.length > 0)
1330 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1337 if (jal.getAlignmentAnnotation() != null)
1339 // Store the annotation shown on the alignment.
1340 AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
1341 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1346 if (jal.getGroups() != null)
1348 JGroup[] groups = new JGroup[jal.getGroups().size()];
1350 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
1352 JGroup jGroup = new JGroup();
1353 groups[++i] = jGroup;
1355 jGroup.setStart(sg.getStartRes());
1356 jGroup.setEnd(sg.getEndRes());
1357 jGroup.setName(sg.getName());
1358 if (groupRefs.containsKey(sg))
1360 // group has references so set its ID field
1361 jGroup.setId(groupRefs.get(sg));
1363 ColourSchemeI colourScheme = sg.getColourScheme();
1364 if (colourScheme != null)
1366 ResidueShaderI groupColourScheme = sg.getGroupColourScheme();
1367 if (groupColourScheme.conservationApplied())
1369 jGroup.setConsThreshold(groupColourScheme.getConservationInc());
1371 if (colourScheme instanceof jalview.schemes.UserColourScheme)
1374 setUserColourScheme(colourScheme, userColours,
1379 jGroup.setColour(colourScheme.getSchemeName());
1382 else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
1384 jGroup.setColour("AnnotationColourGradient");
1385 jGroup.setAnnotationColours(constructAnnotationColours(
1386 (jalview.schemes.AnnotationColourGradient) colourScheme,
1387 userColours, object));
1389 else if (colourScheme instanceof jalview.schemes.UserColourScheme)
1392 setUserColourScheme(colourScheme, userColours, object));
1396 jGroup.setColour(colourScheme.getSchemeName());
1399 jGroup.setPidThreshold(groupColourScheme.getThreshold());
1402 jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
1403 jGroup.setDisplayBoxes(sg.getDisplayBoxes());
1404 jGroup.setDisplayText(sg.getDisplayText());
1405 jGroup.setColourText(sg.getColourText());
1406 jGroup.setTextCol1(sg.textColour.getRGB());
1407 jGroup.setTextCol2(sg.textColour2.getRGB());
1408 jGroup.setTextColThreshold(sg.thresholdTextColour);
1409 jGroup.setShowUnconserved(sg.getShowNonconserved());
1410 jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1411 jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
1412 jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
1413 jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1414 for (SequenceI seq : sg.getSequences())
1416 // jGroup.addSeq(seqHash(seq));
1417 jGroup.getSeq().add(seqHash(seq));
1421 //jms.setJGroup(groups);
1423 for (JGroup grp : groups)
1425 object.getJGroup().add(grp);
1430 // /////////SAVE VIEWPORT
1431 Viewport view = new Viewport();
1432 view.setTitle(ap.alignFrame.getTitle());
1433 view.setSequenceSetId(
1434 makeHashCode(av.getSequenceSetId(), av.getSequenceSetId()));
1435 view.setId(av.getViewId());
1436 if (av.getCodingComplement() != null)
1438 view.setComplementId(av.getCodingComplement().getViewId());
1440 view.setViewName(av.getViewName());
1441 view.setGatheredViews(av.isGatherViewsHere());
1443 Rectangle size = ap.av.getExplodedGeometry();
1444 Rectangle position = size;
1447 size = ap.alignFrame.getBounds();
1448 if (av.getCodingComplement() != null)
1450 position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
1458 view.setXpos(position.x);
1459 view.setYpos(position.y);
1461 view.setWidth(size.width);
1462 view.setHeight(size.height);
1464 view.setStartRes(vpRanges.getStartRes());
1465 view.setStartSeq(vpRanges.getStartSeq());
1467 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1469 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1470 userColours, object));
1473 .getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1475 AnnotationColourScheme ac = constructAnnotationColours(
1476 (jalview.schemes.AnnotationColourGradient) av
1477 .getGlobalColourScheme(),
1478 userColours, object);
1480 view.setAnnotationColours(ac);
1481 view.setBgColour("AnnotationColourGradient");
1485 view.setBgColour(ColourSchemeProperty
1486 .getColourName(av.getGlobalColourScheme()));
1489 ResidueShaderI vcs = av.getResidueShading();
1490 ColourSchemeI cs = av.getGlobalColourScheme();
1494 if (vcs.conservationApplied())
1496 view.setConsThreshold(vcs.getConservationInc());
1497 if (cs instanceof jalview.schemes.UserColourScheme)
1499 view.setBgColour(setUserColourScheme(cs, userColours, object));
1502 view.setPidThreshold(vcs.getThreshold());
1505 view.setConservationSelected(av.getConservationSelected());
1506 view.setPidSelected(av.getAbovePIDThreshold());
1507 final Font font = av.getFont();
1508 view.setFontName(font.getName());
1509 view.setFontSize(font.getSize());
1510 view.setFontStyle(font.getStyle());
1511 view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
1512 view.setRenderGaps(av.isRenderGaps());
1513 view.setShowAnnotation(av.isShowAnnotation());
1514 view.setShowBoxes(av.getShowBoxes());
1515 view.setShowColourText(av.getColourText());
1516 view.setShowFullId(av.getShowJVSuffix());
1517 view.setRightAlignIds(av.isRightAlignIds());
1518 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1519 view.setShowText(av.getShowText());
1520 view.setShowUnconserved(av.getShowUnconserved());
1521 view.setWrapAlignment(av.getWrapAlignment());
1522 view.setTextCol1(av.getTextColour().getRGB());
1523 view.setTextCol2(av.getTextColour2().getRGB());
1524 view.setTextColThreshold(av.getThresholdTextColour());
1525 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1526 view.setShowSequenceLogo(av.isShowSequenceLogo());
1527 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1528 view.setShowGroupConsensus(av.isShowGroupConsensus());
1529 view.setShowGroupConservation(av.isShowGroupConservation());
1530 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1531 view.setShowDbRefTooltip(av.isShowDBRefs());
1532 view.setFollowHighlight(av.isFollowHighlight());
1533 view.setFollowSelection(av.followSelection);
1534 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1535 if (av.getFeaturesDisplayed() != null)
1537 FeatureSettings fs = new FeatureSettings();
1539 FeatureRenderer fr = ap.getSeqPanel().seqCanvas
1540 .getFeatureRenderer();
1541 String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
1543 Vector<String> settingsAdded = new Vector<>();
1544 if (renderOrder != null)
1546 for (String featureType : renderOrder)
1548 FeatureSettings.Setting setting = new FeatureSettings.Setting();
1549 setting.setType(featureType);
1552 * save any filter for the feature type
1554 FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
1555 if (filter != null) {
1556 Iterator<FeatureMatcherI> filters = filter.getMatchers().iterator();
1557 FeatureMatcherI firstFilter = filters.next();
1558 setting.setMatcherSet(Jalview2XML.marshalFilter(
1559 firstFilter, filters, filter.isAnded()));
1563 * save colour scheme for the feature type
1565 FeatureColourI fcol = fr.getFeatureStyle(featureType);
1566 if (!fcol.isSimpleColour())
1568 setting.setColour(fcol.getMaxColour().getRGB());
1569 setting.setMincolour(fcol.getMinColour().getRGB());
1570 setting.setMin(fcol.getMin());
1571 setting.setMax(fcol.getMax());
1572 setting.setColourByLabel(fcol.isColourByLabel());
1573 if (fcol.isColourByAttribute())
1575 String[] attName = fcol.getAttributeName();
1576 setting.getAttributeName().add(attName[0]);
1577 if (attName.length > 1)
1579 setting.getAttributeName().add(attName[1]);
1582 setting.setAutoScale(fcol.isAutoScaled());
1583 setting.setThreshold(fcol.getThreshold());
1584 Color noColour = fcol.getNoColour();
1585 if (noColour == null)
1587 setting.setNoValueColour(NoValueColour.NONE);
1589 else if (noColour.equals(fcol.getMaxColour()))
1591 setting.setNoValueColour(NoValueColour.MAX);
1595 setting.setNoValueColour(NoValueColour.MIN);
1597 // -1 = No threshold, 0 = Below, 1 = Above
1598 setting.setThreshstate(fcol.isAboveThreshold() ? 1
1599 : (fcol.isBelowThreshold() ? 0 : -1));
1603 setting.setColour(fcol.getColour().getRGB());
1607 av.getFeaturesDisplayed().isVisible(featureType));
1609 .getOrder(featureType);
1612 setting.setOrder(rorder);
1614 /// fs.addSetting(setting);
1615 fs.getSetting().add(setting);
1616 settingsAdded.addElement(featureType);
1620 // is groups actually supposed to be a map here ?
1621 Iterator<String> en = fr.getFeatureGroups().iterator();
1622 Vector<String> groupsAdded = new Vector<>();
1623 while (en.hasNext())
1625 String grp = en.next();
1626 if (groupsAdded.contains(grp))
1630 Group g = new Group();
1632 g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
1635 fs.getGroup().add(g);
1636 groupsAdded.addElement(grp);
1638 // jms.setFeatureSettings(fs);
1639 object.setFeatureSettings(fs);
1642 if (av.hasHiddenColumns())
1644 jalview.datamodel.HiddenColumns hidden = av.getAlignment()
1645 .getHiddenColumns();
1648 warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1652 Iterator<int[]> hiddenRegions = hidden.iterator();
1653 while (hiddenRegions.hasNext())
1655 int[] region = hiddenRegions.next();
1656 HiddenColumns hc = new HiddenColumns();
1657 hc.setStart(region[0]);
1658 hc.setEnd(region[1]);
1659 // view.addHiddenColumns(hc);
1660 view.getHiddenColumns().add(hc);
1664 if (calcIdSet.size() > 0)
1666 for (String calcId : calcIdSet)
1668 if (calcId.trim().length() > 0)
1670 CalcIdParam cidp = createCalcIdParam(calcId, av);
1671 // Some calcIds have no parameters.
1674 // view.addCalcIdParam(cidp);
1675 view.getCalcIdParam().add(cidp);
1681 // jms.addViewport(view);
1682 object.getViewport().add(view);
1684 // object.setJalviewModelSequence(jms);
1685 // object.getVamsasModel().addSequenceSet(vamsasSet);
1686 object.getVamsasModel().getSequenceSet().add(vamsasSet);
1688 if (jout != null && fileName != null)
1690 // We may not want to write the object to disk,
1691 // eg we can copy the alignViewport to a new view object
1692 // using save and then load
1695 fileName = fileName.replace('\\', '/');
1696 System.out.println("Writing jar entry " + fileName);
1697 JarEntry entry = new JarEntry(fileName);
1698 jout.putNextEntry(entry);
1699 PrintWriter pout = new PrintWriter(
1700 new OutputStreamWriter(jout, UTF_8));
1701 JAXBContext jaxbContext = JAXBContext
1702 .newInstance(JalviewModel.class);
1703 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
1705 // output pretty printed
1706 // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1707 jaxbMarshaller.marshal(
1708 new ObjectFactory().createJalviewModel(object), pout);
1710 // jaxbMarshaller.marshal(object, pout);
1711 // marshaller.marshal(object);
1714 } catch (Exception ex)
1716 // TODO: raise error in GUI if marshalling failed.
1717 System.err.println("Error writing Jalview project");
1718 ex.printStackTrace();
1725 * Writes PCA viewer attributes and computed values to an XML model object and
1726 * adds it to the JalviewModel. Any exceptions are reported by logging.
1728 protected void savePCA(PCAPanel panel, JalviewModel object)
1732 PcaViewer viewer = new PcaViewer();
1733 viewer.setHeight(panel.getHeight());
1734 viewer.setWidth(panel.getWidth());
1735 viewer.setXpos(panel.getX());
1736 viewer.setYpos(panel.getY());
1737 viewer.setTitle(panel.getTitle());
1738 PCAModel pcaModel = panel.getPcaModel();
1739 viewer.setScoreModelName(pcaModel.getScoreModelName());
1740 viewer.setXDim(panel.getSelectedDimensionIndex(X));
1741 viewer.setYDim(panel.getSelectedDimensionIndex(Y));
1742 viewer.setZDim(panel.getSelectedDimensionIndex(Z));
1744 panel.getRotatableCanvas().getBackgroundColour().getRGB());
1745 viewer.setScaleFactor(panel.getRotatableCanvas().getScaleFactor());
1746 float[] spMin = panel.getRotatableCanvas().getSeqMin();
1747 SeqPointMin spmin = new SeqPointMin();
1748 spmin.setXPos(spMin[0]);
1749 spmin.setYPos(spMin[1]);
1750 spmin.setZPos(spMin[2]);
1751 viewer.setSeqPointMin(spmin);
1752 float[] spMax = panel.getRotatableCanvas().getSeqMax();
1753 SeqPointMax spmax = new SeqPointMax();
1754 spmax.setXPos(spMax[0]);
1755 spmax.setYPos(spMax[1]);
1756 spmax.setZPos(spMax[2]);
1757 viewer.setSeqPointMax(spmax);
1758 viewer.setShowLabels(panel.getRotatableCanvas().isShowLabels());
1759 viewer.setLinkToAllViews(
1760 panel.getRotatableCanvas().isApplyToAllViews());
1761 SimilarityParamsI sp = pcaModel.getSimilarityParameters();
1762 viewer.setIncludeGaps(sp.includeGaps());
1763 viewer.setMatchGaps(sp.matchGaps());
1764 viewer.setIncludeGappedColumns(sp.includeGappedColumns());
1765 viewer.setDenominateByShortestLength(sp.denominateByShortestLength());
1768 * sequence points on display
1770 for (jalview.datamodel.SequencePoint spt : pcaModel
1771 .getSequencePoints())
1773 SequencePoint point = new SequencePoint();
1774 point.setSequenceRef(seqHash(spt.getSequence()));
1775 point.setXPos(spt.coord.x);
1776 point.setYPos(spt.coord.y);
1777 point.setZPos(spt.coord.z);
1778 viewer.getSequencePoint().add(point);
1782 * (end points of) axes on display
1784 for (Point p : panel.getRotatableCanvas().getAxisEndPoints())
1787 Axis axis = new Axis();
1791 viewer.getAxis().add(axis);
1795 * raw PCA data (note we are not restoring PCA inputs here -
1796 * alignment view, score model, similarity parameters)
1798 PcaDataType data = new PcaDataType();
1799 viewer.setPcaData(data);
1800 PCA pca = pcaModel.getPcaData();
1802 DoubleMatrix pm = new DoubleMatrix();
1803 saveDoubleMatrix(pca.getPairwiseScores(), pm);
1804 data.setPairwiseMatrix(pm);
1806 DoubleMatrix tm = new DoubleMatrix();
1807 saveDoubleMatrix(pca.getTridiagonal(), tm);
1808 data.setTridiagonalMatrix(tm);
1810 DoubleMatrix eigenMatrix = new DoubleMatrix();
1811 data.setEigenMatrix(eigenMatrix);
1812 saveDoubleMatrix(pca.getEigenmatrix(), eigenMatrix);
1814 object.getPcaViewer().add(viewer);
1815 } catch (Throwable t)
1817 Cache.log.error("Error saving PCA: " + t.getMessage());
1822 * Stores values from a matrix into an XML element, including (if present) the
1827 * @see #loadDoubleMatrix(DoubleMatrix)
1829 protected void saveDoubleMatrix(MatrixI m, DoubleMatrix xmlMatrix)
1831 xmlMatrix.setRows(m.height());
1832 xmlMatrix.setColumns(m.width());
1833 for (int i = 0; i < m.height(); i++)
1835 DoubleVector row = new DoubleVector();
1836 for (int j = 0; j < m.width(); j++)
1838 row.getV().add(m.getValue(i, j));
1840 xmlMatrix.getRow().add(row);
1842 if (m.getD() != null)
1844 DoubleVector dVector = new DoubleVector();
1845 for (double d : m.getD())
1847 dVector.getV().add(d);
1849 xmlMatrix.setD(dVector);
1851 if (m.getE() != null)
1853 DoubleVector eVector = new DoubleVector();
1854 for (double e : m.getE())
1856 eVector.getV().add(e);
1858 xmlMatrix.setE(eVector);
1863 * Loads XML matrix data into a new Matrix object, including the D and/or E
1864 * vectors (if present)
1868 * @see Jalview2XML#saveDoubleMatrix(MatrixI, DoubleMatrix)
1870 protected MatrixI loadDoubleMatrix(DoubleMatrix mData)
1872 int rows = mData.getRows();
1873 double[][] vals = new double[rows][];
1875 for (int i = 0; i < rows; i++)
1877 List<Double> dVector = mData.getRow().get(i).getV();
1878 vals[i] = new double[dVector.size()];
1880 for (Double d : dVector)
1886 MatrixI m = new Matrix(vals);
1888 if (mData.getD() != null)
1890 List<Double> dVector = mData.getD().getV();
1891 double[] vec = new double[dVector.size()];
1893 for (Double d : dVector)
1899 if (mData.getE() != null)
1901 List<Double> dVector = mData.getE().getV();
1902 double[] vec = new double[dVector.size()];
1904 for (Double d : dVector)
1915 * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
1916 * for each viewer, with
1918 * <li>viewer geometry (position, size, split pane divider location)</li>
1919 * <li>index of the selected structure in the viewer (currently shows gapped
1921 * <li>the id of the annotation holding RNA secondary structure</li>
1922 * <li>(currently only one SS is shown per viewer, may be more in future)</li>
1924 * Varna viewer state is also written out (in native Varna XML) to separate
1925 * project jar entries. A separate entry is written for each RNA structure
1926 * displayed, with the naming convention
1928 * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
1936 * @param storeDataset
1938 protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
1939 final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
1940 boolean storeDataset)
1942 if (Desktop.getDesktopPane() == null)
1946 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1947 for (int f = frames.length - 1; f > -1; f--)
1949 if (frames[f] instanceof AppVarna)
1951 AppVarna varna = (AppVarna) frames[f];
1953 * link the sequence to every viewer that is showing it and is linked to
1954 * its alignment panel
1956 if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
1958 String viewId = varna.getViewId();
1959 RnaViewer rna = new RnaViewer();
1960 rna.setViewId(viewId);
1961 rna.setTitle(varna.getTitle());
1962 rna.setXpos(varna.getX());
1963 rna.setYpos(varna.getY());
1964 rna.setWidth(varna.getWidth());
1965 rna.setHeight(varna.getHeight());
1966 rna.setDividerLocation(varna.getDividerLocation());
1967 rna.setSelectedRna(varna.getSelectedIndex());
1968 // jseq.addRnaViewer(rna);
1969 jseq.getRnaViewer().add(rna);
1972 * Store each Varna panel's state once in the project per sequence.
1973 * First time through only (storeDataset==false)
1975 // boolean storeSessions = false;
1976 // String sequenceViewId = viewId + seqsToIds.get(jds);
1977 // if (!storeDataset && !viewIds.contains(sequenceViewId))
1979 // viewIds.add(sequenceViewId);
1980 // storeSessions = true;
1982 for (RnaModel model : varna.getModels())
1984 if (model.seq == jds)
1987 * VARNA saves each view (sequence or alignment secondary
1988 * structure, gapped or trimmed) as a separate XML file
1990 String jarEntryName = rnaSessions.get(model);
1991 if (jarEntryName == null)
1994 String varnaStateFile = varna.getStateInfo(model.rna);
1995 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
1996 copyFileToJar(jout, varnaStateFile, jarEntryName);
1997 rnaSessions.put(model, jarEntryName);
1999 SecondaryStructure ss = new SecondaryStructure();
2000 String annotationId = varna.getAnnotation(jds).annotationId;
2001 ss.setAnnotationId(annotationId);
2002 ss.setViewerState(jarEntryName);
2003 ss.setGapped(model.gapped);
2004 ss.setTitle(model.title);
2005 // rna.addSecondaryStructure(ss);
2006 rna.getSecondaryStructure().add(ss);
2015 * Copy the contents of a file to a new entry added to the output jar
2019 * @param jarEntryName
2021 protected void copyFileToJar(JarOutputStream jout, String infilePath,
2022 String jarEntryName)
2024 DataInputStream dis = null;
2027 File file = new File(infilePath);
2028 if (file.exists() && jout != null)
2030 dis = new DataInputStream(new FileInputStream(file));
2031 byte[] data = new byte[(int) file.length()];
2032 dis.readFully(data);
2033 writeJarEntry(jout, jarEntryName, data);
2035 } catch (Exception ex)
2037 ex.printStackTrace();
2045 } catch (IOException e)
2054 * Write the data to a new entry of given name in the output jar file
2057 * @param jarEntryName
2059 * @throws IOException
2061 protected void writeJarEntry(JarOutputStream jout, String jarEntryName,
2062 byte[] data) throws IOException
2066 jarEntryName = jarEntryName.replace('\\','/');
2067 System.out.println("Writing jar entry " + jarEntryName);
2068 jout.putNextEntry(new JarEntry(jarEntryName));
2069 DataOutputStream dout = new DataOutputStream(jout);
2070 dout.write(data, 0, data.length);
2077 * Save the state of a structure viewer
2082 * the archive XML element under which to save the state
2085 * @param matchedFile
2089 protected String saveStructureState(AlignmentPanel ap, SequenceI jds,
2090 Pdbids pdb, PDBEntry entry, List<String> viewIds,
2091 String matchedFile, StructureViewerBase viewFrame)
2093 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
2096 * Look for any bindings for this viewer to the PDB file of interest
2097 * (including part matches excluding chain id)
2099 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
2101 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
2102 final String pdbId = pdbentry.getId();
2103 if (!pdbId.equals(entry.getId())
2104 && !(entry.getId().length() > 4 && entry.getId().toLowerCase()
2105 .startsWith(pdbId.toLowerCase())))
2108 * not interested in a binding to a different PDB entry here
2112 if (matchedFile == null)
2114 matchedFile = pdbentry.getFile();
2116 else if (!matchedFile.equals(pdbentry.getFile()))
2119 "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
2120 + pdbentry.getFile());
2124 // can get at it if the ID
2125 // match is ambiguous (e.g.
2128 for (int smap = 0; smap < viewFrame.getBinding()
2129 .getSequence()[peid].length; smap++)
2131 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
2132 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
2134 StructureState state = new StructureState();
2135 state.setVisible(true);
2136 state.setXpos(viewFrame.getX());
2137 state.setYpos(viewFrame.getY());
2138 state.setWidth(viewFrame.getWidth());
2139 state.setHeight(viewFrame.getHeight());
2140 final String viewId = viewFrame.getViewId();
2141 state.setViewId(viewId);
2142 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
2143 state.setColourwithAlignPanel(viewFrame.isUsedforcolourby(ap));
2144 state.setColourByJmol(viewFrame.isColouredByViewer());
2145 state.setType(viewFrame.getViewerType().toString());
2146 // pdb.addStructureState(state);
2147 pdb.getStructureState().add(state);
2155 * Populates the AnnotationColourScheme xml for save. This captures the
2156 * settings of the options in the 'Colour by Annotation' dialog.
2159 * @param userColours
2163 private AnnotationColourScheme constructAnnotationColours(
2164 AnnotationColourGradient acg, List<UserColourScheme> userColours,
2167 AnnotationColourScheme ac = new AnnotationColourScheme();
2168 ac.setAboveThreshold(acg.getAboveThreshold());
2169 ac.setThreshold(acg.getAnnotationThreshold());
2170 // 2.10.2 save annotationId (unique) not annotation label
2171 ac.setAnnotation(acg.getAnnotation().annotationId);
2172 if (acg.getBaseColour() instanceof UserColourScheme)
2175 setUserColourScheme(acg.getBaseColour(), userColours, jm));
2180 ColourSchemeProperty.getColourName(acg.getBaseColour()));
2183 ac.setMaxColour(acg.getMaxColour().getRGB());
2184 ac.setMinColour(acg.getMinColour().getRGB());
2185 ac.setPerSequence(acg.isSeqAssociated());
2186 ac.setPredefinedColours(acg.isPredefinedColours());
2190 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
2191 IdentityHashMap<SequenceGroup, String> groupRefs,
2192 AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
2193 SequenceSet vamsasSet)
2196 for (int i = 0; i < aa.length; i++)
2198 Annotation an = new Annotation();
2200 AlignmentAnnotation annotation = aa[i];
2201 if (annotation.annotationId != null)
2203 annotationIds.put(annotation.annotationId, annotation);
2206 an.setId(annotation.annotationId);
2208 an.setVisible(annotation.visible);
2210 an.setDescription(annotation.description);
2212 if (annotation.sequenceRef != null)
2214 // 2.9 JAL-1781 xref on sequence id rather than name
2215 an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
2217 if (annotation.groupRef != null)
2219 String groupIdr = groupRefs.get(annotation.groupRef);
2220 if (groupIdr == null)
2222 // make a locally unique String
2223 groupRefs.put(annotation.groupRef,
2224 groupIdr = ("" + System.currentTimeMillis()
2225 + annotation.groupRef.getName()
2226 + groupRefs.size()));
2228 an.setGroupRef(groupIdr.toString());
2231 // store all visualization attributes for annotation
2232 an.setGraphHeight(annotation.graphHeight);
2233 an.setCentreColLabels(annotation.centreColLabels);
2234 an.setScaleColLabels(annotation.scaleColLabel);
2235 an.setShowAllColLabels(annotation.showAllColLabels);
2236 an.setBelowAlignment(annotation.belowAlignment);
2238 if (annotation.graph > 0)
2241 an.setGraphType(annotation.graph);
2242 an.setGraphGroup(annotation.graphGroup);
2243 if (annotation.getThreshold() != null)
2245 ThresholdLine line = new ThresholdLine();
2246 line.setLabel(annotation.getThreshold().label);
2247 line.setValue(annotation.getThreshold().value);
2248 line.setColour(annotation.getThreshold().colour.getRGB());
2249 an.setThresholdLine(line);
2257 an.setLabel(annotation.label);
2259 if (annotation == av.getAlignmentQualityAnnot()
2260 || annotation == av.getAlignmentConservationAnnotation()
2261 || annotation == av.getAlignmentConsensusAnnotation()
2262 || annotation.autoCalculated)
2264 // new way of indicating autocalculated annotation -
2265 an.setAutoCalculated(annotation.autoCalculated);
2267 if (annotation.hasScore())
2269 an.setScore(annotation.getScore());
2272 if (annotation.getCalcId() != null)
2274 calcIdSet.add(annotation.getCalcId());
2275 an.setCalcId(annotation.getCalcId());
2277 if (annotation.hasProperties())
2279 for (String pr : annotation.getProperties())
2281 jalview.xml.binding.jalview.Annotation.Property prop = new jalview.xml.binding.jalview.Annotation.Property();
2283 prop.setValue(annotation.getProperty(pr));
2284 // an.addProperty(prop);
2285 an.getProperty().add(prop);
2289 AnnotationElement ae;
2290 if (annotation.annotations != null)
2292 an.setScoreOnly(false);
2293 for (int a = 0; a < annotation.annotations.length; a++)
2295 if ((annotation == null) || (annotation.annotations[a] == null))
2300 ae = new AnnotationElement();
2301 if (annotation.annotations[a].description != null)
2303 ae.setDescription(annotation.annotations[a].description);
2305 if (annotation.annotations[a].displayCharacter != null)
2307 ae.setDisplayCharacter(
2308 annotation.annotations[a].displayCharacter);
2311 if (!Float.isNaN(annotation.annotations[a].value))
2313 ae.setValue(annotation.annotations[a].value);
2317 if (annotation.annotations[a].secondaryStructure > ' ')
2319 ae.setSecondaryStructure(
2320 annotation.annotations[a].secondaryStructure + "");
2323 if (annotation.annotations[a].colour != null
2324 && annotation.annotations[a].colour != java.awt.Color.black)
2326 ae.setColour(annotation.annotations[a].colour.getRGB());
2329 // an.addAnnotationElement(ae);
2330 an.getAnnotationElement().add(ae);
2331 if (annotation.autoCalculated)
2333 // only write one non-null entry into the annotation row -
2334 // sufficient to get the visualization attributes necessary to
2342 an.setScoreOnly(true);
2344 if (!storeDS || (storeDS && !annotation.autoCalculated))
2346 // skip autocalculated annotation - these are only provided for
2348 // vamsasSet.addAnnotation(an);
2349 vamsasSet.getAnnotation().add(an);
2355 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
2357 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
2358 if (settings != null)
2360 CalcIdParam vCalcIdParam = new CalcIdParam();
2361 vCalcIdParam.setCalcId(calcId);
2362 // vCalcIdParam.addServiceURL(settings.getServiceURI());
2363 vCalcIdParam.getServiceURL().add(settings.getServiceURI());
2364 // generic URI allowing a third party to resolve another instance of the
2365 // service used for this calculation
2366 for (String url : settings.getServiceURLs())
2368 // vCalcIdParam.addServiceURL(urls);
2369 vCalcIdParam.getServiceURL().add(url);
2371 vCalcIdParam.setVersion("1.0");
2372 if (settings.getPreset() != null)
2374 WsParamSetI setting = settings.getPreset();
2375 vCalcIdParam.setName(setting.getName());
2376 vCalcIdParam.setDescription(setting.getDescription());
2380 vCalcIdParam.setName("");
2381 vCalcIdParam.setDescription("Last used parameters");
2383 // need to be able to recover 1) settings 2) user-defined presets or
2384 // recreate settings from preset 3) predefined settings provided by
2385 // service - or settings that can be transferred (or discarded)
2386 vCalcIdParam.setParameters(
2387 settings.getWsParamFile().replace("\n", "|\\n|"));
2388 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
2389 // todo - decide if updateImmediately is needed for any projects.
2391 return vCalcIdParam;
2396 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
2399 if (calcIdParam.getVersion().equals("1.0"))
2401 final String[] calcIds = calcIdParam.getServiceURL().toArray(new String[0]);
2402 Jws2Instance service = Jws2Discoverer.getInstance()
2403 .getPreferredServiceFor(calcIds);
2404 if (service != null)
2406 WsParamSetI parmSet = null;
2409 parmSet = service.getParamStore().parseServiceParameterFile(
2410 calcIdParam.getName(), calcIdParam.getDescription(),
2412 calcIdParam.getParameters().replace("|\\n|", "\n"));
2413 } catch (IOException x)
2415 warn("Couldn't parse parameter data for "
2416 + calcIdParam.getCalcId(), x);
2419 List<ArgumentI> argList = null;
2420 if (calcIdParam.getName().length() > 0)
2422 parmSet = service.getParamStore()
2423 .getPreset(calcIdParam.getName());
2424 if (parmSet != null)
2426 // TODO : check we have a good match with settings in AACon -
2427 // otherwise we'll need to create a new preset
2432 argList = parmSet.getArguments();
2435 AAConSettings settings = new AAConSettings(
2436 calcIdParam.isAutoUpdate(), service, parmSet, argList);
2437 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
2438 calcIdParam.isNeedsUpdate());
2443 warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
2447 throw new Error(MessageManager.formatMessage(
2448 "error.unsupported_version_calcIdparam", new Object[]
2449 { calcIdParam.toString() }));
2453 * External mapping between jalview objects and objects yielding a valid and
2454 * unique object ID string. This is null for normal Jalview project IO, but
2455 * non-null when a jalview project is being read or written as part of a
2458 IdentityHashMap jv2vobj = null;
2461 * Construct a unique ID for jvobj using either existing bindings or if none
2462 * exist, the result of the hashcode call for the object.
2465 * jalview data object
2466 * @return unique ID for referring to jvobj
2468 private String makeHashCode(Object jvobj, String altCode)
2470 if (jv2vobj != null)
2472 Object id = jv2vobj.get(jvobj);
2475 return id.toString();
2477 // check string ID mappings
2478 if (jvids2vobj != null && jvobj instanceof String)
2480 id = jvids2vobj.get(jvobj);
2484 return id.toString();
2486 // give up and warn that something has gone wrong
2487 warn("Cannot find ID for object in external mapping : " + jvobj);
2493 * return local jalview object mapped to ID, if it exists
2497 * @return null or object bound to idcode
2499 private Object retrieveExistingObj(String idcode)
2501 if (idcode != null && vobj2jv != null)
2503 return vobj2jv.get(idcode);
2509 * binding from ID strings from external mapping table to jalview data model
2512 private Hashtable vobj2jv;
2514 private Sequence createVamsasSequence(String id, SequenceI jds)
2516 return createVamsasSequence(true, id, jds, null);
2519 private Sequence createVamsasSequence(boolean recurse, String id,
2520 SequenceI jds, SequenceI parentseq)
2522 Sequence vamsasSeq = new Sequence();
2523 vamsasSeq.setId(id);
2524 vamsasSeq.setName(jds.getName());
2525 vamsasSeq.setSequence(jds.getSequenceAsString());
2526 vamsasSeq.setDescription(jds.getDescription());
2527 List<DBRefEntry> dbrefs = null;
2528 if (jds.getDatasetSequence() != null)
2530 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
2534 // seqId==dsseqid so we can tell which sequences really are
2535 // dataset sequences only
2536 vamsasSeq.setDsseqid(id);
2537 dbrefs = jds.getDBRefs();
2538 if (parentseq == null)
2545 for (int d = 0, nd = dbrefs.size(); d < nd; d++)
2547 DBRef dbref = new DBRef();
2548 DBRefEntry ref = dbrefs.get(d);
2549 dbref.setSource(ref.getSource());
2550 dbref.setVersion(ref.getVersion());
2551 dbref.setAccessionId(ref.getAccessionId());
2554 Mapping mp = createVamsasMapping(ref.getMap(), parentseq,
2556 dbref.setMapping(mp);
2558 // vamsasSeq.addDBRef(dbref);
2559 vamsasSeq.getDBRef().add(dbref);
2565 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
2566 SequenceI parentseq, SequenceI jds, boolean recurse)
2569 if (jmp.getMap() != null)
2573 jalview.util.MapList mlst = jmp.getMap();
2574 List<int[]> r = mlst.getFromRanges();
2575 for (int[] range : r)
2577 MapListFrom mfrom = new MapListFrom();
2578 mfrom.setStart(range[0]);
2579 mfrom.setEnd(range[1]);
2580 // mp.addMapListFrom(mfrom);
2581 mp.getMapListFrom().add(mfrom);
2583 r = mlst.getToRanges();
2584 for (int[] range : r)
2586 MapListTo mto = new MapListTo();
2587 mto.setStart(range[0]);
2588 mto.setEnd(range[1]);
2589 // mp.addMapListTo(mto);
2590 mp.getMapListTo().add(mto);
2592 mp.setMapFromUnit(BigInteger.valueOf(mlst.getFromRatio()));
2593 mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
2594 if (jmp.getTo() != null)
2596 // MappingChoice mpc = new MappingChoice();
2598 // check/create ID for the sequence referenced by getTo()
2601 SequenceI ps = null;
2602 if (parentseq != jmp.getTo()
2603 && parentseq.getDatasetSequence() != jmp.getTo())
2605 // chaining dbref rather than a handshaking one
2606 jmpid = seqHash(ps = jmp.getTo());
2610 jmpid = seqHash(ps = parentseq);
2612 // mpc.setDseqFor(jmpid);
2613 mp.setDseqFor(jmpid);
2614 if (!seqRefIds.containsKey(jmpid))
2616 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
2617 seqRefIds.put(jmpid, ps);
2621 jalview.bin.Cache.log.debug("reusing DseqFor ID");
2624 // mp.setMappingChoice(mpc);
2630 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
2631 List<UserColourScheme> userColours, JalviewModel jm)
2634 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
2635 boolean newucs = false;
2636 if (!userColours.contains(ucs))
2638 userColours.add(ucs);
2641 id = "ucs" + userColours.indexOf(ucs);
2644 // actually create the scheme's entry in the XML model
2645 java.awt.Color[] colours = ucs.getColours();
2646 UserColours uc = new UserColours();
2647 // UserColourScheme jbucs = new UserColourScheme();
2648 JalviewUserColours jbucs = new JalviewUserColours();
2650 for (int i = 0; i < colours.length; i++)
2652 Colour col = new Colour();
2653 col.setName(ResidueProperties.aa[i]);
2654 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2655 // jbucs.addColour(col);
2656 jbucs.getColour().add(col);
2658 if (ucs.getLowerCaseColours() != null)
2660 colours = ucs.getLowerCaseColours();
2661 for (int i = 0; i < colours.length; i++)
2663 Colour col = new Colour();
2664 col.setName(ResidueProperties.aa[i].toLowerCase());
2665 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2666 // jbucs.addColour(col);
2667 jbucs.getColour().add(col);
2672 uc.setUserColourScheme(jbucs);
2673 // jm.addUserColours(uc);
2674 jm.getUserColours().add(uc);
2680 jalview.schemes.UserColourScheme getUserColourScheme(
2681 JalviewModel jm, String id)
2683 List<UserColours> uc = jm.getUserColours();
2684 UserColours colours = null;
2686 for (int i = 0; i < uc.length; i++)
2688 if (uc[i].getId().equals(id))
2695 for (UserColours c : uc)
2697 if (c.getId().equals(id))
2704 java.awt.Color[] newColours = new java.awt.Color[24];
2706 for (int i = 0; i < 24; i++)
2708 newColours[i] = new java.awt.Color(Integer.parseInt(
2709 // colours.getUserColourScheme().getColour(i).getRGB(), 16));
2710 colours.getUserColourScheme().getColour().get(i).getRGB(),
2714 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
2717 if (colours.getUserColourScheme().getColour().size()/*Count()*/ > 24)
2719 newColours = new java.awt.Color[23];
2720 for (int i = 0; i < 23; i++)
2722 newColours[i] = new java.awt.Color(Integer.parseInt(
2723 colours.getUserColourScheme().getColour().get(i + 24)
2727 ucs.setLowerCaseColours(newColours);
2734 * contains last error message (if any) encountered by XML loader.
2736 String errorMessage = null;
2739 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
2740 * exceptions are raised during project XML parsing
2742 public boolean attemptversion1parse = false;
2745 * JalviewJS only -- to preserve bytes in AlignFrame
2752 * Load a jalview project archive from a jar file
2755 * - HTTP URL or filename
2757 public AlignFrame loadJalviewAlign(final Object file)
2760 jalview.gui.AlignFrame af = null;
2764 // create list to store references for any new Jmol viewers created
2765 newStructureViewers = new Vector<>();
2766 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
2767 // Workaround is to make sure caller implements the JarInputStreamProvider
2769 // so we can re-open the jar input stream for each entry.
2771 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
2772 af = loadJalviewAlign(jprovider);
2775 af.setMenusForViewport();
2777 } catch (MalformedURLException e)
2779 errorMessage = "Invalid URL format for '" + file + "'";
2785 // BH 2019 -- can't wait
2786 SwingUtilities.invokeLater(new Runnable()
2791 setLoadingFinishedForNewStructureViewers();
2794 } catch (Exception x)
2796 System.err.println("Error loading alignment: " + x.getMessage());
2802 @SuppressWarnings("unused")
2803 private jarInputStreamProvider createjarInputStreamProvider(final Object ofile) throws MalformedURLException {
2805 // BH 2018 allow for bytes already attached to File object
2807 String file = (ofile instanceof File ? ((File) ofile).getCanonicalPath() : ofile.toString());
2808 byte[] bytes = Platform.isJS() ? Platform.getFileBytes((File) ofile)
2812 this.file = (File) ofile;
2815 errorMessage = null;
2816 uniqueSetSuffix = null;
2818 viewportsAdded.clear();
2819 frefedSequence = null;
2821 if (file.startsWith("http://")) {
2822 url = new URL(file);
2824 final URL _url = url;
2825 return new jarInputStreamProvider() {
2828 public JarInputStream getJarInputStream() throws IOException {
2829 if (bytes != null) {
2830 // System.out.println("Jalview2XML: opening byte jarInputStream for bytes.length=" + bytes.length);
2831 return new JarInputStream(new ByteArrayInputStream(bytes));
2834 // System.out.println("Jalview2XML: opening url jarInputStream for " + _url);
2835 return new JarInputStream(_url.openStream());
2837 // System.out.println("Jalview2XML: opening file jarInputStream for " + file);
2838 return new JarInputStream(new FileInputStream(file));
2843 public String getFilename() {
2847 } catch (IOException e) {
2848 e.printStackTrace();
2854 * Recover jalview session from a jalview project archive. Caller may
2855 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
2856 * themselves. Any null fields will be initialised with default values,
2857 * non-null fields are left alone.
2862 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
2864 errorMessage = null;
2865 if (uniqueSetSuffix == null)
2867 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
2869 if (seqRefIds == null)
2873 AlignFrame af = null, _af = null;
2874 IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
2875 Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
2876 final String file = jprovider.getFilename();
2878 List<AlignFrame> alignFrames = new ArrayList<>();
2882 JarInputStream jin = null;
2883 JarEntry jarentry = null;
2887 // Look for all the entry names ending with ".xml"
2888 // This includes all panels and at least one frame.
2889 // Platform.timeCheck(null, Platform.TIME_MARK);
2892 jin = jprovider.getJarInputStream();
2893 for (int i = 0; i < entryCount; i++)
2895 jarentry = jin.getNextJarEntry();
2897 String name = (jarentry == null ? null : jarentry.getName());
2899 // System.out.println("Jalview2XML opening " + name);
2900 if (name != null && name.endsWith(".xml"))
2903 // DataSet for.... is read last.
2906 // The question here is what to do with the two
2907 // .xml files in the jvp file.
2908 // Some number of them, "...Dataset for...", will be the
2909 // Only AlignPanels and will have Viewport.
2910 // One or more will be the source data, with the DBRefs.
2912 // JVP file writing (above) ensures tha the AlignPanels are written
2913 // first, then all relevant datasets (which are
2914 // Jalview.datamodel.Alignment).
2917 // Platform.timeCheck("Jalview2XML JAXB " + name, Platform.TIME_MARK);
2918 JAXBContext jc = JAXBContext
2919 .newInstance("jalview.xml.binding.jalview");
2920 XMLStreamReader streamReader = XMLInputFactory.newInstance()
2921 .createXMLStreamReader(jin);
2922 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
2923 JAXBElement<JalviewModel> jbe = um
2924 .unmarshal(streamReader, JalviewModel.class);
2925 JalviewModel model = jbe.getValue();
2927 if (true) // !skipViewport(object))
2929 // Q: Do we have to load from the model, even if it
2930 // does not have a viewport, could we discover that early on?
2931 // Q: Do we need to load this object?
2932 _af = loadFromObject(model, file, true, jprovider);
2933 // Platform.timeCheck("Jalview2XML.loadFromObject",
2934 // Platform.TIME_MARK);
2938 alignFrames.add(_af);
2940 if (_af != null && model.getViewport().size() > 0)
2943 // That is, this is one of the AlignmentPanel models
2946 // store a reference to the first view
2949 if (_af.getViewport().isGatherViewsHere())
2951 // if this is a gathered view, keep its reference since
2952 // after gathering views, only this frame will remain
2954 gatherToThisFrame.put(_af.getViewport().getSequenceSetId(),
2957 // Save dataset to register mappings once all resolved
2958 importedDatasets.put(
2959 af.getViewport().getAlignment().getDataset(),
2960 af.getViewport().getAlignment().getDataset());
2963 // Platform.timeCheck("JAXB " + name, Platform.TIME_MARK);
2966 else if (jarentry != null)
2968 // Some other file here.
2971 } while (jarentry != null);
2972 // Platform.timeCheck("JAXB loop exit", Platform.TIME_MARK);
2973 resolveFrefedSequences();
2974 // Platform.timeCheck("JAXB resolveFrefed", Platform.TIME_MARK);
2976 } catch (IOException ex)
2978 ex.printStackTrace();
2979 errorMessage = "Couldn't locate Jalview XML file : " + file;
2981 "Exception whilst loading jalview XML file : " + ex + "\n");
2982 } catch (Exception ex)
2984 System.err.println("Parsing as Jalview Version 2 file failed.");
2985 ex.printStackTrace(System.err);
2986 if (attemptversion1parse)
2988 // used to attempt to parse as V1 castor-generated xml
2990 if (Desktop.getInstance() != null)
2992 Desktop.getInstance().stopLoading();
2996 System.out.println("Successfully loaded archive file");
2999 ex.printStackTrace();
3002 "Exception whilst loading jalview XML file : " + ex + "\n");
3003 } catch (OutOfMemoryError e)
3005 // Don't use the OOM Window here
3006 errorMessage = "Out of memory loading jalview XML file";
3007 System.err.println("Out of memory whilst loading jalview XML file");
3008 e.printStackTrace();
3011 for (AlignFrame alf : alignFrames)
3013 alf.alignPanel.setHoldRepaint(false);
3019 * Regather multiple views (with the same sequence set id) to the frame (if
3020 * any) that is flagged as the one to gather to, i.e. convert them to tabbed
3021 * views instead of separate frames. Note this doesn't restore a state where
3022 * some expanded views in turn have tabbed views - the last "first tab" read
3023 * in will play the role of gatherer for all.
3025 for (AlignFrame fr : gatherToThisFrame.values())
3027 Desktop.getInstance().gatherViews(fr);
3030 restoreSplitFrames();
3031 for (AlignmentI ds : importedDatasets.keySet())
3033 if (ds.getCodonFrames() != null)
3035 Desktop.getStructureSelectionManager()
3036 .registerMappings(ds.getCodonFrames());
3039 if (errorMessage != null)
3044 if (Desktop.getInstance() != null)
3046 Desktop.getInstance().stopLoading();
3053 * Try to reconstruct and display SplitFrame windows, where each contains
3054 * complementary dna and protein alignments. Done by pairing up AlignFrame
3055 * objects (created earlier) which have complementary viewport ids associated.
3057 protected void restoreSplitFrames()
3059 List<SplitFrame> gatherTo = new ArrayList<>();
3060 List<AlignFrame> addedToSplitFrames = new ArrayList<>();
3061 Map<String, AlignFrame> dna = new HashMap<>();
3064 * Identify the DNA alignments
3066 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3069 AlignFrame af = candidate.getValue();
3070 if (af.getViewport().getAlignment().isNucleotide())
3072 dna.put(candidate.getKey().getId(), af);
3077 * Try to match up the protein complements
3079 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3082 AlignFrame af = candidate.getValue();
3083 if (!af.getViewport().getAlignment().isNucleotide())
3085 String complementId = candidate.getKey().getComplementId();
3086 // only non-null complements should be in the Map
3087 if (complementId != null && dna.containsKey(complementId))
3089 final AlignFrame dnaFrame = dna.get(complementId);
3090 SplitFrame sf = createSplitFrame(dnaFrame, af);
3091 addedToSplitFrames.add(dnaFrame);
3092 addedToSplitFrames.add(af);
3093 dnaFrame.setMenusForViewport();
3094 af.setMenusForViewport();
3095 if (af.getViewport().isGatherViewsHere())
3104 * Open any that we failed to pair up (which shouldn't happen!) as
3105 * standalone AlignFrame's.
3107 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3110 AlignFrame af = candidate.getValue();
3111 if (!addedToSplitFrames.contains(af))
3113 Viewport view = candidate.getKey();
3114 Desktop.addInternalFrame(af, view.getTitle(),
3115 safeInt(view.getWidth()), safeInt(view.getHeight()));
3116 af.setMenusForViewport();
3117 System.err.println("Failed to restore view " + view.getTitle()
3118 + " to split frame");
3123 * Gather back into tabbed views as flagged.
3125 for (SplitFrame sf : gatherTo)
3127 Desktop.getInstance().gatherViews(sf);
3130 splitFrameCandidates.clear();
3134 * Construct and display one SplitFrame holding DNA and protein alignments.
3137 * @param proteinFrame
3140 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
3141 AlignFrame proteinFrame)
3143 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
3144 String title = MessageManager.getString("label.linked_view_title");
3145 int width = (int) dnaFrame.getBounds().getWidth();
3146 int height = (int) (dnaFrame.getBounds().getHeight()
3147 + proteinFrame.getBounds().getHeight() + 50);
3150 * SplitFrame location is saved to both enclosed frames
3152 splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
3153 Desktop.addInternalFrame(splitFrame, title, width, height);
3156 * And compute cDNA consensus (couldn't do earlier with consensus as
3157 * mappings were not yet present)
3159 proteinFrame.getViewport().alignmentChanged(proteinFrame.alignPanel);
3165 * check errorMessage for a valid error message and raise an error box in the
3166 * GUI or write the current errorMessage to stderr and then clear the error
3169 protected void reportErrors()
3171 reportErrors(false);
3174 protected void reportErrors(final boolean saving)
3176 if (errorMessage != null)
3178 final String finalErrorMessage = errorMessage;
3181 javax.swing.SwingUtilities.invokeLater(new Runnable()
3186 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
3188 "Error " + (saving ? "saving" : "loading")
3190 JvOptionPane.WARNING_MESSAGE);
3196 System.err.println("Problem loading Jalview file: " + errorMessage);
3199 errorMessage = null;
3202 Map<String, String> alreadyLoadedPDB = new HashMap<>();
3205 * when set, local views will be updated from view stored in JalviewXML
3206 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
3207 * sync if this is set to true.
3209 private final boolean updateLocalViews = false;
3212 * Returns the path to a temporary file holding the PDB file for the given PDB
3213 * id. The first time of asking, searches for a file of that name in the
3214 * Jalview project jar, and copies it to a new temporary file. Any repeat
3215 * requests just return the path to the file previously created.
3221 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
3224 if (alreadyLoadedPDB.containsKey(pdbId))
3226 return alreadyLoadedPDB.get(pdbId).toString();
3229 String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
3231 if (tempFile != null)
3233 alreadyLoadedPDB.put(pdbId, tempFile);
3239 * Copies the jar entry of given name to a new temporary file and returns the
3240 * path to the file, or null if the entry is not found.
3243 * @param jarEntryName
3245 * a prefix for the temporary file name, must be at least three
3248 * null or original file - so new file can be given the same suffix
3252 protected String copyJarEntry(jarInputStreamProvider jprovider,
3253 String jarEntryName, String prefix, String origFile)
3255 BufferedReader in = null;
3256 PrintWriter out = null;
3257 String suffix = ".tmp";
3258 if (origFile == null)
3260 origFile = jarEntryName;
3262 int sfpos = origFile.lastIndexOf(".");
3263 if (sfpos > -1 && sfpos < (origFile.length() - 3))
3265 suffix = "." + origFile.substring(sfpos + 1);
3269 JarInputStream jin = jprovider.getJarInputStream();
3271 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
3272 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
3273 * FileInputStream(jprovider)); }
3276 JarEntry entry = null;
3279 entry = jin.getNextJarEntry();
3280 } while (entry != null && !entry.getName().equals(jarEntryName));
3283 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
3284 File outFile = File.createTempFile(prefix, suffix);
3285 outFile.deleteOnExit();
3286 out = new PrintWriter(new FileOutputStream(outFile));
3289 while ((data = in.readLine()) != null)
3294 String t = outFile.getAbsolutePath();
3299 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
3301 } catch (Exception ex)
3303 ex.printStackTrace();
3311 } catch (IOException e)
3325 private class JvAnnotRow
3327 public JvAnnotRow(int i, AlignmentAnnotation jaa)
3334 * persisted version of annotation row from which to take vis properties
3336 public jalview.datamodel.AlignmentAnnotation template;
3339 * original position of the annotation row in the alignment
3345 * Load alignment frame from jalview XML DOM object. For a DOM object that
3346 * includes one or more Viewport elements (one with a title that does NOT
3347 * contain "Dataset for"), create the frame.
3349 * @param jalviewModel
3352 * filename source string
3353 * @param loadTreesAndStructures
3354 * when false only create Viewport
3356 * data source provider
3357 * @return alignment frame created from view stored in DOM
3359 AlignFrame loadFromObject(JalviewModel jalviewModel, String file,
3360 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
3363 // Platform.timeCheck("Jalview2XML.loadFromObject0", Platform.TIME_MARK);
3365 SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet().get(0);
3366 List<Sequence> vamsasSeqs = vamsasSet.getSequence();
3369 // JalviewModelSequence jms = object.getJalviewModelSequence();
3371 // Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
3373 Viewport view = (jalviewModel.getViewport().size() > 0)
3374 ? jalviewModel.getViewport().get(0)
3377 // ////////////////////////////////
3378 // INITIALISE ALIGNMENT SEQUENCESETID AND VIEWID
3381 // If we just load in the same jar file again, the sequenceSetId
3382 // will be the same, and we end up with multiple references
3383 // to the same sequenceSet. We must modify this id on load
3384 // so that each load of the file gives a unique id
3387 * used to resolve correct alignment dataset for alignments with multiple
3390 String uniqueSeqSetId = null;
3391 String viewId = null;
3394 uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
3395 viewId = (view.getId() == null ? null
3396 : view.getId() + uniqueSetSuffix);
3399 // Platform.timeCheck("Jalview2XML.loadFromObject1", Platform.TIME_MARK);
3400 // ////////////////////////////////
3403 List<SequenceI> hiddenSeqs = null;
3405 List<SequenceI> tmpseqs = new ArrayList<>();
3407 boolean multipleView = false;
3408 SequenceI referenceseqForView = null;
3409 // JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
3410 List<JSeq> jseqs = jalviewModel.getJSeq();
3411 int vi = 0; // counter in vamsasSeq array
3412 for (int i = 0; i < jseqs.size(); i++)
3414 JSeq jseq = jseqs.get(i);
3415 String seqId = jseq.getId();
3417 SequenceI tmpSeq = seqRefIds.get(seqId);
3421 if (!incompleteSeqs.containsKey(seqId))
3423 // may not need this check, but keep it for at least 2.9,1 release
3424 if (tmpSeq.getStart() != jseq.getStart()
3425 || tmpSeq.getEnd() != jseq.getEnd())
3428 "Warning JAL-2154 regression: updating start/end for sequence "
3429 + tmpSeq.toString() + " to " + jseq);
3434 incompleteSeqs.remove(seqId);
3436 if (vamsasSeqs.size() > vi
3437 && vamsasSeqs.get(vi).getId().equals(seqId))
3439 // most likely we are reading a dataset XML document so
3440 // update from vamsasSeq section of XML for this sequence
3441 tmpSeq.setName(vamsasSeqs.get(vi).getName());
3442 tmpSeq.setDescription(vamsasSeqs.get(vi).getDescription());
3443 tmpSeq.setSequence(vamsasSeqs.get(vi).getSequence());
3448 // reading multiple views, so vamsasSeq set is a subset of JSeq
3449 multipleView = true;
3451 tmpSeq.setStart(jseq.getStart());
3452 tmpSeq.setEnd(jseq.getEnd());
3453 tmpseqs.add(tmpSeq);
3457 Sequence vamsasSeq = vamsasSeqs.get(vi);
3458 tmpSeq = new jalview.datamodel.Sequence(vamsasSeq.getName(),
3459 vamsasSeq.getSequence());
3460 tmpSeq.setDescription(vamsasSeq.getDescription());
3461 tmpSeq.setStart(jseq.getStart());
3462 tmpSeq.setEnd(jseq.getEnd());
3463 tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
3464 seqRefIds.put(vamsasSeq.getId(), tmpSeq);
3465 tmpseqs.add(tmpSeq);
3469 if (safeBoolean(jseq.isViewreference()))
3471 referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
3474 if (jseq.isHidden() != null && jseq.isHidden().booleanValue())
3476 if (hiddenSeqs == null)
3478 hiddenSeqs = new ArrayList<>();
3481 hiddenSeqs.add(tmpSeq);
3485 // Platform.timeCheck("Jalview2XML.loadFromObject-seq",
3486 // Platform.TIME_MARK);
3488 // Create the alignment object from the sequence set
3489 // ///////////////////////////////
3490 SequenceI[] orderedSeqs = tmpseqs
3491 .toArray(new SequenceI[tmpseqs.size()]);
3493 AlignmentI al = null;
3494 // so we must create or recover the dataset alignment before going further
3495 // ///////////////////////////////
3496 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
3498 // older jalview projects do not have a dataset - so creat alignment and
3500 al = new Alignment(orderedSeqs);
3501 al.setDataset(null);
3505 boolean isdsal = jalviewModel.getViewport().isEmpty();
3508 // we are importing a dataset record, so
3509 // recover reference to an alignment already materialsed as dataset
3510 al = getDatasetFor(vamsasSet.getDatasetId());
3514 // materialse the alignment
3515 al = new Alignment(orderedSeqs);
3519 addDatasetRef(vamsasSet.getDatasetId(), al);
3522 // finally, verify all data in vamsasSet is actually present in al
3523 // passing on flag indicating if it is actually a stored dataset
3524 recoverDatasetFor(vamsasSet, al, isdsal, uniqueSeqSetId);
3527 // Platform.timeCheck("Jalview2XML.loadFromObject-align",
3528 // Platform.TIME_MARK);
3529 if (referenceseqForView != null)
3531 al.setSeqrep(referenceseqForView);
3533 // / Add the alignment properties
3534 for (int i = 0; i < vamsasSet.getSequenceSetProperties().size(); i++)
3536 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties()
3538 al.setProperty(ssp.getKey(), ssp.getValue());
3541 // Platform.timeCheck("Jalview2XML.loadFromObject-setseqprop",
3542 // Platform.TIME_MARK);
3543 // ///////////////////////////////
3545 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
3548 // load sequence features, database references and any associated PDB
3549 // structures for the alignment
3551 // prior to 2.10, this part would only be executed the first time a
3552 // sequence was encountered, but not afterwards.
3553 // now, for 2.10 projects, this is also done if the xml doc includes
3554 // dataset sequences not actually present in any particular view.
3556 // Platform.timeCheck("J2XML features0", Platform.TIME_RESET);
3557 for (int i = 0; i < vamsasSeqs.size(); i++)
3559 JSeq jseq = jseqs.get(i);
3560 if (jseq.getFeatures().size() > 0)
3562 List<Feature> features = jseq.getFeatures();
3563 for (int f = 0; f < features.size(); f++)
3565 Feature feat = features.get(f);
3566 SequenceFeature sf = new SequenceFeature(feat.getType(),
3567 feat.getDescription(), feat.getBegin(), feat.getEnd(),
3568 safeFloat(feat.getScore()), feat.getFeatureGroup());
3569 sf.setStatus(feat.getStatus());
3572 * load any feature attributes - include map-valued attributes
3574 Map<String, Map<String, String>> mapAttributes = new HashMap<>();
3575 for (int od = 0; od < feat.getOtherData().size(); od++)
3577 OtherData keyValue = feat.getOtherData().get(od);
3578 String attributeName = keyValue.getKey();
3579 String attributeValue = keyValue.getValue();
3580 if (attributeName.startsWith("LINK"))
3582 sf.addLink(attributeValue);
3586 String subAttribute = keyValue.getKey2();
3587 if (subAttribute == null)
3589 // simple string-valued attribute
3590 sf.setValue(attributeName, attributeValue);
3594 // attribute 'key' has sub-attribute 'key2'
3595 if (!mapAttributes.containsKey(attributeName))
3597 mapAttributes.put(attributeName, new HashMap<>());
3599 mapAttributes.get(attributeName).put(subAttribute,
3604 for (Entry<String, Map<String, String>> mapAttribute : mapAttributes
3607 sf.setValue(mapAttribute.getKey(), mapAttribute.getValue());
3610 // adds feature to datasequence's feature set (since Jalview 2.10)
3611 // Platform.timeCheck(null, Platform.TIME_SET);
3612 al.getSequenceAt(i).addSequenceFeature(sf);
3613 // Platform.timeCheck(null, Platform.TIME_MARK);
3616 if (vamsasSeqs.get(i).getDBRef().size() > 0)
3618 // adds dbrefs to datasequence's set (since Jalview 2.10)
3620 al.getSequenceAt(i).getDatasetSequence() == null
3621 ? al.getSequenceAt(i)
3622 : al.getSequenceAt(i).getDatasetSequence(),
3625 if (jseq.getPdbids().size() > 0)
3627 List<Pdbids> ids = jseq.getPdbids();
3628 for (int p = 0; p < ids.size(); p++)
3630 Pdbids pdbid = ids.get(p);
3631 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
3632 entry.setId(pdbid.getId());
3633 if (pdbid.getType() != null)
3635 if (PDBEntry.Type.getType(pdbid.getType()) != null)
3637 entry.setType(PDBEntry.Type.getType(pdbid.getType()));
3641 entry.setType(PDBEntry.Type.FILE);
3644 // jprovider is null when executing 'New View'
3645 if (pdbid.getFile() != null && jprovider != null)
3647 if (!pdbloaded.containsKey(pdbid.getFile()))
3649 entry.setFile(loadPDBFile(jprovider, pdbid.getId(),
3654 entry.setFile(pdbloaded.get(pdbid.getId()).toString());
3658 if (pdbid.getPdbentryItem() != null)
3660 for (PdbentryItem item : pdbid.getPdbentryItem())
3662 for (Property pr : item.getProperty())
3664 entry.setProperty(pr.getName(), pr.getValue());
3669 for (Property prop : pdbid.getProperty())
3671 entry.setProperty(prop.getName(), prop.getValue());
3673 Desktop.getStructureSelectionManager()
3674 .registerPDBEntry(entry);
3675 // adds PDBEntry to datasequence's set (since Jalview 2.10)
3676 if (al.getSequenceAt(i).getDatasetSequence() != null)
3678 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
3682 al.getSequenceAt(i).addPDBId(entry);
3689 // Platform.timeCheck("features done", Platform.TIME_GET);
3690 // Platform.timeCheck("Jalview2XML.loadFromObject-endmultiview",
3691 // Platform.TIME_MARK);
3692 } // end !multipleview
3694 // ///////////////////////////////
3695 // LOAD SEQUENCE MAPPINGS
3697 if (vamsasSet.getAlcodonFrame().size() > 0)
3699 // TODO Potentially this should only be done once for all views of an
3701 List<AlcodonFrame> alc = vamsasSet.getAlcodonFrame();
3702 for (int i = 0; i < alc.size(); i++)
3704 AlignedCodonFrame cf = new AlignedCodonFrame();
3705 if (alc.get(i).getAlcodMap().size() > 0)
3707 List<AlcodMap> maps = alc.get(i).getAlcodMap();
3708 for (int m = 0; m < maps.size(); m++)
3710 AlcodMap map = maps.get(m);
3711 SequenceI dnaseq = seqRefIds.get(map.getDnasq());
3713 jalview.datamodel.Mapping mapping = null;
3714 // attach to dna sequence reference.
3715 if (map.getMapping() != null)
3717 mapping = addMapping(map.getMapping());
3718 if (dnaseq != null && mapping.getTo() != null)
3720 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
3726 newAlcodMapRef(map.getDnasq(), cf, mapping));
3730 al.addCodonFrame(cf);
3733 // Platform.timeCheck("Jalview2XML.loadFromObject-seqmap",
3734 // Platform.TIME_MARK);
3737 // ////////////////////////////////
3739 List<JvAnnotRow> autoAlan = new ArrayList<>();
3742 * store any annotations which forward reference a group's ID
3744 Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
3746 if (vamsasSet.getAnnotation().size()/*Count()*/ > 0)
3748 List<Annotation> an = vamsasSet.getAnnotation();
3750 for (int i = 0; i < an.size(); i++)
3752 Annotation annotation = an.get(i);
3755 * test if annotation is automatically calculated for this view only
3757 boolean autoForView = false;
3758 if (annotation.getLabel().equals("Quality")
3759 || annotation.getLabel().equals("Conservation")
3760 || annotation.getLabel().equals("Consensus"))
3762 // Kludge for pre 2.5 projects which lacked the autocalculated flag
3764 // JAXB has no has() test; schema defaults value to false
3765 // if (!annotation.hasAutoCalculated())
3767 // annotation.setAutoCalculated(true);
3770 if (autoForView || annotation.isAutoCalculated())
3772 // remove ID - we don't recover annotation from other views for
3773 // view-specific annotation
3774 annotation.setId(null);
3777 // set visibility for other annotation in this view
3778 String annotationId = annotation.getId();
3779 if (annotationId != null && annotationIds.containsKey(annotationId))
3781 AlignmentAnnotation jda = annotationIds.get(annotationId);
3782 // in principle Visible should always be true for annotation displayed
3783 // in multiple views
3784 if (annotation.isVisible() != null)
3786 jda.visible = annotation.isVisible();
3789 al.addAnnotation(jda);
3793 // Construct new annotation from model.
3794 List<AnnotationElement> ae = annotation.getAnnotationElement();
3795 // System.err.println(
3796 // "Jalview2XML processing " + ae.size() + " annotations");
3798 jalview.datamodel.Annotation[] anot = null;
3799 java.awt.Color firstColour = null;
3801 if (!annotation.isScoreOnly())
3803 anot = new jalview.datamodel.Annotation[al.getWidth()];
3804 for (int aa = 0; aa < ae.size() && aa < anot.length; aa++)
3806 AnnotationElement annElement = ae.get(aa);
3807 anpos = annElement.getPosition();
3809 if (anpos >= anot.length)
3814 float value = safeFloat(annElement.getValue());
3815 anot[anpos] = new jalview.datamodel.Annotation(
3816 annElement.getDisplayCharacter(),
3817 annElement.getDescription(),
3818 (annElement.getSecondaryStructure() == null
3819 || annElement.getSecondaryStructure()
3823 .getSecondaryStructure()
3826 anot[anpos].colour = new Color(safeInt(annElement.getColour()));
3827 if (firstColour == null)
3829 firstColour = anot[anpos].colour;
3833 // create the new AlignmentAnnotation
3834 jalview.datamodel.AlignmentAnnotation jaa = null;
3836 if (annotation.isGraph())
3838 float llim = 0, hlim = 0;
3839 // if (autoForView || an[i].isAutoCalculated()) {
3842 jaa = new jalview.datamodel.AlignmentAnnotation(
3843 annotation.getLabel(), annotation.getDescription(), anot,
3844 llim, hlim, safeInt(annotation.getGraphType()));
3846 jaa.graphGroup = safeInt(annotation.getGraphGroup());
3847 jaa._linecolour = firstColour;
3848 if (annotation.getThresholdLine() != null)
3850 jaa.setThreshold(new jalview.datamodel.GraphLine(
3851 safeFloat(annotation.getThresholdLine().getValue()),
3852 annotation.getThresholdLine().getLabel(),
3853 new java.awt.Color(safeInt(
3854 annotation.getThresholdLine().getColour()))));
3856 if (autoForView || annotation.isAutoCalculated())
3858 // Hardwire the symbol display line to ensure that labels for
3859 // histograms are displayed
3865 jaa = new jalview.datamodel.AlignmentAnnotation(
3866 annotation.getLabel(), annotation.getDescription(), anot);
3867 jaa._linecolour = firstColour;
3869 // register new annotation
3870 // Annotation graphs such as Conservation will not have id.
3871 if (annotation.getId() != null)
3873 annotationIds.put(annotation.getId(), jaa);
3874 jaa.annotationId = annotation.getId();
3876 // recover sequence association
3877 String sequenceRef = annotation.getSequenceRef();
3878 if (sequenceRef != null)
3880 // from 2.9 sequenceRef is to sequence id (JAL-1781)
3881 SequenceI sequence = seqRefIds.get(sequenceRef);
3882 if (sequence == null)
3884 // in pre-2.9 projects sequence ref is to sequence name
3885 sequence = al.findName(sequenceRef);
3887 if (sequence != null)
3889 jaa.createSequenceMapping(sequence, 1, true);
3890 sequence.addAlignmentAnnotation(jaa);
3893 // and make a note of any group association
3894 if (annotation.getGroupRef() != null
3895 && annotation.getGroupRef().length() > 0)
3897 List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
3898 .get(annotation.getGroupRef());
3901 aal = new ArrayList<>();
3902 groupAnnotRefs.put(annotation.getGroupRef(), aal);
3907 if (annotation.getScore() != null)
3909 jaa.setScore(annotation.getScore().doubleValue());
3911 if (annotation.isVisible() != null)
3913 jaa.visible = annotation.isVisible().booleanValue();
3916 if (annotation.isCentreColLabels() != null)
3918 jaa.centreColLabels = annotation.isCentreColLabels()
3922 if (annotation.isScaleColLabels() != null)
3924 jaa.scaleColLabel = annotation.isScaleColLabels().booleanValue();
3926 if (annotation.isAutoCalculated())
3928 // newer files have an 'autoCalculated' flag and store calculation
3929 // state in viewport properties
3930 jaa.autoCalculated = true; // means annotation will be marked for
3931 // update at end of load.
3933 if (annotation.getGraphHeight() != null)
3935 jaa.graphHeight = annotation.getGraphHeight().intValue();
3937 jaa.belowAlignment = annotation.isBelowAlignment();
3938 jaa.setCalcId(annotation.getCalcId());
3939 if (annotation.getProperty().size() > 0)
3941 for (Annotation.Property prop : annotation
3944 jaa.setProperty(prop.getName(), prop.getValue());
3947 if (jaa.autoCalculated)
3949 autoAlan.add(new JvAnnotRow(i, jaa));
3952 // if (!autoForView)
3954 // add autocalculated group annotation and any user created annotation
3956 al.addAnnotation(jaa);
3959 // Platform.timeCheck("Jalview2XML.loadFromObject-annot",
3960 // Platform.TIME_MARK);
3962 // ///////////////////////
3964 // Create alignment markup and styles for this view
3965 if (jalviewModel.getJGroup().size() > 0)
3967 List<JGroup> groups = jalviewModel.getJGroup();
3968 boolean addAnnotSchemeGroup = false;
3969 for (int i = 0; i < groups.size(); i++)
3971 JGroup jGroup = groups.get(i);
3972 ColourSchemeI cs = null;
3973 if (jGroup.getColour() != null)
3975 if (jGroup.getColour().startsWith("ucs"))
3977 cs = getUserColourScheme(jalviewModel, jGroup.getColour());
3979 else if (jGroup.getColour().equals("AnnotationColourGradient")
3980 && jGroup.getAnnotationColours() != null)
3982 addAnnotSchemeGroup = true;
3986 cs = ColourSchemeProperty.getColourScheme(null, al,
3987 jGroup.getColour());
3990 int pidThreshold = safeInt(jGroup.getPidThreshold());
3992 Vector<SequenceI> seqs = new Vector<>();
3994 for (int s = 0; s < jGroup.getSeq().size(); s++)
3996 String seqId = jGroup.getSeq().get(s);
3997 SequenceI ts = seqRefIds.get(seqId);
4001 seqs.addElement(ts);
4005 if (seqs.size() < 1)
4010 SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
4011 safeBoolean(jGroup.isDisplayBoxes()),
4012 safeBoolean(jGroup.isDisplayText()),
4013 safeBoolean(jGroup.isColourText()),
4014 safeInt(jGroup.getStart()), safeInt(jGroup.getEnd()));
4015 sg.getGroupColourScheme().setThreshold(pidThreshold, true);
4016 sg.getGroupColourScheme()
4017 .setConservationInc(safeInt(jGroup.getConsThreshold()));
4018 sg.setOutlineColour(new Color(safeInt(jGroup.getOutlineColour())));
4020 sg.textColour = new Color(safeInt(jGroup.getTextCol1()));
4021 sg.textColour2 = new Color(safeInt(jGroup.getTextCol2()));
4022 sg.setShowNonconserved(safeBoolean(jGroup.isShowUnconserved()));
4023 sg.thresholdTextColour = safeInt(jGroup.getTextColThreshold());
4024 // attributes with a default in the schema are never null
4025 sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
4026 sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
4027 sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
4028 sg.setIgnoreGapsConsensus(jGroup.isIgnoreGapsinConsensus());
4029 if (jGroup.getConsThreshold() != null
4030 && jGroup.getConsThreshold().intValue() != 0)
4032 Conservation c = new Conservation("All", sg.getSequences(null), 0,
4035 c.verdict(false, 25);
4036 sg.cs.setConservation(c);
4039 if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
4041 // re-instate unique group/annotation row reference
4042 List<AlignmentAnnotation> jaal = groupAnnotRefs
4043 .get(jGroup.getId());
4046 for (AlignmentAnnotation jaa : jaal)
4049 if (jaa.autoCalculated)
4051 // match up and try to set group autocalc alignment row for this
4053 if (jaa.label.startsWith("Consensus for "))
4055 sg.setConsensus(jaa);
4057 // match up and try to set group autocalc alignment row for this
4059 if (jaa.label.startsWith("Conservation for "))
4061 sg.setConservationRow(jaa);
4068 if (addAnnotSchemeGroup)
4070 // reconstruct the annotation colourscheme
4071 sg.setColourScheme(constructAnnotationColour(
4072 jGroup.getAnnotationColours(), null, al, jalviewModel, false));
4075 // Platform.timeCheck("Jalview2XML.loadFromObject-groups",
4076 // Platform.TIME_MARK);
4080 // only dataset in this model, so just return.
4083 // ///////////////////////////////
4086 // now check to see if we really need to create a new viewport.
4087 if (multipleView && viewportsAdded.size() == 0)
4089 // We recovered an alignment for which a viewport already exists.
4090 // TODO: fix up any settings necessary for overlaying stored state onto
4091 // state recovered from another document. (may not be necessary).
4092 // we may need a binding from a viewport in memory to one recovered from
4094 // and then recover its containing af to allow the settings to be applied.
4095 // TODO: fix for vamsas demo
4097 "About to recover a viewport for existing alignment: Sequence set ID is "
4099 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
4100 if (seqsetobj != null)
4102 if (seqsetobj instanceof String)
4104 uniqueSeqSetId = (String) seqsetobj;
4106 "Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
4112 "Warning : Collision between sequence set ID string and existing jalview object mapping.");
4116 // Platform.timeCheck("Jalview2XML.loadFromObject-viewport",
4117 // Platform.TIME_MARK);
4120 * indicate that annotation colours are applied across all groups (pre
4121 * Jalview 2.8.1 behaviour)
4123 boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan("2.8.1",
4124 jalviewModel.getVersion());
4126 AlignFrame af = null;
4127 AlignmentPanel ap = null;
4128 AlignViewport av = null;
4131 // Check to see if this alignment already has a view id == viewId
4132 jalview.gui.AlignmentPanel views[] = Desktop
4133 .getAlignmentPanels(uniqueSeqSetId);
4134 if (views != null && views.length > 0)
4136 for (int v = 0; v < views.length; v++)
4140 if (av.getViewId().equalsIgnoreCase(viewId))
4142 // recover the existing alignpanel, alignframe, viewport
4145 // TODO: could even skip resetting view settings if we don't want to
4146 // change the local settings from other jalview processes
4154 af = loadViewport(file, jseqs, hiddenSeqs, al, jalviewModel, view,
4155 uniqueSeqSetId, viewId, autoAlan);
4156 av = af.getViewport();
4157 // note that this only retrieves the most recently accessed
4158 // tab of an AlignFrame.
4163 * Load any trees, PDB structures and viewers
4165 * Not done if flag is false (when this method is used for New View)
4167 final AlignFrame af0 = af;
4168 final AlignViewport av0 = av;
4169 final AlignmentPanel ap0 = ap;
4170 // Platform.timeCheck("Jalview2XML.loadFromObject-beforetree",
4171 // Platform.TIME_MARK);
4172 if (loadTreesAndStructures)
4174 if (!jalviewModel.getTree().isEmpty())
4176 SwingUtilities.invokeLater(new Runnable()
4181 // Platform.timeCheck(null, Platform.TIME_MARK);
4182 loadTrees(jalviewModel, view, af0, av0, ap0);
4183 // Platform.timeCheck("Jalview2XML.loadTrees", Platform.TIME_MARK);
4187 if (!jalviewModel.getPcaViewer().isEmpty())
4189 SwingUtilities.invokeLater(new Runnable()
4194 // Platform.timeCheck(null, Platform.TIME_MARK);
4195 loadPCAViewers(jalviewModel, ap0);
4196 // Platform.timeCheck("Jalview2XML.loadPCA", Platform.TIME_MARK);
4200 SwingUtilities.invokeLater(new Runnable()
4205 // Platform.timeCheck(null, Platform.TIME_MARK);
4206 loadPDBStructures(jprovider, jseqs, af0, ap0);
4207 // Platform.timeCheck("Jalview2XML.loadPDB", Platform.TIME_MARK);
4210 SwingUtilities.invokeLater(new Runnable()
4215 loadRnaViewers(jprovider, jseqs, ap0);
4219 // and finally return.
4220 // but do not set holdRepaint true just yet, because this could be the
4221 // initial frame with just its dataset.
4226 * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
4227 * panel is restored from separate jar entries, two (gapped and trimmed) per
4228 * sequence and secondary structure.
4230 * Currently each viewer shows just one sequence and structure (gapped and
4231 * trimmed), however this method is designed to support multiple sequences or
4232 * structures in viewers if wanted in future.
4238 protected void loadRnaViewers(jarInputStreamProvider jprovider,
4239 List<JSeq> jseqs, AlignmentPanel ap)
4242 * scan the sequences for references to viewers; create each one the first
4243 * time it is referenced, add Rna models to existing viewers
4245 for (JSeq jseq : jseqs)
4247 for (int i = 0; i < jseq.getRnaViewer().size(); i++)
4249 RnaViewer viewer = jseq.getRnaViewer().get(i);
4250 AppVarna appVarna = findOrCreateVarnaViewer(viewer, uniqueSetSuffix,
4253 for (int j = 0; j < viewer.getSecondaryStructure().size(); j++)
4255 SecondaryStructure ss = viewer.getSecondaryStructure().get(j);
4256 SequenceI seq = seqRefIds.get(jseq.getId());
4257 AlignmentAnnotation ann = this.annotationIds
4258 .get(ss.getAnnotationId());
4261 * add the structure to the Varna display (with session state copied
4262 * from the jar to a temporary file)
4264 boolean gapped = safeBoolean(ss.isGapped());
4265 String rnaTitle = ss.getTitle();
4266 String sessionState = ss.getViewerState();
4267 String tempStateFile = copyJarEntry(jprovider, sessionState,
4269 RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
4270 appVarna.addModelSession(rna, rnaTitle, tempStateFile);
4272 appVarna.setInitialSelection(safeInt(viewer.getSelectedRna()));
4278 * Locate and return an already instantiated matching AppVarna, or create one
4282 * @param viewIdSuffix
4286 protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
4287 String viewIdSuffix, AlignmentPanel ap)
4290 * on each load a suffix is appended to the saved viewId, to avoid conflicts
4291 * if load is repeated
4293 String postLoadId = viewer.getViewId() + viewIdSuffix;
4294 for (JInternalFrame frame : getAllFrames())
4296 if (frame instanceof AppVarna)
4298 AppVarna varna = (AppVarna) frame;
4299 if (postLoadId.equals(varna.getViewId()))
4301 // this viewer is already instantiated
4302 // could in future here add ap as another 'parent' of the
4303 // AppVarna window; currently just 1-to-many
4310 * viewer not found - make it
4312 RnaViewerModel model = new RnaViewerModel(postLoadId, viewer.getTitle(),
4313 safeInt(viewer.getXpos()), safeInt(viewer.getYpos()),
4314 safeInt(viewer.getWidth()), safeInt(viewer.getHeight()),
4315 safeInt(viewer.getDividerLocation()));
4316 AppVarna varna = new AppVarna(model, ap);
4322 * Load any saved trees
4330 protected void loadTrees(JalviewModel jm, Viewport view,
4331 AlignFrame af, AlignViewport av, AlignmentPanel ap)
4333 // TODO result of automated refactoring - are all these parameters needed?
4336 for (int t = 0; t < jm.getTree().size(); t++)
4339 Tree tree = jm.getTree().get(t);
4341 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
4344 tp = af.showNewickTree(new NewickFile(tree.getNewick()),
4345 tree.getTitle(), safeInt(tree.getWidth()),
4346 safeInt(tree.getHeight()), safeInt(tree.getXpos()),
4347 safeInt(tree.getYpos()));
4348 if (tree.getId() != null)
4350 // perhaps bind the tree id to something ?
4355 // update local tree attributes ?
4356 // TODO: should check if tp has been manipulated by user - if so its
4357 // settings shouldn't be modified
4358 tp.setTitle(tree.getTitle());
4359 tp.setBounds(new Rectangle(safeInt(tree.getXpos()),
4360 safeInt(tree.getYpos()), safeInt(tree.getWidth()),
4361 safeInt(tree.getHeight())));
4362 tp.setViewport(av); // af.viewport;
4363 // TODO: verify 'associate with all views' works still
4364 tp.getTreeCanvas().setViewport(av); // af.viewport;
4365 tp.getTreeCanvas().setAssociatedPanel(ap); // af.alignPanel;
4367 tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
4370 warn("There was a problem recovering stored Newick tree: \n"
4371 + tree.getNewick());
4375 tp.fitToWindow.setState(safeBoolean(tree.isFitToWindow()));
4376 tp.fitToWindow_actionPerformed(null);
4378 if (tree.getFontName() != null)
4381 new Font(tree.getFontName(), safeInt(tree.getFontStyle()),
4382 safeInt(tree.getFontSize())));
4387 new Font(view.getFontName(), safeInt(view.getFontStyle()),
4388 safeInt(view.getFontSize())));
4391 tp.showPlaceholders(safeBoolean(tree.isMarkUnlinked()));
4392 tp.showBootstrap(safeBoolean(tree.isShowBootstrap()));
4393 tp.showDistances(safeBoolean(tree.isShowDistances()));
4395 tp.getTreeCanvas().setThreshold(safeFloat(tree.getThreshold()));
4397 if (safeBoolean(tree.isCurrentTree()))
4399 af.getViewport().setCurrentTree(tp.getTree());
4403 } catch (Exception ex)
4405 ex.printStackTrace();
4410 * Load and link any saved structure viewers.
4417 protected void loadPDBStructures(jarInputStreamProvider jprovider,
4418 List<JSeq> jseqs, AlignFrame af, AlignmentPanel ap)
4421 * Run through all PDB ids on the alignment, and collect mappings between
4422 * distinct view ids and all sequences referring to that view.
4424 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
4426 for (int i = 0; i < jseqs.size(); i++)
4428 JSeq jseq = jseqs.get(i);
4429 if (jseq.getPdbids().size() > 0)
4431 List<Pdbids> ids = jseq.getPdbids();
4432 for (int p = 0; p < ids.size(); p++)
4434 Pdbids pdbid = ids.get(p);
4435 final int structureStateCount = pdbid.getStructureState().size();
4436 for (int s = 0; s < structureStateCount; s++)
4438 // check to see if we haven't already created this structure view
4439 final StructureState structureState = pdbid
4440 .getStructureState().get(s);
4441 String sviewid = (structureState.getViewId() == null) ? null
4442 : structureState.getViewId() + uniqueSetSuffix;
4443 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
4444 // Originally : pdbid.getFile()
4445 // : TODO: verify external PDB file recovery still works in normal
4446 // jalview project load
4448 loadPDBFile(jprovider, pdbid.getId(), pdbid.getFile()));
4449 jpdb.setId(pdbid.getId());
4451 int x = safeInt(structureState.getXpos());
4452 int y = safeInt(structureState.getYpos());
4453 int width = safeInt(structureState.getWidth());
4454 int height = safeInt(structureState.getHeight());
4456 // Probably don't need to do this anymore...
4457 // Desktop.getDesktop().getComponentAt(x, y);
4458 // TODO: NOW: check that this recovers the PDB file correctly.
4459 String pdbFile = loadPDBFile(jprovider, pdbid.getId(),
4461 jalview.datamodel.SequenceI seq = seqRefIds
4462 .get(jseq.getId() + "");
4463 if (sviewid == null)
4465 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width + ","
4468 if (!structureViewers.containsKey(sviewid))
4470 structureViewers.put(sviewid,
4471 new StructureViewerModel(x, y, width, height, false,
4472 false, true, structureState.getViewId(),
4473 structureState.getType()));
4474 // Legacy pre-2.7 conversion JAL-823 :
4475 // do not assume any view has to be linked for colour by
4479 // assemble String[] { pdb files }, String[] { id for each
4480 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
4481 // seqs_file 2}, boolean[] {
4482 // linkAlignPanel,superposeWithAlignpanel}} from hash
4483 StructureViewerModel jmoldat = structureViewers.get(sviewid);
4484 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
4485 || structureState.isAlignwithAlignPanel());
4488 * Default colour by linked panel to false if not specified (e.g.
4489 * for pre-2.7 projects)
4491 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
4492 colourWithAlignPanel |= structureState.isColourwithAlignPanel();
4493 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
4496 * Default colour by viewer to true if not specified (e.g. for
4499 boolean colourByViewer = jmoldat.isColourByViewer();
4500 colourByViewer &= structureState.isColourByJmol();
4501 jmoldat.setColourByViewer(colourByViewer);
4503 if (jmoldat.getStateData().length() < structureState
4504 .getValue()/*Content()*/.length())
4506 jmoldat.setStateData(structureState.getValue());// Content());
4508 if (pdbid.getFile() != null)
4510 File mapkey = new File(pdbid.getFile());
4511 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
4512 if (seqstrmaps == null)
4514 jmoldat.getFileData().put(mapkey,
4515 seqstrmaps = jmoldat.new StructureData(pdbFile,
4518 if (!seqstrmaps.getSeqList().contains(seq))
4520 seqstrmaps.getSeqList().add(seq);
4526 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");
4533 // Instantiate the associated structure views
4534 for (Entry<String, StructureViewerModel> entry : structureViewers
4539 createOrLinkStructureViewer(entry, af, ap, jprovider);
4540 } catch (Exception e)
4543 "Error loading structure viewer: " + e.getMessage());
4544 // failed - try the next one
4556 protected void createOrLinkStructureViewer(
4557 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
4558 AlignmentPanel ap, jarInputStreamProvider jprovider)
4560 final StructureViewerModel stateData = viewerData.getValue();
4563 * Search for any viewer windows already open from other alignment views
4564 * that exactly match the stored structure state
4566 StructureViewerBase comp = findMatchingViewer(viewerData);
4570 linkStructureViewer(ap, comp, stateData);
4575 * From 2.9: stateData.type contains JMOL or CHIMERA, data is in jar entry
4576 * "viewer_"+stateData.viewId
4578 if (ViewerType.CHIMERA.toString().equals(stateData.getType()))
4580 createChimeraViewer(viewerData, af, jprovider);
4585 * else Jmol (if pre-2.9, stateData contains JMOL state string)
4587 createJmolViewer(viewerData, af, jprovider);
4592 * Create a new Chimera viewer.
4598 protected void createChimeraViewer(
4599 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
4600 jarInputStreamProvider jprovider)
4602 StructureViewerModel data = viewerData.getValue();
4603 String chimeraSessionFile = data.getStateData();
4606 * Copy Chimera session from jar entry "viewer_"+viewId to a temporary file
4608 * NB this is the 'saved' viewId as in the project file XML, _not_ the
4609 * 'uniquified' sviewid used to reconstruct the viewer here
4611 String viewerJarEntryName = getViewerJarEntryName(data.getViewId());
4612 chimeraSessionFile = copyJarEntry(jprovider, viewerJarEntryName,
4615 Set<Entry<File, StructureData>> fileData = data.getFileData()
4617 List<PDBEntry> pdbs = new ArrayList<>();
4618 List<SequenceI[]> allseqs = new ArrayList<>();
4619 for (Entry<File, StructureData> pdb : fileData)
4621 String filePath = pdb.getValue().getFilePath();
4622 String pdbId = pdb.getValue().getPdbId();
4623 // pdbs.add(new PDBEntry(filePath, pdbId));
4624 pdbs.add(new PDBEntry(pdbId, null, PDBEntry.Type.PDB, filePath));
4625 final List<SequenceI> seqList = pdb.getValue().getSeqList();
4626 SequenceI[] seqs = seqList.toArray(new SequenceI[seqList.size()]);
4630 boolean colourByChimera = data.isColourByViewer();
4631 boolean colourBySequence = data.isColourWithAlignPanel();
4633 // TODO use StructureViewer as a factory here, see JAL-1761
4634 final PDBEntry[] pdbArray = pdbs.toArray(new PDBEntry[pdbs.size()]);
4635 final SequenceI[][] seqsArray = allseqs
4636 .toArray(new SequenceI[allseqs.size()][]);
4637 String newViewId = viewerData.getKey();
4639 ChimeraViewFrame cvf = new ChimeraViewFrame(chimeraSessionFile,
4640 af.alignPanel, pdbArray, seqsArray, colourByChimera,
4641 colourBySequence, newViewId);
4642 cvf.setSize(data.getWidth(), data.getHeight());
4643 cvf.setLocation(data.getX(), data.getY());
4647 * Create a new Jmol window. First parse the Jmol state to translate filenames
4648 * loaded into the view, and record the order in which files are shown in the
4649 * Jmol view, so we can add the sequence mappings in same order.
4655 protected void createJmolViewer(
4656 final Entry<String, StructureViewerModel> viewerData,
4657 AlignFrame af, jarInputStreamProvider jprovider)
4659 final StructureViewerModel svattrib = viewerData.getValue();
4660 String state = svattrib.getStateData();
4663 * Pre-2.9: state element value is the Jmol state string
4665 * 2.9+: @type is "JMOL", state data is in a Jar file member named "viewer_"
4668 if (ViewerType.JMOL.toString().equals(svattrib.getType()))
4670 state = readJarEntry(jprovider,
4671 getViewerJarEntryName(svattrib.getViewId()));
4674 List<String> pdbfilenames = new ArrayList<>();
4675 List<SequenceI[]> seqmaps = new ArrayList<>();
4676 List<String> pdbids = new ArrayList<>();
4677 StringBuilder newFileLoc = new StringBuilder(64);
4678 int cp = 0, ncp, ecp;
4679 Map<File, StructureData> oldFiles = svattrib.getFileData();
4680 while ((ncp = state.indexOf("load ", cp)) > -1)
4684 // look for next filename in load statement
4685 newFileLoc.append(state.substring(cp,
4686 ncp = (state.indexOf("\"", ncp + 1) + 1)));
4687 String oldfilenam = state.substring(ncp,
4688 ecp = state.indexOf("\"", ncp));
4689 // recover the new mapping data for this old filename
4690 // have to normalize filename - since Jmol and jalview do
4692 // translation differently.
4693 StructureData filedat = oldFiles.get(new File(oldfilenam));
4694 if (filedat == null)
4696 String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
4697 filedat = oldFiles.get(new File(reformatedOldFilename));
4699 newFileLoc.append(Platform.escapeString(filedat.getFilePath()));
4700 pdbfilenames.add(filedat.getFilePath());
4701 pdbids.add(filedat.getPdbId());
4702 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4703 newFileLoc.append("\"");
4704 cp = ecp + 1; // advance beyond last \" and set cursor so we can
4705 // look for next file statement.
4706 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
4710 // just append rest of state
4711 newFileLoc.append(state.substring(cp));
4715 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
4716 newFileLoc = new StringBuilder(state);
4717 newFileLoc.append("; load append ");
4718 for (File id : oldFiles.keySet())
4720 // add this and any other pdb files that should be present in
4722 StructureData filedat = oldFiles.get(id);
4723 newFileLoc.append(filedat.getFilePath());
4724 pdbfilenames.add(filedat.getFilePath());
4725 pdbids.add(filedat.getPdbId());
4726 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4727 newFileLoc.append(" \"");
4728 newFileLoc.append(filedat.getFilePath());
4729 newFileLoc.append("\"");
4732 newFileLoc.append(";");
4735 if (newFileLoc.length() == 0)
4739 int histbug = newFileLoc.indexOf("history = ");
4743 * change "history = [true|false];" to "history = [1|0];"
4746 int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";", histbug);
4747 String val = (diff == -1) ? null
4748 : newFileLoc.substring(histbug, diff);
4749 if (val != null && val.length() >= 4)
4751 if (val.contains("e")) // eh? what can it be?
4753 if (val.trim().equals("true"))
4761 newFileLoc.replace(histbug, diff, val);
4766 final String[] pdbf = pdbfilenames
4767 .toArray(new String[pdbfilenames.size()]);
4768 final String[] id = pdbids.toArray(new String[pdbids.size()]);
4769 final SequenceI[][] sq = seqmaps
4770 .toArray(new SequenceI[seqmaps.size()][]);
4771 final String fileloc = newFileLoc.toString();
4772 final String sviewid = viewerData.getKey();
4773 final AlignFrame alf = af;
4774 final Rectangle rect = new Rectangle(svattrib.getX(), svattrib.getY(),
4775 svattrib.getWidth(), svattrib.getHeight());
4778 javax.swing.SwingUtilities.invokeLater(new Runnable()
4783 JalviewStructureDisplayI sview = null;
4786 sview = new StructureViewer(
4787 alf.alignPanel.getStructureSelectionManager())
4788 .createView(StructureViewer.ViewerType.JMOL,
4789 pdbf, id, sq, alf.alignPanel, svattrib,
4790 fileloc, rect, sviewid);
4791 addNewStructureViewer(sview);
4792 } catch (OutOfMemoryError ex)
4794 new OOMWarning("restoring structure view for PDB id " + id,
4795 (OutOfMemoryError) ex.getCause());
4796 if (sview != null && sview.isVisible())
4798 sview.closeViewer(false);
4799 sview.setVisible(false);
4805 // } catch (InvocationTargetException ex)
4807 // warn("Unexpected error when opening Jmol view.", ex);
4809 // } catch (InterruptedException e)
4811 // // e.printStackTrace();
4817 * Generates a name for the entry in the project jar file to hold state
4818 * information for a structure viewer
4823 protected String getViewerJarEntryName(String viewId)
4825 return VIEWER_PREFIX + viewId;
4829 * Returns any open frame that matches given structure viewer data. The match
4830 * is based on the unique viewId, or (for older project versions) the frame's
4836 protected StructureViewerBase findMatchingViewer(
4837 Entry<String, StructureViewerModel> viewerData)
4839 final String sviewid = viewerData.getKey();
4840 final StructureViewerModel svattrib = viewerData.getValue();
4841 StructureViewerBase comp = null;
4842 JInternalFrame[] frames = getAllFrames();
4843 for (JInternalFrame frame : frames)
4845 if (frame instanceof StructureViewerBase)
4848 * Post jalview 2.4 schema includes structure view id
4850 if (sviewid != null && ((StructureViewerBase) frame).getViewId()
4853 comp = (StructureViewerBase) frame;
4854 break; // break added in 2.9
4857 * Otherwise test for matching position and size of viewer frame
4859 else if (frame.getX() == svattrib.getX()
4860 && frame.getY() == svattrib.getY()
4861 && frame.getHeight() == svattrib.getHeight()
4862 && frame.getWidth() == svattrib.getWidth())
4864 comp = (StructureViewerBase) frame;
4865 // no break in faint hope of an exact match on viewId
4873 * Link an AlignmentPanel to an existing structure viewer.
4878 * @param useinViewerSuperpos
4879 * @param usetoColourbyseq
4880 * @param viewerColouring
4882 protected void linkStructureViewer(AlignmentPanel ap,
4883 StructureViewerBase viewer, StructureViewerModel stateData)
4885 // NOTE: if the jalview project is part of a shared session then
4886 // view synchronization should/could be done here.
4888 final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
4889 final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
4890 final boolean viewerColouring = stateData.isColourByViewer();
4891 Map<File, StructureData> oldFiles = stateData.getFileData();
4894 * Add mapping for sequences in this view to an already open viewer
4896 final AAStructureBindingModel binding = viewer.getBinding();
4897 for (File id : oldFiles.keySet())
4899 // add this and any other pdb files that should be present in the
4901 StructureData filedat = oldFiles.get(id);
4902 String pdbFile = filedat.getFilePath();
4903 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
4904 binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE,
4906 binding.addSequenceForStructFile(pdbFile, seq);
4908 // and add the AlignmentPanel's reference to the view panel
4909 viewer.addAlignmentPanel(ap);
4910 if (useinViewerSuperpos)
4912 viewer.useAlignmentPanelForSuperposition(ap);
4916 viewer.excludeAlignmentPanelForSuperposition(ap);
4918 if (usetoColourbyseq)
4920 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
4924 viewer.excludeAlignmentPanelForColourbyseq(ap);
4929 * Get all frames within the Desktop.
4933 protected JInternalFrame[] getAllFrames()
4935 JInternalFrame[] frames = null;
4936 // TODO is this necessary - is it safe - risk of hanging?
4941 frames = Desktop.getDesktopPane().getAllFrames();
4942 } catch (ArrayIndexOutOfBoundsException e)
4944 // occasional No such child exceptions are thrown here...
4948 } catch (InterruptedException f)
4952 } while (frames == null);
4957 * Answers true if 'version' is equal to or later than 'supported', where each
4958 * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
4959 * changes. Development and test values for 'version' are leniently treated
4963 * - minimum version we are comparing against
4965 * - version of data being processsed
4968 public static boolean isVersionStringLaterThan(String supported,
4971 if (supported == null || version == null
4972 || version.equalsIgnoreCase("DEVELOPMENT BUILD")
4973 || version.equalsIgnoreCase("Test")
4974 || version.equalsIgnoreCase("AUTOMATED BUILD"))
4976 System.err.println("Assuming project file with "
4977 + (version == null ? "null" : version)
4978 + " is compatible with Jalview version " + supported);
4983 return StringUtils.compareVersions(version, supported, "b") >= 0;
4987 Vector<JalviewStructureDisplayI> newStructureViewers = null;
4989 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
4991 if (newStructureViewers != null)
4993 sview.getBinding().setFinishedLoadingFromArchive(false);
4994 newStructureViewers.add(sview);
4998 protected void setLoadingFinishedForNewStructureViewers()
5000 if (newStructureViewers != null)
5002 for (JalviewStructureDisplayI sview : newStructureViewers)
5004 sview.getBinding().setFinishedLoadingFromArchive(true);
5006 newStructureViewers.clear();
5007 newStructureViewers = null;
5011 AlignFrame loadViewport(String fileName, List<JSeq> JSEQ,
5012 List<SequenceI> hiddenSeqs, AlignmentI al, JalviewModel jm,
5013 Viewport view, String uniqueSeqSetId, String viewId,
5014 List<JvAnnotRow> autoAlan)
5016 AlignFrame af = null;
5017 af = new AlignFrame(al, safeInt(view.getWidth()),
5018 safeInt(view.getHeight()), uniqueSeqSetId, viewId)
5022 // protected void processKeyEvent(java.awt.event.KeyEvent e) {
5023 // System.out.println("Jalview2XML AF " + e);
5024 // super.processKeyEvent(e);
5030 af.alignPanel.setHoldRepaint(true);
5031 af.setFileName(fileName, FileFormat.Jalview);
5032 af.setFileObject(file); // BH 2019 JAL-3436
5034 final AlignViewport viewport = af.getViewport();
5035 for (int i = 0; i < JSEQ.size(); i++)
5037 int colour = safeInt(JSEQ.get(i).getColour());
5038 viewport.setSequenceColour(viewport.getAlignment().getSequenceAt(i),
5044 viewport.setColourByReferenceSeq(true);
5045 viewport.setDisplayReferenceSeq(true);
5048 viewport.setGatherViewsHere(safeBoolean(view.isGatheredViews()));
5050 if (view.getSequenceSetId() != null)
5052 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
5054 viewport.setSequenceSetId(uniqueSeqSetId);
5057 // propagate shared settings to this new view
5058 viewport.setHistoryList(av.getHistoryList());
5059 viewport.setRedoList(av.getRedoList());
5063 viewportsAdded.put(uniqueSeqSetId, viewport);
5065 // TODO: check if this method can be called repeatedly without
5066 // side-effects if alignpanel already registered.
5067 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
5069 // apply Hidden regions to view.
5070 if (hiddenSeqs != null)
5072 for (int s = 0; s < JSEQ.size(); s++)
5074 SequenceGroup hidden = new SequenceGroup();
5075 boolean isRepresentative = false;
5076 for (int r = 0; r < JSEQ.get(s).getHiddenSequences().size(); r++)
5078 isRepresentative = true;
5079 SequenceI sequenceToHide = al
5080 .getSequenceAt(JSEQ.get(s).getHiddenSequences().get(r));
5081 hidden.addSequence(sequenceToHide, false);
5082 // remove from hiddenSeqs list so we don't try to hide it twice
5083 hiddenSeqs.remove(sequenceToHide);
5085 if (isRepresentative)
5087 SequenceI representativeSequence = al.getSequenceAt(s);
5088 hidden.addSequence(representativeSequence, false);
5089 viewport.hideRepSequences(representativeSequence, hidden);
5093 SequenceI[] hseqs = hiddenSeqs
5094 .toArray(new SequenceI[hiddenSeqs.size()]);
5095 viewport.hideSequence(hseqs);
5098 // recover view properties and display parameters
5100 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
5101 viewport.setAbovePIDThreshold(safeBoolean(view.isPidSelected()));
5102 final int pidThreshold = safeInt(view.getPidThreshold());
5103 viewport.setThreshold(pidThreshold);
5105 viewport.setColourText(safeBoolean(view.isShowColourText()));
5107 viewport.setConservationSelected(
5108 safeBoolean(view.isConservationSelected()));
5109 viewport.setIncrement(safeInt(view.getConsThreshold()));
5110 viewport.setShowJVSuffix(safeBoolean(view.isShowFullId()));
5111 viewport.setRightAlignIds(safeBoolean(view.isRightAlignIds()));
5112 viewport.setFont(new Font(view.getFontName(),
5113 safeInt(view.getFontStyle()), safeInt(view.getFontSize())),
5115 ViewStyleI vs = viewport.getViewStyle();
5116 vs.setScaleProteinAsCdna(view.isScaleProteinAsCdna());
5117 viewport.setViewStyle(vs);
5118 // TODO: allow custom charWidth/Heights to be restored by updating them
5119 // after setting font - which means set above to false
5120 viewport.setRenderGaps(safeBoolean(view.isRenderGaps()));
5121 viewport.setWrapAlignment(safeBoolean(view.isWrapAlignment()));
5122 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
5124 viewport.setShowBoxes(safeBoolean(view.isShowBoxes()));
5126 viewport.setShowText(safeBoolean(view.isShowText()));
5128 viewport.setTextColour(new Color(safeInt(view.getTextCol1())));
5129 viewport.setTextColour2(new Color(safeInt(view.getTextCol2())));
5130 viewport.setThresholdTextColour(safeInt(view.getTextColThreshold()));
5131 viewport.setShowUnconserved(view.isShowUnconserved());
5132 viewport.getRanges().setStartRes(safeInt(view.getStartRes()));
5134 if (view.getViewName() != null)
5136 viewport.setViewName(view.getViewName());
5137 af.setInitialTabVisible();
5139 int x = safeInt(view.getXpos());
5140 int y = safeInt(view.getYpos());
5141 int w = safeInt(view.getWidth());
5142 int h = safeInt(view.getHeight());
5143 // // BH we cannot let the title bar go off the top
5144 // if (Platform.isJS())
5146 // x = Math.max(50 - w, x);
5147 // y = Math.max(0, y);
5150 af.setBounds(x, y, w, h);
5151 // startSeq set in af.alignPanel.updateLayout below
5152 af.alignPanel.updateLayout();
5153 ColourSchemeI cs = null;
5154 // apply colourschemes
5155 if (view.getBgColour() != null)
5157 if (view.getBgColour().startsWith("ucs"))
5159 cs = getUserColourScheme(jm, view.getBgColour());
5161 else if (view.getBgColour().startsWith("Annotation"))
5163 AnnotationColourScheme viewAnnColour = view.getAnnotationColours();
5164 cs = constructAnnotationColour(viewAnnColour, af, al, jm, true);
5171 cs = ColourSchemeProperty.getColourScheme(af.getViewport(), al,
5172 view.getBgColour());
5177 * turn off 'alignment colour applies to all groups'
5178 * while restoring global colour scheme
5180 viewport.setColourAppliesToAllGroups(false);
5181 viewport.setGlobalColourScheme(cs);
5182 viewport.getResidueShading().setThreshold(pidThreshold,
5183 view.isIgnoreGapsinConsensus());
5184 viewport.getResidueShading()
5185 .setConsensus(viewport.getSequenceConsensusHash());
5186 if (safeBoolean(view.isConservationSelected()) && cs != null)
5188 viewport.getResidueShading()
5189 .setConservationInc(safeInt(view.getConsThreshold()));
5191 af.changeColour(cs);
5192 viewport.setColourAppliesToAllGroups(true);
5194 viewport.setShowSequenceFeatures(
5195 safeBoolean(view.isShowSequenceFeatures()));
5197 viewport.setCentreColumnLabels(view.isCentreColumnLabels());
5198 viewport.setIgnoreGapsConsensus(view.isIgnoreGapsinConsensus(), null);
5199 viewport.setFollowHighlight(view.isFollowHighlight());
5200 viewport.followSelection = view.isFollowSelection();
5201 viewport.setShowConsensusHistogram(view.isShowConsensusHistogram());
5202 viewport.setShowSequenceLogo(view.isShowSequenceLogo());
5203 viewport.setNormaliseSequenceLogo(view.isNormaliseSequenceLogo());
5204 viewport.setShowDBRefs(safeBoolean(view.isShowDbRefTooltip()));
5205 viewport.setShowNPFeats(safeBoolean(view.isShowNPfeatureTooltip()));
5206 viewport.setShowGroupConsensus(view.isShowGroupConsensus());
5207 viewport.setShowGroupConservation(view.isShowGroupConservation());
5209 // recover feature settings
5210 if (jm.getFeatureSettings() != null)
5212 FeatureRenderer fr = af.alignPanel.getSeqPanel().seqCanvas
5213 .getFeatureRenderer();
5214 FeaturesDisplayed fdi;
5215 viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
5216 String[] renderOrder = new String[jm.getFeatureSettings().getSetting()
5218 Map<String, FeatureColourI> featureColours = new Hashtable<>();
5219 Map<String, Float> featureOrder = new Hashtable<>();
5221 for (int fs = 0; fs < jm.getFeatureSettings().getSetting()
5224 Setting setting = jm.getFeatureSettings().getSetting().get(fs);
5225 String featureType = setting.getType();
5228 * restore feature filters (if any)
5230 jalview.xml.binding.jalview.FeatureMatcherSet filters = setting
5232 if (filters != null)
5234 FeatureMatcherSetI filter = Jalview2XML.parseFilter(featureType,
5236 if (!filter.isEmpty())
5238 fr.setFeatureFilter(featureType, filter);
5243 * restore feature colour scheme
5245 Color maxColour = new Color(setting.getColour());
5246 if (setting.getMincolour() != null)
5249 * minColour is always set unless a simple colour
5250 * (including for colour by label though it doesn't use it)
5252 Color minColour = new Color(setting.getMincolour().intValue());
5253 Color noValueColour = minColour;
5254 NoValueColour noColour = setting.getNoValueColour();
5255 if (noColour == NoValueColour.NONE)
5257 noValueColour = null;
5259 else if (noColour == NoValueColour.MAX)
5261 noValueColour = maxColour;
5263 float min = safeFloat(safeFloat(setting.getMin()));
5264 float max = setting.getMax() == null ? 1f
5265 : setting.getMax().floatValue();
5266 FeatureColourI gc = new FeatureColour(maxColour, minColour,
5267 maxColour, noValueColour, min, max);
5268 if (setting.getAttributeName().size() > 0)
5270 gc.setAttributeName(setting.getAttributeName().toArray(
5271 new String[setting.getAttributeName().size()]));
5273 if (setting.getThreshold() != null)
5275 gc.setThreshold(setting.getThreshold().floatValue());
5276 int threshstate = safeInt(setting.getThreshstate());
5277 // -1 = None, 0 = Below, 1 = Above threshold
5278 if (threshstate == 0)
5280 gc.setBelowThreshold(true);
5282 else if (threshstate == 1)
5284 gc.setAboveThreshold(true);
5287 gc.setAutoScaled(true); // default
5288 if (setting.isAutoScale() != null)
5290 gc.setAutoScaled(setting.isAutoScale());
5292 if (setting.isColourByLabel() != null)
5294 gc.setColourByLabel(setting.isColourByLabel());
5296 // and put in the feature colour table.
5297 featureColours.put(featureType, gc);
5301 featureColours.put(featureType, new FeatureColour(maxColour));
5303 renderOrder[fs] = featureType;
5304 if (setting.getOrder() != null)
5306 featureOrder.put(featureType, setting.getOrder().floatValue());
5310 featureOrder.put(featureType, new Float(
5311 fs / jm.getFeatureSettings().getSetting().size()));
5313 if (safeBoolean(setting.isDisplay()))
5315 fdi.setVisible(featureType);
5318 Map<String, Boolean> fgtable = new Hashtable<>();
5319 for (int gs = 0; gs < jm.getFeatureSettings().getGroup().size(); gs++)
5321 Group grp = jm.getFeatureSettings().getGroup().get(gs);
5322 fgtable.put(grp.getName(), new Boolean(grp.isDisplay()));
5324 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
5325 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
5326 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
5327 FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
5328 fgtable, featureColours, 1.0f, featureOrder);
5329 fr.transferSettings(frs);
5332 if (view.getHiddenColumns().size() > 0)
5334 for (int c = 0; c < view.getHiddenColumns().size(); c++)
5336 final HiddenColumns hc = view.getHiddenColumns().get(c);
5337 viewport.hideColumns(safeInt(hc.getStart()),
5338 safeInt(hc.getEnd()) /* +1 */);
5341 if (view.getCalcIdParam() != null)
5343 for (CalcIdParam calcIdParam : view.getCalcIdParam())
5345 if (calcIdParam != null)
5347 if (recoverCalcIdParam(calcIdParam, viewport))
5352 warn("Couldn't recover parameters for "
5353 + calcIdParam.getCalcId());
5358 af.setMenusFromViewport(viewport);
5359 af.setTitle(view.getTitle());
5360 // TODO: we don't need to do this if the viewport is aready visible.
5362 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
5363 * has a 'cdna/protein complement' view, in which case save it in order to
5364 * populate a SplitFrame once all views have been read in.
5366 String complementaryViewId = view.getComplementId();
5367 if (complementaryViewId == null)
5369 Dimension dim = Platform.getDimIfEmbedded(af,
5370 safeInt(view.getWidth()), safeInt(view.getHeight()));
5371 Desktop.addInternalFrame(af, view.getTitle(), dim.width, dim.height);
5372 // recompute any autoannotation
5373 af.alignPanel.updateAnnotation(false, true);
5374 reorderAutoannotation(af, al, autoAlan);
5375 af.alignPanel.alignmentChanged();
5379 splitFrameCandidates.put(view, af);
5385 * Reads saved data to restore Colour by Annotation settings
5387 * @param viewAnnColour
5391 * @param checkGroupAnnColour
5394 private ColourSchemeI constructAnnotationColour(
5395 AnnotationColourScheme viewAnnColour, AlignFrame af,
5396 AlignmentI al, JalviewModel model, boolean checkGroupAnnColour)
5398 boolean propagateAnnColour = false;
5399 AlignmentI annAlignment = af != null ? af.getViewport().getAlignment()
5401 if (checkGroupAnnColour && al.getGroups() != null
5402 && al.getGroups().size() > 0)
5404 // pre 2.8.1 behaviour
5405 // check to see if we should transfer annotation colours
5406 propagateAnnColour = true;
5407 for (SequenceGroup sg : al.getGroups())
5409 if (sg.getColourScheme() instanceof AnnotationColourGradient)
5411 propagateAnnColour = false;
5417 * 2.10.2- : saved annotationId is AlignmentAnnotation.annotationId
5419 String annotationId = viewAnnColour.getAnnotation();
5420 AlignmentAnnotation matchedAnnotation = annotationIds.get(annotationId);
5423 * pre 2.10.2: saved annotationId is AlignmentAnnotation.label
5425 if (matchedAnnotation == null
5426 && annAlignment.getAlignmentAnnotation() != null)
5428 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
5431 .equals(annAlignment.getAlignmentAnnotation()[i].label))
5433 matchedAnnotation = annAlignment.getAlignmentAnnotation()[i];
5438 if (matchedAnnotation == null)
5440 System.err.println("Failed to match annotation colour scheme for "
5444 if (matchedAnnotation.getThreshold() == null)
5446 matchedAnnotation.setThreshold(
5447 new GraphLine(safeFloat(viewAnnColour.getThreshold()),
5448 "Threshold", Color.black));
5451 AnnotationColourGradient cs = null;
5452 if (viewAnnColour.getColourScheme().equals("None"))
5454 cs = new AnnotationColourGradient(matchedAnnotation,
5455 new Color(safeInt(viewAnnColour.getMinColour())),
5456 new Color(safeInt(viewAnnColour.getMaxColour())),
5457 safeInt(viewAnnColour.getAboveThreshold()));
5459 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
5461 cs = new AnnotationColourGradient(matchedAnnotation,
5462 getUserColourScheme(model, viewAnnColour.getColourScheme()),
5463 safeInt(viewAnnColour.getAboveThreshold()));
5467 cs = new AnnotationColourGradient(matchedAnnotation,
5468 ColourSchemeProperty.getColourScheme(af.getViewport(), al,
5469 viewAnnColour.getColourScheme()),
5470 safeInt(viewAnnColour.getAboveThreshold()));
5473 boolean perSequenceOnly = safeBoolean(viewAnnColour.isPerSequence());
5474 boolean useOriginalColours = safeBoolean(
5475 viewAnnColour.isPredefinedColours());
5476 cs.setSeqAssociated(perSequenceOnly);
5477 cs.setPredefinedColours(useOriginalColours);
5479 if (propagateAnnColour && al.getGroups() != null)
5481 // Also use these settings for all the groups
5482 for (int g = 0; g < al.getGroups().size(); g++)
5484 SequenceGroup sg = al.getGroups().get(g);
5485 if (sg.getGroupColourScheme() == null)
5490 AnnotationColourGradient groupScheme = new AnnotationColourGradient(
5491 matchedAnnotation, sg.getColourScheme(),
5492 safeInt(viewAnnColour.getAboveThreshold()));
5493 sg.setColourScheme(groupScheme);
5494 groupScheme.setSeqAssociated(perSequenceOnly);
5495 groupScheme.setPredefinedColours(useOriginalColours);
5501 private void reorderAutoannotation(AlignFrame af, AlignmentI al,
5502 List<JvAnnotRow> autoAlan)
5504 // copy over visualization settings for autocalculated annotation in the
5506 if (al.getAlignmentAnnotation() != null)
5509 * Kludge for magic autoannotation names (see JAL-811)
5511 String[] magicNames = new String[] { "Consensus", "Quality",
5513 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
5514 Hashtable<String, JvAnnotRow> visan = new Hashtable<>();
5515 for (String nm : magicNames)
5517 visan.put(nm, nullAnnot);
5519 for (JvAnnotRow auan : autoAlan)
5521 visan.put(auan.template.label
5522 + (auan.template.getCalcId() == null ? ""
5523 : "\t" + auan.template.getCalcId()),
5526 int hSize = al.getAlignmentAnnotation().length;
5527 List<JvAnnotRow> reorder = new ArrayList<>();
5528 // work through any autoCalculated annotation already on the view
5529 // removing it if it should be placed in a different location on the
5530 // annotation panel.
5531 List<String> remains = new ArrayList<>(visan.keySet());
5532 for (int h = 0; h < hSize; h++)
5534 jalview.datamodel.AlignmentAnnotation jalan = al
5535 .getAlignmentAnnotation()[h];
5536 if (jalan.autoCalculated)
5539 JvAnnotRow valan = visan.get(k = jalan.label);
5540 if (jalan.getCalcId() != null)
5542 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
5547 // delete the auto calculated row from the alignment
5548 al.deleteAnnotation(jalan, false);
5552 if (valan != nullAnnot)
5554 if (jalan != valan.template)
5556 // newly created autoannotation row instance
5557 // so keep a reference to the visible annotation row
5558 // and copy over all relevant attributes
5559 if (valan.template.graphHeight >= 0)
5562 jalan.graphHeight = valan.template.graphHeight;
5564 jalan.visible = valan.template.visible;
5566 reorder.add(new JvAnnotRow(valan.order, jalan));
5571 // Add any (possibly stale) autocalculated rows that were not appended to
5572 // the view during construction
5573 for (String other : remains)
5575 JvAnnotRow othera = visan.get(other);
5576 if (othera != nullAnnot && othera.template.getCalcId() != null
5577 && othera.template.getCalcId().length() > 0)
5579 reorder.add(othera);
5582 // now put the automatic annotation in its correct place
5583 int s = 0, srt[] = new int[reorder.size()];
5584 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
5585 for (JvAnnotRow jvar : reorder)
5588 srt[s++] = jvar.order;
5591 jalview.util.QuickSort.sort(srt, rws);
5592 // and re-insert the annotation at its correct position
5593 for (JvAnnotRow jvar : rws)
5595 al.addAnnotation(jvar.template, jvar.order);
5597 af.alignPanel.adjustAnnotationHeight();
5601 Hashtable skipList = null;
5604 * TODO remove this method
5607 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
5608 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
5609 * throw new Error("Implementation Error. No skipList defined for this
5610 * Jalview2XML instance."); } return (AlignFrame)
5611 * skipList.get(view.getSequenceSetId()); }
5615 * Check if the Jalview view contained in object should be skipped or not.
5618 * @return true if view's sequenceSetId is a key in skipList
5620 private boolean skipViewport(JalviewModel object)
5622 if (skipList == null)
5626 String id = object.getViewport().get(0).getSequenceSetId();
5627 if (skipList.containsKey(id))
5629 if (Cache.log != null && Cache.log.isDebugEnabled())
5631 Cache.log.debug("Skipping seuqence set id " + id);
5638 public void addToSkipList(AlignFrame af)
5640 if (skipList == null)
5642 skipList = new Hashtable();
5644 skipList.put(af.getViewport().getSequenceSetId(), af);
5647 public void clearSkipList()
5649 if (skipList != null)
5656 private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
5657 boolean ignoreUnrefed, String uniqueSeqSetId)
5659 jalview.datamodel.AlignmentI ds = getDatasetFor(
5660 vamsasSet.getDatasetId());
5661 AlignmentI xtant_ds = ds;
5662 if (xtant_ds == null)
5664 // good chance we are about to create a new dataset, but check if we've
5665 // seen some of the dataset sequence IDs before.
5666 // TODO: skip this check if we are working with project generated by
5667 // version 2.11 or later
5668 xtant_ds = checkIfHasDataset(vamsasSet.getSequence());
5669 if (xtant_ds != null)
5672 addDatasetRef(vamsasSet.getDatasetId(), ds);
5675 Vector dseqs = null;
5678 // recovering an alignment View
5679 AlignmentI seqSetDS = getDatasetFor(UNIQSEQSETID + uniqueSeqSetId);
5680 if (seqSetDS != null)
5682 if (ds != null && ds != seqSetDS)
5684 warn("JAL-3171 regression: Overwriting a dataset reference for an alignment"
5685 + " - CDS/Protein crossreference data may be lost");
5686 if (xtant_ds != null)
5688 // This can only happen if the unique sequence set ID was bound to a
5689 // dataset that did not contain any of the sequences in the view
5690 // currently being restored.
5691 warn("JAL-3171 SERIOUS! TOTAL CONFUSION - please consider contacting the Jalview Development team so they can investigate why your project caused this message to be displayed.");
5695 addDatasetRef(vamsasSet.getDatasetId(), ds);
5700 // try even harder to restore dataset
5701 AlignmentI xtantDS = checkIfHasDataset(vamsasSet.getSequence());
5702 // create a list of new dataset sequences
5703 dseqs = new Vector();
5705 for (int i = 0, iSize = vamsasSet.getSequence().size(); i < iSize; i++)
5707 Sequence vamsasSeq = vamsasSet.getSequence().get(i);
5708 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed, i);
5710 // create a new dataset
5713 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
5714 dseqs.copyInto(dsseqs);
5715 ds = new jalview.datamodel.Alignment(dsseqs);
5716 // debug("Jalview2XML Created new dataset " + vamsasSet.getDatasetId()
5717 // + " for alignment " + System.identityHashCode(al));
5718 addDatasetRef(vamsasSet.getDatasetId(), ds);
5720 // set the dataset for the newly imported alignment.
5721 if (al.getDataset() == null && !ignoreUnrefed)
5724 // register dataset for the alignment's uniqueSeqSetId for legacy projects
5725 addDatasetRef(UNIQSEQSETID + uniqueSeqSetId, ds);
5727 updateSeqDatasetBinding(vamsasSet.getSequence(), ds);
5731 * XML dataset sequence ID to materialised dataset reference
5733 HashMap<String, AlignmentI> seqToDataset = new HashMap<>();
5736 * @return the first materialised dataset reference containing a dataset
5737 * sequence referenced in the given view
5739 * - sequences from the view
5741 AlignmentI checkIfHasDataset(List<Sequence> list)
5743 for (Sequence restoredSeq : list)
5745 AlignmentI datasetFor = seqToDataset.get(restoredSeq.getDsseqid());
5746 if (datasetFor != null)
5755 * Register ds as the containing dataset for the dataset sequences referenced
5756 * by sequences in list
5759 * - sequences in a view
5762 void updateSeqDatasetBinding(List<Sequence> list, AlignmentI ds)
5764 for (Sequence restoredSeq : list)
5766 AlignmentI prevDS = seqToDataset.put(restoredSeq.getDsseqid(), ds);
5767 if (prevDS != null && prevDS != ds)
5769 warn("Dataset sequence appears in many datasets: "
5770 + restoredSeq.getDsseqid());
5771 // TODO: try to merge!
5778 * sequence definition to create/merge dataset sequence for
5782 * vector to add new dataset sequence to
5783 * @param ignoreUnrefed
5784 * - when true, don't create new sequences from vamsasSeq if it's id
5785 * doesn't already have an asssociated Jalview sequence.
5787 * - used to reorder the sequence in the alignment according to the
5788 * vamsasSeq array ordering, to preserve ordering of dataset
5790 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
5791 AlignmentI ds, Vector dseqs, boolean ignoreUnrefed, int vseqpos)
5793 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
5795 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
5796 boolean reorder = false;
5797 SequenceI dsq = null;
5798 if (sq != null && sq.getDatasetSequence() != null)
5800 dsq = sq.getDatasetSequence();
5806 if (sq == null && ignoreUnrefed)
5810 String sqid = vamsasSeq.getDsseqid();
5813 // need to create or add a new dataset sequence reference to this sequence
5816 dsq = seqRefIds.get(sqid);
5821 // make a new dataset sequence
5822 dsq = sq.createDatasetSequence();
5825 // make up a new dataset reference for this sequence
5826 sqid = seqHash(dsq);
5828 dsq.setVamsasId(uniqueSetSuffix + sqid);
5829 seqRefIds.put(sqid, dsq);
5834 dseqs.addElement(dsq);
5839 ds.addSequence(dsq);
5845 { // make this dataset sequence sq's dataset sequence
5846 sq.setDatasetSequence(dsq);
5847 // and update the current dataset alignment
5852 if (!dseqs.contains(dsq))
5859 if (ds.findIndex(dsq) < 0)
5861 ds.addSequence(dsq);
5868 // TODO: refactor this as a merge dataset sequence function
5869 // now check that sq (the dataset sequence) sequence really is the union of
5870 // all references to it
5871 // boolean pre = sq.getStart() < dsq.getStart();
5872 // boolean post = sq.getEnd() > dsq.getEnd();
5876 // StringBuffer sb = new StringBuffer();
5877 String newres = jalview.analysis.AlignSeq.extractGaps(
5878 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
5879 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
5880 && newres.length() > dsq.getLength())
5882 // Update with the longer sequence.
5886 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
5887 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
5888 * sb.append(newres.substring(newres.length() - sq.getEnd() -
5889 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
5891 dsq.setSequence(newres);
5893 // TODO: merges will never happen if we 'know' we have the real dataset
5894 // sequence - this should be detected when id==dssid
5896 "DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
5897 // + (pre ? "prepended" : "") + " "
5898 // + (post ? "appended" : ""));
5903 // sequence refs are identical. We may need to update the existing dataset
5904 // alignment with this one, though.
5905 if (ds != null && dseqs == null)
5907 int opos = ds.findIndex(dsq);
5908 SequenceI tseq = null;
5909 if (opos != -1 && vseqpos != opos)
5911 // remove from old position
5912 ds.deleteSequence(dsq);
5914 if (vseqpos < ds.getHeight())
5916 if (vseqpos != opos)
5918 // save sequence at destination position
5919 tseq = ds.getSequenceAt(vseqpos);
5920 ds.replaceSequenceAt(vseqpos, dsq);
5921 ds.addSequence(tseq);
5926 ds.addSequence(dsq);
5933 * TODO use AlignmentI here and in related methods - needs
5934 * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
5936 Hashtable<String, AlignmentI> datasetIds = null;
5938 IdentityHashMap<AlignmentI, String> dataset2Ids = null;
5940 private AlignmentI getDatasetFor(String datasetId)
5942 if (datasetIds == null)
5944 datasetIds = new Hashtable<>();
5947 if (datasetIds.containsKey(datasetId))
5949 return datasetIds.get(datasetId);
5954 private void addDatasetRef(String datasetId, AlignmentI dataset)
5956 if (datasetIds == null)
5958 datasetIds = new Hashtable<>();
5960 datasetIds.put(datasetId, dataset);
5964 * make a new dataset ID for this jalview dataset alignment
5969 private String getDatasetIdRef(AlignmentI dataset)
5971 if (dataset.getDataset() != null)
5973 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
5975 String datasetId = makeHashCode(dataset, null);
5976 if (datasetId == null)
5978 // make a new datasetId and record it
5979 if (dataset2Ids == null)
5981 dataset2Ids = new IdentityHashMap<>();
5985 datasetId = dataset2Ids.get(dataset);
5987 if (datasetId == null)
5989 datasetId = "ds" + dataset2Ids.size() + 1;
5990 dataset2Ids.put(dataset, datasetId);
5996 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
5998 for (int d = 0; d < sequence.getDBRef().size(); d++)
6000 DBRef dr = sequence.getDBRef().get(d);
6001 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
6002 dr.getSource(), dr.getVersion(), dr.getAccessionId());
6003 if (dr.getMapping() != null)
6005 entry.setMap(addMapping(dr.getMapping()));
6007 datasetSequence.addDBRef(entry);
6011 private jalview.datamodel.Mapping addMapping(Mapping m)
6013 SequenceI dsto = null;
6014 // Mapping m = dr.getMapping();
6015 int fr[] = new int[m.getMapListFrom().size() * 2];
6016 Iterator<MapListFrom> from = m.getMapListFrom().iterator();// enumerateMapListFrom();
6017 for (int _i = 0; from.hasNext(); _i += 2)
6019 MapListFrom mf = from.next();
6020 fr[_i] = mf.getStart();
6021 fr[_i + 1] = mf.getEnd();
6023 int fto[] = new int[m.getMapListTo().size() * 2];
6024 Iterator<MapListTo> to = m.getMapListTo().iterator();// enumerateMapListTo();
6025 for (int _i = 0; to.hasNext(); _i += 2)
6027 MapListTo mf = to.next();
6028 fto[_i] = mf.getStart();
6029 fto[_i + 1] = mf.getEnd();
6031 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto, fr,
6032 fto, m.getMapFromUnit().intValue(),
6033 m.getMapToUnit().intValue());
6036 * (optional) choice of dseqFor or Sequence
6038 if (m.getDseqFor() != null)
6040 String dsfor = m.getDseqFor();
6041 if (seqRefIds.containsKey(dsfor))
6046 jmap.setTo(seqRefIds.get(dsfor));
6050 frefedSequence.add(newMappingRef(dsfor, jmap));
6053 else if (m.getSequence() != null)
6056 * local sequence definition
6058 Sequence ms = m.getSequence();
6059 SequenceI djs = null;
6060 String sqid = ms.getDsseqid();
6061 if (sqid != null && sqid.length() > 0)
6064 * recover dataset sequence
6066 djs = seqRefIds.get(sqid);
6071 "Warning - making up dataset sequence id for DbRef sequence map reference");
6072 sqid = ((Object) ms).toString(); // make up a new hascode for
6073 // undefined dataset sequence hash
6074 // (unlikely to happen)
6080 * make a new dataset sequence and add it to refIds hash
6082 djs = new jalview.datamodel.Sequence(ms.getName(),
6084 djs.setStart(jmap.getMap().getToLowest());
6085 djs.setEnd(jmap.getMap().getToHighest());
6086 djs.setVamsasId(uniqueSetSuffix + sqid);
6088 incompleteSeqs.put(sqid, djs);
6089 seqRefIds.put(sqid, djs);
6092 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
6101 * Provides a 'copy' of an alignment view (on action New View) by 'saving' the
6102 * view as XML (but not to file), and then reloading it
6107 public AlignmentPanel copyAlignPanel(AlignmentPanel ap)
6110 JalviewModel jm = saveState(ap, null, null, null);
6113 jm.getVamsasModel().getSequenceSet().get(0).getDatasetId(),
6114 ap.getAlignment().getDataset());
6116 uniqueSetSuffix = "";
6117 // jm.getJalviewModelSequence().getViewport(0).setId(null);
6118 jm.getViewport().get(0).setId(null);
6119 // we don't overwrite the view we just copied
6121 if (this.frefedSequence == null)
6123 frefedSequence = new Vector<>();
6126 viewportsAdded.clear();
6128 AlignFrame af = loadFromObject(jm, null, false, null);
6129 af.getAlignPanels().clear();
6130 af.closeMenuItem_actionPerformed(true);
6131 af.alignPanel.setHoldRepaint(false);
6133 return af.alignPanel;
6136 private Hashtable jvids2vobj;
6138 private void warn(String msg)
6143 private void warn(String msg, Exception e)
6145 if (Cache.log != null)
6149 Cache.log.warn(msg, e);
6153 Cache.log.warn(msg);
6158 System.err.println("Warning: " + msg);
6161 e.printStackTrace();
6166 private void debug(String string)
6168 debug(string, null);
6171 private void debug(String msg, Exception e)
6173 if (Cache.log != null)
6177 Cache.log.debug(msg, e);
6181 Cache.log.debug(msg);
6186 System.err.println("Warning: " + msg);
6189 e.printStackTrace();
6195 * set the object to ID mapping tables used to write/recover objects and XML
6196 * ID strings for the jalview project. If external tables are provided then
6197 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
6198 * object goes out of scope. - also populates the datasetIds hashtable with
6199 * alignment objects containing dataset sequences
6202 * Map from ID strings to jalview datamodel
6204 * Map from jalview datamodel to ID strings
6208 public void setObjectMappingTables(Hashtable vobj2jv,
6209 IdentityHashMap jv2vobj)
6211 this.jv2vobj = jv2vobj;
6212 this.vobj2jv = vobj2jv;
6213 Iterator ds = jv2vobj.keySet().iterator();
6215 while (ds.hasNext())
6217 Object jvobj = ds.next();
6218 id = jv2vobj.get(jvobj).toString();
6219 if (jvobj instanceof jalview.datamodel.Alignment)
6221 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
6223 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
6226 else if (jvobj instanceof jalview.datamodel.Sequence)
6228 // register sequence object so the XML parser can recover it.
6229 if (seqRefIds == null)
6231 seqRefIds = new HashMap<>();
6233 if (seqsToIds == null)
6235 seqsToIds = new IdentityHashMap<>();
6237 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
6238 seqsToIds.put((SequenceI) jvobj, id);
6240 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
6243 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
6244 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
6245 if (jvann.annotationId == null)
6247 jvann.annotationId = anid;
6249 if (!jvann.annotationId.equals(anid))
6251 // TODO verify that this is the correct behaviour
6252 this.warn("Overriding Annotation ID for " + anid
6253 + " from different id : " + jvann.annotationId);
6254 jvann.annotationId = anid;
6257 else if (jvobj instanceof String)
6259 if (jvids2vobj == null)
6261 jvids2vobj = new Hashtable();
6262 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
6267 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
6273 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
6274 * objects created from the project archive. If string is null (default for
6275 * construction) then suffix will be set automatically.
6279 public void setUniqueSetSuffix(String string)
6281 uniqueSetSuffix = string;
6286 * uses skipList2 as the skipList for skipping views on sequence sets
6287 * associated with keys in the skipList
6291 public void setSkipList(Hashtable skipList2)
6293 skipList = skipList2;
6297 * Reads the jar entry of given name and returns its contents, or null if the
6298 * entry is not found.
6301 * @param jarEntryName
6304 protected String readJarEntry(jarInputStreamProvider jprovider,
6305 String jarEntryName)
6307 String result = null;
6308 BufferedReader in = null;
6313 * Reopen the jar input stream and traverse its entries to find a matching
6316 JarInputStream jin = jprovider.getJarInputStream();
6317 JarEntry entry = null;
6320 entry = jin.getNextJarEntry();
6321 } while (entry != null && !entry.getName().equals(jarEntryName));
6325 StringBuilder out = new StringBuilder(256);
6326 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
6329 while ((data = in.readLine()) != null)
6333 result = out.toString();
6337 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
6339 } catch (Exception ex)
6341 ex.printStackTrace();
6349 } catch (IOException e)
6360 * Returns an incrementing counter (0, 1, 2...)
6364 private synchronized int nextCounter()
6370 * Loads any saved PCA viewers
6375 protected void loadPCAViewers(JalviewModel model, AlignmentPanel ap)
6379 List<PcaViewer> pcaviewers = model.getPcaViewer();
6380 for (PcaViewer viewer : pcaviewers)
6382 String modelName = viewer.getScoreModelName();
6383 SimilarityParamsI params = new SimilarityParams(
6384 viewer.isIncludeGappedColumns(), viewer.isMatchGaps(),
6385 viewer.isIncludeGaps(),
6386 viewer.isDenominateByShortestLength());
6389 * create the panel (without computing the PCA)
6391 PCAPanel panel = new PCAPanel(ap, modelName, params);
6393 panel.setTitle(viewer.getTitle());
6394 panel.setBounds(new Rectangle(viewer.getXpos(), viewer.getYpos(),
6395 viewer.getWidth(), viewer.getHeight()));
6397 boolean showLabels = viewer.isShowLabels();
6398 panel.setShowLabels(showLabels);
6399 panel.getRotatableCanvas().setShowLabels(showLabels);
6400 panel.getRotatableCanvas()
6401 .setBgColour(new Color(viewer.getBgColour()));
6402 panel.getRotatableCanvas()
6403 .setApplyToAllViews(viewer.isLinkToAllViews());
6406 * load PCA output data
6408 ScoreModelI scoreModel = ScoreModels.getInstance()
6409 .getScoreModel(modelName, ap);
6410 PCA pca = new PCA(null, scoreModel, params);
6411 PcaDataType pcaData = viewer.getPcaData();
6413 MatrixI pairwise = loadDoubleMatrix(pcaData.getPairwiseMatrix());
6414 pca.setPairwiseScores(pairwise);
6416 MatrixI triDiag = loadDoubleMatrix(pcaData.getTridiagonalMatrix());
6417 pca.setTridiagonal(triDiag);
6419 MatrixI result = loadDoubleMatrix(pcaData.getEigenMatrix());
6420 pca.setEigenmatrix(result);
6422 panel.getPcaModel().setPCA(pca);
6425 * we haven't saved the input data! (JAL-2647 to do)
6427 panel.setInputData(null);
6430 * add the sequence points for the PCA display
6432 List<jalview.datamodel.SequencePoint> seqPoints = new ArrayList<>();
6433 for (SequencePoint sp : viewer.getSequencePoint())
6435 String seqId = sp.getSequenceRef();
6436 SequenceI seq = seqRefIds.get(seqId);
6439 throw new IllegalStateException(
6440 "Unmatched seqref for PCA: " + seqId);
6442 Point pt = new Point(sp.getXPos(), sp.getYPos(), sp.getZPos());
6443 jalview.datamodel.SequencePoint seqPoint = new jalview.datamodel.SequencePoint(
6445 seqPoints.add(seqPoint);
6447 panel.getRotatableCanvas().setPoints(seqPoints, seqPoints.size());
6450 * set min-max ranges and scale after setPoints (which recomputes them)
6452 panel.getRotatableCanvas().setScaleFactor(viewer.getScaleFactor());
6453 SeqPointMin spMin = viewer.getSeqPointMin();
6454 float[] min = new float[] { spMin.getXPos(), spMin.getYPos(),
6456 SeqPointMax spMax = viewer.getSeqPointMax();
6457 float[] max = new float[] { spMax.getXPos(), spMax.getYPos(),
6459 panel.getRotatableCanvas().setSeqMinMax(min, max);
6461 // todo: hold points list in PCAModel only
6462 panel.getPcaModel().setSequencePoints(seqPoints);
6464 panel.setSelectedDimensionIndex(viewer.getXDim(), X);
6465 panel.setSelectedDimensionIndex(viewer.getYDim(), Y);
6466 panel.setSelectedDimensionIndex(viewer.getZDim(), Z);
6468 // is this duplication needed?
6469 panel.setTop(seqPoints.size() - 1);
6470 panel.getPcaModel().setTop(seqPoints.size() - 1);
6473 * add the axes' end points for the display
6475 for (int i = 0; i < 3; i++)
6477 Axis axis = viewer.getAxis().get(i);
6478 panel.getRotatableCanvas().getAxisEndPoints()[i] = new Point(
6479 axis.getXPos(), axis.getYPos(), axis.getZPos());
6482 Dimension dim = Platform.getDimIfEmbedded(panel, 475, 450);
6483 Desktop.addInternalFrame(panel, MessageManager.formatMessage(
6484 "label.calc_title", "PCA", modelName), dim.width,
6487 } catch (Exception ex)
6489 Cache.log.error("Error loading PCA: " + ex.toString());
6494 * Populates an XML model of the feature colour scheme for one feature type
6496 * @param featureType
6500 public static Colour marshalColour(
6501 String featureType, FeatureColourI fcol)
6503 Colour col = new Colour();
6504 if (fcol.isSimpleColour())
6506 col.setRGB(Format.getHexString(fcol.getColour()));
6510 col.setRGB(Format.getHexString(fcol.getMaxColour()));
6511 col.setMin(fcol.getMin());
6512 col.setMax(fcol.getMax());
6513 col.setMinRGB(jalview.util.Format.getHexString(fcol.getMinColour()));
6514 col.setAutoScale(fcol.isAutoScaled());
6515 col.setThreshold(fcol.getThreshold());
6516 col.setColourByLabel(fcol.isColourByLabel());
6517 col.setThreshType(fcol.isAboveThreshold() ? ThresholdType.ABOVE
6518 : (fcol.isBelowThreshold() ? ThresholdType.BELOW
6519 : ThresholdType.NONE));
6520 if (fcol.isColourByAttribute())
6522 final String[] attName = fcol.getAttributeName();
6523 col.getAttributeName().add(attName[0]);
6524 if (attName.length > 1)
6526 col.getAttributeName().add(attName[1]);
6529 Color noColour = fcol.getNoColour();
6530 if (noColour == null)
6532 col.setNoValueColour(NoValueColour.NONE);
6534 else if (noColour == fcol.getMaxColour())
6536 col.setNoValueColour(NoValueColour.MAX);
6540 col.setNoValueColour(NoValueColour.MIN);
6543 col.setName(featureType);
6548 * Populates an XML model of the feature filter(s) for one feature type
6550 * @param firstMatcher
6551 * the first (or only) match condition)
6553 * remaining match conditions (if any)
6555 * if true, conditions are and-ed, else or-ed
6557 public static jalview.xml.binding.jalview.FeatureMatcherSet marshalFilter(
6558 FeatureMatcherI firstMatcher, Iterator<FeatureMatcherI> filters,
6561 jalview.xml.binding.jalview.FeatureMatcherSet result = new jalview.xml.binding.jalview.FeatureMatcherSet();
6563 if (filters.hasNext())
6568 CompoundMatcher compound = new CompoundMatcher();
6569 compound.setAnd(and);
6570 jalview.xml.binding.jalview.FeatureMatcherSet matcher1 = marshalFilter(
6571 firstMatcher, Collections.emptyIterator(), and);
6572 // compound.addMatcherSet(matcher1);
6573 compound.getMatcherSet().add(matcher1);
6574 FeatureMatcherI nextMatcher = filters.next();
6575 jalview.xml.binding.jalview.FeatureMatcherSet matcher2 = marshalFilter(
6576 nextMatcher, filters, and);
6577 // compound.addMatcherSet(matcher2);
6578 compound.getMatcherSet().add(matcher2);
6579 result.setCompoundMatcher(compound);
6584 * single condition matcher
6586 // MatchCondition matcherModel = new MatchCondition();
6587 jalview.xml.binding.jalview.FeatureMatcher matcherModel = new jalview.xml.binding.jalview.FeatureMatcher();
6588 matcherModel.setCondition(
6589 firstMatcher.getMatcher().getCondition().getStableName());
6590 matcherModel.setValue(firstMatcher.getMatcher().getPattern());
6591 if (firstMatcher.isByAttribute())
6593 matcherModel.setBy(FilterBy.BY_ATTRIBUTE);
6594 // matcherModel.setAttributeName(firstMatcher.getAttribute());
6595 String[] attName = firstMatcher.getAttribute();
6596 matcherModel.getAttributeName().add(attName[0]); // attribute
6597 if (attName.length > 1)
6599 matcherModel.getAttributeName().add(attName[1]); // sub-attribute
6602 else if (firstMatcher.isByLabel())
6604 matcherModel.setBy(FilterBy.BY_LABEL);
6606 else if (firstMatcher.isByScore())
6608 matcherModel.setBy(FilterBy.BY_SCORE);
6610 result.setMatchCondition(matcherModel);
6617 * Loads one XML model of a feature filter to a Jalview object
6619 * @param featureType
6620 * @param matcherSetModel
6623 public static FeatureMatcherSetI parseFilter(
6625 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel)
6627 FeatureMatcherSetI result = new FeatureMatcherSet();
6630 parseFilterConditions(result, matcherSetModel, true);
6631 } catch (IllegalStateException e)
6633 // mixing AND and OR conditions perhaps
6635 String.format("Error reading filter conditions for '%s': %s",
6636 featureType, e.getMessage()));
6637 // return as much as was parsed up to the error
6644 * Adds feature match conditions to matcherSet as unmarshalled from XML
6645 * (possibly recursively for compound conditions)
6648 * @param matcherSetModel
6650 * if true, multiple conditions are AND-ed, else they are OR-ed
6651 * @throws IllegalStateException
6652 * if AND and OR conditions are mixed
6654 protected static void parseFilterConditions(
6655 FeatureMatcherSetI matcherSet,
6656 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel,
6659 jalview.xml.binding.jalview.FeatureMatcher mc = matcherSetModel
6660 .getMatchCondition();
6666 FilterBy filterBy = mc.getBy();
6667 Condition cond = Condition.fromString(mc.getCondition());
6668 String pattern = mc.getValue();
6669 FeatureMatcherI matchCondition = null;
6670 if (filterBy == FilterBy.BY_LABEL)
6672 matchCondition = FeatureMatcher.byLabel(cond, pattern);
6674 else if (filterBy == FilterBy.BY_SCORE)
6676 matchCondition = FeatureMatcher.byScore(cond, pattern);
6679 else if (filterBy == FilterBy.BY_ATTRIBUTE)
6681 final List<String> attributeName = mc.getAttributeName();
6682 String[] attNames = attributeName
6683 .toArray(new String[attributeName.size()]);
6684 matchCondition = FeatureMatcher.byAttribute(cond, pattern,
6689 * note this throws IllegalStateException if AND-ing to a
6690 * previously OR-ed compound condition, or vice versa
6694 matcherSet.and(matchCondition);
6698 matcherSet.or(matchCondition);
6704 * compound condition
6706 List<jalview.xml.binding.jalview.FeatureMatcherSet> matchers = matcherSetModel
6707 .getCompoundMatcher().getMatcherSet();
6708 boolean anded = matcherSetModel.getCompoundMatcher().isAnd();
6709 if (matchers.size() == 2)
6711 parseFilterConditions(matcherSet, matchers.get(0), anded);
6712 parseFilterConditions(matcherSet, matchers.get(1), anded);
6716 System.err.println("Malformed compound filter condition");
6722 * Loads one XML model of a feature colour to a Jalview object
6724 * @param colourModel
6727 public static FeatureColourI parseColour(Colour colourModel)
6729 FeatureColourI colour = null;
6731 if (colourModel.getMax() != null)
6733 Color mincol = null;
6734 Color maxcol = null;
6735 Color noValueColour = null;
6739 mincol = new Color(Integer.parseInt(colourModel.getMinRGB(), 16));
6740 maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6741 } catch (Exception e)
6743 Cache.log.warn("Couldn't parse out graduated feature color.", e);
6746 NoValueColour noCol = colourModel.getNoValueColour();
6747 if (noCol == NoValueColour.MIN)
6749 noValueColour = mincol;
6751 else if (noCol == NoValueColour.MAX)
6753 noValueColour = maxcol;
6756 colour = new FeatureColour(maxcol, mincol, maxcol, noValueColour,
6757 safeFloat(colourModel.getMin()),
6758 safeFloat(colourModel.getMax()));
6759 final List<String> attributeName = colourModel.getAttributeName();
6760 String[] attributes = attributeName
6761 .toArray(new String[attributeName.size()]);
6762 if (attributes != null && attributes.length > 0)
6764 colour.setAttributeName(attributes);
6766 if (colourModel.isAutoScale() != null)
6768 colour.setAutoScaled(colourModel.isAutoScale().booleanValue());
6770 if (colourModel.isColourByLabel() != null)
6772 colour.setColourByLabel(
6773 colourModel.isColourByLabel().booleanValue());
6775 if (colourModel.getThreshold() != null)
6777 colour.setThreshold(colourModel.getThreshold().floatValue());
6779 ThresholdType ttyp = colourModel.getThreshType();
6780 if (ttyp == ThresholdType.ABOVE)
6782 colour.setAboveThreshold(true);
6784 else if (ttyp == ThresholdType.BELOW)
6786 colour.setBelowThreshold(true);
6791 Color color = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6792 colour = new FeatureColour(color);