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 java.awt.Color;
29 import java.awt.Rectangle;
30 import java.io.BufferedReader;
31 import java.io.ByteArrayInputStream;
33 import java.io.FileInputStream;
34 import java.io.FileOutputStream;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.InputStreamReader;
38 import java.io.OutputStream;
39 import java.io.OutputStreamWriter;
40 import java.io.PrintWriter;
41 import java.lang.reflect.InvocationTargetException;
42 import java.math.BigInteger;
43 import java.net.MalformedURLException;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Collections;
48 import java.util.Enumeration;
49 import java.util.GregorianCalendar;
50 import java.util.HashMap;
51 import java.util.HashSet;
52 import java.util.Hashtable;
53 import java.util.IdentityHashMap;
54 import java.util.Iterator;
55 import java.util.LinkedHashMap;
56 import java.util.List;
57 import java.util.Locale;
59 import java.util.Map.Entry;
61 import java.util.Vector;
62 import java.util.jar.JarEntry;
63 import java.util.jar.JarInputStream;
64 import java.util.jar.JarOutputStream;
66 import javax.swing.JInternalFrame;
67 import javax.swing.SwingUtilities;
68 import javax.xml.bind.JAXBContext;
69 import javax.xml.bind.JAXBElement;
70 import javax.xml.bind.Marshaller;
71 import javax.xml.datatype.DatatypeConfigurationException;
72 import javax.xml.datatype.DatatypeFactory;
73 import javax.xml.datatype.XMLGregorianCalendar;
74 import javax.xml.stream.XMLInputFactory;
75 import javax.xml.stream.XMLStreamReader;
77 import jalview.analysis.Conservation;
78 import jalview.analysis.PCA;
79 import jalview.analysis.scoremodels.ScoreModels;
80 import jalview.analysis.scoremodels.SimilarityParams;
81 import jalview.api.FeatureColourI;
82 import jalview.api.ViewStyleI;
83 import jalview.api.analysis.ScoreModelI;
84 import jalview.api.analysis.SimilarityParamsI;
85 import jalview.api.structures.JalviewStructureDisplayI;
86 import jalview.bin.Cache;
87 import jalview.bin.Console;
88 import jalview.datamodel.AlignedCodonFrame;
89 import jalview.datamodel.Alignment;
90 import jalview.datamodel.AlignmentAnnotation;
91 import jalview.datamodel.AlignmentI;
92 import jalview.datamodel.ContactMatrix;
93 import jalview.datamodel.ContactMatrixI;
94 import jalview.datamodel.DBRefEntry;
95 import jalview.datamodel.GeneLocus;
96 import jalview.datamodel.GraphLine;
97 import jalview.datamodel.PDBEntry;
98 import jalview.datamodel.Point;
99 import jalview.datamodel.RnaViewerModel;
100 import jalview.datamodel.SequenceFeature;
101 import jalview.datamodel.SequenceGroup;
102 import jalview.datamodel.SequenceI;
103 import jalview.datamodel.StructureViewerModel;
104 import jalview.datamodel.StructureViewerModel.StructureData;
105 import jalview.datamodel.features.FeatureMatcher;
106 import jalview.datamodel.features.FeatureMatcherI;
107 import jalview.datamodel.features.FeatureMatcherSet;
108 import jalview.datamodel.features.FeatureMatcherSetI;
109 import jalview.ext.varna.RnaModel;
110 import jalview.gui.AlignFrame;
111 import jalview.gui.AlignViewport;
112 import jalview.gui.AlignmentPanel;
113 import jalview.gui.AppVarna;
114 import jalview.gui.Desktop;
115 import jalview.gui.JvOptionPane;
116 import jalview.gui.OOMWarning;
117 import jalview.gui.OverviewPanel;
118 import jalview.gui.PCAPanel;
119 import jalview.gui.PaintRefresher;
120 import jalview.gui.SplitFrame;
121 import jalview.gui.StructureViewer;
122 import jalview.gui.StructureViewer.ViewerType;
123 import jalview.gui.StructureViewerBase;
124 import jalview.gui.TreePanel;
125 import jalview.io.BackupFiles;
126 import jalview.io.DataSourceType;
127 import jalview.io.FileFormat;
128 import jalview.io.NewickFile;
129 import jalview.math.Matrix;
130 import jalview.math.MatrixI;
131 import jalview.renderer.ResidueShaderI;
132 import jalview.schemes.AnnotationColourGradient;
133 import jalview.schemes.ColourSchemeI;
134 import jalview.schemes.ColourSchemeProperty;
135 import jalview.schemes.FeatureColour;
136 import jalview.schemes.ResidueProperties;
137 import jalview.schemes.UserColourScheme;
138 import jalview.structure.StructureSelectionManager;
139 import jalview.structures.models.AAStructureBindingModel;
140 import jalview.util.Format;
141 import jalview.util.HttpUtils;
142 import jalview.util.MessageManager;
143 import jalview.util.Platform;
144 import jalview.util.StringUtils;
145 import jalview.util.jarInputStreamProvider;
146 import jalview.util.matcher.Condition;
147 import jalview.viewmodel.AlignmentViewport;
148 import jalview.viewmodel.PCAModel;
149 import jalview.viewmodel.ViewportRanges;
150 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
151 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
152 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
153 import jalview.ws.datamodel.alphafold.PAEContactMatrix;
154 import jalview.ws.jws2.Jws2Discoverer;
155 import jalview.ws.jws2.dm.AAConSettings;
156 import jalview.ws.jws2.jabaws2.Jws2Instance;
157 import jalview.ws.params.ArgumentI;
158 import jalview.ws.params.AutoCalcSetting;
159 import jalview.ws.params.WsParamSetI;
160 import jalview.xml.binding.jalview.AlcodonFrame;
161 import jalview.xml.binding.jalview.AlcodonFrame.AlcodMap;
162 import jalview.xml.binding.jalview.Annotation;
163 import jalview.xml.binding.jalview.Annotation.ThresholdLine;
164 import jalview.xml.binding.jalview.AnnotationColourScheme;
165 import jalview.xml.binding.jalview.AnnotationElement;
166 import jalview.xml.binding.jalview.DoubleMatrix;
167 import jalview.xml.binding.jalview.DoubleVector;
168 import jalview.xml.binding.jalview.Feature;
169 import jalview.xml.binding.jalview.Feature.OtherData;
170 import jalview.xml.binding.jalview.FeatureMatcherSet.CompoundMatcher;
171 import jalview.xml.binding.jalview.FilterBy;
172 import jalview.xml.binding.jalview.JalviewModel;
173 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings;
174 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Group;
175 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Setting;
176 import jalview.xml.binding.jalview.JalviewModel.JGroup;
177 import jalview.xml.binding.jalview.JalviewModel.JSeq;
178 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids;
179 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids.StructureState;
180 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer;
181 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer.SecondaryStructure;
182 import jalview.xml.binding.jalview.JalviewModel.PcaViewer;
183 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.Axis;
184 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SeqPointMax;
185 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SeqPointMin;
186 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SequencePoint;
187 import jalview.xml.binding.jalview.JalviewModel.Tree;
188 import jalview.xml.binding.jalview.JalviewModel.UserColours;
189 import jalview.xml.binding.jalview.JalviewModel.Viewport;
190 import jalview.xml.binding.jalview.JalviewModel.Viewport.CalcIdParam;
191 import jalview.xml.binding.jalview.JalviewModel.Viewport.HiddenColumns;
192 import jalview.xml.binding.jalview.JalviewModel.Viewport.Overview;
193 import jalview.xml.binding.jalview.JalviewUserColours;
194 import jalview.xml.binding.jalview.JalviewUserColours.Colour;
195 import jalview.xml.binding.jalview.MapListType.MapListFrom;
196 import jalview.xml.binding.jalview.MapListType.MapListTo;
197 import jalview.xml.binding.jalview.Mapping;
198 import jalview.xml.binding.jalview.MatrixType;
199 import jalview.xml.binding.jalview.NoValueColour;
200 import jalview.xml.binding.jalview.ObjectFactory;
201 import jalview.xml.binding.jalview.PcaDataType;
202 import jalview.xml.binding.jalview.Pdbentry.Property;
203 import jalview.xml.binding.jalview.Sequence;
204 import jalview.xml.binding.jalview.Sequence.DBRef;
205 import jalview.xml.binding.jalview.SequenceSet;
206 import jalview.xml.binding.jalview.SequenceSet.SequenceSetProperties;
207 import jalview.xml.binding.jalview.ThresholdType;
208 import jalview.xml.binding.jalview.VAMSAS;
211 * Write out the current jalview desktop state as a Jalview XML stream.
213 * Note: the vamsas objects referred to here are primitive versions of the
214 * VAMSAS project schema elements - they are not the same and most likely never
218 * @version $Revision: 1.134 $
220 public class Jalview2XML
223 // BH 2018 we add the .jvp binary extension to J2S so that
224 // it will declare that binary when we do the file save from the browser
228 Platform.addJ2SBinaryType(".jvp?");
231 private static final String VIEWER_PREFIX = "viewer_";
233 private static final String RNA_PREFIX = "rna_";
235 private static final String UTF_8 = "UTF-8";
238 * used in decision if quit confirmation should be issued
240 private static boolean stateSavedUpToDate = false;
243 * prefix for recovering datasets for alignments with multiple views where
244 * non-existent dataset IDs were written for some views
246 private static final String UNIQSEQSETID = "uniqueSeqSetId.";
248 // use this with nextCounter() to make unique names for entities
249 private int counter = 0;
252 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
253 * of sequence objects are created.
255 IdentityHashMap<SequenceI, String> seqsToIds = null;
258 * jalview XML Sequence ID to jalview sequence object reference (both dataset
259 * and alignment sequences. Populated as XML reps of sequence objects are
262 Map<String, SequenceI> seqRefIds = null;
264 Map<String, SequenceI> incompleteSeqs = null;
266 List<SeqFref> frefedSequence = null;
268 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
271 * Map of reconstructed AlignFrame objects that appear to have come from
272 * SplitFrame objects (have a dna/protein complement view).
274 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
277 * Map from displayed rna structure models to their saved session state jar
280 private Map<RnaModel, String> rnaSessions = new HashMap<>();
283 * A helper method for safely using the value of an optional attribute that
284 * may be null if not present in the XML. Answers the boolean value, or false
290 public static boolean safeBoolean(Boolean b)
292 return b == null ? false : b.booleanValue();
296 * A helper method for safely using the value of an optional attribute that
297 * may be null if not present in the XML. Answers the integer value, or zero
303 public static int safeInt(Integer i)
305 return i == null ? 0 : i.intValue();
309 * A helper method for safely using the value of an optional attribute that
310 * may be null if not present in the XML. Answers the float value, or zero if
316 public static float safeFloat(Float f)
318 return f == null ? 0f : f.floatValue();
322 * create/return unique hash string for sq
325 * @return new or existing unique string for sq
327 String seqHash(SequenceI sq)
329 if (seqsToIds == null)
333 if (seqsToIds.containsKey(sq))
335 return seqsToIds.get(sq);
339 // create sequential key
340 String key = "sq" + (seqsToIds.size() + 1);
341 key = makeHashCode(sq, key); // check we don't have an external reference
343 seqsToIds.put(sq, key);
350 if (seqsToIds == null)
352 seqsToIds = new IdentityHashMap<>();
354 if (seqRefIds == null)
356 seqRefIds = new HashMap<>();
358 if (incompleteSeqs == null)
360 incompleteSeqs = new HashMap<>();
362 if (frefedSequence == null)
364 frefedSequence = new ArrayList<>();
372 public Jalview2XML(boolean raiseGUI)
374 this.raiseGUI = raiseGUI;
378 * base class for resolving forward references to sequences by their ID
383 abstract class SeqFref
389 public SeqFref(String _sref, String type)
395 public String getSref()
400 public SequenceI getSrefSeq()
402 return seqRefIds.get(sref);
405 public boolean isResolvable()
407 return seqRefIds.get(sref) != null;
410 public SequenceI getSrefDatasetSeq()
412 SequenceI sq = seqRefIds.get(sref);
415 while (sq.getDatasetSequence() != null)
417 sq = sq.getDatasetSequence();
424 * @return true if the forward reference was fully resolved
426 abstract boolean resolve();
429 public String toString()
431 return type + " reference to " + sref;
436 * create forward reference for a mapping
442 public SeqFref newMappingRef(final String sref,
443 final jalview.datamodel.Mapping _jmap)
445 SeqFref fref = new SeqFref(sref, "Mapping")
447 public jalview.datamodel.Mapping jmap = _jmap;
452 SequenceI seq = getSrefDatasetSeq();
464 public SeqFref newAlcodMapRef(final String sref,
465 final AlignedCodonFrame _cf,
466 final jalview.datamodel.Mapping _jmap)
469 SeqFref fref = new SeqFref(sref, "Codon Frame")
471 AlignedCodonFrame cf = _cf;
473 public jalview.datamodel.Mapping mp = _jmap;
476 public boolean isResolvable()
478 return super.isResolvable() && mp.getTo() != null;
484 SequenceI seq = getSrefDatasetSeq();
489 cf.addMap(seq, mp.getTo(), mp.getMap());
496 public void resolveFrefedSequences()
498 Iterator<SeqFref> nextFref = frefedSequence.iterator();
499 int toresolve = frefedSequence.size();
500 int unresolved = 0, failedtoresolve = 0;
501 while (nextFref.hasNext())
503 SeqFref ref = nextFref.next();
504 if (ref.isResolvable())
516 } catch (Exception x)
519 "IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
532 System.err.println("Jalview Project Import: There were " + unresolved
533 + " forward references left unresolved on the stack.");
535 if (failedtoresolve > 0)
537 System.err.println("SERIOUS! " + failedtoresolve
538 + " resolvable forward references failed to resolve.");
540 if (incompleteSeqs != null && incompleteSeqs.size() > 0)
543 "Jalview Project Import: There are " + incompleteSeqs.size()
544 + " sequences which may have incomplete metadata.");
545 if (incompleteSeqs.size() < 10)
547 for (SequenceI s : incompleteSeqs.values())
549 System.err.println(s.toString());
555 "Too many to report. Skipping output of incomplete sequences.");
561 * This maintains a map of viewports, the key being the seqSetId. Important to
562 * set historyItem and redoList for multiple views
564 Map<String, AlignViewport> viewportsAdded = new HashMap<>();
566 Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
568 String uniqueSetSuffix = "";
571 * List of pdbfiles added to Jar
573 List<String> pdbfiles = null;
575 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
576 public void saveState(File statefile)
578 FileOutputStream fos = null;
583 fos = new FileOutputStream(statefile);
585 JarOutputStream jout = new JarOutputStream(fos);
589 } catch (Exception e)
591 Console.error("Couln't write Jalview state to " + statefile, e);
592 // TODO: inform user of the problem - they need to know if their data was
594 if (errorMessage == null)
596 errorMessage = "Did't write Jalview Archive to output file '"
597 + statefile + "' - See console error log for details";
601 errorMessage += "(Didn't write Jalview Archive to output file '"
612 } catch (IOException e)
622 * Writes a jalview project archive to the given Jar output stream.
626 public void saveState(JarOutputStream jout)
628 AlignFrame[] frames = Desktop.getAlignFrames();
630 setStateSavedUpToDate(true);
632 if (Cache.getDefault("DEBUG_DELAY_SAVE", false))
634 int n = debugDelaySave;
638 Console.debug("***** debugging save sleep " + i + "/" + n);
642 } catch (InterruptedException e)
644 // TODO Auto-generated catch block
655 saveAllFrames(Arrays.asList(frames), jout);
659 * core method for storing state for a set of AlignFrames.
662 * - frames involving all data to be exported (including containing
665 * - project output stream
667 private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
669 Hashtable<String, AlignFrame> dsses = new Hashtable<>();
672 * ensure cached data is clear before starting
674 // todo tidy up seqRefIds, seqsToIds initialisation / reset
676 splitFrameCandidates.clear();
681 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
682 // //////////////////////////////////////////////////
684 List<String> shortNames = new ArrayList<>();
685 List<String> viewIds = new ArrayList<>();
688 for (int i = frames.size() - 1; i > -1; i--)
690 AlignFrame af = frames.get(i);
692 if (skipList != null && skipList
693 .containsKey(af.getViewport().getSequenceSetId()))
698 String shortName = makeFilename(af, shortNames);
700 int apSize = af.getAlignPanels().size();
702 for (int ap = 0; ap < apSize; ap++)
704 AlignmentPanel apanel = (AlignmentPanel) af.getAlignPanels()
706 String fileName = apSize == 1 ? shortName : ap + shortName;
707 if (!fileName.endsWith(".xml"))
709 fileName = fileName + ".xml";
712 saveState(apanel, fileName, jout, viewIds);
714 String dssid = getDatasetIdRef(
715 af.getViewport().getAlignment().getDataset());
716 if (!dsses.containsKey(dssid))
718 dsses.put(dssid, af);
723 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
729 } catch (Exception foo)
733 } catch (Exception ex)
735 // TODO: inform user of the problem - they need to know if their data was
737 if (errorMessage == null)
739 errorMessage = "Couldn't write Jalview Archive - see error output for details";
741 ex.printStackTrace();
746 * Generates a distinct file name, based on the title of the AlignFrame, by
747 * appending _n for increasing n until an unused name is generated. The new
748 * name (without its extension) is added to the list.
752 * @return the generated name, with .xml extension
754 protected String makeFilename(AlignFrame af, List<String> namesUsed)
756 String shortName = af.getTitle();
758 if (shortName.indexOf(File.separatorChar) > -1)
760 shortName = shortName
761 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
766 while (namesUsed.contains(shortName))
768 if (shortName.endsWith("_" + (count - 1)))
770 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
773 shortName = shortName.concat("_" + count);
777 namesUsed.add(shortName);
779 if (!shortName.endsWith(".xml"))
781 shortName = shortName + ".xml";
786 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
787 public boolean saveAlignment(AlignFrame af, String jarFile,
792 // create backupfiles object and get new temp filename destination
793 boolean doBackup = BackupFiles.getEnabled();
794 BackupFiles backupfiles = doBackup ? new BackupFiles(jarFile) : null;
795 FileOutputStream fos = new FileOutputStream(
796 doBackup ? backupfiles.getTempFilePath() : jarFile);
798 if (Cache.getDefault("DEBUG_DELAY_SAVE", false))
800 int n = debugDelaySave;
804 Console.debug("***** debugging save sleep " + i + "/" + n);
808 } catch (InterruptedException e)
810 // TODO Auto-generated catch block
817 JarOutputStream jout = new JarOutputStream(fos);
818 List<AlignFrame> frames = new ArrayList<>();
820 // resolve splitframes
821 if (af.getViewport().getCodingComplement() != null)
823 frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
829 saveAllFrames(frames, jout);
833 } catch (Exception foo)
837 boolean success = true;
841 backupfiles.setWriteSuccess(success);
842 success = backupfiles.rollBackupsAndRenameTempFile();
846 } catch (Exception ex)
848 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
849 ex.printStackTrace();
854 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
855 String fileName, JarOutputStream jout)
858 for (String dssids : dsses.keySet())
860 AlignFrame _af = dsses.get(dssids);
861 String jfileName = fileName + " Dataset for " + _af.getTitle();
862 if (!jfileName.endsWith(".xml"))
864 jfileName = jfileName + ".xml";
866 saveState(_af.alignPanel, jfileName, true, jout, null);
871 * create a JalviewModel from an alignment view and marshall it to a
875 * panel to create jalview model for
877 * name of alignment panel written to output stream
884 public JalviewModel saveState(AlignmentPanel ap, String fileName,
885 JarOutputStream jout, List<String> viewIds)
887 return saveState(ap, fileName, false, jout, viewIds);
891 * create a JalviewModel from an alignment view and marshall it to a
895 * panel to create jalview model for
897 * name of alignment panel written to output stream
899 * when true, only write the dataset for the alignment, not the data
900 * associated with the view.
906 public JalviewModel saveState(AlignmentPanel ap, String fileName,
907 boolean storeDS, JarOutputStream jout, List<String> viewIds)
911 viewIds = new ArrayList<>();
916 List<UserColourScheme> userColours = new ArrayList<>();
918 AlignViewport av = ap.av;
919 ViewportRanges vpRanges = av.getRanges();
921 final ObjectFactory objectFactory = new ObjectFactory();
922 JalviewModel object = objectFactory.createJalviewModel();
923 object.setVamsasModel(new VAMSAS());
925 // object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
928 GregorianCalendar c = new GregorianCalendar();
929 DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
930 XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(c);// gregorianCalendar);
931 object.setCreationDate(now);
932 } catch (DatatypeConfigurationException e)
934 System.err.println("error writing date: " + e.toString());
936 object.setVersion(Cache.getDefault("VERSION", "Development Build"));
939 * rjal is full height alignment, jal is actual alignment with full metadata
940 * but excludes hidden sequences.
942 jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
944 if (av.hasHiddenRows())
946 rjal = jal.getHiddenSequences().getFullAlignment();
949 SequenceSet vamsasSet = new SequenceSet();
951 // JalviewModelSequence jms = new JalviewModelSequence();
953 vamsasSet.setGapChar(jal.getGapCharacter() + "");
955 if (jal.getDataset() != null)
957 // dataset id is the dataset's hashcode
958 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
961 // switch jal and the dataset
962 jal = jal.getDataset();
966 if (jal.getProperties() != null)
968 Enumeration en = jal.getProperties().keys();
969 while (en.hasMoreElements())
971 String key = en.nextElement().toString();
972 SequenceSetProperties ssp = new SequenceSetProperties();
974 ssp.setValue(jal.getProperties().get(key).toString());
975 // vamsasSet.addSequenceSetProperties(ssp);
976 vamsasSet.getSequenceSetProperties().add(ssp);
981 Set<String> calcIdSet = new HashSet<>();
982 // record the set of vamsas sequence XML POJO we create.
983 HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
985 for (final SequenceI jds : rjal.getSequences())
987 final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
988 : jds.getDatasetSequence();
989 String id = seqHash(jds);
990 if (vamsasSetIds.get(id) == null)
992 if (seqRefIds.get(id) != null && !storeDS)
994 // This happens for two reasons: 1. multiple views are being
996 // 2. the hashCode has collided with another sequence's code. This
998 // HAPPEN! (PF00072.15.stk does this)
999 // JBPNote: Uncomment to debug writing out of files that do not read
1000 // back in due to ArrayOutOfBoundExceptions.
1001 // System.err.println("vamsasSeq backref: "+id+"");
1002 // System.err.println(jds.getName()+"
1003 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
1004 // System.err.println("Hashcode: "+seqHash(jds));
1005 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
1006 // System.err.println(rsq.getName()+"
1007 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
1008 // System.err.println("Hashcode: "+seqHash(rsq));
1012 vamsasSeq = createVamsasSequence(id, jds);
1013 // vamsasSet.addSequence(vamsasSeq);
1014 vamsasSet.getSequence().add(vamsasSeq);
1015 vamsasSetIds.put(id, vamsasSeq);
1016 seqRefIds.put(id, jds);
1020 jseq.setStart(jds.getStart());
1021 jseq.setEnd(jds.getEnd());
1022 jseq.setColour(av.getSequenceColour(jds).getRGB());
1024 jseq.setId(id); // jseq id should be a string not a number
1027 // Store any sequences this sequence represents
1028 if (av.hasHiddenRows())
1030 // use rjal, contains the full height alignment
1032 av.getAlignment().getHiddenSequences().isHidden(jds));
1034 if (av.isHiddenRepSequence(jds))
1036 jalview.datamodel.SequenceI[] reps = av
1037 .getRepresentedSequences(jds).getSequencesInOrder(rjal);
1039 for (int h = 0; h < reps.length; h++)
1043 // jseq.addHiddenSequences(rjal.findIndex(reps[h]));
1044 jseq.getHiddenSequences().add(rjal.findIndex(reps[h]));
1049 // mark sequence as reference - if it is the reference for this view
1050 if (jal.hasSeqrep())
1052 jseq.setViewreference(jds == jal.getSeqrep());
1056 // TODO: omit sequence features from each alignment view's XML dump if we
1057 // are storing dataset
1058 List<SequenceFeature> sfs = jds.getSequenceFeatures();
1059 for (SequenceFeature sf : sfs)
1061 // Features features = new Features();
1062 Feature features = new Feature();
1064 features.setBegin(sf.getBegin());
1065 features.setEnd(sf.getEnd());
1066 features.setDescription(sf.getDescription());
1067 features.setType(sf.getType());
1068 features.setFeatureGroup(sf.getFeatureGroup());
1069 features.setScore(sf.getScore());
1070 if (sf.links != null)
1072 for (int l = 0; l < sf.links.size(); l++)
1074 OtherData keyValue = new OtherData();
1075 keyValue.setKey("LINK_" + l);
1076 keyValue.setValue(sf.links.elementAt(l).toString());
1077 // features.addOtherData(keyValue);
1078 features.getOtherData().add(keyValue);
1081 if (sf.otherDetails != null)
1084 * save feature attributes, which may be simple strings or
1085 * map valued (have sub-attributes)
1087 for (Entry<String, Object> entry : sf.otherDetails.entrySet())
1089 String key = entry.getKey();
1090 Object value = entry.getValue();
1091 if (value instanceof Map<?, ?>)
1093 for (Entry<String, Object> subAttribute : ((Map<String, Object>) value)
1096 OtherData otherData = new OtherData();
1097 otherData.setKey(key);
1098 otherData.setKey2(subAttribute.getKey());
1099 otherData.setValue(subAttribute.getValue().toString());
1100 // features.addOtherData(otherData);
1101 features.getOtherData().add(otherData);
1106 OtherData otherData = new OtherData();
1107 otherData.setKey(key);
1108 otherData.setValue(value.toString());
1109 // features.addOtherData(otherData);
1110 features.getOtherData().add(otherData);
1115 // jseq.addFeatures(features);
1116 jseq.getFeatures().add(features);
1119 if (jdatasq.getAllPDBEntries() != null)
1121 Enumeration<PDBEntry> en = jdatasq.getAllPDBEntries().elements();
1122 while (en.hasMoreElements())
1124 Pdbids pdb = new Pdbids();
1125 jalview.datamodel.PDBEntry entry = en.nextElement();
1127 String pdbId = entry.getId();
1129 pdb.setType(entry.getType());
1132 * Store any structure views associated with this sequence. This
1133 * section copes with duplicate entries in the project, so a dataset
1134 * only view *should* be coped with sensibly.
1136 // This must have been loaded, is it still visible?
1137 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1138 String matchedFile = null;
1139 for (int f = frames.length - 1; f > -1; f--)
1141 if (frames[f] instanceof StructureViewerBase)
1143 StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
1144 matchedFile = saveStructureViewer(ap, jds, pdb, entry,
1145 viewIds, matchedFile, viewFrame);
1147 * Only store each structure viewer's state once in the project
1148 * jar. First time through only (storeDS==false)
1150 String viewId = viewFrame.getViewId();
1151 String viewerType = viewFrame.getViewerType().toString();
1152 if (!storeDS && !viewIds.contains(viewId))
1154 viewIds.add(viewId);
1155 File viewerState = viewFrame.saveSession();
1156 if (viewerState != null)
1158 copyFileToJar(jout, viewerState.getPath(),
1159 getViewerJarEntryName(viewId), viewerType);
1164 "Failed to save viewer state for " + viewerType);
1170 if (matchedFile != null || entry.getFile() != null)
1172 if (entry.getFile() != null)
1175 matchedFile = entry.getFile();
1177 pdb.setFile(matchedFile); // entry.getFile());
1178 if (pdbfiles == null)
1180 pdbfiles = new ArrayList<>();
1183 if (!pdbfiles.contains(pdbId))
1185 pdbfiles.add(pdbId);
1186 copyFileToJar(jout, matchedFile, pdbId, pdbId);
1190 Enumeration<String> props = entry.getProperties();
1191 if (props.hasMoreElements())
1193 // PdbentryItem item = new PdbentryItem();
1194 while (props.hasMoreElements())
1196 Property prop = new Property();
1197 String key = props.nextElement();
1199 prop.setValue(entry.getProperty(key).toString());
1200 // item.addProperty(prop);
1201 pdb.getProperty().add(prop);
1203 // pdb.addPdbentryItem(item);
1206 // jseq.addPdbids(pdb);
1207 jseq.getPdbids().add(pdb);
1211 saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
1213 // jms.addJSeq(jseq);
1214 object.getJSeq().add(jseq);
1217 if (!storeDS && av.hasHiddenRows())
1219 jal = av.getAlignment();
1223 if (storeDS && jal.getCodonFrames() != null)
1225 List<AlignedCodonFrame> jac = jal.getCodonFrames();
1226 for (AlignedCodonFrame acf : jac)
1228 AlcodonFrame alc = new AlcodonFrame();
1229 if (acf.getProtMappings() != null
1230 && acf.getProtMappings().length > 0)
1232 boolean hasMap = false;
1233 SequenceI[] dnas = acf.getdnaSeqs();
1234 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1235 for (int m = 0; m < pmaps.length; m++)
1237 AlcodMap alcmap = new AlcodMap();
1238 alcmap.setDnasq(seqHash(dnas[m]));
1240 createVamsasMapping(pmaps[m], dnas[m], null, false));
1241 // alc.addAlcodMap(alcmap);
1242 alc.getAlcodMap().add(alcmap);
1247 // vamsasSet.addAlcodonFrame(alc);
1248 vamsasSet.getAlcodonFrame().add(alc);
1251 // TODO: delete this ? dead code from 2.8.3->2.9 ?
1253 // AlcodonFrame alc = new AlcodonFrame();
1254 // vamsasSet.addAlcodonFrame(alc);
1255 // for (int p = 0; p < acf.aaWidth; p++)
1257 // Alcodon cmap = new Alcodon();
1258 // if (acf.codons[p] != null)
1260 // // Null codons indicate a gapped column in the translated peptide
1262 // cmap.setPos1(acf.codons[p][0]);
1263 // cmap.setPos2(acf.codons[p][1]);
1264 // cmap.setPos3(acf.codons[p][2]);
1266 // alc.addAlcodon(cmap);
1268 // if (acf.getProtMappings() != null
1269 // && acf.getProtMappings().length > 0)
1271 // SequenceI[] dnas = acf.getdnaSeqs();
1272 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1273 // for (int m = 0; m < pmaps.length; m++)
1275 // AlcodMap alcmap = new AlcodMap();
1276 // alcmap.setDnasq(seqHash(dnas[m]));
1277 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1279 // alc.addAlcodMap(alcmap);
1286 // /////////////////////////////////
1287 if (!storeDS && av.getCurrentTree() != null)
1289 // FIND ANY ASSOCIATED TREES
1290 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
1291 if (Desktop.desktop != null)
1293 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1295 for (int t = 0; t < frames.length; t++)
1297 if (frames[t] instanceof TreePanel)
1299 TreePanel tp = (TreePanel) frames[t];
1301 if (tp.getTreeCanvas().getViewport().getAlignment() == jal)
1303 JalviewModel.Tree tree = new JalviewModel.Tree();
1304 tree.setTitle(tp.getTitle());
1305 tree.setCurrentTree((av.getCurrentTree() == tp.getTree()));
1306 tree.setNewick(tp.getTree().print());
1307 tree.setThreshold(tp.getTreeCanvas().getThreshold());
1309 tree.setFitToWindow(tp.fitToWindow.getState());
1310 tree.setFontName(tp.getTreeFont().getName());
1311 tree.setFontSize(tp.getTreeFont().getSize());
1312 tree.setFontStyle(tp.getTreeFont().getStyle());
1313 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
1315 tree.setShowBootstrap(tp.bootstrapMenu.getState());
1316 tree.setShowDistances(tp.distanceMenu.getState());
1318 tree.setHeight(tp.getHeight());
1319 tree.setWidth(tp.getWidth());
1320 tree.setXpos(tp.getX());
1321 tree.setYpos(tp.getY());
1322 tree.setId(makeHashCode(tp, null));
1323 tree.setLinkToAllViews(
1324 tp.getTreeCanvas().isApplyToAllViews());
1326 // jms.addTree(tree);
1327 object.getTree().add(tree);
1337 if (!storeDS && Desktop.desktop != null)
1339 for (JInternalFrame frame : Desktop.desktop.getAllFrames())
1341 if (frame instanceof PCAPanel)
1343 PCAPanel panel = (PCAPanel) frame;
1344 if (panel.getAlignViewport().getAlignment() == jal)
1346 savePCA(panel, object);
1354 * store forward refs from an annotationRow to any groups
1356 IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
1359 for (SequenceI sq : jal.getSequences())
1361 // Store annotation on dataset sequences only
1362 AlignmentAnnotation[] aa = sq.getAnnotation();
1363 if (aa != null && aa.length > 0)
1365 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1372 if (jal.getAlignmentAnnotation() != null)
1374 // Store the annotation shown on the alignment.
1375 AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
1376 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1381 if (jal.getGroups() != null)
1383 JGroup[] groups = new JGroup[jal.getGroups().size()];
1385 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
1387 JGroup jGroup = new JGroup();
1388 groups[++i] = jGroup;
1390 jGroup.setStart(sg.getStartRes());
1391 jGroup.setEnd(sg.getEndRes());
1392 jGroup.setName(sg.getName());
1393 if (groupRefs.containsKey(sg))
1395 // group has references so set its ID field
1396 jGroup.setId(groupRefs.get(sg));
1398 ColourSchemeI colourScheme = sg.getColourScheme();
1399 if (colourScheme != null)
1401 ResidueShaderI groupColourScheme = sg.getGroupColourScheme();
1402 if (groupColourScheme.conservationApplied())
1404 jGroup.setConsThreshold(groupColourScheme.getConservationInc());
1406 if (colourScheme instanceof jalview.schemes.UserColourScheme)
1408 jGroup.setColour(setUserColourScheme(colourScheme,
1409 userColours, object));
1413 jGroup.setColour(colourScheme.getSchemeName());
1416 else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
1418 jGroup.setColour("AnnotationColourGradient");
1419 jGroup.setAnnotationColours(constructAnnotationColours(
1420 (jalview.schemes.AnnotationColourGradient) colourScheme,
1421 userColours, object));
1423 else if (colourScheme instanceof jalview.schemes.UserColourScheme)
1426 setUserColourScheme(colourScheme, userColours, object));
1430 jGroup.setColour(colourScheme.getSchemeName());
1433 jGroup.setPidThreshold(groupColourScheme.getThreshold());
1436 jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
1437 jGroup.setDisplayBoxes(sg.getDisplayBoxes());
1438 jGroup.setDisplayText(sg.getDisplayText());
1439 jGroup.setColourText(sg.getColourText());
1440 jGroup.setTextCol1(sg.textColour.getRGB());
1441 jGroup.setTextCol2(sg.textColour2.getRGB());
1442 jGroup.setTextColThreshold(sg.thresholdTextColour);
1443 jGroup.setShowUnconserved(sg.getShowNonconserved());
1444 jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1445 jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
1446 jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
1447 jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1448 for (SequenceI seq : sg.getSequences())
1450 // jGroup.addSeq(seqHash(seq));
1451 jGroup.getSeq().add(seqHash(seq));
1455 // jms.setJGroup(groups);
1457 for (JGroup grp : groups)
1459 object.getJGroup().add(grp);
1464 // /////////SAVE VIEWPORT
1465 Viewport view = new Viewport();
1466 view.setTitle(ap.alignFrame.getTitle());
1467 view.setSequenceSetId(
1468 makeHashCode(av.getSequenceSetId(), av.getSequenceSetId()));
1469 view.setId(av.getViewId());
1470 if (av.getCodingComplement() != null)
1472 view.setComplementId(av.getCodingComplement().getViewId());
1474 view.setViewName(av.getViewName());
1475 view.setGatheredViews(av.isGatherViewsHere());
1477 Rectangle size = ap.av.getExplodedGeometry();
1478 Rectangle position = size;
1481 size = ap.alignFrame.getBounds();
1482 if (av.getCodingComplement() != null)
1484 position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
1492 view.setXpos(position.x);
1493 view.setYpos(position.y);
1495 view.setWidth(size.width);
1496 view.setHeight(size.height);
1498 view.setStartRes(vpRanges.getStartRes());
1499 view.setStartSeq(vpRanges.getStartSeq());
1501 OverviewPanel ov = ap.getOverviewPanel();
1504 Overview overview = new Overview();
1505 overview.setTitle(ov.getTitle());
1506 Rectangle bounds = ov.getFrameBounds();
1507 overview.setXpos(bounds.x);
1508 overview.setYpos(bounds.y);
1509 overview.setWidth(bounds.width);
1510 overview.setHeight(bounds.height);
1511 overview.setShowHidden(ov.isShowHiddenRegions());
1512 overview.setGapColour(ov.getCanvas().getGapColour().getRGB());
1513 overview.setResidueColour(
1514 ov.getCanvas().getResidueColour().getRGB());
1515 overview.setHiddenColour(ov.getCanvas().getHiddenColour().getRGB());
1516 view.setOverview(overview);
1518 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1520 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1521 userColours, object));
1524 .getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1526 AnnotationColourScheme ac = constructAnnotationColours(
1527 (jalview.schemes.AnnotationColourGradient) av
1528 .getGlobalColourScheme(),
1529 userColours, object);
1531 view.setAnnotationColours(ac);
1532 view.setBgColour("AnnotationColourGradient");
1536 view.setBgColour(ColourSchemeProperty
1537 .getColourName(av.getGlobalColourScheme()));
1540 ResidueShaderI vcs = av.getResidueShading();
1541 ColourSchemeI cs = av.getGlobalColourScheme();
1545 if (vcs.conservationApplied())
1547 view.setConsThreshold(vcs.getConservationInc());
1548 if (cs instanceof jalview.schemes.UserColourScheme)
1550 view.setBgColour(setUserColourScheme(cs, userColours, object));
1553 view.setPidThreshold(vcs.getThreshold());
1556 view.setConservationSelected(av.getConservationSelected());
1557 view.setPidSelected(av.getAbovePIDThreshold());
1558 view.setCharHeight(av.getCharHeight());
1559 view.setCharWidth(av.getCharWidth());
1560 final Font font = av.getFont();
1561 view.setFontName(font.getName());
1562 view.setFontSize(font.getSize());
1563 view.setFontStyle(font.getStyle());
1564 view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
1565 view.setRenderGaps(av.isRenderGaps());
1566 view.setShowAnnotation(av.isShowAnnotation());
1567 view.setShowBoxes(av.getShowBoxes());
1568 view.setShowColourText(av.getColourText());
1569 view.setShowFullId(av.getShowJVSuffix());
1570 view.setRightAlignIds(av.isRightAlignIds());
1571 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1572 view.setShowText(av.getShowText());
1573 view.setShowUnconserved(av.getShowUnconserved());
1574 view.setWrapAlignment(av.getWrapAlignment());
1575 view.setTextCol1(av.getTextColour().getRGB());
1576 view.setTextCol2(av.getTextColour2().getRGB());
1577 view.setTextColThreshold(av.getThresholdTextColour());
1578 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1579 view.setShowSequenceLogo(av.isShowSequenceLogo());
1580 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1581 view.setShowGroupConsensus(av.isShowGroupConsensus());
1582 view.setShowGroupConservation(av.isShowGroupConservation());
1583 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1584 view.setShowDbRefTooltip(av.isShowDBRefs());
1585 view.setFollowHighlight(av.isFollowHighlight());
1586 view.setFollowSelection(av.followSelection);
1587 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1588 view.setShowComplementFeatures(av.isShowComplementFeatures());
1589 view.setShowComplementFeaturesOnTop(
1590 av.isShowComplementFeaturesOnTop());
1591 if (av.getFeaturesDisplayed() != null)
1593 FeatureSettings fs = new FeatureSettings();
1595 FeatureRendererModel fr = ap.getSeqPanel().seqCanvas
1596 .getFeatureRenderer();
1597 String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
1599 Vector<String> settingsAdded = new Vector<>();
1600 if (renderOrder != null)
1602 for (String featureType : renderOrder)
1604 FeatureSettings.Setting setting = new FeatureSettings.Setting();
1605 setting.setType(featureType);
1608 * save any filter for the feature type
1610 FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
1613 Iterator<FeatureMatcherI> filters = filter.getMatchers()
1615 FeatureMatcherI firstFilter = filters.next();
1616 setting.setMatcherSet(Jalview2XML.marshalFilter(firstFilter,
1617 filters, filter.isAnded()));
1621 * save colour scheme for the feature type
1623 FeatureColourI fcol = fr.getFeatureStyle(featureType);
1624 if (!fcol.isSimpleColour())
1626 setting.setColour(fcol.getMaxColour().getRGB());
1627 setting.setMincolour(fcol.getMinColour().getRGB());
1628 setting.setMin(fcol.getMin());
1629 setting.setMax(fcol.getMax());
1630 setting.setColourByLabel(fcol.isColourByLabel());
1631 if (fcol.isColourByAttribute())
1633 String[] attName = fcol.getAttributeName();
1634 setting.getAttributeName().add(attName[0]);
1635 if (attName.length > 1)
1637 setting.getAttributeName().add(attName[1]);
1640 setting.setAutoScale(fcol.isAutoScaled());
1641 setting.setThreshold(fcol.getThreshold());
1642 Color noColour = fcol.getNoColour();
1643 if (noColour == null)
1645 setting.setNoValueColour(NoValueColour.NONE);
1647 else if (noColour.equals(fcol.getMaxColour()))
1649 setting.setNoValueColour(NoValueColour.MAX);
1653 setting.setNoValueColour(NoValueColour.MIN);
1655 // -1 = No threshold, 0 = Below, 1 = Above
1656 setting.setThreshstate(fcol.isAboveThreshold() ? 1
1657 : (fcol.isBelowThreshold() ? 0 : -1));
1661 setting.setColour(fcol.getColour().getRGB());
1665 av.getFeaturesDisplayed().isVisible(featureType));
1666 float rorder = fr.getOrder(featureType);
1669 setting.setOrder(rorder);
1671 /// fs.addSetting(setting);
1672 fs.getSetting().add(setting);
1673 settingsAdded.addElement(featureType);
1677 // is groups actually supposed to be a map here ?
1678 Iterator<String> en = fr.getFeatureGroups().iterator();
1679 Vector<String> groupsAdded = new Vector<>();
1680 while (en.hasNext())
1682 String grp = en.next();
1683 if (groupsAdded.contains(grp))
1687 Group g = new Group();
1689 g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
1692 fs.getGroup().add(g);
1693 groupsAdded.addElement(grp);
1695 // jms.setFeatureSettings(fs);
1696 object.setFeatureSettings(fs);
1699 if (av.hasHiddenColumns())
1701 jalview.datamodel.HiddenColumns hidden = av.getAlignment()
1702 .getHiddenColumns();
1706 "REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1710 Iterator<int[]> hiddenRegions = hidden.iterator();
1711 while (hiddenRegions.hasNext())
1713 int[] region = hiddenRegions.next();
1714 HiddenColumns hc = new HiddenColumns();
1715 hc.setStart(region[0]);
1716 hc.setEnd(region[1]);
1717 // view.addHiddenColumns(hc);
1718 view.getHiddenColumns().add(hc);
1722 if (calcIdSet.size() > 0)
1724 for (String calcId : calcIdSet)
1726 if (calcId.trim().length() > 0)
1728 CalcIdParam cidp = createCalcIdParam(calcId, av);
1729 // Some calcIds have no parameters.
1732 // view.addCalcIdParam(cidp);
1733 view.getCalcIdParam().add(cidp);
1739 // jms.addViewport(view);
1740 object.getViewport().add(view);
1742 // object.setJalviewModelSequence(jms);
1743 // object.getVamsasModel().addSequenceSet(vamsasSet);
1744 object.getVamsasModel().getSequenceSet().add(vamsasSet);
1746 if (jout != null && fileName != null)
1748 // We may not want to write the object to disk,
1749 // eg we can copy the alignViewport to a new view object
1750 // using save and then load
1753 fileName = fileName.replace('\\', '/');
1754 System.out.println("Writing jar entry " + fileName);
1755 JarEntry entry = new JarEntry(fileName);
1756 jout.putNextEntry(entry);
1757 PrintWriter pout = new PrintWriter(
1758 new OutputStreamWriter(jout, UTF_8));
1759 JAXBContext jaxbContext = JAXBContext
1760 .newInstance(JalviewModel.class);
1761 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
1763 // output pretty printed
1764 // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1765 jaxbMarshaller.marshal(
1766 new ObjectFactory().createJalviewModel(object), pout);
1768 // jaxbMarshaller.marshal(object, pout);
1769 // marshaller.marshal(object);
1772 } catch (Exception ex)
1774 // TODO: raise error in GUI if marshalling failed.
1775 System.err.println("Error writing Jalview project");
1776 ex.printStackTrace();
1783 * Writes PCA viewer attributes and computed values to an XML model object and
1784 * adds it to the JalviewModel. Any exceptions are reported by logging.
1786 protected void savePCA(PCAPanel panel, JalviewModel object)
1790 PcaViewer viewer = new PcaViewer();
1791 viewer.setHeight(panel.getHeight());
1792 viewer.setWidth(panel.getWidth());
1793 viewer.setXpos(panel.getX());
1794 viewer.setYpos(panel.getY());
1795 viewer.setTitle(panel.getTitle());
1796 PCAModel pcaModel = panel.getPcaModel();
1797 viewer.setScoreModelName(pcaModel.getScoreModelName());
1798 viewer.setXDim(panel.getSelectedDimensionIndex(X));
1799 viewer.setYDim(panel.getSelectedDimensionIndex(Y));
1800 viewer.setZDim(panel.getSelectedDimensionIndex(Z));
1802 panel.getRotatableCanvas().getBackgroundColour().getRGB());
1803 viewer.setScaleFactor(panel.getRotatableCanvas().getScaleFactor());
1804 float[] spMin = panel.getRotatableCanvas().getSeqMin();
1805 SeqPointMin spmin = new SeqPointMin();
1806 spmin.setXPos(spMin[0]);
1807 spmin.setYPos(spMin[1]);
1808 spmin.setZPos(spMin[2]);
1809 viewer.setSeqPointMin(spmin);
1810 float[] spMax = panel.getRotatableCanvas().getSeqMax();
1811 SeqPointMax spmax = new SeqPointMax();
1812 spmax.setXPos(spMax[0]);
1813 spmax.setYPos(spMax[1]);
1814 spmax.setZPos(spMax[2]);
1815 viewer.setSeqPointMax(spmax);
1816 viewer.setShowLabels(panel.getRotatableCanvas().isShowLabels());
1817 viewer.setLinkToAllViews(
1818 panel.getRotatableCanvas().isApplyToAllViews());
1819 SimilarityParamsI sp = pcaModel.getSimilarityParameters();
1820 viewer.setIncludeGaps(sp.includeGaps());
1821 viewer.setMatchGaps(sp.matchGaps());
1822 viewer.setIncludeGappedColumns(sp.includeGappedColumns());
1823 viewer.setDenominateByShortestLength(sp.denominateByShortestLength());
1826 * sequence points on display
1828 for (jalview.datamodel.SequencePoint spt : pcaModel
1829 .getSequencePoints())
1831 SequencePoint point = new SequencePoint();
1832 point.setSequenceRef(seqHash(spt.getSequence()));
1833 point.setXPos(spt.coord.x);
1834 point.setYPos(spt.coord.y);
1835 point.setZPos(spt.coord.z);
1836 viewer.getSequencePoint().add(point);
1840 * (end points of) axes on display
1842 for (Point p : panel.getRotatableCanvas().getAxisEndPoints())
1845 Axis axis = new Axis();
1849 viewer.getAxis().add(axis);
1853 * raw PCA data (note we are not restoring PCA inputs here -
1854 * alignment view, score model, similarity parameters)
1856 PcaDataType data = new PcaDataType();
1857 viewer.setPcaData(data);
1858 PCA pca = pcaModel.getPcaData();
1860 DoubleMatrix pm = new DoubleMatrix();
1861 saveDoubleMatrix(pca.getPairwiseScores(), pm);
1862 data.setPairwiseMatrix(pm);
1864 DoubleMatrix tm = new DoubleMatrix();
1865 saveDoubleMatrix(pca.getTridiagonal(), tm);
1866 data.setTridiagonalMatrix(tm);
1868 DoubleMatrix eigenMatrix = new DoubleMatrix();
1869 data.setEigenMatrix(eigenMatrix);
1870 saveDoubleMatrix(pca.getEigenmatrix(), eigenMatrix);
1872 object.getPcaViewer().add(viewer);
1873 } catch (Throwable t)
1875 Console.error("Error saving PCA: " + t.getMessage());
1880 * Stores values from a matrix into an XML element, including (if present) the
1885 * @see #loadDoubleMatrix(DoubleMatrix)
1887 protected void saveDoubleMatrix(MatrixI m, DoubleMatrix xmlMatrix)
1889 xmlMatrix.setRows(m.height());
1890 xmlMatrix.setColumns(m.width());
1891 for (int i = 0; i < m.height(); i++)
1893 DoubleVector row = new DoubleVector();
1894 for (int j = 0; j < m.width(); j++)
1896 row.getV().add(m.getValue(i, j));
1898 xmlMatrix.getRow().add(row);
1900 if (m.getD() != null)
1902 DoubleVector dVector = new DoubleVector();
1903 for (double d : m.getD())
1905 dVector.getV().add(d);
1907 xmlMatrix.setD(dVector);
1909 if (m.getE() != null)
1911 DoubleVector eVector = new DoubleVector();
1912 for (double e : m.getE())
1914 eVector.getV().add(e);
1916 xmlMatrix.setE(eVector);
1921 * Loads XML matrix data into a new Matrix object, including the D and/or E
1922 * vectors (if present)
1926 * @see Jalview2XML#saveDoubleMatrix(MatrixI, DoubleMatrix)
1928 protected MatrixI loadDoubleMatrix(DoubleMatrix mData)
1930 int rows = mData.getRows();
1931 double[][] vals = new double[rows][];
1933 for (int i = 0; i < rows; i++)
1935 List<Double> dVector = mData.getRow().get(i).getV();
1936 vals[i] = new double[dVector.size()];
1938 for (Double d : dVector)
1944 MatrixI m = new Matrix(vals);
1946 if (mData.getD() != null)
1948 List<Double> dVector = mData.getD().getV();
1949 double[] vec = new double[dVector.size()];
1951 for (Double d : dVector)
1957 if (mData.getE() != null)
1959 List<Double> dVector = mData.getE().getV();
1960 double[] vec = new double[dVector.size()];
1962 for (Double d : dVector)
1973 * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
1974 * for each viewer, with
1976 * <li>viewer geometry (position, size, split pane divider location)</li>
1977 * <li>index of the selected structure in the viewer (currently shows gapped
1979 * <li>the id of the annotation holding RNA secondary structure</li>
1980 * <li>(currently only one SS is shown per viewer, may be more in future)</li>
1982 * Varna viewer state is also written out (in native Varna XML) to separate
1983 * project jar entries. A separate entry is written for each RNA structure
1984 * displayed, with the naming convention
1986 * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
1994 * @param storeDataset
1996 protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
1997 final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
1998 boolean storeDataset)
2000 if (Desktop.desktop == null)
2004 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2005 for (int f = frames.length - 1; f > -1; f--)
2007 if (frames[f] instanceof AppVarna)
2009 AppVarna varna = (AppVarna) frames[f];
2011 * link the sequence to every viewer that is showing it and is linked to
2012 * its alignment panel
2014 if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
2016 String viewId = varna.getViewId();
2017 RnaViewer rna = new RnaViewer();
2018 rna.setViewId(viewId);
2019 rna.setTitle(varna.getTitle());
2020 rna.setXpos(varna.getX());
2021 rna.setYpos(varna.getY());
2022 rna.setWidth(varna.getWidth());
2023 rna.setHeight(varna.getHeight());
2024 rna.setDividerLocation(varna.getDividerLocation());
2025 rna.setSelectedRna(varna.getSelectedIndex());
2026 // jseq.addRnaViewer(rna);
2027 jseq.getRnaViewer().add(rna);
2030 * Store each Varna panel's state once in the project per sequence.
2031 * First time through only (storeDataset==false)
2033 // boolean storeSessions = false;
2034 // String sequenceViewId = viewId + seqsToIds.get(jds);
2035 // if (!storeDataset && !viewIds.contains(sequenceViewId))
2037 // viewIds.add(sequenceViewId);
2038 // storeSessions = true;
2040 for (RnaModel model : varna.getModels())
2042 if (model.seq == jds)
2045 * VARNA saves each view (sequence or alignment secondary
2046 * structure, gapped or trimmed) as a separate XML file
2048 String jarEntryName = rnaSessions.get(model);
2049 if (jarEntryName == null)
2052 String varnaStateFile = varna.getStateInfo(model.rna);
2053 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
2054 copyFileToJar(jout, varnaStateFile, jarEntryName, "Varna");
2055 rnaSessions.put(model, jarEntryName);
2057 SecondaryStructure ss = new SecondaryStructure();
2058 String annotationId = varna.getAnnotation(jds).annotationId;
2059 ss.setAnnotationId(annotationId);
2060 ss.setViewerState(jarEntryName);
2061 ss.setGapped(model.gapped);
2062 ss.setTitle(model.title);
2063 // rna.addSecondaryStructure(ss);
2064 rna.getSecondaryStructure().add(ss);
2073 * Copy the contents of a file to a new entry added to the output jar
2077 * @param jarEntryName
2079 * additional identifying info to log to the console
2081 protected void copyFileToJar(JarOutputStream jout, String infilePath,
2082 String jarEntryName, String msg)
2084 try (InputStream is = new FileInputStream(infilePath))
2086 File file = new File(infilePath);
2087 if (file.exists() && jout != null)
2090 "Writing jar entry " + jarEntryName + " (" + msg + ")");
2091 jout.putNextEntry(new JarEntry(jarEntryName));
2094 // dis = new DataInputStream(new FileInputStream(file));
2095 // byte[] data = new byte[(int) file.length()];
2096 // dis.readFully(data);
2097 // writeJarEntry(jout, jarEntryName, data);
2099 } catch (Exception ex)
2101 ex.printStackTrace();
2106 * Copies input to output, in 4K buffers; handles any data (text or binary)
2110 * @throws IOException
2112 protected void copyAll(InputStream in, OutputStream out)
2115 byte[] buffer = new byte[4096];
2117 while ((bytesRead = in.read(buffer)) != -1)
2119 out.write(buffer, 0, bytesRead);
2124 * Save the state of a structure viewer
2129 * the archive XML element under which to save the state
2132 * @param matchedFile
2136 protected String saveStructureViewer(AlignmentPanel ap, SequenceI jds,
2137 Pdbids pdb, PDBEntry entry, List<String> viewIds,
2138 String matchedFile, StructureViewerBase viewFrame)
2140 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
2143 * Look for any bindings for this viewer to the PDB file of interest
2144 * (including part matches excluding chain id)
2146 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
2148 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
2149 final String pdbId = pdbentry.getId();
2150 if (!pdbId.equals(entry.getId()) && !(entry.getId().length() > 4
2151 && entry.getId().toLowerCase(Locale.ROOT)
2152 .startsWith(pdbId.toLowerCase(Locale.ROOT))))
2155 * not interested in a binding to a different PDB entry here
2159 if (matchedFile == null)
2161 matchedFile = pdbentry.getFile();
2163 else if (!matchedFile.equals(pdbentry.getFile()))
2166 "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
2167 + pdbentry.getFile());
2171 // can get at it if the ID
2172 // match is ambiguous (e.g.
2175 for (int smap = 0; smap < viewFrame.getBinding()
2176 .getSequence()[peid].length; smap++)
2178 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
2179 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
2181 StructureState state = new StructureState();
2182 state.setVisible(true);
2183 state.setXpos(viewFrame.getX());
2184 state.setYpos(viewFrame.getY());
2185 state.setWidth(viewFrame.getWidth());
2186 state.setHeight(viewFrame.getHeight());
2187 final String viewId = viewFrame.getViewId();
2188 state.setViewId(viewId);
2189 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
2190 state.setColourwithAlignPanel(viewFrame.isUsedForColourBy(ap));
2191 state.setColourByJmol(viewFrame.isColouredByViewer());
2192 state.setType(viewFrame.getViewerType().toString());
2193 // pdb.addStructureState(state);
2194 pdb.getStructureState().add(state);
2202 * Populates the AnnotationColourScheme xml for save. This captures the
2203 * settings of the options in the 'Colour by Annotation' dialog.
2206 * @param userColours
2210 private AnnotationColourScheme constructAnnotationColours(
2211 AnnotationColourGradient acg, List<UserColourScheme> userColours,
2214 AnnotationColourScheme ac = new AnnotationColourScheme();
2215 ac.setAboveThreshold(acg.getAboveThreshold());
2216 ac.setThreshold(acg.getAnnotationThreshold());
2217 // 2.10.2 save annotationId (unique) not annotation label
2218 ac.setAnnotation(acg.getAnnotation().annotationId);
2219 if (acg.getBaseColour() instanceof UserColourScheme)
2222 setUserColourScheme(acg.getBaseColour(), userColours, jm));
2227 ColourSchemeProperty.getColourName(acg.getBaseColour()));
2230 ac.setMaxColour(acg.getMaxColour().getRGB());
2231 ac.setMinColour(acg.getMinColour().getRGB());
2232 ac.setPerSequence(acg.isSeqAssociated());
2233 ac.setPredefinedColours(acg.isPredefinedColours());
2237 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
2238 IdentityHashMap<SequenceGroup, String> groupRefs,
2239 AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
2240 SequenceSet vamsasSet)
2243 for (int i = 0; i < aa.length; i++)
2245 Annotation an = new Annotation();
2247 AlignmentAnnotation annotation = aa[i];
2248 if (annotation.annotationId != null)
2250 annotationIds.put(annotation.annotationId, annotation);
2253 an.setId(annotation.annotationId);
2255 an.setVisible(annotation.visible);
2257 an.setDescription(annotation.description);
2259 if (annotation.sequenceRef != null)
2261 // 2.9 JAL-1781 xref on sequence id rather than name
2262 an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
2264 if (annotation.groupRef != null)
2266 String groupIdr = groupRefs.get(annotation.groupRef);
2267 if (groupIdr == null)
2269 // make a locally unique String
2270 groupRefs.put(annotation.groupRef,
2271 groupIdr = ("" + System.currentTimeMillis()
2272 + annotation.groupRef.getName()
2273 + groupRefs.size()));
2275 an.setGroupRef(groupIdr.toString());
2278 // store all visualization attributes for annotation
2279 an.setGraphHeight(annotation.graphHeight);
2280 an.setCentreColLabels(annotation.centreColLabels);
2281 an.setScaleColLabels(annotation.scaleColLabel);
2282 an.setShowAllColLabels(annotation.showAllColLabels);
2283 an.setBelowAlignment(annotation.belowAlignment);
2285 if (annotation.graph > 0)
2288 an.setGraphType(annotation.graph);
2289 an.setGraphGroup(annotation.graphGroup);
2290 if (annotation.getThreshold() != null)
2292 ThresholdLine line = new ThresholdLine();
2293 line.setLabel(annotation.getThreshold().label);
2294 line.setValue(annotation.getThreshold().value);
2295 line.setColour(annotation.getThreshold().colour.getRGB());
2296 an.setThresholdLine(line);
2298 if (annotation.graph==AlignmentAnnotation.CONTACT_MAP)
2300 if (annotation.sequenceRef.getContactMaps()!=null)
2302 ContactMatrixI cm = annotation.sequenceRef.getContactMatrixFor(annotation);
2305 MatrixType xmlmat = new MatrixType();
2306 xmlmat.setType(cm.getType());
2307 xmlmat.setRows(BigInteger.valueOf(cm.getWidth()));
2308 xmlmat.setCols(BigInteger.valueOf(cm.getHeight()));
2309 xmlmat.setValue(ContactMatrix.contactToFloatString(cm));
2310 an.getContactmatrix().add(xmlmat);
2320 an.setLabel(annotation.label);
2322 if (annotation == av.getAlignmentQualityAnnot()
2323 || annotation == av.getAlignmentConservationAnnotation()
2324 || annotation == av.getAlignmentConsensusAnnotation()
2325 || annotation.autoCalculated)
2327 // new way of indicating autocalculated annotation -
2328 an.setAutoCalculated(annotation.autoCalculated);
2330 if (annotation.hasScore())
2332 an.setScore(annotation.getScore());
2335 if (annotation.getCalcId() != null)
2337 calcIdSet.add(annotation.getCalcId());
2338 an.setCalcId(annotation.getCalcId());
2340 if (annotation.hasProperties())
2342 for (String pr : annotation.getProperties())
2344 jalview.xml.binding.jalview.Annotation.Property prop = new jalview.xml.binding.jalview.Annotation.Property();
2346 prop.setValue(annotation.getProperty(pr));
2347 // an.addProperty(prop);
2348 an.getProperty().add(prop);
2352 AnnotationElement ae;
2353 if (annotation.annotations != null)
2355 an.setScoreOnly(false);
2356 for (int a = 0; a < annotation.annotations.length; a++)
2358 if ((annotation == null) || (annotation.annotations[a] == null))
2363 ae = new AnnotationElement();
2364 if (annotation.annotations[a].description != null)
2366 ae.setDescription(annotation.annotations[a].description);
2368 if (annotation.annotations[a].displayCharacter != null)
2370 ae.setDisplayCharacter(
2371 annotation.annotations[a].displayCharacter);
2374 if (!Float.isNaN(annotation.annotations[a].value))
2376 ae.setValue(annotation.annotations[a].value);
2380 if (annotation.annotations[a].secondaryStructure > ' ')
2382 ae.setSecondaryStructure(
2383 annotation.annotations[a].secondaryStructure + "");
2386 if (annotation.annotations[a].colour != null
2387 && annotation.annotations[a].colour != java.awt.Color.black)
2389 ae.setColour(annotation.annotations[a].colour.getRGB());
2392 // an.addAnnotationElement(ae);
2393 an.getAnnotationElement().add(ae);
2394 if (annotation.autoCalculated)
2396 // only write one non-null entry into the annotation row -
2397 // sufficient to get the visualization attributes necessary to
2405 an.setScoreOnly(true);
2407 if (!storeDS || (storeDS && !annotation.autoCalculated))
2409 // skip autocalculated annotation - these are only provided for
2411 // vamsasSet.addAnnotation(an);
2412 vamsasSet.getAnnotation().add(an);
2418 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
2420 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
2421 if (settings != null)
2423 CalcIdParam vCalcIdParam = new CalcIdParam();
2424 vCalcIdParam.setCalcId(calcId);
2425 // vCalcIdParam.addServiceURL(settings.getServiceURI());
2426 vCalcIdParam.getServiceURL().add(settings.getServiceURI());
2427 // generic URI allowing a third party to resolve another instance of the
2428 // service used for this calculation
2429 for (String url : settings.getServiceURLs())
2431 // vCalcIdParam.addServiceURL(urls);
2432 vCalcIdParam.getServiceURL().add(url);
2434 vCalcIdParam.setVersion("1.0");
2435 if (settings.getPreset() != null)
2437 WsParamSetI setting = settings.getPreset();
2438 vCalcIdParam.setName(setting.getName());
2439 vCalcIdParam.setDescription(setting.getDescription());
2443 vCalcIdParam.setName("");
2444 vCalcIdParam.setDescription("Last used parameters");
2446 // need to be able to recover 1) settings 2) user-defined presets or
2447 // recreate settings from preset 3) predefined settings provided by
2448 // service - or settings that can be transferred (or discarded)
2449 vCalcIdParam.setParameters(
2450 settings.getWsParamFile().replace("\n", "|\\n|"));
2451 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
2452 // todo - decide if updateImmediately is needed for any projects.
2454 return vCalcIdParam;
2459 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
2462 if (calcIdParam.getVersion().equals("1.0"))
2464 final String[] calcIds = calcIdParam.getServiceURL()
2465 .toArray(new String[0]);
2466 Jws2Instance service = Jws2Discoverer.getDiscoverer()
2467 .getPreferredServiceFor(calcIds);
2468 if (service != null)
2470 WsParamSetI parmSet = null;
2473 parmSet = service.getParamStore().parseServiceParameterFile(
2474 calcIdParam.getName(), calcIdParam.getDescription(),
2476 calcIdParam.getParameters().replace("|\\n|", "\n"));
2477 } catch (IOException x)
2479 Console.warn("Couldn't parse parameter data for "
2480 + calcIdParam.getCalcId(), x);
2483 List<ArgumentI> argList = null;
2484 if (calcIdParam.getName().length() > 0)
2486 parmSet = service.getParamStore()
2487 .getPreset(calcIdParam.getName());
2488 if (parmSet != null)
2490 // TODO : check we have a good match with settings in AACon -
2491 // otherwise we'll need to create a new preset
2496 argList = parmSet.getArguments();
2499 AAConSettings settings = new AAConSettings(
2500 calcIdParam.isAutoUpdate(), service, parmSet, argList);
2501 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
2502 calcIdParam.isNeedsUpdate());
2508 "Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
2512 throw new Error(MessageManager.formatMessage(
2513 "error.unsupported_version_calcIdparam", new Object[]
2514 { calcIdParam.toString() }));
2518 * External mapping between jalview objects and objects yielding a valid and
2519 * unique object ID string. This is null for normal Jalview project IO, but
2520 * non-null when a jalview project is being read or written as part of a
2523 IdentityHashMap jv2vobj = null;
2526 * Construct a unique ID for jvobj using either existing bindings or if none
2527 * exist, the result of the hashcode call for the object.
2530 * jalview data object
2531 * @return unique ID for referring to jvobj
2533 private String makeHashCode(Object jvobj, String altCode)
2535 if (jv2vobj != null)
2537 Object id = jv2vobj.get(jvobj);
2540 return id.toString();
2542 // check string ID mappings
2543 if (jvids2vobj != null && jvobj instanceof String)
2545 id = jvids2vobj.get(jvobj);
2549 return id.toString();
2551 // give up and warn that something has gone wrong
2553 "Cannot find ID for object in external mapping : " + jvobj);
2559 * return local jalview object mapped to ID, if it exists
2563 * @return null or object bound to idcode
2565 private Object retrieveExistingObj(String idcode)
2567 if (idcode != null && vobj2jv != null)
2569 return vobj2jv.get(idcode);
2575 * binding from ID strings from external mapping table to jalview data model
2578 private Hashtable vobj2jv;
2580 private Sequence createVamsasSequence(String id, SequenceI jds)
2582 return createVamsasSequence(true, id, jds, null);
2585 private Sequence createVamsasSequence(boolean recurse, String id,
2586 SequenceI jds, SequenceI parentseq)
2588 Sequence vamsasSeq = new Sequence();
2589 vamsasSeq.setId(id);
2590 vamsasSeq.setName(jds.getName());
2591 vamsasSeq.setSequence(jds.getSequenceAsString());
2592 vamsasSeq.setDescription(jds.getDescription());
2593 List<DBRefEntry> dbrefs = null;
2594 if (jds.getDatasetSequence() != null)
2596 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
2600 // seqId==dsseqid so we can tell which sequences really are
2601 // dataset sequences only
2602 vamsasSeq.setDsseqid(id);
2603 dbrefs = jds.getDBRefs();
2604 if (parentseq == null)
2611 * save any dbrefs; special subclass GeneLocus is flagged as 'locus'
2615 for (int d = 0, nd = dbrefs.size(); d < nd; d++)
2617 DBRef dbref = new DBRef();
2618 DBRefEntry ref = dbrefs.get(d);
2619 dbref.setSource(ref.getSource());
2620 dbref.setVersion(ref.getVersion());
2621 dbref.setAccessionId(ref.getAccessionId());
2622 dbref.setCanonical(ref.isCanonical());
2623 if (ref instanceof GeneLocus)
2625 dbref.setLocus(true);
2629 Mapping mp = createVamsasMapping(ref.getMap(), parentseq, jds,
2631 dbref.setMapping(mp);
2633 vamsasSeq.getDBRef().add(dbref);
2639 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
2640 SequenceI parentseq, SequenceI jds, boolean recurse)
2643 if (jmp.getMap() != null)
2647 jalview.util.MapList mlst = jmp.getMap();
2648 List<int[]> r = mlst.getFromRanges();
2649 for (int[] range : r)
2651 MapListFrom mfrom = new MapListFrom();
2652 mfrom.setStart(range[0]);
2653 mfrom.setEnd(range[1]);
2654 // mp.addMapListFrom(mfrom);
2655 mp.getMapListFrom().add(mfrom);
2657 r = mlst.getToRanges();
2658 for (int[] range : r)
2660 MapListTo mto = new MapListTo();
2661 mto.setStart(range[0]);
2662 mto.setEnd(range[1]);
2663 // mp.addMapListTo(mto);
2664 mp.getMapListTo().add(mto);
2666 mp.setMapFromUnit(BigInteger.valueOf(mlst.getFromRatio()));
2667 mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
2668 if (jmp.getTo() != null)
2670 // MappingChoice mpc = new MappingChoice();
2672 // check/create ID for the sequence referenced by getTo()
2675 SequenceI ps = null;
2676 if (parentseq != jmp.getTo()
2677 && parentseq.getDatasetSequence() != jmp.getTo())
2679 // chaining dbref rather than a handshaking one
2680 jmpid = seqHash(ps = jmp.getTo());
2684 jmpid = seqHash(ps = parentseq);
2686 // mpc.setDseqFor(jmpid);
2687 mp.setDseqFor(jmpid);
2688 if (!seqRefIds.containsKey(jmpid))
2690 Console.debug("creatign new DseqFor ID");
2691 seqRefIds.put(jmpid, ps);
2695 Console.debug("reusing DseqFor ID");
2698 // mp.setMappingChoice(mpc);
2704 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
2705 List<UserColourScheme> userColours, JalviewModel jm)
2708 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
2709 boolean newucs = false;
2710 if (!userColours.contains(ucs))
2712 userColours.add(ucs);
2715 id = "ucs" + userColours.indexOf(ucs);
2718 // actually create the scheme's entry in the XML model
2719 java.awt.Color[] colours = ucs.getColours();
2720 UserColours uc = new UserColours();
2721 // UserColourScheme jbucs = new UserColourScheme();
2722 JalviewUserColours jbucs = new JalviewUserColours();
2724 for (int i = 0; i < colours.length; i++)
2726 Colour col = new Colour();
2727 col.setName(ResidueProperties.aa[i]);
2728 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2729 // jbucs.addColour(col);
2730 jbucs.getColour().add(col);
2732 if (ucs.getLowerCaseColours() != null)
2734 colours = ucs.getLowerCaseColours();
2735 for (int i = 0; i < colours.length; i++)
2737 Colour col = new Colour();
2738 col.setName(ResidueProperties.aa[i].toLowerCase(Locale.ROOT));
2739 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2740 // jbucs.addColour(col);
2741 jbucs.getColour().add(col);
2746 uc.setUserColourScheme(jbucs);
2747 // jm.addUserColours(uc);
2748 jm.getUserColours().add(uc);
2754 jalview.schemes.UserColourScheme getUserColourScheme(JalviewModel jm,
2757 List<UserColours> uc = jm.getUserColours();
2758 UserColours colours = null;
2760 for (int i = 0; i < uc.length; i++)
2762 if (uc[i].getId().equals(id))
2769 for (UserColours c : uc)
2771 if (c.getId().equals(id))
2778 java.awt.Color[] newColours = new java.awt.Color[24];
2780 for (int i = 0; i < 24; i++)
2782 newColours[i] = new java.awt.Color(Integer.parseInt(
2783 // colours.getUserColourScheme().getColour(i).getRGB(), 16));
2784 colours.getUserColourScheme().getColour().get(i).getRGB(),
2788 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
2791 if (colours.getUserColourScheme().getColour().size()/*Count()*/ > 24)
2793 newColours = new java.awt.Color[23];
2794 for (int i = 0; i < 23; i++)
2796 newColours[i] = new java.awt.Color(
2797 Integer.parseInt(colours.getUserColourScheme().getColour()
2798 .get(i + 24).getRGB(), 16));
2800 ucs.setLowerCaseColours(newColours);
2807 * contains last error message (if any) encountered by XML loader.
2809 String errorMessage = null;
2812 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
2813 * exceptions are raised during project XML parsing
2815 public boolean attemptversion1parse = false;
2818 * Load a jalview project archive from a jar file
2821 * - HTTP URL or filename
2823 public AlignFrame loadJalviewAlign(final Object file)
2826 jalview.gui.AlignFrame af = null;
2830 // create list to store references for any new Jmol viewers created
2831 newStructureViewers = new Vector<>();
2832 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
2833 // Workaround is to make sure caller implements the JarInputStreamProvider
2835 // so we can re-open the jar input stream for each entry.
2837 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
2838 af = loadJalviewAlign(jprovider);
2841 af.setMenusForViewport();
2843 } catch (MalformedURLException e)
2845 errorMessage = "Invalid URL format for '" + file + "'";
2851 SwingUtilities.invokeAndWait(new Runnable()
2856 setLoadingFinishedForNewStructureViewers();
2859 } catch (Exception x)
2861 System.err.println("Error loading alignment: " + x.getMessage());
2867 @SuppressWarnings("unused")
2868 private jarInputStreamProvider createjarInputStreamProvider(
2869 final Object ofile) throws MalformedURLException
2872 // BH 2018 allow for bytes already attached to File object
2875 String file = (ofile instanceof File
2876 ? ((File) ofile).getCanonicalPath()
2877 : ofile.toString());
2878 byte[] bytes = Platform.isJS() ? Platform.getFileBytes((File) ofile)
2881 errorMessage = null;
2882 uniqueSetSuffix = null;
2884 viewportsAdded.clear();
2885 frefedSequence = null;
2887 if (HttpUtils.startsWithHttpOrHttps(file))
2889 url = new URL(file);
2891 final URL _url = url;
2892 return new jarInputStreamProvider()
2896 public JarInputStream getJarInputStream() throws IOException
2900 // System.out.println("Jalview2XML: opening byte jarInputStream for
2901 // bytes.length=" + bytes.length);
2902 return new JarInputStream(new ByteArrayInputStream(bytes));
2906 // System.out.println("Jalview2XML: opening url jarInputStream for "
2908 return new JarInputStream(_url.openStream());
2912 // System.out.println("Jalview2XML: opening file jarInputStream for
2914 return new JarInputStream(new FileInputStream(file));
2919 public String getFilename()
2924 } catch (IOException e)
2926 e.printStackTrace();
2932 * Recover jalview session from a jalview project archive. Caller may
2933 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
2934 * themselves. Any null fields will be initialised with default values,
2935 * non-null fields are left alone.
2940 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
2942 errorMessage = null;
2943 if (uniqueSetSuffix == null)
2945 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
2947 if (seqRefIds == null)
2951 AlignFrame af = null, _af = null;
2952 IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
2953 Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
2954 final String file = jprovider.getFilename();
2957 JarInputStream jin = null;
2958 JarEntry jarentry = null;
2963 jin = jprovider.getJarInputStream();
2964 for (int i = 0; i < entryCount; i++)
2966 jarentry = jin.getNextJarEntry();
2969 if (jarentry != null && jarentry.getName().endsWith(".xml"))
2971 JAXBContext jc = JAXBContext
2972 .newInstance("jalview.xml.binding.jalview");
2973 XMLStreamReader streamReader = XMLInputFactory.newInstance()
2974 .createXMLStreamReader(jin);
2975 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
2976 JAXBElement<JalviewModel> jbe = um.unmarshal(streamReader,
2977 JalviewModel.class);
2978 JalviewModel object = jbe.getValue();
2980 if (true) // !skipViewport(object))
2982 _af = loadFromObject(object, file, true, jprovider);
2983 if (_af != null && object.getViewport().size() > 0)
2984 // getJalviewModelSequence().getViewportCount() > 0)
2988 // store a reference to the first view
2991 if (_af.getViewport().isGatherViewsHere())
2993 // if this is a gathered view, keep its reference since
2994 // after gathering views, only this frame will remain
2996 gatherToThisFrame.put(_af.getViewport().getSequenceSetId(),
2999 // Save dataset to register mappings once all resolved
3000 importedDatasets.put(
3001 af.getViewport().getAlignment().getDataset(),
3002 af.getViewport().getAlignment().getDataset());
3007 else if (jarentry != null)
3009 // Some other file here.
3012 } while (jarentry != null);
3014 resolveFrefedSequences();
3015 } catch (IOException ex)
3017 ex.printStackTrace();
3018 errorMessage = "Couldn't locate Jalview XML file : " + file;
3020 "Exception whilst loading jalview XML file : " + ex + "\n");
3021 } catch (Exception ex)
3023 System.err.println("Parsing as Jalview Version 2 file failed.");
3024 ex.printStackTrace(System.err);
3025 if (attemptversion1parse)
3027 // used to attempt to parse as V1 castor-generated xml
3029 if (Desktop.instance != null)
3031 Desktop.instance.stopLoading();
3035 System.out.println("Successfully loaded archive file");
3038 ex.printStackTrace();
3041 "Exception whilst loading jalview XML file : " + ex + "\n");
3042 } catch (OutOfMemoryError e)
3044 // Don't use the OOM Window here
3045 errorMessage = "Out of memory loading jalview XML file";
3046 System.err.println("Out of memory whilst loading jalview XML file");
3047 e.printStackTrace();
3051 * Regather multiple views (with the same sequence set id) to the frame (if
3052 * any) that is flagged as the one to gather to, i.e. convert them to tabbed
3053 * views instead of separate frames. Note this doesn't restore a state where
3054 * some expanded views in turn have tabbed views - the last "first tab" read
3055 * in will play the role of gatherer for all.
3057 for (AlignFrame fr : gatherToThisFrame.values())
3059 Desktop.instance.gatherViews(fr);
3062 restoreSplitFrames();
3063 for (AlignmentI ds : importedDatasets.keySet())
3065 if (ds.getCodonFrames() != null)
3067 StructureSelectionManager
3068 .getStructureSelectionManager(Desktop.instance)
3069 .registerMappings(ds.getCodonFrames());
3072 if (errorMessage != null)
3077 if (Desktop.instance != null)
3079 Desktop.instance.stopLoading();
3086 * Try to reconstruct and display SplitFrame windows, where each contains
3087 * complementary dna and protein alignments. Done by pairing up AlignFrame
3088 * objects (created earlier) which have complementary viewport ids associated.
3090 protected void restoreSplitFrames()
3092 List<SplitFrame> gatherTo = new ArrayList<>();
3093 List<AlignFrame> addedToSplitFrames = new ArrayList<>();
3094 Map<String, AlignFrame> dna = new HashMap<>();
3097 * Identify the DNA alignments
3099 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3102 AlignFrame af = candidate.getValue();
3103 if (af.getViewport().getAlignment().isNucleotide())
3105 dna.put(candidate.getKey().getId(), af);
3110 * Try to match up the protein complements
3112 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3115 AlignFrame af = candidate.getValue();
3116 if (!af.getViewport().getAlignment().isNucleotide())
3118 String complementId = candidate.getKey().getComplementId();
3119 // only non-null complements should be in the Map
3120 if (complementId != null && dna.containsKey(complementId))
3122 final AlignFrame dnaFrame = dna.get(complementId);
3123 SplitFrame sf = createSplitFrame(dnaFrame, af);
3124 addedToSplitFrames.add(dnaFrame);
3125 addedToSplitFrames.add(af);
3126 dnaFrame.setMenusForViewport();
3127 af.setMenusForViewport();
3128 if (af.getViewport().isGatherViewsHere())
3137 * Open any that we failed to pair up (which shouldn't happen!) as
3138 * standalone AlignFrame's.
3140 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3143 AlignFrame af = candidate.getValue();
3144 if (!addedToSplitFrames.contains(af))
3146 Viewport view = candidate.getKey();
3147 Desktop.addInternalFrame(af, view.getTitle(),
3148 safeInt(view.getWidth()), safeInt(view.getHeight()));
3149 af.setMenusForViewport();
3150 System.err.println("Failed to restore view " + view.getTitle()
3151 + " to split frame");
3156 * Gather back into tabbed views as flagged.
3158 for (SplitFrame sf : gatherTo)
3160 Desktop.instance.gatherViews(sf);
3163 splitFrameCandidates.clear();
3167 * Construct and display one SplitFrame holding DNA and protein alignments.
3170 * @param proteinFrame
3173 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
3174 AlignFrame proteinFrame)
3176 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
3177 String title = MessageManager.getString("label.linked_view_title");
3178 int width = (int) dnaFrame.getBounds().getWidth();
3179 int height = (int) (dnaFrame.getBounds().getHeight()
3180 + proteinFrame.getBounds().getHeight() + 50);
3183 * SplitFrame location is saved to both enclosed frames
3185 splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
3186 Desktop.addInternalFrame(splitFrame, title, width, height);
3189 * And compute cDNA consensus (couldn't do earlier with consensus as
3190 * mappings were not yet present)
3192 proteinFrame.getViewport().alignmentChanged(proteinFrame.alignPanel);
3198 * check errorMessage for a valid error message and raise an error box in the
3199 * GUI or write the current errorMessage to stderr and then clear the error
3202 protected void reportErrors()
3204 reportErrors(false);
3207 protected void reportErrors(final boolean saving)
3209 if (errorMessage != null)
3211 final String finalErrorMessage = errorMessage;
3214 javax.swing.SwingUtilities.invokeLater(new Runnable()
3219 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
3221 "Error " + (saving ? "saving" : "loading")
3223 JvOptionPane.WARNING_MESSAGE);
3229 System.err.println("Problem loading Jalview file: " + errorMessage);
3232 errorMessage = null;
3235 Map<String, String> alreadyLoadedPDB = new HashMap<>();
3238 * when set, local views will be updated from view stored in JalviewXML
3239 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
3240 * sync if this is set to true.
3242 private final boolean updateLocalViews = false;
3245 * Returns the path to a temporary file holding the PDB file for the given PDB
3246 * id. The first time of asking, searches for a file of that name in the
3247 * Jalview project jar, and copies it to a new temporary file. Any repeat
3248 * requests just return the path to the file previously created.
3254 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
3257 if (alreadyLoadedPDB.containsKey(pdbId))
3259 return alreadyLoadedPDB.get(pdbId).toString();
3262 String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
3264 if (tempFile != null)
3266 alreadyLoadedPDB.put(pdbId, tempFile);
3272 * Copies the jar entry of given name to a new temporary file and returns the
3273 * path to the file, or null if the entry is not found.
3276 * @param jarEntryName
3278 * a prefix for the temporary file name, must be at least three
3280 * @param suffixModel
3281 * null or original file - so new file can be given the same suffix
3285 protected String copyJarEntry(jarInputStreamProvider jprovider,
3286 String jarEntryName, String prefix, String suffixModel)
3288 String suffix = ".tmp";
3289 if (suffixModel == null)
3291 suffixModel = jarEntryName;
3293 int sfpos = suffixModel.lastIndexOf(".");
3294 if (sfpos > -1 && sfpos < (suffixModel.length() - 1))
3296 suffix = "." + suffixModel.substring(sfpos + 1);
3299 try (JarInputStream jin = jprovider.getJarInputStream())
3301 JarEntry entry = null;
3304 entry = jin.getNextJarEntry();
3305 } while (entry != null && !entry.getName().equals(jarEntryName));
3309 // in = new BufferedReader(new InputStreamReader(jin, UTF_8));
3310 File outFile = File.createTempFile(prefix, suffix);
3311 outFile.deleteOnExit();
3312 try (OutputStream os = new FileOutputStream(outFile))
3316 String t = outFile.getAbsolutePath();
3322 "Couldn't find entry in Jalview Jar for " + jarEntryName);
3324 } catch (Exception ex)
3326 ex.printStackTrace();
3332 private class JvAnnotRow
3334 public JvAnnotRow(int i, AlignmentAnnotation jaa)
3341 * persisted version of annotation row from which to take vis properties
3343 public jalview.datamodel.AlignmentAnnotation template;
3346 * original position of the annotation row in the alignment
3352 * Load alignment frame from jalview XML DOM object
3354 * @param jalviewModel
3357 * filename source string
3358 * @param loadTreesAndStructures
3359 * when false only create Viewport
3361 * data source provider
3362 * @return alignment frame created from view stored in DOM
3364 AlignFrame loadFromObject(JalviewModel jalviewModel, String file,
3365 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
3367 SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet()
3369 List<Sequence> vamsasSeqs = vamsasSet.getSequence();
3371 // JalviewModelSequence jms = object.getJalviewModelSequence();
3373 // Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
3375 Viewport view = (jalviewModel.getViewport().size() > 0)
3376 ? jalviewModel.getViewport().get(0)
3379 // ////////////////////////////////
3380 // INITIALISE ALIGNMENT SEQUENCESETID AND VIEWID
3383 // If we just load in the same jar file again, the sequenceSetId
3384 // will be the same, and we end up with multiple references
3385 // to the same sequenceSet. We must modify this id on load
3386 // so that each load of the file gives a unique id
3389 * used to resolve correct alignment dataset for alignments with multiple
3392 String uniqueSeqSetId = null;
3393 String viewId = null;
3396 uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
3397 viewId = (view.getId() == null ? null
3398 : view.getId() + uniqueSetSuffix);
3401 // ////////////////////////////////
3404 List<SequenceI> hiddenSeqs = null;
3406 List<SequenceI> tmpseqs = new ArrayList<>();
3408 boolean multipleView = false;
3409 SequenceI referenceseqForView = null;
3410 // JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
3411 List<JSeq> jseqs = jalviewModel.getJSeq();
3412 int vi = 0; // counter in vamsasSeq array
3413 for (int i = 0; i < jseqs.size(); i++)
3415 JSeq jseq = jseqs.get(i);
3416 String seqId = jseq.getId();
3418 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())
3427 System.err.println(String.format(
3428 "Warning JAL-2154 regression: updating start/end for sequence %s from %d/%d to %d/%d",
3429 tmpSeq.getName(), tmpSeq.getStart(), tmpSeq.getEnd(),
3430 jseq.getStart(), jseq.getEnd()));
3435 incompleteSeqs.remove(seqId);
3437 if (vamsasSeqs.size() > vi
3438 && vamsasSeqs.get(vi).getId().equals(seqId))
3440 // most likely we are reading a dataset XML document so
3441 // update from vamsasSeq section of XML for this sequence
3442 tmpSeq.setName(vamsasSeqs.get(vi).getName());
3443 tmpSeq.setDescription(vamsasSeqs.get(vi).getDescription());
3444 tmpSeq.setSequence(vamsasSeqs.get(vi).getSequence());
3449 // reading multiple views, so vamsasSeq set is a subset of JSeq
3450 multipleView = true;
3452 tmpSeq.setStart(jseq.getStart());
3453 tmpSeq.setEnd(jseq.getEnd());
3454 tmpseqs.add(tmpSeq);
3458 Sequence vamsasSeq = vamsasSeqs.get(vi);
3459 tmpSeq = new jalview.datamodel.Sequence(vamsasSeq.getName(),
3460 vamsasSeq.getSequence());
3461 tmpSeq.setDescription(vamsasSeq.getDescription());
3462 tmpSeq.setStart(jseq.getStart());
3463 tmpSeq.setEnd(jseq.getEnd());
3464 tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
3465 seqRefIds.put(vamsasSeq.getId(), tmpSeq);
3466 tmpseqs.add(tmpSeq);
3470 if (safeBoolean(jseq.isViewreference()))
3472 referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
3475 if (jseq.isHidden() != null && jseq.isHidden().booleanValue())
3477 if (hiddenSeqs == null)
3479 hiddenSeqs = new ArrayList<>();
3482 hiddenSeqs.add(tmpSeq);
3487 // Create the alignment object from the sequence set
3488 // ///////////////////////////////
3489 SequenceI[] orderedSeqs = tmpseqs
3490 .toArray(new SequenceI[tmpseqs.size()]);
3492 AlignmentI al = null;
3493 // so we must create or recover the dataset alignment before going further
3494 // ///////////////////////////////
3495 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
3497 // older jalview projects do not have a dataset - so creat alignment and
3499 al = new Alignment(orderedSeqs);
3500 al.setDataset(null);
3504 boolean isdsal = jalviewModel.getViewport().isEmpty();
3507 // we are importing a dataset record, so
3508 // recover reference to an alignment already materialsed as dataset
3509 al = getDatasetFor(vamsasSet.getDatasetId());
3513 // materialse the alignment
3514 al = new Alignment(orderedSeqs);
3518 addDatasetRef(vamsasSet.getDatasetId(), al);
3521 // finally, verify all data in vamsasSet is actually present in al
3522 // passing on flag indicating if it is actually a stored dataset
3523 recoverDatasetFor(vamsasSet, al, isdsal, uniqueSeqSetId);
3526 if (referenceseqForView != null)
3528 al.setSeqrep(referenceseqForView);
3530 // / Add the alignment properties
3531 for (int i = 0; i < vamsasSet.getSequenceSetProperties().size(); i++)
3533 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties()
3535 al.setProperty(ssp.getKey(), ssp.getValue());
3538 // ///////////////////////////////
3540 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
3543 // load sequence features, database references and any associated PDB
3544 // structures for the alignment
3546 // prior to 2.10, this part would only be executed the first time a
3547 // sequence was encountered, but not afterwards.
3548 // now, for 2.10 projects, this is also done if the xml doc includes
3549 // dataset sequences not actually present in any particular view.
3551 for (int i = 0; i < vamsasSeqs.size(); i++)
3553 JSeq jseq = jseqs.get(i);
3554 if (jseq.getFeatures().size() > 0)
3556 List<Feature> features = jseq.getFeatures();
3557 for (int f = 0; f < features.size(); f++)
3559 Feature feat = features.get(f);
3560 SequenceFeature sf = new SequenceFeature(feat.getType(),
3561 feat.getDescription(), feat.getBegin(), feat.getEnd(),
3562 safeFloat(feat.getScore()), feat.getFeatureGroup());
3563 sf.setStatus(feat.getStatus());
3566 * load any feature attributes - include map-valued attributes
3568 Map<String, Map<String, String>> mapAttributes = new HashMap<>();
3569 for (int od = 0; od < feat.getOtherData().size(); od++)
3571 OtherData keyValue = feat.getOtherData().get(od);
3572 String attributeName = keyValue.getKey();
3573 String attributeValue = keyValue.getValue();
3574 if (attributeName.startsWith("LINK"))
3576 sf.addLink(attributeValue);
3580 String subAttribute = keyValue.getKey2();
3581 if (subAttribute == null)
3583 // simple string-valued attribute
3584 sf.setValue(attributeName, attributeValue);
3588 // attribute 'key' has sub-attribute 'key2'
3589 if (!mapAttributes.containsKey(attributeName))
3591 mapAttributes.put(attributeName, new HashMap<>());
3593 mapAttributes.get(attributeName).put(subAttribute,
3598 for (Entry<String, Map<String, String>> mapAttribute : mapAttributes
3601 sf.setValue(mapAttribute.getKey(), mapAttribute.getValue());
3604 // adds feature to datasequence's feature set (since Jalview 2.10)
3605 al.getSequenceAt(i).addSequenceFeature(sf);
3608 if (vamsasSeqs.get(i).getDBRef().size() > 0)
3610 // adds dbrefs to datasequence's set (since Jalview 2.10)
3612 al.getSequenceAt(i).getDatasetSequence() == null
3613 ? al.getSequenceAt(i)
3614 : al.getSequenceAt(i).getDatasetSequence(),
3617 if (jseq.getPdbids().size() > 0)
3619 List<Pdbids> ids = jseq.getPdbids();
3620 for (int p = 0; p < ids.size(); p++)
3622 Pdbids pdbid = ids.get(p);
3623 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
3624 entry.setId(pdbid.getId());
3625 if (pdbid.getType() != null)
3627 if (PDBEntry.Type.getType(pdbid.getType()) != null)
3629 entry.setType(PDBEntry.Type.getType(pdbid.getType()));
3633 entry.setType(PDBEntry.Type.FILE);
3636 // jprovider is null when executing 'New View'
3637 if (pdbid.getFile() != null && jprovider != null)
3639 if (!pdbloaded.containsKey(pdbid.getFile()))
3641 entry.setFile(loadPDBFile(jprovider, pdbid.getId(),
3646 entry.setFile(pdbloaded.get(pdbid.getId()).toString());
3650 if (pdbid.getPdbentryItem() != null)
3652 for (PdbentryItem item : pdbid.getPdbentryItem())
3654 for (Property pr : item.getProperty())
3656 entry.setProperty(pr.getName(), pr.getValue());
3661 for (Property prop : pdbid.getProperty())
3663 entry.setProperty(prop.getName(), prop.getValue());
3665 StructureSelectionManager
3666 .getStructureSelectionManager(Desktop.instance)
3667 .registerPDBEntry(entry);
3668 // adds PDBEntry to datasequence's set (since Jalview 2.10)
3669 if (al.getSequenceAt(i).getDatasetSequence() != null)
3671 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
3675 al.getSequenceAt(i).addPDBId(entry);
3680 } // end !multipleview
3682 // ///////////////////////////////
3683 // LOAD SEQUENCE MAPPINGS
3685 if (vamsasSet.getAlcodonFrame().size() > 0)
3687 // TODO Potentially this should only be done once for all views of an
3689 List<AlcodonFrame> alc = vamsasSet.getAlcodonFrame();
3690 for (int i = 0; i < alc.size(); i++)
3692 AlignedCodonFrame cf = new AlignedCodonFrame();
3693 if (alc.get(i).getAlcodMap().size() > 0)
3695 List<AlcodMap> maps = alc.get(i).getAlcodMap();
3696 for (int m = 0; m < maps.size(); m++)
3698 AlcodMap map = maps.get(m);
3699 SequenceI dnaseq = seqRefIds.get(map.getDnasq());
3701 jalview.datamodel.Mapping mapping = null;
3702 // attach to dna sequence reference.
3703 if (map.getMapping() != null)
3705 mapping = addMapping(map.getMapping());
3706 if (dnaseq != null && mapping.getTo() != null)
3708 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
3714 .add(newAlcodMapRef(map.getDnasq(), cf, mapping));
3718 al.addCodonFrame(cf);
3723 // ////////////////////////////////
3725 List<JvAnnotRow> autoAlan = new ArrayList<>();
3728 * store any annotations which forward reference a group's ID
3730 Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
3732 if (vamsasSet.getAnnotation().size()/*Count()*/ > 0)
3734 List<Annotation> an = vamsasSet.getAnnotation();
3736 for (int i = 0; i < an.size(); i++)
3738 Annotation annotation = an.get(i);
3741 * test if annotation is automatically calculated for this view only
3743 boolean autoForView = false;
3744 if (annotation.getLabel().equals("Quality")
3745 || annotation.getLabel().equals("Conservation")
3746 || annotation.getLabel().equals("Consensus"))
3748 // Kludge for pre 2.5 projects which lacked the autocalculated flag
3750 // JAXB has no has() test; schema defaults value to false
3751 // if (!annotation.hasAutoCalculated())
3753 // annotation.setAutoCalculated(true);
3756 if (autoForView || annotation.isAutoCalculated())
3758 // remove ID - we don't recover annotation from other views for
3759 // view-specific annotation
3760 annotation.setId(null);
3763 // set visibility for other annotation in this view
3764 String annotationId = annotation.getId();
3765 if (annotationId != null && annotationIds.containsKey(annotationId))
3767 AlignmentAnnotation jda = annotationIds.get(annotationId);
3768 // in principle Visible should always be true for annotation displayed
3769 // in multiple views
3770 if (annotation.isVisible() != null)
3772 jda.visible = annotation.isVisible();
3775 al.addAnnotation(jda);
3779 // Construct new annotation from model.
3780 List<AnnotationElement> ae = annotation.getAnnotationElement();
3781 jalview.datamodel.Annotation[] anot = null;
3782 java.awt.Color firstColour = null;
3784 if (!annotation.isScoreOnly())
3786 anot = new jalview.datamodel.Annotation[al.getWidth()];
3787 for (int aa = 0; aa < ae.size() && aa < anot.length; aa++)
3789 AnnotationElement annElement = ae.get(aa);
3790 anpos = annElement.getPosition();
3792 if (anpos >= anot.length)
3797 float value = safeFloat(annElement.getValue());
3798 anot[anpos] = new jalview.datamodel.Annotation(
3799 annElement.getDisplayCharacter(),
3800 annElement.getDescription(),
3801 (annElement.getSecondaryStructure() == null
3802 || annElement.getSecondaryStructure()
3806 .getSecondaryStructure()
3809 anot[anpos].colour = new Color(safeInt(annElement.getColour()));
3810 if (firstColour == null)
3812 firstColour = anot[anpos].colour;
3816 jalview.datamodel.AlignmentAnnotation jaa = null;
3818 if (annotation.isGraph())
3820 float llim = 0, hlim = 0;
3821 // if (autoForView || an[i].isAutoCalculated()) {
3824 jaa = new jalview.datamodel.AlignmentAnnotation(
3825 annotation.getLabel(), annotation.getDescription(), anot,
3826 llim, hlim, safeInt(annotation.getGraphType()));
3828 jaa.graphGroup = safeInt(annotation.getGraphGroup());
3829 jaa._linecolour = firstColour;
3830 if (annotation.getThresholdLine() != null)
3832 jaa.setThreshold(new jalview.datamodel.GraphLine(
3833 safeFloat(annotation.getThresholdLine().getValue()),
3834 annotation.getThresholdLine().getLabel(),
3835 new java.awt.Color(safeInt(
3836 annotation.getThresholdLine().getColour()))));
3838 if (autoForView || annotation.isAutoCalculated())
3840 // Hardwire the symbol display line to ensure that labels for
3841 // histograms are displayed
3847 jaa = new jalview.datamodel.AlignmentAnnotation(
3848 annotation.getLabel(), annotation.getDescription(), anot);
3849 jaa._linecolour = firstColour;
3851 // register new annotation
3852 if (annotation.getId() != null)
3854 annotationIds.put(annotation.getId(), jaa);
3855 jaa.annotationId = annotation.getId();
3857 // recover sequence association
3858 String sequenceRef = annotation.getSequenceRef();
3859 if (sequenceRef != null)
3861 // from 2.9 sequenceRef is to sequence id (JAL-1781)
3862 SequenceI sequence = seqRefIds.get(sequenceRef);
3863 if (sequence == null)
3865 // in pre-2.9 projects sequence ref is to sequence name
3866 sequence = al.findName(sequenceRef);
3868 if (sequence != null)
3870 jaa.createSequenceMapping(sequence, 1, true);
3871 sequence.addAlignmentAnnotation(jaa);
3874 // and make a note of any group association
3875 if (annotation.getGroupRef() != null
3876 && annotation.getGroupRef().length() > 0)
3878 List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
3879 .get(annotation.getGroupRef());
3882 aal = new ArrayList<>();
3883 groupAnnotRefs.put(annotation.getGroupRef(), aal);
3888 if (annotation.getScore() != null)
3890 jaa.setScore(annotation.getScore().doubleValue());
3892 if (annotation.isVisible() != null)
3894 jaa.visible = annotation.isVisible().booleanValue();
3897 if (annotation.isCentreColLabels() != null)
3899 jaa.centreColLabels = annotation.isCentreColLabels()
3903 if (annotation.isScaleColLabels() != null)
3905 jaa.scaleColLabel = annotation.isScaleColLabels().booleanValue();
3907 if (annotation.isAutoCalculated())
3909 // newer files have an 'autoCalculated' flag and store calculation
3910 // state in viewport properties
3911 jaa.autoCalculated = true; // means annotation will be marked for
3912 // update at end of load.
3914 if (annotation.getGraphHeight() != null)
3916 jaa.graphHeight = annotation.getGraphHeight().intValue();
3918 jaa.belowAlignment = annotation.isBelowAlignment();
3919 jaa.setCalcId(annotation.getCalcId());
3920 if (annotation.getProperty().size() > 0)
3922 for (Annotation.Property prop : annotation.getProperty())
3924 jaa.setProperty(prop.getName(), prop.getValue());
3927 if (jaa.graph == AlignmentAnnotation.CONTACT_MAP)
3929 if (annotation.getContactmatrix() != null
3930 && annotation.getContactmatrix().size() > 0)
3932 for (MatrixType xmlmat : annotation.getContactmatrix())
3934 if (PAEContactMatrix.PAEMATRIX.equals(xmlmat.getType()))
3936 if (!xmlmat.getRows().equals(xmlmat.getCols()))
3938 Console.error("Can't handle non square PAE Matrices");
3942 float[][] elements = ContactMatrix
3943 .fromFloatStringToContacts(xmlmat.getValue(),
3944 xmlmat.getCols().intValue(),
3945 xmlmat.getRows().intValue());
3947 PAEContactMatrix newpae = new PAEContactMatrix(
3948 jaa.sequenceRef, elements);
3949 jaa.sequenceRef.addContactListFor(jaa, newpae);
3954 Console.error("Ignoring CONTACT_MAP annotation with type "
3955 + xmlmat.getType());
3961 if (jaa.autoCalculated)
3963 autoAlan.add(new JvAnnotRow(i, jaa));
3966 // if (!autoForView)
3968 // add autocalculated group annotation and any user created annotation
3970 al.addAnnotation(jaa);
3974 // ///////////////////////
3976 // Create alignment markup and styles for this view
3977 if (jalviewModel.getJGroup().size() > 0)
3979 List<JGroup> groups = jalviewModel.getJGroup();
3980 boolean addAnnotSchemeGroup = false;
3981 for (int i = 0; i < groups.size(); i++)
3983 JGroup jGroup = groups.get(i);
3984 ColourSchemeI cs = null;
3985 if (jGroup.getColour() != null)
3987 if (jGroup.getColour().startsWith("ucs"))
3989 cs = getUserColourScheme(jalviewModel, jGroup.getColour());
3991 else if (jGroup.getColour().equals("AnnotationColourGradient")
3992 && jGroup.getAnnotationColours() != null)
3994 addAnnotSchemeGroup = true;
3998 cs = ColourSchemeProperty.getColourScheme(null, al,
3999 jGroup.getColour());
4002 int pidThreshold = safeInt(jGroup.getPidThreshold());
4004 Vector<SequenceI> seqs = new Vector<>();
4006 for (int s = 0; s < jGroup.getSeq().size(); s++)
4008 String seqId = jGroup.getSeq().get(s);
4009 SequenceI ts = seqRefIds.get(seqId);
4013 seqs.addElement(ts);
4017 if (seqs.size() < 1)
4022 SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
4023 safeBoolean(jGroup.isDisplayBoxes()),
4024 safeBoolean(jGroup.isDisplayText()),
4025 safeBoolean(jGroup.isColourText()),
4026 safeInt(jGroup.getStart()), safeInt(jGroup.getEnd()));
4027 sg.getGroupColourScheme().setThreshold(pidThreshold, true);
4028 sg.getGroupColourScheme()
4029 .setConservationInc(safeInt(jGroup.getConsThreshold()));
4030 sg.setOutlineColour(new Color(safeInt(jGroup.getOutlineColour())));
4032 sg.textColour = new Color(safeInt(jGroup.getTextCol1()));
4033 sg.textColour2 = new Color(safeInt(jGroup.getTextCol2()));
4034 sg.setShowNonconserved(safeBoolean(jGroup.isShowUnconserved()));
4035 sg.thresholdTextColour = safeInt(jGroup.getTextColThreshold());
4036 // attributes with a default in the schema are never null
4037 sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
4038 sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
4039 sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
4040 sg.setIgnoreGapsConsensus(jGroup.isIgnoreGapsinConsensus());
4041 if (jGroup.getConsThreshold() != null
4042 && jGroup.getConsThreshold().intValue() != 0)
4044 Conservation c = new Conservation("All", sg.getSequences(null), 0,
4047 c.verdict(false, 25);
4048 sg.cs.setConservation(c);
4051 if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
4053 // re-instate unique group/annotation row reference
4054 List<AlignmentAnnotation> jaal = groupAnnotRefs
4055 .get(jGroup.getId());
4058 for (AlignmentAnnotation jaa : jaal)
4061 if (jaa.autoCalculated)
4063 // match up and try to set group autocalc alignment row for this
4065 if (jaa.label.startsWith("Consensus for "))
4067 sg.setConsensus(jaa);
4069 // match up and try to set group autocalc alignment row for this
4071 if (jaa.label.startsWith("Conservation for "))
4073 sg.setConservationRow(jaa);
4080 if (addAnnotSchemeGroup)
4082 // reconstruct the annotation colourscheme
4084 constructAnnotationColour(jGroup.getAnnotationColours(),
4085 null, al, jalviewModel, false));
4091 // only dataset in this model, so just return.
4094 // ///////////////////////////////
4097 AlignFrame af = null;
4098 AlignViewport av = null;
4099 // now check to see if we really need to create a new viewport.
4100 if (multipleView && viewportsAdded.size() == 0)
4102 // We recovered an alignment for which a viewport already exists.
4103 // TODO: fix up any settings necessary for overlaying stored state onto
4104 // state recovered from another document. (may not be necessary).
4105 // we may need a binding from a viewport in memory to one recovered from
4107 // and then recover its containing af to allow the settings to be applied.
4108 // TODO: fix for vamsas demo
4110 "About to recover a viewport for existing alignment: Sequence set ID is "
4112 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
4113 if (seqsetobj != null)
4115 if (seqsetobj instanceof String)
4117 uniqueSeqSetId = (String) seqsetobj;
4119 "Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
4125 "Warning : Collision between sequence set ID string and existing jalview object mapping.");
4131 * indicate that annotation colours are applied across all groups (pre
4132 * Jalview 2.8.1 behaviour)
4134 boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan("2.8.1",
4135 jalviewModel.getVersion());
4137 AlignmentPanel ap = null;
4138 boolean isnewview = true;
4141 // Check to see if this alignment already has a view id == viewId
4142 jalview.gui.AlignmentPanel views[] = Desktop
4143 .getAlignmentPanels(uniqueSeqSetId);
4144 if (views != null && views.length > 0)
4146 for (int v = 0; v < views.length; v++)
4148 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
4150 // recover the existing alignpanel, alignframe, viewport
4151 af = views[v].alignFrame;
4154 // TODO: could even skip resetting view settings if we don't want to
4155 // change the local settings from other jalview processes
4164 af = loadViewport(file, jseqs, hiddenSeqs, al, jalviewModel, view,
4165 uniqueSeqSetId, viewId, autoAlan);
4166 av = af.getViewport();
4171 * Load any trees, PDB structures and viewers, Overview
4173 * Not done if flag is false (when this method is used for New View)
4175 if (loadTreesAndStructures)
4177 loadTrees(jalviewModel, view, af, av, ap);
4178 loadPCAViewers(jalviewModel, ap);
4179 loadPDBStructures(jprovider, jseqs, af, ap);
4180 loadRnaViewers(jprovider, jseqs, ap);
4181 loadOverview(view, jalviewModel.getVersion(), af);
4183 // and finally return.
4188 * Load Overview window, restoring colours, 'show hidden regions' flag, title
4189 * and geometry as saved
4194 protected void loadOverview(Viewport view, String version, AlignFrame af)
4196 if (!isVersionStringLaterThan("2.11.3",
4197 version) && view.getOverview()==null)
4202 * first close any Overview that was opened automatically
4203 * (if so configured in Preferences) so that the view is
4204 * restored in the same state as saved
4206 af.alignPanel.closeOverviewPanel();
4208 Overview overview = view.getOverview();
4209 if (overview != null)
4211 OverviewPanel overviewPanel = af
4212 .openOverviewPanel(overview.isShowHidden());
4213 overviewPanel.setTitle(overview.getTitle());
4214 overviewPanel.setFrameBounds(overview.getXpos(), overview.getYpos(),
4215 overview.getWidth(), overview.getHeight());
4216 Color gap = new Color(overview.getGapColour());
4217 Color residue = new Color(overview.getResidueColour());
4218 Color hidden = new Color(overview.getHiddenColour());
4219 overviewPanel.getCanvas().setColours(gap, residue, hidden);
4224 * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
4225 * panel is restored from separate jar entries, two (gapped and trimmed) per
4226 * sequence and secondary structure.
4228 * Currently each viewer shows just one sequence and structure (gapped and
4229 * trimmed), however this method is designed to support multiple sequences or
4230 * structures in viewers if wanted in future.
4236 private void loadRnaViewers(jarInputStreamProvider jprovider,
4237 List<JSeq> jseqs, AlignmentPanel ap)
4240 * scan the sequences for references to viewers; create each one the first
4241 * time it is referenced, add Rna models to existing viewers
4243 for (JSeq jseq : jseqs)
4245 for (int i = 0; i < jseq.getRnaViewer().size(); i++)
4247 RnaViewer viewer = jseq.getRnaViewer().get(i);
4248 AppVarna appVarna = findOrCreateVarnaViewer(viewer, uniqueSetSuffix,
4251 for (int j = 0; j < viewer.getSecondaryStructure().size(); j++)
4253 SecondaryStructure ss = viewer.getSecondaryStructure().get(j);
4254 SequenceI seq = seqRefIds.get(jseq.getId());
4255 AlignmentAnnotation ann = this.annotationIds
4256 .get(ss.getAnnotationId());
4259 * add the structure to the Varna display (with session state copied
4260 * from the jar to a temporary file)
4262 boolean gapped = safeBoolean(ss.isGapped());
4263 String rnaTitle = ss.getTitle();
4264 String sessionState = ss.getViewerState();
4265 String tempStateFile = copyJarEntry(jprovider, sessionState,
4267 RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
4268 appVarna.addModelSession(rna, rnaTitle, tempStateFile);
4270 appVarna.setInitialSelection(safeInt(viewer.getSelectedRna()));
4276 * Locate and return an already instantiated matching AppVarna, or create one
4280 * @param viewIdSuffix
4284 protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
4285 String viewIdSuffix, AlignmentPanel ap)
4288 * on each load a suffix is appended to the saved viewId, to avoid conflicts
4289 * if load is repeated
4291 String postLoadId = viewer.getViewId() + viewIdSuffix;
4292 for (JInternalFrame frame : getAllFrames())
4294 if (frame instanceof AppVarna)
4296 AppVarna varna = (AppVarna) frame;
4297 if (postLoadId.equals(varna.getViewId()))
4299 // this viewer is already instantiated
4300 // could in future here add ap as another 'parent' of the
4301 // AppVarna window; currently just 1-to-many
4308 * viewer not found - make it
4310 RnaViewerModel model = new RnaViewerModel(postLoadId, viewer.getTitle(),
4311 safeInt(viewer.getXpos()), safeInt(viewer.getYpos()),
4312 safeInt(viewer.getWidth()), safeInt(viewer.getHeight()),
4313 safeInt(viewer.getDividerLocation()));
4314 AppVarna varna = new AppVarna(model, ap);
4320 * Load any saved trees
4328 protected void loadTrees(JalviewModel jm, Viewport view, AlignFrame af,
4329 AlignViewport av, AlignmentPanel ap)
4331 // TODO result of automated refactoring - are all these parameters needed?
4334 for (int t = 0; t < jm.getTree().size(); t++)
4337 Tree tree = jm.getTree().get(t);
4339 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
4342 tp = af.showNewickTree(new NewickFile(tree.getNewick()),
4343 tree.getTitle(), safeInt(tree.getWidth()),
4344 safeInt(tree.getHeight()), safeInt(tree.getXpos()),
4345 safeInt(tree.getYpos()));
4346 if (tree.getId() != null)
4348 // perhaps bind the tree id to something ?
4353 // update local tree attributes ?
4354 // TODO: should check if tp has been manipulated by user - if so its
4355 // settings shouldn't be modified
4356 tp.setTitle(tree.getTitle());
4357 tp.setBounds(new Rectangle(safeInt(tree.getXpos()),
4358 safeInt(tree.getYpos()), safeInt(tree.getWidth()),
4359 safeInt(tree.getHeight())));
4360 tp.setViewport(av); // af.viewport;
4361 // TODO: verify 'associate with all views' works still
4362 tp.getTreeCanvas().setViewport(av); // af.viewport;
4363 tp.getTreeCanvas().setAssociatedPanel(ap); // af.alignPanel;
4365 tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
4369 "There was a problem recovering stored Newick tree: \n"
4370 + tree.getNewick());
4374 tp.fitToWindow.setState(safeBoolean(tree.isFitToWindow()));
4375 tp.fitToWindow_actionPerformed(null);
4377 if (tree.getFontName() != null)
4380 new Font(tree.getFontName(), safeInt(tree.getFontStyle()),
4381 safeInt(tree.getFontSize())));
4386 new Font(view.getFontName(), safeInt(view.getFontStyle()),
4387 safeInt(view.getFontSize())));
4390 tp.showPlaceholders(safeBoolean(tree.isMarkUnlinked()));
4391 tp.showBootstrap(safeBoolean(tree.isShowBootstrap()));
4392 tp.showDistances(safeBoolean(tree.isShowDistances()));
4394 tp.getTreeCanvas().setThreshold(safeFloat(tree.getThreshold()));
4396 if (safeBoolean(tree.isCurrentTree()))
4398 af.getViewport().setCurrentTree(tp.getTree());
4402 } catch (Exception ex)
4404 ex.printStackTrace();
4409 * Load and link any saved structure viewers.
4416 protected void loadPDBStructures(jarInputStreamProvider jprovider,
4417 List<JSeq> jseqs, AlignFrame af, AlignmentPanel ap)
4420 * Run through all PDB ids on the alignment, and collect mappings between
4421 * distinct view ids and all sequences referring to that view.
4423 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
4425 for (int i = 0; i < jseqs.size(); i++)
4427 JSeq jseq = jseqs.get(i);
4428 if (jseq.getPdbids().size() > 0)
4430 List<Pdbids> ids = jseq.getPdbids();
4431 for (int p = 0; p < ids.size(); p++)
4433 Pdbids pdbid = ids.get(p);
4434 final int structureStateCount = pdbid.getStructureState().size();
4435 for (int s = 0; s < structureStateCount; s++)
4437 // check to see if we haven't already created this structure view
4438 final StructureState structureState = pdbid.getStructureState()
4440 String sviewid = (structureState.getViewId() == null) ? null
4441 : structureState.getViewId() + uniqueSetSuffix;
4442 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
4443 // Originally : pdbid.getFile()
4444 // : TODO: verify external PDB file recovery still works in normal
4445 // jalview project load
4447 loadPDBFile(jprovider, pdbid.getId(), pdbid.getFile()));
4448 jpdb.setId(pdbid.getId());
4450 int x = safeInt(structureState.getXpos());
4451 int y = safeInt(structureState.getYpos());
4452 int width = safeInt(structureState.getWidth());
4453 int height = safeInt(structureState.getHeight());
4455 // Probably don't need to do this anymore...
4456 // Desktop.desktop.getComponentAt(x, y);
4457 // TODO: NOW: check that this recovers the PDB file correctly.
4458 String pdbFile = loadPDBFile(jprovider, pdbid.getId(),
4460 jalview.datamodel.SequenceI seq = seqRefIds
4461 .get(jseq.getId() + "");
4462 if (sviewid == null)
4464 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width + ","
4467 if (!structureViewers.containsKey(sviewid))
4469 String viewerType = structureState.getType();
4470 if (viewerType == null) // pre Jalview 2.9
4472 viewerType = ViewerType.JMOL.toString();
4474 structureViewers.put(sviewid,
4475 new StructureViewerModel(x, y, width, height, false,
4476 false, true, structureState.getViewId(),
4478 // Legacy pre-2.7 conversion JAL-823 :
4479 // do not assume any view has to be linked for colour by
4483 // assemble String[] { pdb files }, String[] { id for each
4484 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
4485 // seqs_file 2}, boolean[] {
4486 // linkAlignPanel,superposeWithAlignpanel}} from hash
4487 StructureViewerModel jmoldat = structureViewers.get(sviewid);
4488 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
4489 || structureState.isAlignwithAlignPanel());
4492 * Default colour by linked panel to false if not specified (e.g.
4493 * for pre-2.7 projects)
4495 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
4496 colourWithAlignPanel |= structureState.isColourwithAlignPanel();
4497 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
4500 * Default colour by viewer to true if not specified (e.g. for
4503 boolean colourByViewer = jmoldat.isColourByViewer();
4504 colourByViewer &= structureState.isColourByJmol();
4505 jmoldat.setColourByViewer(colourByViewer);
4507 if (jmoldat.getStateData().length() < structureState.getValue()
4508 /*Content()*/.length())
4510 jmoldat.setStateData(structureState.getValue());// Content());
4512 if (pdbid.getFile() != null)
4514 File mapkey = new File(pdbid.getFile());
4515 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
4516 if (seqstrmaps == null)
4518 jmoldat.getFileData().put(mapkey,
4519 seqstrmaps = jmoldat.new StructureData(pdbFile,
4522 if (!seqstrmaps.getSeqList().contains(seq))
4524 seqstrmaps.getSeqList().add(seq);
4530 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");
4531 Console.warn(errorMessage);
4537 // Instantiate the associated structure views
4538 for (Entry<String, StructureViewerModel> entry : structureViewers
4543 createOrLinkStructureViewer(entry, af, ap, jprovider);
4544 } catch (Exception e)
4547 "Error loading structure viewer: " + e.getMessage());
4548 // failed - try the next one
4560 protected void createOrLinkStructureViewer(
4561 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
4562 AlignmentPanel ap, jarInputStreamProvider jprovider)
4564 final StructureViewerModel stateData = viewerData.getValue();
4567 * Search for any viewer windows already open from other alignment views
4568 * that exactly match the stored structure state
4570 StructureViewerBase comp = findMatchingViewer(viewerData);
4574 linkStructureViewer(ap, comp, stateData);
4578 String type = stateData.getType();
4581 ViewerType viewerType = ViewerType.valueOf(type);
4582 createStructureViewer(viewerType, viewerData, af, jprovider);
4583 } catch (IllegalArgumentException | NullPointerException e)
4585 // TODO JAL-3619 show error dialog / offer an alternative viewer
4586 Console.error("Invalid structure viewer type: " + type);
4591 * Generates a name for the entry in the project jar file to hold state
4592 * information for a structure viewer
4597 protected String getViewerJarEntryName(String viewId)
4599 return VIEWER_PREFIX + viewId;
4603 * Returns any open frame that matches given structure viewer data. The match
4604 * is based on the unique viewId, or (for older project versions) the frame's
4610 protected StructureViewerBase findMatchingViewer(
4611 Entry<String, StructureViewerModel> viewerData)
4613 final String sviewid = viewerData.getKey();
4614 final StructureViewerModel svattrib = viewerData.getValue();
4615 StructureViewerBase comp = null;
4616 JInternalFrame[] frames = getAllFrames();
4617 for (JInternalFrame frame : frames)
4619 if (frame instanceof StructureViewerBase)
4622 * Post jalview 2.4 schema includes structure view id
4624 if (sviewid != null && ((StructureViewerBase) frame).getViewId()
4627 comp = (StructureViewerBase) frame;
4628 break; // break added in 2.9
4631 * Otherwise test for matching position and size of viewer frame
4633 else if (frame.getX() == svattrib.getX()
4634 && frame.getY() == svattrib.getY()
4635 && frame.getHeight() == svattrib.getHeight()
4636 && frame.getWidth() == svattrib.getWidth())
4638 comp = (StructureViewerBase) frame;
4639 // no break in faint hope of an exact match on viewId
4647 * Link an AlignmentPanel to an existing structure viewer.
4652 * @param useinViewerSuperpos
4653 * @param usetoColourbyseq
4654 * @param viewerColouring
4656 protected void linkStructureViewer(AlignmentPanel ap,
4657 StructureViewerBase viewer, StructureViewerModel stateData)
4659 // NOTE: if the jalview project is part of a shared session then
4660 // view synchronization should/could be done here.
4662 final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
4663 final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
4664 final boolean viewerColouring = stateData.isColourByViewer();
4665 Map<File, StructureData> oldFiles = stateData.getFileData();
4668 * Add mapping for sequences in this view to an already open viewer
4670 final AAStructureBindingModel binding = viewer.getBinding();
4671 for (File id : oldFiles.keySet())
4673 // add this and any other pdb files that should be present in the
4675 StructureData filedat = oldFiles.get(id);
4676 String pdbFile = filedat.getFilePath();
4677 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
4678 binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE,
4680 binding.addSequenceForStructFile(pdbFile, seq);
4682 // and add the AlignmentPanel's reference to the view panel
4683 viewer.addAlignmentPanel(ap);
4684 if (useinViewerSuperpos)
4686 viewer.useAlignmentPanelForSuperposition(ap);
4690 viewer.excludeAlignmentPanelForSuperposition(ap);
4692 if (usetoColourbyseq)
4694 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
4698 viewer.excludeAlignmentPanelForColourbyseq(ap);
4703 * Get all frames within the Desktop.
4707 protected JInternalFrame[] getAllFrames()
4709 JInternalFrame[] frames = null;
4710 // TODO is this necessary - is it safe - risk of hanging?
4715 frames = Desktop.desktop.getAllFrames();
4716 } catch (ArrayIndexOutOfBoundsException e)
4718 // occasional No such child exceptions are thrown here...
4722 } catch (InterruptedException f)
4726 } while (frames == null);
4731 * Answers true if 'version' is equal to or later than 'supported', where each
4732 * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
4733 * changes. Development and test values for 'version' are leniently treated
4737 * - minimum version we are comparing against
4739 * - version of data being processsed
4740 * @return true if version is equal to or later than supported
4742 public static boolean isVersionStringLaterThan(String supported,
4745 if (supported == null || version == null
4746 || version.equalsIgnoreCase("DEVELOPMENT BUILD")
4747 || version.equalsIgnoreCase("Test")
4748 || version.equalsIgnoreCase("AUTOMATED BUILD"))
4750 System.err.println("Assuming project file with "
4751 + (version == null ? "null" : version)
4752 + " is compatible with Jalview version " + supported);
4757 return StringUtils.compareVersions(version, supported, "b") >= 0;
4761 Vector<JalviewStructureDisplayI> newStructureViewers = null;
4763 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
4765 if (newStructureViewers != null)
4767 sview.getBinding().setFinishedLoadingFromArchive(false);
4768 newStructureViewers.add(sview);
4772 protected void setLoadingFinishedForNewStructureViewers()
4774 if (newStructureViewers != null)
4776 for (JalviewStructureDisplayI sview : newStructureViewers)
4778 sview.getBinding().setFinishedLoadingFromArchive(true);
4780 newStructureViewers.clear();
4781 newStructureViewers = null;
4785 AlignFrame loadViewport(String file, List<JSeq> JSEQ,
4786 List<SequenceI> hiddenSeqs, AlignmentI al, JalviewModel jm,
4787 Viewport view, String uniqueSeqSetId, String viewId,
4788 List<JvAnnotRow> autoAlan)
4790 AlignFrame af = null;
4791 af = new AlignFrame(al, safeInt(view.getWidth()),
4792 safeInt(view.getHeight()), uniqueSeqSetId, viewId)
4796 // protected void processKeyEvent(java.awt.event.KeyEvent e) {
4797 // System.out.println("Jalview2XML AF " + e);
4798 // super.processKeyEvent(e);
4805 af.setFileName(file, FileFormat.Jalview);
4807 final AlignViewport viewport = af.getViewport();
4808 for (int i = 0; i < JSEQ.size(); i++)
4810 int colour = safeInt(JSEQ.get(i).getColour());
4811 viewport.setSequenceColour(viewport.getAlignment().getSequenceAt(i),
4817 viewport.setColourByReferenceSeq(true);
4818 viewport.setDisplayReferenceSeq(true);
4821 viewport.setGatherViewsHere(safeBoolean(view.isGatheredViews()));
4823 if (view.getSequenceSetId() != null)
4825 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
4827 viewport.setSequenceSetId(uniqueSeqSetId);
4830 // propagate shared settings to this new view
4831 viewport.setHistoryList(av.getHistoryList());
4832 viewport.setRedoList(av.getRedoList());
4836 viewportsAdded.put(uniqueSeqSetId, viewport);
4838 // TODO: check if this method can be called repeatedly without
4839 // side-effects if alignpanel already registered.
4840 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
4842 // apply Hidden regions to view.
4843 if (hiddenSeqs != null)
4845 for (int s = 0; s < JSEQ.size(); s++)
4847 SequenceGroup hidden = new SequenceGroup();
4848 boolean isRepresentative = false;
4849 for (int r = 0; r < JSEQ.get(s).getHiddenSequences().size(); r++)
4851 isRepresentative = true;
4852 SequenceI sequenceToHide = al
4853 .getSequenceAt(JSEQ.get(s).getHiddenSequences().get(r));
4854 hidden.addSequence(sequenceToHide, false);
4855 // remove from hiddenSeqs list so we don't try to hide it twice
4856 hiddenSeqs.remove(sequenceToHide);
4858 if (isRepresentative)
4860 SequenceI representativeSequence = al.getSequenceAt(s);
4861 hidden.addSequence(representativeSequence, false);
4862 viewport.hideRepSequences(representativeSequence, hidden);
4866 SequenceI[] hseqs = hiddenSeqs
4867 .toArray(new SequenceI[hiddenSeqs.size()]);
4868 viewport.hideSequence(hseqs);
4871 // recover view properties and display parameters
4873 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
4874 viewport.setAbovePIDThreshold(safeBoolean(view.isPidSelected()));
4875 final int pidThreshold = safeInt(view.getPidThreshold());
4876 viewport.setThreshold(pidThreshold);
4878 viewport.setColourText(safeBoolean(view.isShowColourText()));
4880 viewport.setConservationSelected(
4881 safeBoolean(view.isConservationSelected()));
4882 viewport.setIncrement(safeInt(view.getConsThreshold()));
4883 viewport.setShowJVSuffix(safeBoolean(view.isShowFullId()));
4884 viewport.setRightAlignIds(safeBoolean(view.isRightAlignIds()));
4885 if (view.getCharWidth()!=null)
4887 viewport.setCharWidth(view.getCharWidth());
4888 viewport.setCharHeight(view.getCharHeight());
4890 viewport.setFont(new Font(view.getFontName(),
4891 safeInt(view.getFontStyle()), safeInt(view.getFontSize())),
4893 ViewStyleI vs = viewport.getViewStyle();
4894 vs.setScaleProteinAsCdna(view.isScaleProteinAsCdna());
4895 viewport.setViewStyle(vs);
4896 // TODO: allow custom charWidth/Heights to be restored by updating them
4897 // after setting font - which means set above to false
4898 viewport.setRenderGaps(safeBoolean(view.isRenderGaps()));
4899 viewport.setWrapAlignment(safeBoolean(view.isWrapAlignment()));
4900 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
4902 viewport.setShowBoxes(safeBoolean(view.isShowBoxes()));
4904 viewport.setShowText(safeBoolean(view.isShowText()));
4906 viewport.setTextColour(new Color(safeInt(view.getTextCol1())));
4907 viewport.setTextColour2(new Color(safeInt(view.getTextCol2())));
4908 viewport.setThresholdTextColour(safeInt(view.getTextColThreshold()));
4909 viewport.setShowUnconserved(view.isShowUnconserved());
4910 viewport.getRanges().setStartRes(safeInt(view.getStartRes()));
4912 if (view.getViewName() != null)
4914 viewport.setViewName(view.getViewName());
4915 af.setInitialTabVisible();
4917 af.setBounds(safeInt(view.getXpos()), safeInt(view.getYpos()),
4918 safeInt(view.getWidth()), safeInt(view.getHeight()));
4919 // startSeq set in af.alignPanel.updateLayout below
4920 af.alignPanel.updateLayout();
4921 ColourSchemeI cs = null;
4922 // apply colourschemes
4923 if (view.getBgColour() != null)
4925 if (view.getBgColour().startsWith("ucs"))
4927 cs = getUserColourScheme(jm, view.getBgColour());
4929 else if (view.getBgColour().startsWith("Annotation"))
4931 AnnotationColourScheme viewAnnColour = view.getAnnotationColours();
4932 cs = constructAnnotationColour(viewAnnColour, af, al, jm, true);
4939 cs = ColourSchemeProperty.getColourScheme(af.getViewport(), al,
4940 view.getBgColour());
4945 * turn off 'alignment colour applies to all groups'
4946 * while restoring global colour scheme
4948 viewport.setColourAppliesToAllGroups(false);
4949 viewport.setGlobalColourScheme(cs);
4950 viewport.getResidueShading().setThreshold(pidThreshold,
4951 view.isIgnoreGapsinConsensus());
4952 viewport.getResidueShading()
4953 .setConsensus(viewport.getSequenceConsensusHash());
4954 if (safeBoolean(view.isConservationSelected()) && cs != null)
4956 viewport.getResidueShading()
4957 .setConservationInc(safeInt(view.getConsThreshold()));
4959 af.changeColour(cs);
4960 viewport.setColourAppliesToAllGroups(true);
4962 viewport.setShowSequenceFeatures(
4963 safeBoolean(view.isShowSequenceFeatures()));
4965 viewport.setCentreColumnLabels(view.isCentreColumnLabels());
4966 viewport.setIgnoreGapsConsensus(view.isIgnoreGapsinConsensus(), null);
4967 viewport.setFollowHighlight(view.isFollowHighlight());
4968 viewport.followSelection = view.isFollowSelection();
4969 viewport.setShowConsensusHistogram(view.isShowConsensusHistogram());
4970 viewport.setShowSequenceLogo(view.isShowSequenceLogo());
4971 viewport.setNormaliseSequenceLogo(view.isNormaliseSequenceLogo());
4972 viewport.setShowDBRefs(safeBoolean(view.isShowDbRefTooltip()));
4973 viewport.setShowNPFeats(safeBoolean(view.isShowNPfeatureTooltip()));
4974 viewport.setShowGroupConsensus(view.isShowGroupConsensus());
4975 viewport.setShowGroupConservation(view.isShowGroupConservation());
4976 viewport.setShowComplementFeatures(view.isShowComplementFeatures());
4977 viewport.setShowComplementFeaturesOnTop(
4978 view.isShowComplementFeaturesOnTop());
4980 // recover feature settings
4981 if (jm.getFeatureSettings() != null)
4983 FeatureRendererModel fr = af.alignPanel.getSeqPanel().seqCanvas
4984 .getFeatureRenderer();
4985 FeaturesDisplayed fdi;
4986 viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
4987 String[] renderOrder = new String[jm.getFeatureSettings().getSetting()
4989 Map<String, FeatureColourI> featureColours = new Hashtable<>();
4990 Map<String, Float> featureOrder = new Hashtable<>();
4992 for (int fs = 0; fs < jm.getFeatureSettings().getSetting()
4995 Setting setting = jm.getFeatureSettings().getSetting().get(fs);
4996 String featureType = setting.getType();
4999 * restore feature filters (if any)
5001 jalview.xml.binding.jalview.FeatureMatcherSet filters = setting
5003 if (filters != null)
5005 FeatureMatcherSetI filter = Jalview2XML.parseFilter(featureType,
5007 if (!filter.isEmpty())
5009 fr.setFeatureFilter(featureType, filter);
5014 * restore feature colour scheme
5016 Color maxColour = new Color(setting.getColour());
5017 if (setting.getMincolour() != null)
5020 * minColour is always set unless a simple colour
5021 * (including for colour by label though it doesn't use it)
5023 Color minColour = new Color(setting.getMincolour().intValue());
5024 Color noValueColour = minColour;
5025 NoValueColour noColour = setting.getNoValueColour();
5026 if (noColour == NoValueColour.NONE)
5028 noValueColour = null;
5030 else if (noColour == NoValueColour.MAX)
5032 noValueColour = maxColour;
5034 float min = safeFloat(safeFloat(setting.getMin()));
5035 float max = setting.getMax() == null ? 1f
5036 : setting.getMax().floatValue();
5037 FeatureColourI gc = new FeatureColour(maxColour, minColour,
5038 maxColour, noValueColour, min, max);
5039 if (setting.getAttributeName().size() > 0)
5041 gc.setAttributeName(setting.getAttributeName().toArray(
5042 new String[setting.getAttributeName().size()]));
5044 if (setting.getThreshold() != null)
5046 gc.setThreshold(setting.getThreshold().floatValue());
5047 int threshstate = safeInt(setting.getThreshstate());
5048 // -1 = None, 0 = Below, 1 = Above threshold
5049 if (threshstate == 0)
5051 gc.setBelowThreshold(true);
5053 else if (threshstate == 1)
5055 gc.setAboveThreshold(true);
5058 gc.setAutoScaled(true); // default
5059 if (setting.isAutoScale() != null)
5061 gc.setAutoScaled(setting.isAutoScale());
5063 if (setting.isColourByLabel() != null)
5065 gc.setColourByLabel(setting.isColourByLabel());
5067 // and put in the feature colour table.
5068 featureColours.put(featureType, gc);
5072 featureColours.put(featureType, new FeatureColour(maxColour));
5074 renderOrder[fs] = featureType;
5075 if (setting.getOrder() != null)
5077 featureOrder.put(featureType, setting.getOrder().floatValue());
5081 featureOrder.put(featureType, Float.valueOf(
5082 fs / jm.getFeatureSettings().getSetting().size()));
5084 if (safeBoolean(setting.isDisplay()))
5086 fdi.setVisible(featureType);
5089 Map<String, Boolean> fgtable = new Hashtable<>();
5090 for (int gs = 0; gs < jm.getFeatureSettings().getGroup().size(); gs++)
5092 Group grp = jm.getFeatureSettings().getGroup().get(gs);
5093 fgtable.put(grp.getName(), Boolean.valueOf(grp.isDisplay()));
5095 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
5096 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
5097 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
5098 FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
5099 fgtable, featureColours, 1.0f, featureOrder);
5100 fr.transferSettings(frs);
5103 if (view.getHiddenColumns().size() > 0)
5105 for (int c = 0; c < view.getHiddenColumns().size(); c++)
5107 final HiddenColumns hc = view.getHiddenColumns().get(c);
5108 viewport.hideColumns(safeInt(hc.getStart()),
5109 safeInt(hc.getEnd()) /* +1 */);
5112 if (view.getCalcIdParam() != null)
5114 for (CalcIdParam calcIdParam : view.getCalcIdParam())
5116 if (calcIdParam != null)
5118 if (recoverCalcIdParam(calcIdParam, viewport))
5123 Console.warn("Couldn't recover parameters for "
5124 + calcIdParam.getCalcId());
5129 af.setMenusFromViewport(viewport);
5130 af.setTitle(view.getTitle());
5131 // TODO: we don't need to do this if the viewport is aready visible.
5133 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
5134 * has a 'cdna/protein complement' view, in which case save it in order to
5135 * populate a SplitFrame once all views have been read in.
5137 String complementaryViewId = view.getComplementId();
5138 if (complementaryViewId == null)
5140 Desktop.addInternalFrame(af, view.getTitle(),
5141 safeInt(view.getWidth()), safeInt(view.getHeight()));
5142 // recompute any autoannotation
5143 af.alignPanel.updateAnnotation(false, true);
5144 reorderAutoannotation(af, al, autoAlan);
5145 af.alignPanel.alignmentChanged();
5149 splitFrameCandidates.put(view, af);
5156 * Reads saved data to restore Colour by Annotation settings
5158 * @param viewAnnColour
5162 * @param checkGroupAnnColour
5165 private ColourSchemeI constructAnnotationColour(
5166 AnnotationColourScheme viewAnnColour, AlignFrame af,
5167 AlignmentI al, JalviewModel model, boolean checkGroupAnnColour)
5169 boolean propagateAnnColour = false;
5170 AlignmentI annAlignment = af != null ? af.getViewport().getAlignment()
5172 if (checkGroupAnnColour && al.getGroups() != null
5173 && al.getGroups().size() > 0)
5175 // pre 2.8.1 behaviour
5176 // check to see if we should transfer annotation colours
5177 propagateAnnColour = true;
5178 for (SequenceGroup sg : al.getGroups())
5180 if (sg.getColourScheme() instanceof AnnotationColourGradient)
5182 propagateAnnColour = false;
5188 * 2.10.2- : saved annotationId is AlignmentAnnotation.annotationId
5190 String annotationId = viewAnnColour.getAnnotation();
5191 AlignmentAnnotation matchedAnnotation = annotationIds.get(annotationId);
5194 * pre 2.10.2: saved annotationId is AlignmentAnnotation.label
5196 if (matchedAnnotation == null
5197 && annAlignment.getAlignmentAnnotation() != null)
5199 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
5202 .equals(annAlignment.getAlignmentAnnotation()[i].label))
5204 matchedAnnotation = annAlignment.getAlignmentAnnotation()[i];
5209 if (matchedAnnotation == null)
5211 System.err.println("Failed to match annotation colour scheme for "
5215 // belt-and-braces create a threshold line if the
5216 // colourscheme needs one but the matchedAnnotation doesn't have one
5217 if (safeInt(viewAnnColour.getAboveThreshold()) != 0
5218 && matchedAnnotation.getThreshold() == null)
5220 matchedAnnotation.setThreshold(
5221 new GraphLine(safeFloat(viewAnnColour.getThreshold()),
5222 "Threshold", Color.black));
5225 AnnotationColourGradient cs = null;
5226 if (viewAnnColour.getColourScheme().equals("None"))
5228 cs = new AnnotationColourGradient(matchedAnnotation,
5229 new Color(safeInt(viewAnnColour.getMinColour())),
5230 new Color(safeInt(viewAnnColour.getMaxColour())),
5231 safeInt(viewAnnColour.getAboveThreshold()));
5233 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
5235 cs = new AnnotationColourGradient(matchedAnnotation,
5236 getUserColourScheme(model, viewAnnColour.getColourScheme()),
5237 safeInt(viewAnnColour.getAboveThreshold()));
5241 cs = new AnnotationColourGradient(matchedAnnotation,
5242 ColourSchemeProperty.getColourScheme(af.getViewport(), al,
5243 viewAnnColour.getColourScheme()),
5244 safeInt(viewAnnColour.getAboveThreshold()));
5247 boolean perSequenceOnly = safeBoolean(viewAnnColour.isPerSequence());
5248 boolean useOriginalColours = safeBoolean(
5249 viewAnnColour.isPredefinedColours());
5250 cs.setSeqAssociated(perSequenceOnly);
5251 cs.setPredefinedColours(useOriginalColours);
5253 if (propagateAnnColour && al.getGroups() != null)
5255 // Also use these settings for all the groups
5256 for (int g = 0; g < al.getGroups().size(); g++)
5258 SequenceGroup sg = al.getGroups().get(g);
5259 if (sg.getGroupColourScheme() == null)
5264 AnnotationColourGradient groupScheme = new AnnotationColourGradient(
5265 matchedAnnotation, sg.getColourScheme(),
5266 safeInt(viewAnnColour.getAboveThreshold()));
5267 sg.setColourScheme(groupScheme);
5268 groupScheme.setSeqAssociated(perSequenceOnly);
5269 groupScheme.setPredefinedColours(useOriginalColours);
5275 private void reorderAutoannotation(AlignFrame af, AlignmentI al,
5276 List<JvAnnotRow> autoAlan)
5278 // copy over visualization settings for autocalculated annotation in the
5280 if (al.getAlignmentAnnotation() != null)
5283 * Kludge for magic autoannotation names (see JAL-811)
5285 String[] magicNames = new String[] { "Consensus", "Quality",
5287 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
5288 Hashtable<String, JvAnnotRow> visan = new Hashtable<>();
5289 for (String nm : magicNames)
5291 visan.put(nm, nullAnnot);
5293 for (JvAnnotRow auan : autoAlan)
5295 visan.put(auan.template.label
5296 + (auan.template.getCalcId() == null ? ""
5297 : "\t" + auan.template.getCalcId()),
5300 int hSize = al.getAlignmentAnnotation().length;
5301 List<JvAnnotRow> reorder = new ArrayList<>();
5302 // work through any autoCalculated annotation already on the view
5303 // removing it if it should be placed in a different location on the
5304 // annotation panel.
5305 List<String> remains = new ArrayList<>(visan.keySet());
5306 for (int h = 0; h < hSize; h++)
5308 jalview.datamodel.AlignmentAnnotation jalan = al
5309 .getAlignmentAnnotation()[h];
5310 if (jalan.autoCalculated)
5313 JvAnnotRow valan = visan.get(k = jalan.label);
5314 if (jalan.getCalcId() != null)
5316 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
5321 // delete the auto calculated row from the alignment
5322 al.deleteAnnotation(jalan, false);
5326 if (valan != nullAnnot)
5328 if (jalan != valan.template)
5330 // newly created autoannotation row instance
5331 // so keep a reference to the visible annotation row
5332 // and copy over all relevant attributes
5333 if (valan.template.graphHeight >= 0)
5336 jalan.graphHeight = valan.template.graphHeight;
5338 jalan.visible = valan.template.visible;
5340 reorder.add(new JvAnnotRow(valan.order, jalan));
5345 // Add any (possibly stale) autocalculated rows that were not appended to
5346 // the view during construction
5347 for (String other : remains)
5349 JvAnnotRow othera = visan.get(other);
5350 if (othera != nullAnnot && othera.template.getCalcId() != null
5351 && othera.template.getCalcId().length() > 0)
5353 reorder.add(othera);
5356 // now put the automatic annotation in its correct place
5357 int s = 0, srt[] = new int[reorder.size()];
5358 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
5359 for (JvAnnotRow jvar : reorder)
5362 srt[s++] = jvar.order;
5365 jalview.util.QuickSort.sort(srt, rws);
5366 // and re-insert the annotation at its correct position
5367 for (JvAnnotRow jvar : rws)
5369 al.addAnnotation(jvar.template, jvar.order);
5371 af.alignPanel.adjustAnnotationHeight();
5375 Hashtable skipList = null;
5378 * TODO remove this method
5381 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
5382 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
5383 * throw new Error("Implementation Error. No skipList defined for this
5384 * Jalview2XML instance."); } return (AlignFrame)
5385 * skipList.get(view.getSequenceSetId()); }
5389 * Check if the Jalview view contained in object should be skipped or not.
5392 * @return true if view's sequenceSetId is a key in skipList
5394 private boolean skipViewport(JalviewModel object)
5396 if (skipList == null)
5400 String id = object.getViewport().get(0).getSequenceSetId();
5401 if (skipList.containsKey(id))
5403 Console.debug("Skipping seuqence set id " + id);
5409 public void addToSkipList(AlignFrame af)
5411 if (skipList == null)
5413 skipList = new Hashtable();
5415 skipList.put(af.getViewport().getSequenceSetId(), af);
5418 public void clearSkipList()
5420 if (skipList != null)
5427 private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
5428 boolean ignoreUnrefed, String uniqueSeqSetId)
5430 jalview.datamodel.AlignmentI ds = getDatasetFor(
5431 vamsasSet.getDatasetId());
5432 AlignmentI xtant_ds = ds;
5433 if (xtant_ds == null)
5435 // good chance we are about to create a new dataset, but check if we've
5436 // seen some of the dataset sequence IDs before.
5437 // TODO: skip this check if we are working with project generated by
5438 // version 2.11 or later
5439 xtant_ds = checkIfHasDataset(vamsasSet.getSequence());
5440 if (xtant_ds != null)
5443 addDatasetRef(vamsasSet.getDatasetId(), ds);
5446 Vector<SequenceI> dseqs = null;
5449 // recovering an alignment View
5450 AlignmentI seqSetDS = getDatasetFor(UNIQSEQSETID + uniqueSeqSetId);
5451 if (seqSetDS != null)
5453 if (ds != null && ds != seqSetDS)
5456 "JAL-3171 regression: Overwriting a dataset reference for an alignment"
5457 + " - CDS/Protein crossreference data may be lost");
5458 if (xtant_ds != null)
5460 // This can only happen if the unique sequence set ID was bound to a
5461 // dataset that did not contain any of the sequences in the view
5462 // currently being restored.
5464 "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.");
5468 addDatasetRef(vamsasSet.getDatasetId(), ds);
5473 // try even harder to restore dataset
5474 AlignmentI xtantDS = checkIfHasDataset(vamsasSet.getSequence());
5475 // create a list of new dataset sequences
5476 dseqs = new Vector<>();
5478 for (int i = 0, iSize = vamsasSet.getSequence().size(); i < iSize; i++)
5480 Sequence vamsasSeq = vamsasSet.getSequence().get(i);
5481 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed, i);
5483 // create a new dataset
5486 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
5487 dseqs.copyInto(dsseqs);
5488 ds = new jalview.datamodel.Alignment(dsseqs);
5489 Console.debug("Created new dataset " + vamsasSet.getDatasetId()
5490 + " for alignment " + System.identityHashCode(al));
5491 addDatasetRef(vamsasSet.getDatasetId(), ds);
5493 // set the dataset for the newly imported alignment.
5494 if (al.getDataset() == null && !ignoreUnrefed)
5497 // register dataset for the alignment's uniqueSeqSetId for legacy projects
5498 addDatasetRef(UNIQSEQSETID + uniqueSeqSetId, ds);
5500 updateSeqDatasetBinding(vamsasSet.getSequence(), ds);
5504 * XML dataset sequence ID to materialised dataset reference
5506 HashMap<String, AlignmentI> seqToDataset = new HashMap<>();
5509 * @return the first materialised dataset reference containing a dataset
5510 * sequence referenced in the given view
5512 * - sequences from the view
5514 AlignmentI checkIfHasDataset(List<Sequence> list)
5516 for (Sequence restoredSeq : list)
5518 AlignmentI datasetFor = seqToDataset.get(restoredSeq.getDsseqid());
5519 if (datasetFor != null)
5528 * Register ds as the containing dataset for the dataset sequences referenced
5529 * by sequences in list
5532 * - sequences in a view
5535 void updateSeqDatasetBinding(List<Sequence> list, AlignmentI ds)
5537 for (Sequence restoredSeq : list)
5539 AlignmentI prevDS = seqToDataset.put(restoredSeq.getDsseqid(), ds);
5540 if (prevDS != null && prevDS != ds)
5542 Console.warn("Dataset sequence appears in many datasets: "
5543 + restoredSeq.getDsseqid());
5544 // TODO: try to merge!
5552 * sequence definition to create/merge dataset sequence for
5556 * vector to add new dataset sequence to
5557 * @param ignoreUnrefed
5558 * - when true, don't create new sequences from vamsasSeq if it's id
5559 * doesn't already have an asssociated Jalview sequence.
5561 * - used to reorder the sequence in the alignment according to the
5562 * vamsasSeq array ordering, to preserve ordering of dataset
5564 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
5565 AlignmentI ds, Vector<SequenceI> dseqs, boolean ignoreUnrefed,
5568 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
5570 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
5571 boolean reorder = false;
5572 SequenceI dsq = null;
5573 if (sq != null && sq.getDatasetSequence() != null)
5575 dsq = sq.getDatasetSequence();
5581 if (sq == null && ignoreUnrefed)
5585 String sqid = vamsasSeq.getDsseqid();
5588 // need to create or add a new dataset sequence reference to this sequence
5591 dsq = seqRefIds.get(sqid);
5596 // make a new dataset sequence
5597 dsq = sq.createDatasetSequence();
5600 // make up a new dataset reference for this sequence
5601 sqid = seqHash(dsq);
5603 dsq.setVamsasId(uniqueSetSuffix + sqid);
5604 seqRefIds.put(sqid, dsq);
5609 dseqs.addElement(dsq);
5614 ds.addSequence(dsq);
5620 { // make this dataset sequence sq's dataset sequence
5621 sq.setDatasetSequence(dsq);
5622 // and update the current dataset alignment
5627 if (!dseqs.contains(dsq))
5634 if (ds.findIndex(dsq) < 0)
5636 ds.addSequence(dsq);
5643 // TODO: refactor this as a merge dataset sequence function
5644 // now check that sq (the dataset sequence) sequence really is the union of
5645 // all references to it
5646 // boolean pre = sq.getStart() < dsq.getStart();
5647 // boolean post = sq.getEnd() > dsq.getEnd();
5651 // StringBuffer sb = new StringBuffer();
5652 String newres = jalview.analysis.AlignSeq.extractGaps(
5653 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
5654 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
5655 && newres.length() > dsq.getLength())
5657 // Update with the longer sequence.
5661 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
5662 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
5663 * sb.append(newres.substring(newres.length() - sq.getEnd() -
5664 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
5666 dsq.setSequence(newres);
5668 // TODO: merges will never happen if we 'know' we have the real dataset
5669 // sequence - this should be detected when id==dssid
5671 "DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
5672 // + (pre ? "prepended" : "") + " "
5673 // + (post ? "appended" : ""));
5678 // sequence refs are identical. We may need to update the existing dataset
5679 // alignment with this one, though.
5680 if (ds != null && dseqs == null)
5682 int opos = ds.findIndex(dsq);
5683 SequenceI tseq = null;
5684 if (opos != -1 && vseqpos != opos)
5686 // remove from old position
5687 ds.deleteSequence(dsq);
5689 if (vseqpos < ds.getHeight())
5691 if (vseqpos != opos)
5693 // save sequence at destination position
5694 tseq = ds.getSequenceAt(vseqpos);
5695 ds.replaceSequenceAt(vseqpos, dsq);
5696 ds.addSequence(tseq);
5701 ds.addSequence(dsq);
5708 * TODO use AlignmentI here and in related methods - needs
5709 * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
5711 Hashtable<String, AlignmentI> datasetIds = null;
5713 IdentityHashMap<AlignmentI, String> dataset2Ids = null;
5715 private AlignmentI getDatasetFor(String datasetId)
5717 if (datasetIds == null)
5719 datasetIds = new Hashtable<>();
5722 if (datasetIds.containsKey(datasetId))
5724 return datasetIds.get(datasetId);
5729 private void addDatasetRef(String datasetId, AlignmentI dataset)
5731 if (datasetIds == null)
5733 datasetIds = new Hashtable<>();
5735 datasetIds.put(datasetId, dataset);
5739 * make a new dataset ID for this jalview dataset alignment
5744 private String getDatasetIdRef(AlignmentI dataset)
5746 if (dataset.getDataset() != null)
5749 "Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
5751 String datasetId = makeHashCode(dataset, null);
5752 if (datasetId == null)
5754 // make a new datasetId and record it
5755 if (dataset2Ids == null)
5757 dataset2Ids = new IdentityHashMap<>();
5761 datasetId = dataset2Ids.get(dataset);
5763 if (datasetId == null)
5765 datasetId = "ds" + dataset2Ids.size() + 1;
5766 dataset2Ids.put(dataset, datasetId);
5773 * Add any saved DBRefEntry's to the sequence. An entry flagged as 'locus' is
5774 * constructed as a special subclass GeneLocus.
5776 * @param datasetSequence
5779 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
5781 for (int d = 0; d < sequence.getDBRef().size(); d++)
5783 DBRef dr = sequence.getDBRef().get(d);
5787 entry = new GeneLocus(dr.getSource(), dr.getVersion(),
5788 dr.getAccessionId());
5792 entry = new DBRefEntry(dr.getSource(), dr.getVersion(),
5793 dr.getAccessionId());
5795 if (dr.getMapping() != null)
5797 entry.setMap(addMapping(dr.getMapping()));
5799 entry.setCanonical(dr.isCanonical());
5800 datasetSequence.addDBRef(entry);
5804 private jalview.datamodel.Mapping addMapping(Mapping m)
5806 SequenceI dsto = null;
5807 // Mapping m = dr.getMapping();
5808 int fr[] = new int[m.getMapListFrom().size() * 2];
5809 Iterator<MapListFrom> from = m.getMapListFrom().iterator();// enumerateMapListFrom();
5810 for (int _i = 0; from.hasNext(); _i += 2)
5812 MapListFrom mf = from.next();
5813 fr[_i] = mf.getStart();
5814 fr[_i + 1] = mf.getEnd();
5816 int fto[] = new int[m.getMapListTo().size() * 2];
5817 Iterator<MapListTo> to = m.getMapListTo().iterator();// enumerateMapListTo();
5818 for (int _i = 0; to.hasNext(); _i += 2)
5820 MapListTo mf = to.next();
5821 fto[_i] = mf.getStart();
5822 fto[_i + 1] = mf.getEnd();
5824 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto, fr,
5825 fto, m.getMapFromUnit().intValue(),
5826 m.getMapToUnit().intValue());
5829 * (optional) choice of dseqFor or Sequence
5831 if (m.getDseqFor() != null)
5833 String dsfor = m.getDseqFor();
5834 if (seqRefIds.containsKey(dsfor))
5839 jmap.setTo(seqRefIds.get(dsfor));
5843 frefedSequence.add(newMappingRef(dsfor, jmap));
5846 else if (m.getSequence() != null)
5849 * local sequence definition
5851 Sequence ms = m.getSequence();
5852 SequenceI djs = null;
5853 String sqid = ms.getDsseqid();
5854 if (sqid != null && sqid.length() > 0)
5857 * recover dataset sequence
5859 djs = seqRefIds.get(sqid);
5864 "Warning - making up dataset sequence id for DbRef sequence map reference");
5865 sqid = ((Object) ms).toString(); // make up a new hascode for
5866 // undefined dataset sequence hash
5867 // (unlikely to happen)
5873 * make a new dataset sequence and add it to refIds hash
5875 djs = new jalview.datamodel.Sequence(ms.getName(),
5877 djs.setStart(jmap.getMap().getToLowest());
5878 djs.setEnd(jmap.getMap().getToHighest());
5879 djs.setVamsasId(uniqueSetSuffix + sqid);
5881 incompleteSeqs.put(sqid, djs);
5882 seqRefIds.put(sqid, djs);
5885 Console.debug("about to recurse on addDBRefs.");
5894 * Provides a 'copy' of an alignment view (on action New View) by 'saving' the
5895 * view as XML (but not to file), and then reloading it
5900 public AlignmentPanel copyAlignPanel(AlignmentPanel ap)
5903 JalviewModel jm = saveState(ap, null, null, null);
5906 jm.getVamsasModel().getSequenceSet().get(0).getDatasetId(),
5907 ap.getAlignment().getDataset());
5909 uniqueSetSuffix = "";
5910 // jm.getJalviewModelSequence().getViewport(0).setId(null);
5911 jm.getViewport().get(0).setId(null);
5912 // we don't overwrite the view we just copied
5914 if (this.frefedSequence == null)
5916 frefedSequence = new Vector<>();
5919 viewportsAdded.clear();
5921 AlignFrame af = loadFromObject(jm, null, false, null);
5922 af.getAlignPanels().clear();
5923 af.closeMenuItem_actionPerformed(true);
5926 * if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
5927 * i<ap.av.getAlignment().getAlignmentAnnotation().length; i++) {
5928 * if(!ap.av.getAlignment().getAlignmentAnnotation()[i].autoCalculated) {
5929 * af.alignPanel.av.getAlignment().getAlignmentAnnotation()[i] =
5930 * ap.av.getAlignment().getAlignmentAnnotation()[i]; } } }
5933 return af.alignPanel;
5936 private Hashtable jvids2vobj;
5939 * set the object to ID mapping tables used to write/recover objects and XML
5940 * ID strings for the jalview project. If external tables are provided then
5941 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
5942 * object goes out of scope. - also populates the datasetIds hashtable with
5943 * alignment objects containing dataset sequences
5946 * Map from ID strings to jalview datamodel
5948 * Map from jalview datamodel to ID strings
5952 public void setObjectMappingTables(Hashtable vobj2jv,
5953 IdentityHashMap jv2vobj)
5955 this.jv2vobj = jv2vobj;
5956 this.vobj2jv = vobj2jv;
5957 Iterator ds = jv2vobj.keySet().iterator();
5959 while (ds.hasNext())
5961 Object jvobj = ds.next();
5962 id = jv2vobj.get(jvobj).toString();
5963 if (jvobj instanceof jalview.datamodel.Alignment)
5965 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
5967 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
5970 else if (jvobj instanceof jalview.datamodel.Sequence)
5972 // register sequence object so the XML parser can recover it.
5973 if (seqRefIds == null)
5975 seqRefIds = new HashMap<>();
5977 if (seqsToIds == null)
5979 seqsToIds = new IdentityHashMap<>();
5981 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
5982 seqsToIds.put((SequenceI) jvobj, id);
5984 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
5987 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
5988 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
5989 if (jvann.annotationId == null)
5991 jvann.annotationId = anid;
5993 if (!jvann.annotationId.equals(anid))
5995 // TODO verify that this is the correct behaviour
5996 Console.warn("Overriding Annotation ID for " + anid
5997 + " from different id : " + jvann.annotationId);
5998 jvann.annotationId = anid;
6001 else if (jvobj instanceof String)
6003 if (jvids2vobj == null)
6005 jvids2vobj = new Hashtable();
6006 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
6011 Console.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
6017 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
6018 * objects created from the project archive. If string is null (default for
6019 * construction) then suffix will be set automatically.
6023 public void setUniqueSetSuffix(String string)
6025 uniqueSetSuffix = string;
6030 * uses skipList2 as the skipList for skipping views on sequence sets
6031 * associated with keys in the skipList
6035 public void setSkipList(Hashtable skipList2)
6037 skipList = skipList2;
6041 * Reads the jar entry of given name and returns its contents, or null if the
6042 * entry is not found.
6045 * @param jarEntryName
6048 protected String readJarEntry(jarInputStreamProvider jprovider,
6049 String jarEntryName)
6051 String result = null;
6052 BufferedReader in = null;
6057 * Reopen the jar input stream and traverse its entries to find a matching
6060 JarInputStream jin = jprovider.getJarInputStream();
6061 JarEntry entry = null;
6064 entry = jin.getNextJarEntry();
6065 } while (entry != null && !entry.getName().equals(jarEntryName));
6069 StringBuilder out = new StringBuilder(256);
6070 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
6073 while ((data = in.readLine()) != null)
6077 result = out.toString();
6082 "Couldn't find entry in Jalview Jar for " + jarEntryName);
6084 } catch (Exception ex)
6086 ex.printStackTrace();
6094 } catch (IOException e)
6105 * Returns an incrementing counter (0, 1, 2...)
6109 private synchronized int nextCounter()
6115 * Loads any saved PCA viewers
6120 protected void loadPCAViewers(JalviewModel model, AlignmentPanel ap)
6124 List<PcaViewer> pcaviewers = model.getPcaViewer();
6125 for (PcaViewer viewer : pcaviewers)
6127 String modelName = viewer.getScoreModelName();
6128 SimilarityParamsI params = new SimilarityParams(
6129 viewer.isIncludeGappedColumns(), viewer.isMatchGaps(),
6130 viewer.isIncludeGaps(),
6131 viewer.isDenominateByShortestLength());
6134 * create the panel (without computing the PCA)
6136 PCAPanel panel = new PCAPanel(ap, modelName, params);
6138 panel.setTitle(viewer.getTitle());
6139 panel.setBounds(new Rectangle(viewer.getXpos(), viewer.getYpos(),
6140 viewer.getWidth(), viewer.getHeight()));
6142 boolean showLabels = viewer.isShowLabels();
6143 panel.setShowLabels(showLabels);
6144 panel.getRotatableCanvas().setShowLabels(showLabels);
6145 panel.getRotatableCanvas()
6146 .setBgColour(new Color(viewer.getBgColour()));
6147 panel.getRotatableCanvas()
6148 .setApplyToAllViews(viewer.isLinkToAllViews());
6151 * load PCA output data
6153 ScoreModelI scoreModel = ScoreModels.getInstance()
6154 .getScoreModel(modelName, ap);
6155 PCA pca = new PCA(null, scoreModel, params);
6156 PcaDataType pcaData = viewer.getPcaData();
6158 MatrixI pairwise = loadDoubleMatrix(pcaData.getPairwiseMatrix());
6159 pca.setPairwiseScores(pairwise);
6161 MatrixI triDiag = loadDoubleMatrix(pcaData.getTridiagonalMatrix());
6162 pca.setTridiagonal(triDiag);
6164 MatrixI result = loadDoubleMatrix(pcaData.getEigenMatrix());
6165 pca.setEigenmatrix(result);
6167 panel.getPcaModel().setPCA(pca);
6170 * we haven't saved the input data! (JAL-2647 to do)
6172 panel.setInputData(null);
6175 * add the sequence points for the PCA display
6177 List<jalview.datamodel.SequencePoint> seqPoints = new ArrayList<>();
6178 for (SequencePoint sp : viewer.getSequencePoint())
6180 String seqId = sp.getSequenceRef();
6181 SequenceI seq = seqRefIds.get(seqId);
6184 throw new IllegalStateException(
6185 "Unmatched seqref for PCA: " + seqId);
6187 Point pt = new Point(sp.getXPos(), sp.getYPos(), sp.getZPos());
6188 jalview.datamodel.SequencePoint seqPoint = new jalview.datamodel.SequencePoint(
6190 seqPoints.add(seqPoint);
6192 panel.getRotatableCanvas().setPoints(seqPoints, seqPoints.size());
6195 * set min-max ranges and scale after setPoints (which recomputes them)
6197 panel.getRotatableCanvas().setScaleFactor(viewer.getScaleFactor());
6198 SeqPointMin spMin = viewer.getSeqPointMin();
6199 float[] min = new float[] { spMin.getXPos(), spMin.getYPos(),
6201 SeqPointMax spMax = viewer.getSeqPointMax();
6202 float[] max = new float[] { spMax.getXPos(), spMax.getYPos(),
6204 panel.getRotatableCanvas().setSeqMinMax(min, max);
6206 // todo: hold points list in PCAModel only
6207 panel.getPcaModel().setSequencePoints(seqPoints);
6209 panel.setSelectedDimensionIndex(viewer.getXDim(), X);
6210 panel.setSelectedDimensionIndex(viewer.getYDim(), Y);
6211 panel.setSelectedDimensionIndex(viewer.getZDim(), Z);
6213 // is this duplication needed?
6214 panel.setTop(seqPoints.size() - 1);
6215 panel.getPcaModel().setTop(seqPoints.size() - 1);
6218 * add the axes' end points for the display
6220 for (int i = 0; i < 3; i++)
6222 Axis axis = viewer.getAxis().get(i);
6223 panel.getRotatableCanvas().getAxisEndPoints()[i] = new Point(
6224 axis.getXPos(), axis.getYPos(), axis.getZPos());
6227 Desktop.addInternalFrame(panel, MessageManager.formatMessage(
6228 "label.calc_title", "PCA", modelName), 475, 450);
6230 } catch (Exception ex)
6232 Console.error("Error loading PCA: " + ex.toString());
6237 * Creates a new structure viewer window
6244 protected void createStructureViewer(ViewerType viewerType,
6245 final Entry<String, StructureViewerModel> viewerData,
6246 AlignFrame af, jarInputStreamProvider jprovider)
6248 final StructureViewerModel viewerModel = viewerData.getValue();
6249 String sessionFilePath = null;
6251 if (viewerType == ViewerType.JMOL)
6253 sessionFilePath = rewriteJmolSession(viewerModel, jprovider);
6257 String viewerJarEntryName = getViewerJarEntryName(
6258 viewerModel.getViewId());
6259 sessionFilePath = copyJarEntry(jprovider, viewerJarEntryName,
6260 "viewerSession", ".tmp");
6262 final String sessionPath = sessionFilePath;
6263 final String sviewid = viewerData.getKey();
6266 SwingUtilities.invokeAndWait(new Runnable()
6271 JalviewStructureDisplayI sview = null;
6274 sview = StructureViewer.createView(viewerType, af.alignPanel,
6275 viewerModel, sessionPath, sviewid);
6276 addNewStructureViewer(sview);
6277 } catch (OutOfMemoryError ex)
6279 new OOMWarning("Restoring structure view for " + viewerType,
6280 (OutOfMemoryError) ex.getCause());
6281 if (sview != null && sview.isVisible())
6283 sview.closeViewer(false);
6284 sview.setVisible(false);
6290 } catch (InvocationTargetException | InterruptedException ex)
6292 Console.warn("Unexpected error when opening " + viewerType
6293 + " structure viewer", ex);
6298 * Rewrites a Jmol session script, saves it to a temporary file, and returns
6299 * the path of the file. "load file" commands are rewritten to change the
6300 * original PDB file names to those created as the Jalview project is loaded.
6306 private String rewriteJmolSession(StructureViewerModel svattrib,
6307 jarInputStreamProvider jprovider)
6309 String state = svattrib.getStateData(); // Jalview < 2.9
6310 if (state == null || state.isEmpty()) // Jalview >= 2.9
6312 String jarEntryName = getViewerJarEntryName(svattrib.getViewId());
6313 state = readJarEntry(jprovider, jarEntryName);
6315 // TODO or simpler? for each key in oldFiles,
6316 // replace key.getPath() in state with oldFiles.get(key).getFilePath()
6317 // (allowing for different path escapings)
6318 StringBuilder rewritten = new StringBuilder(state.length());
6319 int cp = 0, ncp, ecp;
6320 Map<File, StructureData> oldFiles = svattrib.getFileData();
6321 while ((ncp = state.indexOf("load ", cp)) > -1)
6325 // look for next filename in load statement
6326 rewritten.append(state.substring(cp,
6327 ncp = (state.indexOf("\"", ncp + 1) + 1)));
6328 String oldfilenam = state.substring(ncp,
6329 ecp = state.indexOf("\"", ncp));
6330 // recover the new mapping data for this old filename
6331 // have to normalize filename - since Jmol and jalview do
6332 // filename translation differently.
6333 StructureData filedat = oldFiles.get(new File(oldfilenam));
6334 if (filedat == null)
6336 String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
6337 filedat = oldFiles.get(new File(reformatedOldFilename));
6339 rewritten.append(Platform.escapeBackslashes(filedat.getFilePath()));
6340 rewritten.append("\"");
6341 cp = ecp + 1; // advance beyond last \" and set cursor so we can
6342 // look for next file statement.
6343 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
6347 // just append rest of state
6348 rewritten.append(state.substring(cp));
6352 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
6353 rewritten = new StringBuilder(state);
6354 rewritten.append("; load append ");
6355 for (File id : oldFiles.keySet())
6357 // add pdb files that should be present in the viewer
6358 StructureData filedat = oldFiles.get(id);
6359 rewritten.append(" \"").append(filedat.getFilePath()).append("\"");
6361 rewritten.append(";");
6364 if (rewritten.length() == 0)
6368 final String history = "history = ";
6369 int historyIndex = rewritten.indexOf(history);
6370 if (historyIndex > -1)
6373 * change "history = [true|false];" to "history = [1|0];"
6375 historyIndex += history.length();
6376 String val = rewritten.substring(historyIndex, historyIndex + 5);
6377 if (val.startsWith("true"))
6379 rewritten.replace(historyIndex, historyIndex + 4, "1");
6381 else if (val.startsWith("false"))
6383 rewritten.replace(historyIndex, historyIndex + 5, "0");
6389 File tmp = File.createTempFile("viewerSession", ".tmp");
6390 try (OutputStream os = new FileOutputStream(tmp))
6392 InputStream is = new ByteArrayInputStream(
6393 rewritten.toString().getBytes());
6395 return tmp.getAbsolutePath();
6397 } catch (IOException e)
6399 Console.error("Error restoring Jmol session: " + e.toString());
6405 * Populates an XML model of the feature colour scheme for one feature type
6407 * @param featureType
6411 public static Colour marshalColour(String featureType,
6412 FeatureColourI fcol)
6414 Colour col = new Colour();
6415 if (fcol.isSimpleColour())
6417 col.setRGB(Format.getHexString(fcol.getColour()));
6421 col.setRGB(Format.getHexString(fcol.getMaxColour()));
6422 col.setMin(fcol.getMin());
6423 col.setMax(fcol.getMax());
6424 col.setMinRGB(jalview.util.Format.getHexString(fcol.getMinColour()));
6425 col.setAutoScale(fcol.isAutoScaled());
6426 col.setThreshold(fcol.getThreshold());
6427 col.setColourByLabel(fcol.isColourByLabel());
6428 col.setThreshType(fcol.isAboveThreshold() ? ThresholdType.ABOVE
6429 : (fcol.isBelowThreshold() ? ThresholdType.BELOW
6430 : ThresholdType.NONE));
6431 if (fcol.isColourByAttribute())
6433 final String[] attName = fcol.getAttributeName();
6434 col.getAttributeName().add(attName[0]);
6435 if (attName.length > 1)
6437 col.getAttributeName().add(attName[1]);
6440 Color noColour = fcol.getNoColour();
6441 if (noColour == null)
6443 col.setNoValueColour(NoValueColour.NONE);
6445 else if (noColour == fcol.getMaxColour())
6447 col.setNoValueColour(NoValueColour.MAX);
6451 col.setNoValueColour(NoValueColour.MIN);
6454 col.setName(featureType);
6459 * Populates an XML model of the feature filter(s) for one feature type
6461 * @param firstMatcher
6462 * the first (or only) match condition)
6464 * remaining match conditions (if any)
6466 * if true, conditions are and-ed, else or-ed
6468 public static jalview.xml.binding.jalview.FeatureMatcherSet marshalFilter(
6469 FeatureMatcherI firstMatcher, Iterator<FeatureMatcherI> filters,
6472 jalview.xml.binding.jalview.FeatureMatcherSet result = new jalview.xml.binding.jalview.FeatureMatcherSet();
6474 if (filters.hasNext())
6479 CompoundMatcher compound = new CompoundMatcher();
6480 compound.setAnd(and);
6481 jalview.xml.binding.jalview.FeatureMatcherSet matcher1 = marshalFilter(
6482 firstMatcher, Collections.emptyIterator(), and);
6483 // compound.addMatcherSet(matcher1);
6484 compound.getMatcherSet().add(matcher1);
6485 FeatureMatcherI nextMatcher = filters.next();
6486 jalview.xml.binding.jalview.FeatureMatcherSet matcher2 = marshalFilter(
6487 nextMatcher, filters, and);
6488 // compound.addMatcherSet(matcher2);
6489 compound.getMatcherSet().add(matcher2);
6490 result.setCompoundMatcher(compound);
6495 * single condition matcher
6497 // MatchCondition matcherModel = new MatchCondition();
6498 jalview.xml.binding.jalview.FeatureMatcher matcherModel = new jalview.xml.binding.jalview.FeatureMatcher();
6499 matcherModel.setCondition(
6500 firstMatcher.getMatcher().getCondition().getStableName());
6501 matcherModel.setValue(firstMatcher.getMatcher().getPattern());
6502 if (firstMatcher.isByAttribute())
6504 matcherModel.setBy(FilterBy.BY_ATTRIBUTE);
6505 // matcherModel.setAttributeName(firstMatcher.getAttribute());
6506 String[] attName = firstMatcher.getAttribute();
6507 matcherModel.getAttributeName().add(attName[0]); // attribute
6508 if (attName.length > 1)
6510 matcherModel.getAttributeName().add(attName[1]); // sub-attribute
6513 else if (firstMatcher.isByLabel())
6515 matcherModel.setBy(FilterBy.BY_LABEL);
6517 else if (firstMatcher.isByScore())
6519 matcherModel.setBy(FilterBy.BY_SCORE);
6521 result.setMatchCondition(matcherModel);
6528 * Loads one XML model of a feature filter to a Jalview object
6530 * @param featureType
6531 * @param matcherSetModel
6534 public static FeatureMatcherSetI parseFilter(String featureType,
6535 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel)
6537 FeatureMatcherSetI result = new FeatureMatcherSet();
6540 parseFilterConditions(result, matcherSetModel, true);
6541 } catch (IllegalStateException e)
6543 // mixing AND and OR conditions perhaps
6545 String.format("Error reading filter conditions for '%s': %s",
6546 featureType, e.getMessage()));
6547 // return as much as was parsed up to the error
6554 * Adds feature match conditions to matcherSet as unmarshalled from XML
6555 * (possibly recursively for compound conditions)
6558 * @param matcherSetModel
6560 * if true, multiple conditions are AND-ed, else they are OR-ed
6561 * @throws IllegalStateException
6562 * if AND and OR conditions are mixed
6564 protected static void parseFilterConditions(FeatureMatcherSetI matcherSet,
6565 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel,
6568 jalview.xml.binding.jalview.FeatureMatcher mc = matcherSetModel
6569 .getMatchCondition();
6575 FilterBy filterBy = mc.getBy();
6576 Condition cond = Condition.fromString(mc.getCondition());
6577 String pattern = mc.getValue();
6578 FeatureMatcherI matchCondition = null;
6579 if (filterBy == FilterBy.BY_LABEL)
6581 matchCondition = FeatureMatcher.byLabel(cond, pattern);
6583 else if (filterBy == FilterBy.BY_SCORE)
6585 matchCondition = FeatureMatcher.byScore(cond, pattern);
6588 else if (filterBy == FilterBy.BY_ATTRIBUTE)
6590 final List<String> attributeName = mc.getAttributeName();
6591 String[] attNames = attributeName
6592 .toArray(new String[attributeName.size()]);
6593 matchCondition = FeatureMatcher.byAttribute(cond, pattern,
6598 * note this throws IllegalStateException if AND-ing to a
6599 * previously OR-ed compound condition, or vice versa
6603 matcherSet.and(matchCondition);
6607 matcherSet.or(matchCondition);
6613 * compound condition
6615 List<jalview.xml.binding.jalview.FeatureMatcherSet> matchers = matcherSetModel
6616 .getCompoundMatcher().getMatcherSet();
6617 boolean anded = matcherSetModel.getCompoundMatcher().isAnd();
6618 if (matchers.size() == 2)
6620 parseFilterConditions(matcherSet, matchers.get(0), anded);
6621 parseFilterConditions(matcherSet, matchers.get(1), anded);
6625 System.err.println("Malformed compound filter condition");
6631 * Loads one XML model of a feature colour to a Jalview object
6633 * @param colourModel
6636 public static FeatureColourI parseColour(Colour colourModel)
6638 FeatureColourI colour = null;
6640 if (colourModel.getMax() != null)
6642 Color mincol = null;
6643 Color maxcol = null;
6644 Color noValueColour = null;
6648 mincol = new Color(Integer.parseInt(colourModel.getMinRGB(), 16));
6649 maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6650 } catch (Exception e)
6652 Console.warn("Couldn't parse out graduated feature color.", e);
6655 NoValueColour noCol = colourModel.getNoValueColour();
6656 if (noCol == NoValueColour.MIN)
6658 noValueColour = mincol;
6660 else if (noCol == NoValueColour.MAX)
6662 noValueColour = maxcol;
6665 colour = new FeatureColour(maxcol, mincol, maxcol, noValueColour,
6666 safeFloat(colourModel.getMin()),
6667 safeFloat(colourModel.getMax()));
6668 final List<String> attributeName = colourModel.getAttributeName();
6669 String[] attributes = attributeName
6670 .toArray(new String[attributeName.size()]);
6671 if (attributes != null && attributes.length > 0)
6673 colour.setAttributeName(attributes);
6675 if (colourModel.isAutoScale() != null)
6677 colour.setAutoScaled(colourModel.isAutoScale().booleanValue());
6679 if (colourModel.isColourByLabel() != null)
6681 colour.setColourByLabel(
6682 colourModel.isColourByLabel().booleanValue());
6684 if (colourModel.getThreshold() != null)
6686 colour.setThreshold(colourModel.getThreshold().floatValue());
6688 ThresholdType ttyp = colourModel.getThreshType();
6689 if (ttyp == ThresholdType.ABOVE)
6691 colour.setAboveThreshold(true);
6693 else if (ttyp == ThresholdType.BELOW)
6695 colour.setBelowThreshold(true);
6700 Color color = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6701 colour = new FeatureColour(color);
6707 public static void setStateSavedUpToDate(boolean s)
6709 Console.debug("Setting overall stateSavedUpToDate to " + s);
6710 stateSavedUpToDate = s;
6713 public static boolean stateSavedUpToDate()
6715 Console.debug("Returning overall stateSavedUpToDate value: "
6716 + stateSavedUpToDate);
6717 return stateSavedUpToDate;
6720 public static boolean allSavedUpToDate()
6722 if (stateSavedUpToDate()) // nothing happened since last project save
6725 AlignFrame[] frames = Desktop.getAlignFrames();
6728 for (int i = 0; i < frames.length; i++)
6730 if (frames[i] == null)
6732 if (!frames[i].getViewport().savedUpToDate())
6733 return false; // at least one alignment is not individually saved
6739 // used for debugging and tests
6740 private static int debugDelaySave = 20;
6742 public static void setDebugDelaySave(int n)