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.BitSet;
48 import java.util.Collections;
49 import java.util.Enumeration;
50 import java.util.GregorianCalendar;
51 import java.util.HashMap;
52 import java.util.HashSet;
53 import java.util.Hashtable;
54 import java.util.IdentityHashMap;
55 import java.util.Iterator;
56 import java.util.LinkedHashMap;
57 import java.util.List;
58 import java.util.Locale;
60 import java.util.Map.Entry;
62 import java.util.Vector;
63 import java.util.jar.JarEntry;
64 import java.util.jar.JarInputStream;
65 import java.util.jar.JarOutputStream;
67 import javax.swing.JInternalFrame;
68 import javax.swing.SwingUtilities;
69 import javax.xml.bind.JAXBContext;
70 import javax.xml.bind.JAXBElement;
71 import javax.xml.bind.Marshaller;
72 import javax.xml.datatype.DatatypeConfigurationException;
73 import javax.xml.datatype.DatatypeFactory;
74 import javax.xml.datatype.XMLGregorianCalendar;
75 import javax.xml.stream.XMLInputFactory;
76 import javax.xml.stream.XMLStreamReader;
78 import jalview.analysis.Conservation;
79 import jalview.analysis.PCA;
80 import jalview.analysis.scoremodels.ScoreModels;
81 import jalview.analysis.scoremodels.SimilarityParams;
82 import jalview.api.FeatureColourI;
83 import jalview.api.ViewStyleI;
84 import jalview.api.analysis.ScoreModelI;
85 import jalview.api.analysis.SimilarityParamsI;
86 import jalview.api.structures.JalviewStructureDisplayI;
87 import jalview.bin.Cache;
88 import jalview.bin.Console;
89 import jalview.bin.Jalview;
90 import jalview.datamodel.AlignedCodonFrame;
91 import jalview.datamodel.Alignment;
92 import jalview.datamodel.AlignmentAnnotation;
93 import jalview.datamodel.AlignmentI;
94 import jalview.datamodel.ContactMatrix;
95 import jalview.datamodel.ContactMatrixI;
96 import jalview.datamodel.DBRefEntry;
97 import jalview.datamodel.GeneLocus;
98 import jalview.datamodel.GraphLine;
99 import jalview.datamodel.GroupSet;
100 import jalview.datamodel.PDBEntry;
101 import jalview.datamodel.Point;
102 import jalview.datamodel.RnaViewerModel;
103 import jalview.datamodel.SequenceFeature;
104 import jalview.datamodel.SequenceGroup;
105 import jalview.datamodel.SequenceI;
106 import jalview.datamodel.StructureViewerModel;
107 import jalview.datamodel.StructureViewerModel.StructureData;
108 import jalview.datamodel.features.FeatureMatcher;
109 import jalview.datamodel.features.FeatureMatcherI;
110 import jalview.datamodel.features.FeatureMatcherSet;
111 import jalview.datamodel.features.FeatureMatcherSetI;
112 import jalview.ext.varna.RnaModel;
113 import jalview.gui.AlignFrame;
114 import jalview.gui.AlignViewport;
115 import jalview.gui.AlignmentPanel;
116 import jalview.gui.AppVarna;
117 import jalview.gui.Desktop;
118 import jalview.gui.JvOptionPane;
119 import jalview.gui.OOMWarning;
120 import jalview.gui.OverviewPanel;
121 import jalview.gui.PCAPanel;
122 import jalview.gui.PaintRefresher;
123 import jalview.gui.SplitFrame;
124 import jalview.gui.StructureViewer;
125 import jalview.gui.StructureViewer.ViewerType;
126 import jalview.gui.StructureViewerBase;
127 import jalview.gui.TreePanel;
128 import jalview.io.BackupFiles;
129 import jalview.io.DataSourceType;
130 import jalview.io.FileFormat;
131 import jalview.io.NewickFile;
132 import jalview.math.Matrix;
133 import jalview.math.MatrixI;
134 import jalview.renderer.ResidueShaderI;
135 import jalview.schemes.AnnotationColourGradient;
136 import jalview.schemes.ColourSchemeI;
137 import jalview.schemes.ColourSchemeProperty;
138 import jalview.schemes.FeatureColour;
139 import jalview.schemes.ResidueProperties;
140 import jalview.schemes.UserColourScheme;
141 import jalview.structure.StructureSelectionManager;
142 import jalview.structures.models.AAStructureBindingModel;
143 import jalview.util.Format;
144 import jalview.util.HttpUtils;
145 import jalview.util.MessageManager;
146 import jalview.util.Platform;
147 import jalview.util.StringUtils;
148 import jalview.util.jarInputStreamProvider;
149 import jalview.util.matcher.Condition;
150 import jalview.viewmodel.AlignmentViewport;
151 import jalview.viewmodel.PCAModel;
152 import jalview.viewmodel.ViewportRanges;
153 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
154 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
155 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
156 import jalview.ws.datamodel.MappableContactMatrixI;
157 import jalview.ws.datamodel.alphafold.PAEContactMatrix;
158 import jalview.ws.jws2.Jws2Discoverer;
159 import jalview.ws.jws2.dm.AAConSettings;
160 import jalview.ws.jws2.jabaws2.Jws2Instance;
161 import jalview.ws.params.ArgumentI;
162 import jalview.ws.params.AutoCalcSetting;
163 import jalview.ws.params.WsParamSetI;
164 import jalview.xml.binding.jalview.AlcodonFrame;
165 import jalview.xml.binding.jalview.AlcodonFrame.AlcodMap;
166 import jalview.xml.binding.jalview.Annotation;
167 import jalview.xml.binding.jalview.Annotation.ThresholdLine;
168 import jalview.xml.binding.jalview.AnnotationColourScheme;
169 import jalview.xml.binding.jalview.AnnotationElement;
170 import jalview.xml.binding.jalview.DoubleMatrix;
171 import jalview.xml.binding.jalview.DoubleVector;
172 import jalview.xml.binding.jalview.Feature;
173 import jalview.xml.binding.jalview.Feature.OtherData;
174 import jalview.xml.binding.jalview.FeatureMatcherSet.CompoundMatcher;
175 import jalview.xml.binding.jalview.FilterBy;
176 import jalview.xml.binding.jalview.JalviewModel;
177 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings;
178 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Group;
179 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Setting;
180 import jalview.xml.binding.jalview.JalviewModel.JGroup;
181 import jalview.xml.binding.jalview.JalviewModel.JSeq;
182 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids;
183 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids.StructureState;
184 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer;
185 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer.SecondaryStructure;
186 import jalview.xml.binding.jalview.JalviewModel.PcaViewer;
187 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.Axis;
188 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SeqPointMax;
189 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SeqPointMin;
190 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SequencePoint;
191 import jalview.xml.binding.jalview.JalviewModel.Tree;
192 import jalview.xml.binding.jalview.JalviewModel.UserColours;
193 import jalview.xml.binding.jalview.JalviewModel.Viewport;
194 import jalview.xml.binding.jalview.JalviewModel.Viewport.CalcIdParam;
195 import jalview.xml.binding.jalview.JalviewModel.Viewport.HiddenColumns;
196 import jalview.xml.binding.jalview.JalviewModel.Viewport.Overview;
197 import jalview.xml.binding.jalview.JalviewUserColours;
198 import jalview.xml.binding.jalview.JalviewUserColours.Colour;
199 import jalview.xml.binding.jalview.MapListType;
200 import jalview.xml.binding.jalview.MapListType.MapListFrom;
201 import jalview.xml.binding.jalview.MapListType.MapListTo;
202 import jalview.xml.binding.jalview.Mapping;
203 import jalview.xml.binding.jalview.MatrixType;
204 import jalview.xml.binding.jalview.NoValueColour;
205 import jalview.xml.binding.jalview.ObjectFactory;
206 import jalview.xml.binding.jalview.PcaDataType;
207 import jalview.xml.binding.jalview.Pdbentry.Property;
208 import jalview.xml.binding.jalview.Sequence;
209 import jalview.xml.binding.jalview.Sequence.DBRef;
210 import jalview.xml.binding.jalview.SequenceSet;
211 import jalview.xml.binding.jalview.SequenceSet.SequenceSetProperties;
212 import jalview.xml.binding.jalview.ThresholdType;
213 import jalview.xml.binding.jalview.VAMSAS;
216 * Write out the current jalview desktop state as a Jalview XML stream.
218 * Note: the vamsas objects referred to here are primitive versions of the
219 * VAMSAS project schema elements - they are not the same and most likely never
223 * @version $Revision: 1.134 $
225 public class Jalview2XML
228 // BH 2018 we add the .jvp binary extension to J2S so that
229 // it will declare that binary when we do the file save from the browser
233 Platform.addJ2SBinaryType(".jvp?");
236 private static final String VIEWER_PREFIX = "viewer_";
238 private static final String RNA_PREFIX = "rna_";
240 private static final String UTF_8 = "UTF-8";
243 * used in decision if quit confirmation should be issued
245 private static boolean stateSavedUpToDate = false;
248 * prefix for recovering datasets for alignments with multiple views where
249 * non-existent dataset IDs were written for some views
251 private static final String UNIQSEQSETID = "uniqueSeqSetId.";
253 // use this with nextCounter() to make unique names for entities
254 private int counter = 0;
257 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
258 * of sequence objects are created.
260 IdentityHashMap<SequenceI, String> seqsToIds = null;
263 * jalview XML Sequence ID to jalview sequence object reference (both dataset
264 * and alignment sequences. Populated as XML reps of sequence objects are
267 Map<String, SequenceI> seqRefIds = null;
269 Map<String, SequenceI> incompleteSeqs = null;
271 List<SeqFref> frefedSequence = null;
273 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
276 * Map of reconstructed AlignFrame objects that appear to have come from
277 * SplitFrame objects (have a dna/protein complement view).
279 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
282 * Map from displayed rna structure models to their saved session state jar
285 private Map<RnaModel, String> rnaSessions = new HashMap<>();
288 * A helper method for safely using the value of an optional attribute that
289 * may be null if not present in the XML. Answers the boolean value, or false
295 public static boolean safeBoolean(Boolean b)
297 return b == null ? false : b.booleanValue();
301 * A helper method for safely using the value of an optional attribute that
302 * may be null if not present in the XML. Answers the integer value, or zero
308 public static int safeInt(Integer i)
310 return i == null ? 0 : i.intValue();
314 * A helper method for safely using the value of an optional attribute that
315 * may be null if not present in the XML. Answers the float value, or zero if
321 public static float safeFloat(Float f)
323 return f == null ? 0f : f.floatValue();
327 * create/return unique hash string for sq
330 * @return new or existing unique string for sq
332 String seqHash(SequenceI sq)
334 if (seqsToIds == null)
338 if (seqsToIds.containsKey(sq))
340 return seqsToIds.get(sq);
344 // create sequential key
345 String key = "sq" + (seqsToIds.size() + 1);
346 key = makeHashCode(sq, key); // check we don't have an external reference
348 seqsToIds.put(sq, key);
355 if (seqsToIds == null)
357 seqsToIds = new IdentityHashMap<>();
359 if (seqRefIds == null)
361 seqRefIds = new HashMap<>();
363 if (incompleteSeqs == null)
365 incompleteSeqs = new HashMap<>();
367 if (frefedSequence == null)
369 frefedSequence = new ArrayList<>();
377 public Jalview2XML(boolean raiseGUI)
379 this.raiseGUI = raiseGUI;
383 * base class for resolving forward references to sequences by their ID
388 abstract class SeqFref
394 public SeqFref(String _sref, String type)
400 public String getSref()
405 public SequenceI getSrefSeq()
407 return seqRefIds.get(sref);
410 public boolean isResolvable()
412 return seqRefIds.get(sref) != null;
415 public SequenceI getSrefDatasetSeq()
417 SequenceI sq = seqRefIds.get(sref);
420 while (sq.getDatasetSequence() != null)
422 sq = sq.getDatasetSequence();
429 * @return true if the forward reference was fully resolved
431 abstract boolean resolve();
434 public String toString()
436 return type + " reference to " + sref;
441 * create forward reference for a mapping
447 public SeqFref newMappingRef(final String sref,
448 final jalview.datamodel.Mapping _jmap)
450 SeqFref fref = new SeqFref(sref, "Mapping")
452 public jalview.datamodel.Mapping jmap = _jmap;
457 SequenceI seq = getSrefDatasetSeq();
469 public SeqFref newAlcodMapRef(final String sref,
470 final AlignedCodonFrame _cf,
471 final jalview.datamodel.Mapping _jmap)
474 SeqFref fref = new SeqFref(sref, "Codon Frame")
476 AlignedCodonFrame cf = _cf;
478 public jalview.datamodel.Mapping mp = _jmap;
481 public boolean isResolvable()
483 return super.isResolvable() && mp.getTo() != null;
489 SequenceI seq = getSrefDatasetSeq();
494 cf.addMap(seq, mp.getTo(), mp.getMap());
501 public void resolveFrefedSequences()
503 Iterator<SeqFref> nextFref = frefedSequence.iterator();
504 int toresolve = frefedSequence.size();
505 int unresolved = 0, failedtoresolve = 0;
506 while (nextFref.hasNext())
508 SeqFref ref = nextFref.next();
509 if (ref.isResolvable())
521 } catch (Exception x)
523 jalview.bin.Console.errPrintln(
524 "IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
537 jalview.bin.Console.errPrintln("Jalview Project Import: There were "
539 + " forward references left unresolved on the stack.");
541 if (failedtoresolve > 0)
543 jalview.bin.Console.errPrintln("SERIOUS! " + failedtoresolve
544 + " resolvable forward references failed to resolve.");
546 if (incompleteSeqs != null && incompleteSeqs.size() > 0)
548 jalview.bin.Console.errPrintln(
549 "Jalview Project Import: There are " + incompleteSeqs.size()
550 + " sequences which may have incomplete metadata.");
551 if (incompleteSeqs.size() < 10)
553 for (SequenceI s : incompleteSeqs.values())
555 jalview.bin.Console.errPrintln(s.toString());
560 jalview.bin.Console.errPrintln(
561 "Too many to report. Skipping output of incomplete sequences.");
567 * This maintains a map of viewports, the key being the seqSetId. Important to
568 * set historyItem and redoList for multiple views
570 Map<String, AlignViewport> viewportsAdded = new HashMap<>();
572 Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
574 String uniqueSetSuffix = "";
577 * List of pdbfiles added to Jar
579 List<String> pdbfiles = null;
581 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
582 public void saveState(File statefile)
584 FileOutputStream fos = null;
589 fos = new FileOutputStream(statefile);
591 JarOutputStream jout = new JarOutputStream(fos);
595 } catch (Exception e)
597 Console.error("Couln't write Jalview state to " + statefile, e);
598 // TODO: inform user of the problem - they need to know if their data was
600 if (errorMessage == null)
602 errorMessage = "Did't write Jalview Archive to output file '"
603 + statefile + "' - See console error log for details";
607 errorMessage += "(Didn't write Jalview Archive to output file '"
618 } catch (IOException e)
628 * Writes a jalview project archive to the given Jar output stream.
632 public void saveState(JarOutputStream jout)
634 AlignFrame[] frames = Desktop.getAlignFrames();
636 setStateSavedUpToDate(true);
638 if (Cache.getDefault("DEBUG_DELAY_SAVE", false))
640 int n = debugDelaySave;
644 Console.debug("***** debugging save sleep " + i + "/" + n);
648 } catch (InterruptedException e)
650 // TODO Auto-generated catch block
661 saveAllFrames(Arrays.asList(frames), jout);
665 * core method for storing state for a set of AlignFrames.
668 * - frames involving all data to be exported (including containing
671 * - project output stream
673 private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
675 Hashtable<String, AlignFrame> dsses = new Hashtable<>();
678 * ensure cached data is clear before starting
680 // todo tidy up seqRefIds, seqsToIds initialisation / reset
682 splitFrameCandidates.clear();
687 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
688 // //////////////////////////////////////////////////
690 List<String> shortNames = new ArrayList<>();
691 List<String> viewIds = new ArrayList<>();
694 for (int i = frames.size() - 1; i > -1; i--)
696 AlignFrame af = frames.get(i);
698 if (skipList != null && skipList
699 .containsKey(af.getViewport().getSequenceSetId()))
704 String shortName = makeFilename(af, shortNames);
706 int apSize = af.getAlignPanels().size();
708 for (int ap = 0; ap < apSize; ap++)
710 AlignmentPanel apanel = (AlignmentPanel) af.getAlignPanels()
712 String fileName = apSize == 1 ? shortName : ap + shortName;
713 if (!fileName.endsWith(".xml"))
715 fileName = fileName + ".xml";
718 saveState(apanel, fileName, jout, viewIds);
720 String dssid = getDatasetIdRef(
721 af.getViewport().getAlignment().getDataset());
722 if (!dsses.containsKey(dssid))
724 dsses.put(dssid, af);
729 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
735 } catch (Exception foo)
739 } catch (Exception ex)
741 // TODO: inform user of the problem - they need to know if their data was
743 if (errorMessage == null)
745 errorMessage = "Couldn't write Jalview Archive - see error output for details";
747 ex.printStackTrace();
752 * Generates a distinct file name, based on the title of the AlignFrame, by
753 * appending _n for increasing n until an unused name is generated. The new
754 * name (without its extension) is added to the list.
758 * @return the generated name, with .xml extension
760 protected String makeFilename(AlignFrame af, List<String> namesUsed)
762 String shortName = af.getTitle();
764 if (shortName.indexOf(File.separatorChar) > -1)
766 shortName = shortName
767 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
772 while (namesUsed.contains(shortName))
774 if (shortName.endsWith("_" + (count - 1)))
776 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
779 shortName = shortName.concat("_" + count);
783 namesUsed.add(shortName);
785 if (!shortName.endsWith(".xml"))
787 shortName = shortName + ".xml";
792 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
793 public boolean saveAlignment(AlignFrame af, String jarFile,
798 // create backupfiles object and get new temp filename destination
799 boolean doBackup = BackupFiles.getEnabled();
800 BackupFiles backupfiles = doBackup ? new BackupFiles(jarFile) : null;
801 FileOutputStream fos = new FileOutputStream(
802 doBackup ? backupfiles.getTempFilePath() : jarFile);
804 if (Cache.getDefault("DEBUG_DELAY_SAVE", false))
806 int n = debugDelaySave;
810 Console.debug("***** debugging save sleep " + i + "/" + n);
814 } catch (InterruptedException e)
816 // TODO Auto-generated catch block
823 JarOutputStream jout = new JarOutputStream(fos);
824 List<AlignFrame> frames = new ArrayList<>();
826 // resolve splitframes
827 if (af.getViewport().getCodingComplement() != null)
829 frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
835 saveAllFrames(frames, jout);
839 } catch (Exception foo)
843 boolean success = true;
847 backupfiles.setWriteSuccess(success);
848 success = backupfiles.rollBackupsAndRenameTempFile();
852 } catch (Exception ex)
854 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
855 ex.printStackTrace();
860 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
861 String fileName, JarOutputStream jout)
864 for (String dssids : dsses.keySet())
866 AlignFrame _af = dsses.get(dssids);
867 String jfileName = fileName + " Dataset for " + _af.getTitle();
868 if (!jfileName.endsWith(".xml"))
870 jfileName = jfileName + ".xml";
872 saveState(_af.alignPanel, jfileName, true, jout, null);
877 * create a JalviewModel from an alignment view and marshall it to a
881 * panel to create jalview model for
883 * name of alignment panel written to output stream
890 public JalviewModel saveState(AlignmentPanel ap, String fileName,
891 JarOutputStream jout, List<String> viewIds)
893 return saveState(ap, fileName, false, jout, viewIds);
897 * create a JalviewModel from an alignment view and marshall it to a
901 * panel to create jalview model for
903 * name of alignment panel written to output stream
905 * when true, only write the dataset for the alignment, not the data
906 * associated with the view.
912 public JalviewModel saveState(AlignmentPanel ap, String fileName,
913 boolean storeDS, JarOutputStream jout, List<String> viewIds)
917 viewIds = new ArrayList<>();
922 List<UserColourScheme> userColours = new ArrayList<>();
924 AlignViewport av = ap.av;
925 ViewportRanges vpRanges = av.getRanges();
927 final ObjectFactory objectFactory = new ObjectFactory();
928 JalviewModel object = objectFactory.createJalviewModel();
929 object.setVamsasModel(new VAMSAS());
931 // object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
934 GregorianCalendar c = new GregorianCalendar();
935 DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
936 XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(c);// gregorianCalendar);
937 object.setCreationDate(now);
938 } catch (DatatypeConfigurationException e)
940 jalview.bin.Console.errPrintln("error writing date: " + e.toString());
942 object.setVersion(Cache.getDefault("VERSION", "Development Build"));
945 * rjal is full height alignment, jal is actual alignment with full metadata
946 * but excludes hidden sequences.
948 jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
950 if (av.hasHiddenRows())
952 rjal = jal.getHiddenSequences().getFullAlignment();
955 SequenceSet vamsasSet = new SequenceSet();
957 // JalviewModelSequence jms = new JalviewModelSequence();
959 vamsasSet.setGapChar(jal.getGapCharacter() + "");
961 if (jal.getDataset() != null)
963 // dataset id is the dataset's hashcode
964 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
967 // switch jal and the dataset
968 jal = jal.getDataset();
972 if (jal.getProperties() != null)
974 Enumeration en = jal.getProperties().keys();
975 while (en.hasMoreElements())
977 String key = en.nextElement().toString();
978 SequenceSetProperties ssp = new SequenceSetProperties();
980 ssp.setValue(jal.getProperties().get(key).toString());
981 // vamsasSet.addSequenceSetProperties(ssp);
982 vamsasSet.getSequenceSetProperties().add(ssp);
987 Set<String> calcIdSet = new HashSet<>();
988 // record the set of vamsas sequence XML POJO we create.
989 HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
991 for (final SequenceI jds : rjal.getSequences())
993 final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
994 : jds.getDatasetSequence();
995 String id = seqHash(jds);
996 if (vamsasSetIds.get(id) == null)
998 if (seqRefIds.get(id) != null && !storeDS)
1000 // This happens for two reasons: 1. multiple views are being
1002 // 2. the hashCode has collided with another sequence's code. This
1004 // HAPPEN! (PF00072.15.stk does this)
1005 // JBPNote: Uncomment to debug writing out of files that do not read
1006 // back in due to ArrayOutOfBoundExceptions.
1007 // jalview.bin.Console.errPrintln("vamsasSeq backref: "+id+"");
1008 // jalview.bin.Console.errPrintln(jds.getName()+"
1009 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
1010 // jalview.bin.Console.errPrintln("Hashcode: "+seqHash(jds));
1011 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
1012 // jalview.bin.Console.errPrintln(rsq.getName()+"
1013 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
1014 // jalview.bin.Console.errPrintln("Hashcode: "+seqHash(rsq));
1018 vamsasSeq = createVamsasSequence(id, jds);
1019 // vamsasSet.addSequence(vamsasSeq);
1020 vamsasSet.getSequence().add(vamsasSeq);
1021 vamsasSetIds.put(id, vamsasSeq);
1022 seqRefIds.put(id, jds);
1026 jseq.setStart(jds.getStart());
1027 jseq.setEnd(jds.getEnd());
1028 jseq.setColour(av.getSequenceColour(jds).getRGB());
1030 jseq.setId(id); // jseq id should be a string not a number
1033 // Store any sequences this sequence represents
1034 if (av.hasHiddenRows())
1036 // use rjal, contains the full height alignment
1038 av.getAlignment().getHiddenSequences().isHidden(jds));
1040 if (av.isHiddenRepSequence(jds))
1042 jalview.datamodel.SequenceI[] reps = av
1043 .getRepresentedSequences(jds).getSequencesInOrder(rjal);
1045 for (int h = 0; h < reps.length; h++)
1049 // jseq.addHiddenSequences(rjal.findIndex(reps[h]));
1050 jseq.getHiddenSequences().add(rjal.findIndex(reps[h]));
1055 // mark sequence as reference - if it is the reference for this view
1056 if (jal.hasSeqrep())
1058 jseq.setViewreference(jds == jal.getSeqrep());
1062 // TODO: omit sequence features from each alignment view's XML dump if we
1063 // are storing dataset
1064 List<SequenceFeature> sfs = jds.getSequenceFeatures();
1065 for (SequenceFeature sf : sfs)
1067 // Features features = new Features();
1068 Feature features = new Feature();
1070 features.setBegin(sf.getBegin());
1071 features.setEnd(sf.getEnd());
1072 features.setDescription(sf.getDescription());
1073 features.setType(sf.getType());
1074 features.setFeatureGroup(sf.getFeatureGroup());
1075 features.setScore(sf.getScore());
1076 if (sf.links != null)
1078 for (int l = 0; l < sf.links.size(); l++)
1080 OtherData keyValue = new OtherData();
1081 keyValue.setKey("LINK_" + l);
1082 keyValue.setValue(sf.links.elementAt(l).toString());
1083 // features.addOtherData(keyValue);
1084 features.getOtherData().add(keyValue);
1087 if (sf.otherDetails != null)
1090 * save feature attributes, which may be simple strings or
1091 * map valued (have sub-attributes)
1093 for (Entry<String, Object> entry : sf.otherDetails.entrySet())
1095 String key = entry.getKey();
1096 Object value = entry.getValue();
1097 if (value instanceof Map<?, ?>)
1099 for (Entry<String, Object> subAttribute : ((Map<String, Object>) value)
1102 OtherData otherData = new OtherData();
1103 otherData.setKey(key);
1104 otherData.setKey2(subAttribute.getKey());
1105 otherData.setValue(subAttribute.getValue().toString());
1106 // features.addOtherData(otherData);
1107 features.getOtherData().add(otherData);
1112 OtherData otherData = new OtherData();
1113 otherData.setKey(key);
1114 otherData.setValue(value.toString());
1115 // features.addOtherData(otherData);
1116 features.getOtherData().add(otherData);
1121 // jseq.addFeatures(features);
1122 jseq.getFeatures().add(features);
1125 if (jdatasq.getAllPDBEntries() != null)
1127 Enumeration<PDBEntry> en = jdatasq.getAllPDBEntries().elements();
1128 while (en.hasMoreElements())
1130 Pdbids pdb = new Pdbids();
1131 jalview.datamodel.PDBEntry entry = en.nextElement();
1133 String pdbId = entry.getId();
1135 pdb.setType(entry.getType());
1138 * Store any structure views associated with this sequence. This
1139 * section copes with duplicate entries in the project, so a dataset
1140 * only view *should* be coped with sensibly.
1142 // This must have been loaded, is it still visible?
1143 List<JalviewStructureDisplayI> viewFrames = new ArrayList<>();
1144 if (Desktop.desktop != null)
1146 JInternalFrame[] jifs = Desktop.desktop.getAllFrames();
1149 for (JInternalFrame jif : jifs)
1151 if (jif instanceof JalviewStructureDisplayI)
1153 viewFrames.add((JalviewStructureDisplayI) jif);
1158 else if (Jalview.isHeadlessMode()
1159 && Jalview.getInstance().getCommands() != null)
1162 StructureViewerBase.getAllStructureViewerBases());
1165 String matchedFile = null;
1166 for (JalviewStructureDisplayI viewFrame : viewFrames)
1168 matchedFile = saveStructureViewer(ap, jds, pdb, entry, viewIds,
1169 matchedFile, viewFrame);
1171 * Only store each structure viewer's state once in the project
1172 * jar. First time through only (storeDS==false)
1174 String viewId = viewFrame.getViewId();
1175 String viewerType = viewFrame.getViewerType().toString();
1176 if (!storeDS && !viewIds.contains(viewId))
1178 viewIds.add(viewId);
1179 File viewerState = viewFrame.saveSession();
1180 if (viewerState != null)
1182 copyFileToJar(jout, viewerState.getPath(),
1183 getViewerJarEntryName(viewId), viewerType);
1188 "Failed to save viewer state for " + viewerType);
1193 if (matchedFile != null || entry.getFile() != null)
1195 if (entry.getFile() != null)
1198 matchedFile = entry.getFile();
1200 pdb.setFile(matchedFile); // entry.getFile());
1201 if (pdbfiles == null)
1203 pdbfiles = new ArrayList<>();
1206 if (!pdbfiles.contains(pdbId))
1208 pdbfiles.add(pdbId);
1209 copyFileToJar(jout, matchedFile, pdbId, pdbId);
1213 Enumeration<String> props = entry.getProperties();
1214 if (props.hasMoreElements())
1216 // PdbentryItem item = new PdbentryItem();
1217 while (props.hasMoreElements())
1219 Property prop = new Property();
1220 String key = props.nextElement();
1222 prop.setValue(entry.getProperty(key).toString());
1223 // item.addProperty(prop);
1224 pdb.getProperty().add(prop);
1226 // pdb.addPdbentryItem(item);
1229 // jseq.addPdbids(pdb);
1230 jseq.getPdbids().add(pdb);
1234 saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
1236 // jms.addJSeq(jseq);
1237 object.getJSeq().add(jseq);
1240 if (!storeDS && av.hasHiddenRows())
1242 jal = av.getAlignment();
1246 if (storeDS && jal.getCodonFrames() != null)
1248 List<AlignedCodonFrame> jac = jal.getCodonFrames();
1249 for (AlignedCodonFrame acf : jac)
1251 AlcodonFrame alc = new AlcodonFrame();
1252 if (acf.getProtMappings() != null
1253 && acf.getProtMappings().length > 0)
1255 boolean hasMap = false;
1256 SequenceI[] dnas = acf.getdnaSeqs();
1257 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1258 for (int m = 0; m < pmaps.length; m++)
1260 AlcodMap alcmap = new AlcodMap();
1261 alcmap.setDnasq(seqHash(dnas[m]));
1263 createVamsasMapping(pmaps[m], dnas[m], null, false));
1264 // alc.addAlcodMap(alcmap);
1265 alc.getAlcodMap().add(alcmap);
1270 // vamsasSet.addAlcodonFrame(alc);
1271 vamsasSet.getAlcodonFrame().add(alc);
1274 // TODO: delete this ? dead code from 2.8.3->2.9 ?
1276 // AlcodonFrame alc = new AlcodonFrame();
1277 // vamsasSet.addAlcodonFrame(alc);
1278 // for (int p = 0; p < acf.aaWidth; p++)
1280 // Alcodon cmap = new Alcodon();
1281 // if (acf.codons[p] != null)
1283 // // Null codons indicate a gapped column in the translated peptide
1285 // cmap.setPos1(acf.codons[p][0]);
1286 // cmap.setPos2(acf.codons[p][1]);
1287 // cmap.setPos3(acf.codons[p][2]);
1289 // alc.addAlcodon(cmap);
1291 // if (acf.getProtMappings() != null
1292 // && acf.getProtMappings().length > 0)
1294 // SequenceI[] dnas = acf.getdnaSeqs();
1295 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1296 // for (int m = 0; m < pmaps.length; m++)
1298 // AlcodMap alcmap = new AlcodMap();
1299 // alcmap.setDnasq(seqHash(dnas[m]));
1300 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1302 // alc.addAlcodMap(alcmap);
1309 // /////////////////////////////////
1310 if (!storeDS && av.getCurrentTree() != null)
1312 // FIND ANY ASSOCIATED TREES
1313 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
1314 if (Desktop.desktop != null)
1316 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1318 for (int t = 0; t < frames.length; t++)
1320 if (frames[t] instanceof TreePanel)
1322 TreePanel tp = (TreePanel) frames[t];
1324 if (tp.getTreeCanvas().getViewport().getAlignment() == jal)
1326 JalviewModel.Tree tree = new JalviewModel.Tree();
1327 tree.setTitle(tp.getTitle());
1328 tree.setCurrentTree((av.getCurrentTree() == tp.getTree()));
1329 tree.setNewick(tp.getTree().print());
1330 tree.setThreshold(tp.getTreeCanvas().getThreshold());
1332 tree.setFitToWindow(tp.fitToWindow.getState());
1333 tree.setFontName(tp.getTreeFont().getName());
1334 tree.setFontSize(tp.getTreeFont().getSize());
1335 tree.setFontStyle(tp.getTreeFont().getStyle());
1336 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
1338 tree.setShowBootstrap(tp.bootstrapMenu.getState());
1339 tree.setShowDistances(tp.distanceMenu.getState());
1341 tree.setHeight(tp.getHeight());
1342 tree.setWidth(tp.getWidth());
1343 tree.setXpos(tp.getX());
1344 tree.setYpos(tp.getY());
1345 tree.setId(makeHashCode(tp, null));
1346 tree.setLinkToAllViews(
1347 tp.getTreeCanvas().isApplyToAllViews());
1350 if (tp.isColumnWise())
1352 tree.setColumnWise(true);
1353 String annId = tp.getAssocAnnotation().annotationId;
1354 tree.setColumnReference(annId);
1356 // jms.addTree(tree);
1357 object.getTree().add(tree);
1367 if (!storeDS && Desktop.desktop != null)
1369 for (JInternalFrame frame : Desktop.desktop.getAllFrames())
1371 if (frame instanceof PCAPanel)
1373 PCAPanel panel = (PCAPanel) frame;
1374 if (panel.getAlignViewport().getAlignment() == jal)
1376 savePCA(panel, object);
1384 * store forward refs from an annotationRow to any groups
1386 IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
1389 for (SequenceI sq : jal.getSequences())
1391 // Store annotation on dataset sequences only
1392 AlignmentAnnotation[] aa = sq.getAnnotation();
1393 if (aa != null && aa.length > 0)
1395 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1402 if (jal.getAlignmentAnnotation() != null)
1404 // Store the annotation shown on the alignment.
1405 AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
1406 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1411 if (jal.getGroups() != null)
1413 JGroup[] groups = new JGroup[jal.getGroups().size()];
1415 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
1417 JGroup jGroup = new JGroup();
1418 groups[++i] = jGroup;
1420 jGroup.setStart(sg.getStartRes());
1421 jGroup.setEnd(sg.getEndRes());
1422 jGroup.setName(sg.getName());
1423 if (groupRefs.containsKey(sg))
1425 // group has references so set its ID field
1426 jGroup.setId(groupRefs.get(sg));
1428 ColourSchemeI colourScheme = sg.getColourScheme();
1429 if (colourScheme != null)
1431 ResidueShaderI groupColourScheme = sg.getGroupColourScheme();
1432 if (groupColourScheme.conservationApplied())
1434 jGroup.setConsThreshold(groupColourScheme.getConservationInc());
1436 if (colourScheme instanceof jalview.schemes.UserColourScheme)
1438 jGroup.setColour(setUserColourScheme(colourScheme,
1439 userColours, object));
1443 jGroup.setColour(colourScheme.getSchemeName());
1446 else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
1448 jGroup.setColour("AnnotationColourGradient");
1449 jGroup.setAnnotationColours(constructAnnotationColours(
1450 (jalview.schemes.AnnotationColourGradient) colourScheme,
1451 userColours, object));
1453 else if (colourScheme instanceof jalview.schemes.UserColourScheme)
1456 setUserColourScheme(colourScheme, userColours, object));
1460 jGroup.setColour(colourScheme.getSchemeName());
1463 jGroup.setPidThreshold(groupColourScheme.getThreshold());
1466 jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
1467 jGroup.setDisplayBoxes(sg.getDisplayBoxes());
1468 jGroup.setDisplayText(sg.getDisplayText());
1469 jGroup.setColourText(sg.getColourText());
1470 jGroup.setTextCol1(sg.textColour.getRGB());
1471 jGroup.setTextCol2(sg.textColour2.getRGB());
1472 jGroup.setTextColThreshold(sg.thresholdTextColour);
1473 jGroup.setShowUnconserved(sg.getShowNonconserved());
1474 jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1475 jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
1476 jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
1477 jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1478 for (SequenceI seq : sg.getSequences())
1480 // jGroup.addSeq(seqHash(seq));
1481 jGroup.getSeq().add(seqHash(seq));
1485 // jms.setJGroup(groups);
1487 for (JGroup grp : groups)
1489 object.getJGroup().add(grp);
1494 // /////////SAVE VIEWPORT
1495 Viewport view = new Viewport();
1496 view.setTitle(ap.alignFrame.getTitle());
1497 view.setSequenceSetId(
1498 makeHashCode(av.getSequenceSetId(), av.getSequenceSetId()));
1499 view.setId(av.getViewId());
1500 if (av.getCodingComplement() != null)
1502 view.setComplementId(av.getCodingComplement().getViewId());
1504 view.setViewName(av.getViewName());
1505 view.setGatheredViews(av.isGatherViewsHere());
1507 Rectangle size = ap.av.getExplodedGeometry();
1508 Rectangle position = size;
1511 size = ap.alignFrame.getBounds();
1512 if (av.getCodingComplement() != null)
1514 position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
1522 view.setXpos(position.x);
1523 view.setYpos(position.y);
1525 view.setWidth(size.width);
1526 view.setHeight(size.height);
1528 view.setStartRes(vpRanges.getStartRes());
1529 view.setStartSeq(vpRanges.getStartSeq());
1531 OverviewPanel ov = ap.getOverviewPanel();
1534 Overview overview = new Overview();
1535 overview.setTitle(ov.getTitle());
1536 Rectangle bounds = ov.getFrameBounds();
1537 overview.setXpos(bounds.x);
1538 overview.setYpos(bounds.y);
1539 overview.setWidth(bounds.width);
1540 overview.setHeight(bounds.height);
1541 overview.setShowHidden(ov.isShowHiddenRegions());
1542 overview.setGapColour(ov.getCanvas().getGapColour().getRGB());
1543 overview.setResidueColour(
1544 ov.getCanvas().getResidueColour().getRGB());
1545 overview.setHiddenColour(ov.getCanvas().getHiddenColour().getRGB());
1546 view.setOverview(overview);
1548 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1550 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1551 userColours, object));
1554 .getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1556 AnnotationColourScheme ac = constructAnnotationColours(
1557 (jalview.schemes.AnnotationColourGradient) av
1558 .getGlobalColourScheme(),
1559 userColours, object);
1561 view.setAnnotationColours(ac);
1562 view.setBgColour("AnnotationColourGradient");
1566 view.setBgColour(ColourSchemeProperty
1567 .getColourName(av.getGlobalColourScheme()));
1570 ResidueShaderI vcs = av.getResidueShading();
1571 ColourSchemeI cs = av.getGlobalColourScheme();
1575 if (vcs.conservationApplied())
1577 view.setConsThreshold(vcs.getConservationInc());
1578 if (cs instanceof jalview.schemes.UserColourScheme)
1580 view.setBgColour(setUserColourScheme(cs, userColours, object));
1583 view.setPidThreshold(vcs.getThreshold());
1586 view.setConservationSelected(av.getConservationSelected());
1587 view.setPidSelected(av.getAbovePIDThreshold());
1588 view.setCharHeight(av.getCharHeight());
1589 view.setCharWidth(av.getCharWidth());
1590 final Font font = av.getFont();
1591 view.setFontName(font.getName());
1592 view.setFontSize(font.getSize());
1593 view.setFontStyle(font.getStyle());
1594 view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
1595 view.setRenderGaps(av.isRenderGaps());
1596 view.setShowAnnotation(av.isShowAnnotation());
1597 view.setShowBoxes(av.getShowBoxes());
1598 view.setShowColourText(av.getColourText());
1599 view.setShowFullId(av.getShowJVSuffix());
1600 view.setRightAlignIds(av.isRightAlignIds());
1601 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1602 view.setShowText(av.getShowText());
1603 view.setShowUnconserved(av.getShowUnconserved());
1604 view.setWrapAlignment(av.getWrapAlignment());
1605 view.setTextCol1(av.getTextColour().getRGB());
1606 view.setTextCol2(av.getTextColour2().getRGB());
1607 view.setTextColThreshold(av.getThresholdTextColour());
1608 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1609 view.setShowSequenceLogo(av.isShowSequenceLogo());
1610 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1611 view.setShowGroupConsensus(av.isShowGroupConsensus());
1612 view.setShowGroupConservation(av.isShowGroupConservation());
1613 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1614 view.setShowDbRefTooltip(av.isShowDBRefs());
1615 view.setFollowHighlight(av.isFollowHighlight());
1616 view.setFollowSelection(av.followSelection);
1617 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1618 view.setShowComplementFeatures(av.isShowComplementFeatures());
1619 view.setShowComplementFeaturesOnTop(
1620 av.isShowComplementFeaturesOnTop());
1621 if (av.getFeaturesDisplayed() != null)
1623 FeatureSettings fs = new FeatureSettings();
1625 FeatureRendererModel fr = ap.getSeqPanel().seqCanvas
1626 .getFeatureRenderer();
1627 String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
1629 Vector<String> settingsAdded = new Vector<>();
1630 if (renderOrder != null)
1632 for (String featureType : renderOrder)
1634 FeatureSettings.Setting setting = new FeatureSettings.Setting();
1635 setting.setType(featureType);
1638 * save any filter for the feature type
1640 FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
1643 Iterator<FeatureMatcherI> filters = filter.getMatchers()
1645 FeatureMatcherI firstFilter = filters.next();
1646 setting.setMatcherSet(Jalview2XML.marshalFilter(firstFilter,
1647 filters, filter.isAnded()));
1651 * save colour scheme for the feature type
1653 FeatureColourI fcol = fr.getFeatureStyle(featureType);
1654 if (!fcol.isSimpleColour())
1656 setting.setColour(fcol.getMaxColour().getRGB());
1657 setting.setMincolour(fcol.getMinColour().getRGB());
1658 setting.setMin(fcol.getMin());
1659 setting.setMax(fcol.getMax());
1660 setting.setColourByLabel(fcol.isColourByLabel());
1661 if (fcol.isColourByAttribute())
1663 String[] attName = fcol.getAttributeName();
1664 setting.getAttributeName().add(attName[0]);
1665 if (attName.length > 1)
1667 setting.getAttributeName().add(attName[1]);
1670 setting.setAutoScale(fcol.isAutoScaled());
1671 setting.setThreshold(fcol.getThreshold());
1672 Color noColour = fcol.getNoColour();
1673 if (noColour == null)
1675 setting.setNoValueColour(NoValueColour.NONE);
1677 else if (noColour.equals(fcol.getMaxColour()))
1679 setting.setNoValueColour(NoValueColour.MAX);
1683 setting.setNoValueColour(NoValueColour.MIN);
1685 // -1 = No threshold, 0 = Below, 1 = Above
1686 setting.setThreshstate(fcol.isAboveThreshold() ? 1
1687 : (fcol.isBelowThreshold() ? 0 : -1));
1691 setting.setColour(fcol.getColour().getRGB());
1695 av.getFeaturesDisplayed().isVisible(featureType));
1696 float rorder = fr.getOrder(featureType);
1699 setting.setOrder(rorder);
1701 /// fs.addSetting(setting);
1702 fs.getSetting().add(setting);
1703 settingsAdded.addElement(featureType);
1707 // is groups actually supposed to be a map here ?
1708 Iterator<String> en = fr.getFeatureGroups().iterator();
1709 Vector<String> groupsAdded = new Vector<>();
1710 while (en.hasNext())
1712 String grp = en.next();
1713 if (groupsAdded.contains(grp))
1717 Group g = new Group();
1719 g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
1722 fs.getGroup().add(g);
1723 groupsAdded.addElement(grp);
1725 // jms.setFeatureSettings(fs);
1726 object.setFeatureSettings(fs);
1729 if (av.hasHiddenColumns())
1731 jalview.datamodel.HiddenColumns hidden = av.getAlignment()
1732 .getHiddenColumns();
1736 "REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1740 Iterator<int[]> hiddenRegions = hidden.iterator();
1741 while (hiddenRegions.hasNext())
1743 int[] region = hiddenRegions.next();
1744 HiddenColumns hc = new HiddenColumns();
1745 hc.setStart(region[0]);
1746 hc.setEnd(region[1]);
1747 // view.addHiddenColumns(hc);
1748 view.getHiddenColumns().add(hc);
1752 if (calcIdSet.size() > 0)
1754 for (String calcId : calcIdSet)
1756 if (calcId.trim().length() > 0)
1758 CalcIdParam cidp = createCalcIdParam(calcId, av);
1759 // Some calcIds have no parameters.
1762 // view.addCalcIdParam(cidp);
1763 view.getCalcIdParam().add(cidp);
1769 // jms.addViewport(view);
1770 object.getViewport().add(view);
1772 // object.setJalviewModelSequence(jms);
1773 // object.getVamsasModel().addSequenceSet(vamsasSet);
1774 object.getVamsasModel().getSequenceSet().add(vamsasSet);
1776 if (jout != null && fileName != null)
1778 // We may not want to write the object to disk,
1779 // eg we can copy the alignViewport to a new view object
1780 // using save and then load
1783 fileName = fileName.replace('\\', '/');
1784 jalview.bin.Console.outPrintln("Writing jar entry " + fileName);
1785 JarEntry entry = new JarEntry(fileName);
1786 jout.putNextEntry(entry);
1787 PrintWriter pout = new PrintWriter(
1788 new OutputStreamWriter(jout, UTF_8));
1789 JAXBContext jaxbContext = JAXBContext
1790 .newInstance(JalviewModel.class);
1791 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
1793 // output pretty printed
1794 // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1795 jaxbMarshaller.marshal(
1796 new ObjectFactory().createJalviewModel(object), pout);
1798 // jaxbMarshaller.marshal(object, pout);
1799 // marshaller.marshal(object);
1802 } catch (Exception ex)
1804 // TODO: raise error in GUI if marshalling failed.
1805 jalview.bin.Console.errPrintln("Error writing Jalview project");
1806 ex.printStackTrace();
1813 * Writes PCA viewer attributes and computed values to an XML model object and
1814 * adds it to the JalviewModel. Any exceptions are reported by logging.
1816 protected void savePCA(PCAPanel panel, JalviewModel object)
1820 PcaViewer viewer = new PcaViewer();
1821 viewer.setHeight(panel.getHeight());
1822 viewer.setWidth(panel.getWidth());
1823 viewer.setXpos(panel.getX());
1824 viewer.setYpos(panel.getY());
1825 viewer.setTitle(panel.getTitle());
1826 PCAModel pcaModel = panel.getPcaModel();
1827 viewer.setScoreModelName(pcaModel.getScoreModelName());
1828 viewer.setXDim(panel.getSelectedDimensionIndex(X));
1829 viewer.setYDim(panel.getSelectedDimensionIndex(Y));
1830 viewer.setZDim(panel.getSelectedDimensionIndex(Z));
1832 panel.getRotatableCanvas().getBackgroundColour().getRGB());
1833 viewer.setScaleFactor(panel.getRotatableCanvas().getScaleFactor());
1834 float[] spMin = panel.getRotatableCanvas().getSeqMin();
1835 SeqPointMin spmin = new SeqPointMin();
1836 spmin.setXPos(spMin[0]);
1837 spmin.setYPos(spMin[1]);
1838 spmin.setZPos(spMin[2]);
1839 viewer.setSeqPointMin(spmin);
1840 float[] spMax = panel.getRotatableCanvas().getSeqMax();
1841 SeqPointMax spmax = new SeqPointMax();
1842 spmax.setXPos(spMax[0]);
1843 spmax.setYPos(spMax[1]);
1844 spmax.setZPos(spMax[2]);
1845 viewer.setSeqPointMax(spmax);
1846 viewer.setShowLabels(panel.getRotatableCanvas().isShowLabels());
1847 viewer.setLinkToAllViews(
1848 panel.getRotatableCanvas().isApplyToAllViews());
1849 SimilarityParamsI sp = pcaModel.getSimilarityParameters();
1850 viewer.setIncludeGaps(sp.includeGaps());
1851 viewer.setMatchGaps(sp.matchGaps());
1852 viewer.setIncludeGappedColumns(sp.includeGappedColumns());
1853 viewer.setDenominateByShortestLength(sp.denominateByShortestLength());
1856 * sequence points on display
1858 for (jalview.datamodel.SequencePoint spt : pcaModel
1859 .getSequencePoints())
1861 SequencePoint point = new SequencePoint();
1862 point.setSequenceRef(seqHash(spt.getSequence()));
1863 point.setXPos(spt.coord.x);
1864 point.setYPos(spt.coord.y);
1865 point.setZPos(spt.coord.z);
1866 viewer.getSequencePoint().add(point);
1870 * (end points of) axes on display
1872 for (Point p : panel.getRotatableCanvas().getAxisEndPoints())
1875 Axis axis = new Axis();
1879 viewer.getAxis().add(axis);
1883 * raw PCA data (note we are not restoring PCA inputs here -
1884 * alignment view, score model, similarity parameters)
1886 PcaDataType data = new PcaDataType();
1887 viewer.setPcaData(data);
1888 PCA pca = pcaModel.getPcaData();
1890 DoubleMatrix pm = new DoubleMatrix();
1891 saveDoubleMatrix(pca.getPairwiseScores(), pm);
1892 data.setPairwiseMatrix(pm);
1894 DoubleMatrix tm = new DoubleMatrix();
1895 saveDoubleMatrix(pca.getTridiagonal(), tm);
1896 data.setTridiagonalMatrix(tm);
1898 DoubleMatrix eigenMatrix = new DoubleMatrix();
1899 data.setEigenMatrix(eigenMatrix);
1900 saveDoubleMatrix(pca.getEigenmatrix(), eigenMatrix);
1902 object.getPcaViewer().add(viewer);
1903 } catch (Throwable t)
1905 Console.error("Error saving PCA: " + t.getMessage());
1910 * Stores values from a matrix into an XML element, including (if present) the
1915 * @see #loadDoubleMatrix(DoubleMatrix)
1917 protected void saveDoubleMatrix(MatrixI m, DoubleMatrix xmlMatrix)
1919 xmlMatrix.setRows(m.height());
1920 xmlMatrix.setColumns(m.width());
1921 for (int i = 0; i < m.height(); i++)
1923 DoubleVector row = new DoubleVector();
1924 for (int j = 0; j < m.width(); j++)
1926 row.getV().add(m.getValue(i, j));
1928 xmlMatrix.getRow().add(row);
1930 if (m.getD() != null)
1932 DoubleVector dVector = new DoubleVector();
1933 for (double d : m.getD())
1935 dVector.getV().add(d);
1937 xmlMatrix.setD(dVector);
1939 if (m.getE() != null)
1941 DoubleVector eVector = new DoubleVector();
1942 for (double e : m.getE())
1944 eVector.getV().add(e);
1946 xmlMatrix.setE(eVector);
1951 * Loads XML matrix data into a new Matrix object, including the D and/or E
1952 * vectors (if present)
1956 * @see Jalview2XML#saveDoubleMatrix(MatrixI, DoubleMatrix)
1958 protected MatrixI loadDoubleMatrix(DoubleMatrix mData)
1960 int rows = mData.getRows();
1961 double[][] vals = new double[rows][];
1963 for (int i = 0; i < rows; i++)
1965 List<Double> dVector = mData.getRow().get(i).getV();
1966 vals[i] = new double[dVector.size()];
1968 for (Double d : dVector)
1974 MatrixI m = new Matrix(vals);
1976 if (mData.getD() != null)
1978 List<Double> dVector = mData.getD().getV();
1979 double[] vec = new double[dVector.size()];
1981 for (Double d : dVector)
1987 if (mData.getE() != null)
1989 List<Double> dVector = mData.getE().getV();
1990 double[] vec = new double[dVector.size()];
1992 for (Double d : dVector)
2003 * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
2004 * for each viewer, with
2006 * <li>viewer geometry (position, size, split pane divider location)</li>
2007 * <li>index of the selected structure in the viewer (currently shows gapped
2009 * <li>the id of the annotation holding RNA secondary structure</li>
2010 * <li>(currently only one SS is shown per viewer, may be more in future)</li>
2012 * Varna viewer state is also written out (in native Varna XML) to separate
2013 * project jar entries. A separate entry is written for each RNA structure
2014 * displayed, with the naming convention
2016 * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
2024 * @param storeDataset
2026 protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
2027 final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
2028 boolean storeDataset)
2030 if (Desktop.desktop == null)
2034 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2035 for (int f = frames.length - 1; f > -1; f--)
2037 if (frames[f] instanceof AppVarna)
2039 AppVarna varna = (AppVarna) frames[f];
2041 * link the sequence to every viewer that is showing it and is linked to
2042 * its alignment panel
2044 if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
2046 String viewId = varna.getViewId();
2047 RnaViewer rna = new RnaViewer();
2048 rna.setViewId(viewId);
2049 rna.setTitle(varna.getTitle());
2050 rna.setXpos(varna.getX());
2051 rna.setYpos(varna.getY());
2052 rna.setWidth(varna.getWidth());
2053 rna.setHeight(varna.getHeight());
2054 rna.setDividerLocation(varna.getDividerLocation());
2055 rna.setSelectedRna(varna.getSelectedIndex());
2056 // jseq.addRnaViewer(rna);
2057 jseq.getRnaViewer().add(rna);
2060 * Store each Varna panel's state once in the project per sequence.
2061 * First time through only (storeDataset==false)
2063 // boolean storeSessions = false;
2064 // String sequenceViewId = viewId + seqsToIds.get(jds);
2065 // if (!storeDataset && !viewIds.contains(sequenceViewId))
2067 // viewIds.add(sequenceViewId);
2068 // storeSessions = true;
2070 for (RnaModel model : varna.getModels())
2072 if (model.seq == jds)
2075 * VARNA saves each view (sequence or alignment secondary
2076 * structure, gapped or trimmed) as a separate XML file
2078 String jarEntryName = rnaSessions.get(model);
2079 if (jarEntryName == null)
2082 String varnaStateFile = varna.getStateInfo(model.rna);
2083 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
2084 copyFileToJar(jout, varnaStateFile, jarEntryName, "Varna");
2085 rnaSessions.put(model, jarEntryName);
2087 SecondaryStructure ss = new SecondaryStructure();
2088 String annotationId = varna.getAnnotation(jds).annotationId;
2089 ss.setAnnotationId(annotationId);
2090 ss.setViewerState(jarEntryName);
2091 ss.setGapped(model.gapped);
2092 ss.setTitle(model.title);
2093 // rna.addSecondaryStructure(ss);
2094 rna.getSecondaryStructure().add(ss);
2103 * Copy the contents of a file to a new entry added to the output jar
2107 * @param jarEntryName
2109 * additional identifying info to log to the console
2111 protected void copyFileToJar(JarOutputStream jout, String infilePath,
2112 String jarEntryName, String msg)
2114 try (InputStream is = new FileInputStream(infilePath))
2116 File file = new File(infilePath);
2117 if (file.exists() && jout != null)
2119 jalview.bin.Console.outPrintln(
2120 "Writing jar entry " + jarEntryName + " (" + msg + ")");
2121 jout.putNextEntry(new JarEntry(jarEntryName));
2124 // dis = new DataInputStream(new FileInputStream(file));
2125 // byte[] data = new byte[(int) file.length()];
2126 // dis.readFully(data);
2127 // writeJarEntry(jout, jarEntryName, data);
2129 } catch (Exception ex)
2131 ex.printStackTrace();
2136 * Copies input to output, in 4K buffers; handles any data (text or binary)
2140 * @throws IOException
2142 protected void copyAll(InputStream in, OutputStream out)
2145 byte[] buffer = new byte[4096];
2147 while ((bytesRead = in.read(buffer)) != -1)
2149 out.write(buffer, 0, bytesRead);
2154 * Save the state of a structure viewer
2159 * the archive XML element under which to save the state
2162 * @param matchedFile
2166 protected String saveStructureViewer(AlignmentPanel ap, SequenceI jds,
2167 Pdbids pdb, PDBEntry entry, List<String> viewIds,
2168 String matchedFile, JalviewStructureDisplayI viewFrame)
2170 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
2173 * Look for any bindings for this viewer to the PDB file of interest
2174 * (including part matches excluding chain id)
2176 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
2178 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
2179 final String pdbId = pdbentry.getId();
2180 if (!pdbId.equals(entry.getId()) && !(entry.getId().length() > 4
2181 && entry.getId().toLowerCase(Locale.ROOT)
2182 .startsWith(pdbId.toLowerCase(Locale.ROOT))))
2185 * not interested in a binding to a different PDB entry here
2189 if (matchedFile == null)
2191 matchedFile = pdbentry.getFile();
2193 else if (!matchedFile.equals(pdbentry.getFile()))
2196 "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
2197 + pdbentry.getFile());
2201 // can get at it if the ID
2202 // match is ambiguous (e.g.
2205 for (int smap = 0; smap < viewFrame.getBinding()
2206 .getSequence()[peid].length; smap++)
2208 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
2209 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
2211 StructureState state = new StructureState();
2212 state.setVisible(true);
2213 state.setXpos(viewFrame.getY());
2214 state.setYpos(viewFrame.getY());
2215 state.setWidth(viewFrame.getWidth());
2216 state.setHeight(viewFrame.getHeight());
2217 final String viewId = viewFrame.getViewId();
2218 state.setViewId(viewId);
2219 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
2220 state.setColourwithAlignPanel(viewFrame.isUsedForColourBy(ap));
2221 state.setColourByJmol(viewFrame.isColouredByViewer());
2222 state.setType(viewFrame.getViewerType().toString());
2223 // pdb.addStructureState(state);
2224 pdb.getStructureState().add(state);
2232 * Populates the AnnotationColourScheme xml for save. This captures the
2233 * settings of the options in the 'Colour by Annotation' dialog.
2236 * @param userColours
2240 private AnnotationColourScheme constructAnnotationColours(
2241 AnnotationColourGradient acg, List<UserColourScheme> userColours,
2244 AnnotationColourScheme ac = new AnnotationColourScheme();
2245 ac.setAboveThreshold(acg.getAboveThreshold());
2246 ac.setThreshold(acg.getAnnotationThreshold());
2247 // 2.10.2 save annotationId (unique) not annotation label
2248 ac.setAnnotation(acg.getAnnotation().annotationId);
2249 if (acg.getBaseColour() instanceof UserColourScheme)
2252 setUserColourScheme(acg.getBaseColour(), userColours, jm));
2257 ColourSchemeProperty.getColourName(acg.getBaseColour()));
2260 ac.setMaxColour(acg.getMaxColour().getRGB());
2261 ac.setMinColour(acg.getMinColour().getRGB());
2262 ac.setPerSequence(acg.isSeqAssociated());
2263 ac.setPredefinedColours(acg.isPredefinedColours());
2267 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
2268 IdentityHashMap<SequenceGroup, String> groupRefs,
2269 AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
2270 SequenceSet vamsasSet)
2273 for (int i = 0; i < aa.length; i++)
2275 Annotation an = new Annotation();
2277 AlignmentAnnotation annotation = aa[i];
2278 if (annotation.annotationId != null)
2280 annotationIds.put(annotation.annotationId, annotation);
2283 an.setId(annotation.annotationId);
2285 an.setVisible(annotation.visible);
2287 an.setDescription(annotation.description);
2289 if (annotation.sequenceRef != null)
2291 // 2.9 JAL-1781 xref on sequence id rather than name
2292 an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
2294 if (annotation.groupRef != null)
2296 String groupIdr = groupRefs.get(annotation.groupRef);
2297 if (groupIdr == null)
2299 // make a locally unique String
2300 groupRefs.put(annotation.groupRef,
2301 groupIdr = ("" + System.currentTimeMillis()
2302 + annotation.groupRef.getName()
2303 + groupRefs.size()));
2305 an.setGroupRef(groupIdr.toString());
2308 // store all visualization attributes for annotation
2309 an.setGraphHeight(annotation.graphHeight);
2310 an.setCentreColLabels(annotation.centreColLabels);
2311 an.setScaleColLabels(annotation.scaleColLabel);
2312 an.setShowAllColLabels(annotation.showAllColLabels);
2313 an.setBelowAlignment(annotation.belowAlignment);
2315 if (annotation.graph > 0)
2318 an.setGraphType(annotation.graph);
2319 an.setGraphGroup(annotation.graphGroup);
2320 if (annotation.getThreshold() != null)
2322 ThresholdLine line = new ThresholdLine();
2323 line.setLabel(annotation.getThreshold().label);
2324 line.setValue(annotation.getThreshold().value);
2325 line.setColour(annotation.getThreshold().colour.getRGB());
2326 an.setThresholdLine(line);
2328 if (annotation.graph == AlignmentAnnotation.CONTACT_MAP)
2330 if (annotation.sequenceRef.getContactMaps() != null)
2332 ContactMatrixI cm = annotation.sequenceRef
2333 .getContactMatrixFor(annotation);
2336 MatrixType xmlmat = new MatrixType();
2337 xmlmat.setType(cm.getType());
2338 xmlmat.setRows(BigInteger.valueOf(cm.getWidth()));
2339 xmlmat.setCols(BigInteger.valueOf(cm.getHeight()));
2340 // consider using an opaque to/from -> allow instance to control
2341 // its representation ?
2342 xmlmat.setElements(ContactMatrix.contactToFloatString(cm));
2345 for (BitSet gp : cm.getGroups())
2347 xmlmat.getGroups().add(stringifyBitset(gp));
2352 // provenance object for tree ?
2353 xmlmat.getNewick().add(cm.getNewick());
2354 xmlmat.setTreeMethod(cm.getTreeMethod());
2356 if (cm.hasCutHeight())
2358 xmlmat.setCutHeight(cm.getCutHeight());
2360 // set/get properties
2361 if (cm instanceof MappableContactMatrixI)
2363 jalview.util.MapList mlst = ((MappableContactMatrixI) cm)
2364 .getMapFor(annotation.sequenceRef);
2367 MapListType mp = new MapListType();
2368 List<int[]> r = mlst.getFromRanges();
2369 for (int[] range : r)
2371 MapListFrom mfrom = new MapListFrom();
2372 mfrom.setStart(range[0]);
2373 mfrom.setEnd(range[1]);
2374 // mp.addMapListFrom(mfrom);
2375 mp.getMapListFrom().add(mfrom);
2377 r = mlst.getToRanges();
2378 for (int[] range : r)
2380 MapListTo mto = new MapListTo();
2381 mto.setStart(range[0]);
2382 mto.setEnd(range[1]);
2383 // mp.addMapListTo(mto);
2384 mp.getMapListTo().add(mto);
2387 BigInteger.valueOf(mlst.getFromRatio()));
2388 mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
2389 xmlmat.setMapping(mp);
2393 an.getContactmatrix().add(xmlmat);
2403 an.setLabel(annotation.label);
2405 if (annotation == av.getAlignmentQualityAnnot()
2406 || annotation == av.getAlignmentConservationAnnotation()
2407 || annotation == av.getAlignmentConsensusAnnotation()
2408 || annotation.autoCalculated)
2410 // new way of indicating autocalculated annotation -
2411 an.setAutoCalculated(annotation.autoCalculated);
2413 if (annotation.hasScore())
2415 an.setScore(annotation.getScore());
2418 if (annotation.getCalcId() != null)
2420 calcIdSet.add(annotation.getCalcId());
2421 an.setCalcId(annotation.getCalcId());
2423 if (annotation.hasProperties())
2425 for (String pr : annotation.getProperties())
2427 jalview.xml.binding.jalview.Property prop = new jalview.xml.binding.jalview.Property();
2429 prop.setValue(annotation.getProperty(pr));
2430 an.getProperty().add(prop);
2434 AnnotationElement ae;
2435 if (annotation.annotations != null)
2437 an.setScoreOnly(false);
2438 for (int a = 0; a < annotation.annotations.length; a++)
2440 if ((annotation == null) || (annotation.annotations[a] == null))
2445 ae = new AnnotationElement();
2446 if (annotation.annotations[a].description != null)
2448 ae.setDescription(annotation.annotations[a].description);
2450 if (annotation.annotations[a].displayCharacter != null)
2452 ae.setDisplayCharacter(
2453 annotation.annotations[a].displayCharacter);
2456 if (!Float.isNaN(annotation.annotations[a].value))
2458 ae.setValue(annotation.annotations[a].value);
2462 if (annotation.annotations[a].secondaryStructure > ' ')
2464 ae.setSecondaryStructure(
2465 annotation.annotations[a].secondaryStructure + "");
2468 if (annotation.annotations[a].colour != null
2469 && annotation.annotations[a].colour != java.awt.Color.black)
2471 ae.setColour(annotation.annotations[a].colour.getRGB());
2474 // an.addAnnotationElement(ae);
2475 an.getAnnotationElement().add(ae);
2476 if (annotation.autoCalculated)
2478 // only write one non-null entry into the annotation row -
2479 // sufficient to get the visualization attributes necessary to
2487 an.setScoreOnly(true);
2489 if (!storeDS || (storeDS && !annotation.autoCalculated))
2491 // skip autocalculated annotation - these are only provided for
2493 // vamsasSet.addAnnotation(an);
2494 vamsasSet.getAnnotation().add(an);
2500 private String stringifyBitset(BitSet gp)
2502 StringBuilder sb = new StringBuilder();
2503 for (long val : gp.toLongArray())
2505 if (sb.length() > 0)
2511 return sb.toString();
2514 private BitSet deStringifyBitset(String stringified)
2516 if ("".equals(stringified) || stringified == null)
2518 return new BitSet();
2520 String[] longvals = stringified.split(",");
2521 long[] newlongvals = new long[longvals.length];
2522 for (int lv = 0; lv < longvals.length; lv++)
2526 newlongvals[lv] = Long.valueOf(longvals[lv]);
2527 } catch (Exception x)
2529 errorMessage += "Couldn't destringify bitset from: '" + stringified
2531 newlongvals[lv] = 0;
2534 return BitSet.valueOf(newlongvals);
2538 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
2540 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
2541 if (settings != null)
2543 CalcIdParam vCalcIdParam = new CalcIdParam();
2544 vCalcIdParam.setCalcId(calcId);
2545 // vCalcIdParam.addServiceURL(settings.getServiceURI());
2546 vCalcIdParam.getServiceURL().add(settings.getServiceURI());
2547 // generic URI allowing a third party to resolve another instance of the
2548 // service used for this calculation
2549 for (String url : settings.getServiceURLs())
2551 // vCalcIdParam.addServiceURL(urls);
2552 vCalcIdParam.getServiceURL().add(url);
2554 vCalcIdParam.setVersion("1.0");
2555 if (settings.getPreset() != null)
2557 WsParamSetI setting = settings.getPreset();
2558 vCalcIdParam.setName(setting.getName());
2559 vCalcIdParam.setDescription(setting.getDescription());
2563 vCalcIdParam.setName("");
2564 vCalcIdParam.setDescription("Last used parameters");
2566 // need to be able to recover 1) settings 2) user-defined presets or
2567 // recreate settings from preset 3) predefined settings provided by
2568 // service - or settings that can be transferred (or discarded)
2569 vCalcIdParam.setParameters(
2570 settings.getWsParamFile().replace("\n", "|\\n|"));
2571 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
2572 // todo - decide if updateImmediately is needed for any projects.
2574 return vCalcIdParam;
2579 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
2582 if (calcIdParam.getVersion().equals("1.0"))
2584 final String[] calcIds = calcIdParam.getServiceURL()
2585 .toArray(new String[0]);
2586 Jws2Instance service = Jws2Discoverer.getDiscoverer()
2587 .getPreferredServiceFor(calcIds);
2588 if (service != null)
2590 WsParamSetI parmSet = null;
2593 parmSet = service.getParamStore().parseServiceParameterFile(
2594 calcIdParam.getName(), calcIdParam.getDescription(),
2596 calcIdParam.getParameters().replace("|\\n|", "\n"));
2597 } catch (IOException x)
2599 Console.warn("Couldn't parse parameter data for "
2600 + calcIdParam.getCalcId(), x);
2603 List<ArgumentI> argList = null;
2604 if (calcIdParam.getName().length() > 0)
2606 parmSet = service.getParamStore()
2607 .getPreset(calcIdParam.getName());
2608 if (parmSet != null)
2610 // TODO : check we have a good match with settings in AACon -
2611 // otherwise we'll need to create a new preset
2616 argList = parmSet.getArguments();
2619 AAConSettings settings = new AAConSettings(
2620 calcIdParam.isAutoUpdate(), service, parmSet, argList);
2621 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
2622 calcIdParam.isNeedsUpdate());
2628 "Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
2632 throw new Error(MessageManager.formatMessage(
2633 "error.unsupported_version_calcIdparam", new Object[]
2634 { calcIdParam.toString() }));
2638 * External mapping between jalview objects and objects yielding a valid and
2639 * unique object ID string. This is null for normal Jalview project IO, but
2640 * non-null when a jalview project is being read or written as part of a
2643 IdentityHashMap jv2vobj = null;
2646 * Construct a unique ID for jvobj using either existing bindings or if none
2647 * exist, the result of the hashcode call for the object.
2650 * jalview data object
2651 * @return unique ID for referring to jvobj
2653 private String makeHashCode(Object jvobj, String altCode)
2655 if (jv2vobj != null)
2657 Object id = jv2vobj.get(jvobj);
2660 return id.toString();
2662 // check string ID mappings
2663 if (jvids2vobj != null && jvobj instanceof String)
2665 id = jvids2vobj.get(jvobj);
2669 return id.toString();
2671 // give up and warn that something has gone wrong
2673 "Cannot find ID for object in external mapping : " + jvobj);
2679 * return local jalview object mapped to ID, if it exists
2683 * @return null or object bound to idcode
2685 private Object retrieveExistingObj(String idcode)
2687 if (idcode != null && vobj2jv != null)
2689 return vobj2jv.get(idcode);
2695 * binding from ID strings from external mapping table to jalview data model
2698 private Hashtable vobj2jv;
2700 private Sequence createVamsasSequence(String id, SequenceI jds)
2702 return createVamsasSequence(true, id, jds, null);
2705 private Sequence createVamsasSequence(boolean recurse, String id,
2706 SequenceI jds, SequenceI parentseq)
2708 Sequence vamsasSeq = new Sequence();
2709 vamsasSeq.setId(id);
2710 vamsasSeq.setName(jds.getName());
2711 vamsasSeq.setSequence(jds.getSequenceAsString());
2712 vamsasSeq.setDescription(jds.getDescription());
2713 List<DBRefEntry> dbrefs = null;
2714 if (jds.getDatasetSequence() != null)
2716 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
2720 // seqId==dsseqid so we can tell which sequences really are
2721 // dataset sequences only
2722 vamsasSeq.setDsseqid(id);
2723 dbrefs = jds.getDBRefs();
2724 if (parentseq == null)
2731 * save any dbrefs; special subclass GeneLocus is flagged as 'locus'
2735 for (int d = 0, nd = dbrefs.size(); d < nd; d++)
2737 DBRef dbref = new DBRef();
2738 DBRefEntry ref = dbrefs.get(d);
2739 dbref.setSource(ref.getSource());
2740 dbref.setVersion(ref.getVersion());
2741 dbref.setAccessionId(ref.getAccessionId());
2742 dbref.setCanonical(ref.isCanonical());
2743 if (ref instanceof GeneLocus)
2745 dbref.setLocus(true);
2749 Mapping mp = createVamsasMapping(ref.getMap(), parentseq, jds,
2751 dbref.setMapping(mp);
2753 vamsasSeq.getDBRef().add(dbref);
2759 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
2760 SequenceI parentseq, SequenceI jds, boolean recurse)
2763 if (jmp.getMap() != null)
2767 jalview.util.MapList mlst = jmp.getMap();
2768 List<int[]> r = mlst.getFromRanges();
2769 for (int[] range : r)
2771 MapListFrom mfrom = new MapListFrom();
2772 mfrom.setStart(range[0]);
2773 mfrom.setEnd(range[1]);
2774 // mp.addMapListFrom(mfrom);
2775 mp.getMapListFrom().add(mfrom);
2777 r = mlst.getToRanges();
2778 for (int[] range : r)
2780 MapListTo mto = new MapListTo();
2781 mto.setStart(range[0]);
2782 mto.setEnd(range[1]);
2783 // mp.addMapListTo(mto);
2784 mp.getMapListTo().add(mto);
2786 mp.setMapFromUnit(BigInteger.valueOf(mlst.getFromRatio()));
2787 mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
2788 if (jmp.getTo() != null)
2790 // MappingChoice mpc = new MappingChoice();
2792 // check/create ID for the sequence referenced by getTo()
2795 SequenceI ps = null;
2796 if (parentseq != jmp.getTo()
2797 && parentseq.getDatasetSequence() != jmp.getTo())
2799 // chaining dbref rather than a handshaking one
2800 jmpid = seqHash(ps = jmp.getTo());
2804 jmpid = seqHash(ps = parentseq);
2806 // mpc.setDseqFor(jmpid);
2807 mp.setDseqFor(jmpid);
2808 if (!seqRefIds.containsKey(jmpid))
2810 Console.debug("creatign new DseqFor ID");
2811 seqRefIds.put(jmpid, ps);
2815 Console.debug("reusing DseqFor ID");
2818 // mp.setMappingChoice(mpc);
2824 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
2825 List<UserColourScheme> userColours, JalviewModel jm)
2828 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
2829 boolean newucs = false;
2830 if (!userColours.contains(ucs))
2832 userColours.add(ucs);
2835 id = "ucs" + userColours.indexOf(ucs);
2838 // actually create the scheme's entry in the XML model
2839 java.awt.Color[] colours = ucs.getColours();
2840 UserColours uc = new UserColours();
2841 // UserColourScheme jbucs = new UserColourScheme();
2842 JalviewUserColours jbucs = new JalviewUserColours();
2844 for (int i = 0; i < colours.length; i++)
2846 Colour col = new Colour();
2847 col.setName(ResidueProperties.aa[i]);
2848 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2849 // jbucs.addColour(col);
2850 jbucs.getColour().add(col);
2852 if (ucs.getLowerCaseColours() != null)
2854 colours = ucs.getLowerCaseColours();
2855 for (int i = 0; i < colours.length; i++)
2857 Colour col = new Colour();
2858 col.setName(ResidueProperties.aa[i].toLowerCase(Locale.ROOT));
2859 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2860 // jbucs.addColour(col);
2861 jbucs.getColour().add(col);
2866 uc.setUserColourScheme(jbucs);
2867 // jm.addUserColours(uc);
2868 jm.getUserColours().add(uc);
2874 jalview.schemes.UserColourScheme getUserColourScheme(JalviewModel jm,
2877 List<UserColours> uc = jm.getUserColours();
2878 UserColours colours = null;
2880 for (int i = 0; i < uc.length; i++)
2882 if (uc[i].getId().equals(id))
2889 for (UserColours c : uc)
2891 if (c.getId().equals(id))
2898 java.awt.Color[] newColours = new java.awt.Color[24];
2900 for (int i = 0; i < 24; i++)
2902 newColours[i] = new java.awt.Color(Integer.parseInt(
2903 // colours.getUserColourScheme().getColour(i).getRGB(), 16));
2904 colours.getUserColourScheme().getColour().get(i).getRGB(),
2908 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
2911 if (colours.getUserColourScheme().getColour().size()/*Count()*/ > 24)
2913 newColours = new java.awt.Color[23];
2914 for (int i = 0; i < 23; i++)
2916 newColours[i] = new java.awt.Color(
2917 Integer.parseInt(colours.getUserColourScheme().getColour()
2918 .get(i + 24).getRGB(), 16));
2920 ucs.setLowerCaseColours(newColours);
2927 * contains last error message (if any) encountered by XML loader.
2929 String errorMessage = null;
2932 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
2933 * exceptions are raised during project XML parsing
2935 public boolean attemptversion1parse = false;
2938 * Load a jalview project archive from a jar file
2941 * - HTTP URL or filename
2943 public AlignFrame loadJalviewAlign(final Object file)
2946 jalview.gui.AlignFrame af = null;
2950 // create list to store references for any new Jmol viewers created
2951 newStructureViewers = new Vector<>();
2952 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
2953 // Workaround is to make sure caller implements the JarInputStreamProvider
2955 // so we can re-open the jar input stream for each entry.
2957 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
2958 af = loadJalviewAlign(jprovider);
2961 af.setMenusForViewport();
2963 } catch (MalformedURLException e)
2965 errorMessage = "Invalid URL format for '" + file + "'";
2971 SwingUtilities.invokeAndWait(new Runnable()
2976 setLoadingFinishedForNewStructureViewers();
2979 } catch (Exception x)
2982 .errPrintln("Error loading alignment: " + x.getMessage());
2988 @SuppressWarnings("unused")
2989 private jarInputStreamProvider createjarInputStreamProvider(
2990 final Object ofile) throws MalformedURLException
2993 // BH 2018 allow for bytes already attached to File object
2996 String file = (ofile instanceof File
2997 ? ((File) ofile).getCanonicalPath()
2998 : ofile.toString());
2999 byte[] bytes = Platform.isJS() ? Platform.getFileBytes((File) ofile)
3002 errorMessage = null;
3003 uniqueSetSuffix = null;
3005 viewportsAdded.clear();
3006 frefedSequence = null;
3008 if (HttpUtils.startsWithHttpOrHttps(file))
3010 url = new URL(file);
3012 final URL _url = url;
3013 return new jarInputStreamProvider()
3017 public JarInputStream getJarInputStream() throws IOException
3021 // jalview.bin.Console.outPrintln("Jalview2XML: opening byte
3022 // jarInputStream for
3023 // bytes.length=" + bytes.length);
3024 return new JarInputStream(new ByteArrayInputStream(bytes));
3028 // jalview.bin.Console.outPrintln("Jalview2XML: opening url
3029 // jarInputStream for "
3031 return new JarInputStream(_url.openStream());
3035 // jalview.bin.Console.outPrintln("Jalview2XML: opening file
3036 // jarInputStream for
3038 return new JarInputStream(new FileInputStream(file));
3043 public String getFilename()
3048 } catch (IOException e)
3050 e.printStackTrace();
3056 * Recover jalview session from a jalview project archive. Caller may
3057 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
3058 * themselves. Any null fields will be initialised with default values,
3059 * non-null fields are left alone.
3064 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
3066 errorMessage = null;
3067 if (uniqueSetSuffix == null)
3069 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
3071 if (seqRefIds == null)
3075 AlignFrame af = null, _af = null;
3076 IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
3077 Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
3078 final String file = jprovider.getFilename();
3081 JarInputStream jin = null;
3082 JarEntry jarentry = null;
3087 jin = jprovider.getJarInputStream();
3088 for (int i = 0; i < entryCount; i++)
3090 jarentry = jin.getNextJarEntry();
3093 if (jarentry != null && jarentry.getName().endsWith(".xml"))
3095 JAXBContext jc = JAXBContext
3096 .newInstance("jalview.xml.binding.jalview");
3097 XMLStreamReader streamReader = XMLInputFactory.newInstance()
3098 .createXMLStreamReader(jin);
3099 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
3100 JAXBElement<JalviewModel> jbe = um.unmarshal(streamReader,
3101 JalviewModel.class);
3102 JalviewModel object = jbe.getValue();
3104 if (true) // !skipViewport(object))
3106 _af = loadFromObject(object, file, true, jprovider);
3107 if (_af != null && object.getViewport().size() > 0)
3108 // getJalviewModelSequence().getViewportCount() > 0)
3112 // store a reference to the first view
3115 if (_af.getViewport().isGatherViewsHere())
3117 // if this is a gathered view, keep its reference since
3118 // after gathering views, only this frame will remain
3120 gatherToThisFrame.put(_af.getViewport().getSequenceSetId(),
3123 // Save dataset to register mappings once all resolved
3124 importedDatasets.put(
3125 af.getViewport().getAlignment().getDataset(),
3126 af.getViewport().getAlignment().getDataset());
3131 else if (jarentry != null)
3133 // Some other file here.
3136 } while (jarentry != null);
3138 resolveFrefedSequences();
3139 } catch (IOException ex)
3141 ex.printStackTrace();
3142 errorMessage = "Couldn't locate Jalview XML file : " + file;
3143 jalview.bin.Console.errPrintln(
3144 "Exception whilst loading jalview XML file : " + ex + "\n");
3145 } catch (Exception ex)
3148 .errPrintln("Parsing as Jalview Version 2 file failed.");
3149 ex.printStackTrace(System.err);
3150 if (attemptversion1parse)
3152 // used to attempt to parse as V1 castor-generated xml
3154 if (Desktop.instance != null)
3156 Desktop.instance.stopLoading();
3160 jalview.bin.Console.outPrintln("Successfully loaded archive file");
3163 ex.printStackTrace();
3165 jalview.bin.Console.errPrintln(
3166 "Exception whilst loading jalview XML file : " + ex + "\n");
3167 } catch (OutOfMemoryError e)
3169 // Don't use the OOM Window here
3170 errorMessage = "Out of memory loading jalview XML file";
3172 .errPrintln("Out of memory whilst loading jalview XML file");
3173 e.printStackTrace();
3177 * Regather multiple views (with the same sequence set id) to the frame (if
3178 * any) that is flagged as the one to gather to, i.e. convert them to tabbed
3179 * views instead of separate frames. Note this doesn't restore a state where
3180 * some expanded views in turn have tabbed views - the last "first tab" read
3181 * in will play the role of gatherer for all.
3183 for (AlignFrame fr : gatherToThisFrame.values())
3185 Desktop.instance.gatherViews(fr);
3188 restoreSplitFrames();
3189 for (AlignmentI ds : importedDatasets.keySet())
3191 if (ds.getCodonFrames() != null)
3193 StructureSelectionManager
3194 .getStructureSelectionManager(Desktop.instance)
3195 .registerMappings(ds.getCodonFrames());
3198 if (errorMessage != null)
3203 if (Desktop.instance != null)
3205 Desktop.instance.stopLoading();
3212 * Try to reconstruct and display SplitFrame windows, where each contains
3213 * complementary dna and protein alignments. Done by pairing up AlignFrame
3214 * objects (created earlier) which have complementary viewport ids associated.
3216 protected void restoreSplitFrames()
3218 List<SplitFrame> gatherTo = new ArrayList<>();
3219 List<AlignFrame> addedToSplitFrames = new ArrayList<>();
3220 Map<String, AlignFrame> dna = new HashMap<>();
3223 * Identify the DNA alignments
3225 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3228 AlignFrame af = candidate.getValue();
3229 if (af.getViewport().getAlignment().isNucleotide())
3231 dna.put(candidate.getKey().getId(), af);
3236 * Try to match up the protein complements
3238 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3241 AlignFrame af = candidate.getValue();
3242 if (!af.getViewport().getAlignment().isNucleotide())
3244 String complementId = candidate.getKey().getComplementId();
3245 // only non-null complements should be in the Map
3246 if (complementId != null && dna.containsKey(complementId))
3248 final AlignFrame dnaFrame = dna.get(complementId);
3249 SplitFrame sf = createSplitFrame(dnaFrame, af);
3250 addedToSplitFrames.add(dnaFrame);
3251 addedToSplitFrames.add(af);
3252 dnaFrame.setMenusForViewport();
3253 af.setMenusForViewport();
3254 if (af.getViewport().isGatherViewsHere())
3263 * Open any that we failed to pair up (which shouldn't happen!) as
3264 * standalone AlignFrame's.
3266 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3269 AlignFrame af = candidate.getValue();
3270 if (!addedToSplitFrames.contains(af))
3272 Viewport view = candidate.getKey();
3273 Desktop.addInternalFrame(af, view.getTitle(),
3274 safeInt(view.getWidth()), safeInt(view.getHeight()));
3275 af.setMenusForViewport();
3276 jalview.bin.Console.errPrintln("Failed to restore view "
3277 + view.getTitle() + " to split frame");
3282 * Gather back into tabbed views as flagged.
3284 for (SplitFrame sf : gatherTo)
3286 Desktop.instance.gatherViews(sf);
3289 splitFrameCandidates.clear();
3293 * Construct and display one SplitFrame holding DNA and protein alignments.
3296 * @param proteinFrame
3299 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
3300 AlignFrame proteinFrame)
3302 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
3303 String title = MessageManager.getString("label.linked_view_title");
3304 int width = (int) dnaFrame.getBounds().getWidth();
3305 int height = (int) (dnaFrame.getBounds().getHeight()
3306 + proteinFrame.getBounds().getHeight() + 50);
3309 * SplitFrame location is saved to both enclosed frames
3311 splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
3312 Desktop.addInternalFrame(splitFrame, title, width, height);
3315 * And compute cDNA consensus (couldn't do earlier with consensus as
3316 * mappings were not yet present)
3318 proteinFrame.getViewport().alignmentChanged(proteinFrame.alignPanel);
3324 * check errorMessage for a valid error message and raise an error box in the
3325 * GUI or write the current errorMessage to stderr and then clear the error
3328 protected void reportErrors()
3330 reportErrors(false);
3333 protected void reportErrors(final boolean saving)
3335 if (errorMessage != null)
3337 final String finalErrorMessage = errorMessage;
3340 javax.swing.SwingUtilities.invokeLater(new Runnable()
3345 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
3347 "Error " + (saving ? "saving" : "loading")
3349 JvOptionPane.WARNING_MESSAGE);
3355 jalview.bin.Console.errPrintln(
3356 "Problem loading Jalview file: " + errorMessage);
3359 errorMessage = null;
3362 Map<String, String> alreadyLoadedPDB = new HashMap<>();
3365 * when set, local views will be updated from view stored in JalviewXML
3366 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
3367 * sync if this is set to true.
3369 private final boolean updateLocalViews = false;
3372 * Returns the path to a temporary file holding the PDB file for the given PDB
3373 * id. The first time of asking, searches for a file of that name in the
3374 * Jalview project jar, and copies it to a new temporary file. Any repeat
3375 * requests just return the path to the file previously created.
3381 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
3384 if (alreadyLoadedPDB.containsKey(pdbId))
3386 return alreadyLoadedPDB.get(pdbId).toString();
3389 String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
3391 if (tempFile != null)
3393 alreadyLoadedPDB.put(pdbId, tempFile);
3399 * Copies the jar entry of given name to a new temporary file and returns the
3400 * path to the file, or null if the entry is not found.
3403 * @param jarEntryName
3405 * a prefix for the temporary file name, must be at least three
3407 * @param suffixModel
3408 * null or original file - so new file can be given the same suffix
3412 protected String copyJarEntry(jarInputStreamProvider jprovider,
3413 String jarEntryName, String prefix, String suffixModel)
3415 String suffix = ".tmp";
3416 if (suffixModel == null)
3418 suffixModel = jarEntryName;
3420 int sfpos = suffixModel.lastIndexOf(".");
3421 if (sfpos > -1 && sfpos < (suffixModel.length() - 1))
3423 suffix = "." + suffixModel.substring(sfpos + 1);
3426 try (JarInputStream jin = jprovider.getJarInputStream())
3428 JarEntry entry = null;
3431 entry = jin.getNextJarEntry();
3432 } while (entry != null && !entry.getName().equals(jarEntryName));
3436 // in = new BufferedReader(new InputStreamReader(jin, UTF_8));
3437 File outFile = File.createTempFile(prefix, suffix);
3438 outFile.deleteOnExit();
3439 try (OutputStream os = new FileOutputStream(outFile))
3443 String t = outFile.getAbsolutePath();
3449 "Couldn't find entry in Jalview Jar for " + jarEntryName);
3451 } catch (Exception ex)
3453 ex.printStackTrace();
3459 private class JvAnnotRow
3461 public JvAnnotRow(int i, AlignmentAnnotation jaa)
3468 * persisted version of annotation row from which to take vis properties
3470 public jalview.datamodel.AlignmentAnnotation template;
3473 * original position of the annotation row in the alignment
3479 * Load alignment frame from jalview XML DOM object
3481 * @param jalviewModel
3484 * filename source string
3485 * @param loadTreesAndStructures
3486 * when false only create Viewport
3488 * data source provider
3489 * @return alignment frame created from view stored in DOM
3491 AlignFrame loadFromObject(JalviewModel jalviewModel, String file,
3492 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
3494 SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet()
3496 List<Sequence> vamsasSeqs = vamsasSet.getSequence();
3498 // JalviewModelSequence jms = object.getJalviewModelSequence();
3500 // Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
3502 Viewport view = (jalviewModel.getViewport().size() > 0)
3503 ? jalviewModel.getViewport().get(0)
3506 // ////////////////////////////////
3507 // INITIALISE ALIGNMENT SEQUENCESETID AND VIEWID
3510 // If we just load in the same jar file again, the sequenceSetId
3511 // will be the same, and we end up with multiple references
3512 // to the same sequenceSet. We must modify this id on load
3513 // so that each load of the file gives a unique id
3516 * used to resolve correct alignment dataset for alignments with multiple
3519 String uniqueSeqSetId = null;
3520 String viewId = null;
3523 uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
3524 viewId = (view.getId() == null ? null
3525 : view.getId() + uniqueSetSuffix);
3528 // ////////////////////////////////
3531 List<SequenceI> hiddenSeqs = null;
3533 List<SequenceI> tmpseqs = new ArrayList<>();
3535 boolean multipleView = false;
3536 SequenceI referenceseqForView = null;
3537 // JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
3538 List<JSeq> jseqs = jalviewModel.getJSeq();
3539 int vi = 0; // counter in vamsasSeq array
3540 for (int i = 0; i < jseqs.size(); i++)
3542 JSeq jseq = jseqs.get(i);
3543 String seqId = jseq.getId();
3545 SequenceI tmpSeq = seqRefIds.get(seqId);
3548 if (!incompleteSeqs.containsKey(seqId))
3550 // may not need this check, but keep it for at least 2.9,1 release
3551 if (tmpSeq.getStart() != jseq.getStart()
3552 || tmpSeq.getEnd() != jseq.getEnd())
3554 jalview.bin.Console.errPrintln(String.format(
3555 "Warning JAL-2154 regression: updating start/end for sequence %s from %d/%d to %d/%d",
3556 tmpSeq.getName(), tmpSeq.getStart(), tmpSeq.getEnd(),
3557 jseq.getStart(), jseq.getEnd()));
3562 incompleteSeqs.remove(seqId);
3564 if (vamsasSeqs.size() > vi
3565 && vamsasSeqs.get(vi).getId().equals(seqId))
3567 // most likely we are reading a dataset XML document so
3568 // update from vamsasSeq section of XML for this sequence
3569 tmpSeq.setName(vamsasSeqs.get(vi).getName());
3570 tmpSeq.setDescription(vamsasSeqs.get(vi).getDescription());
3571 tmpSeq.setSequence(vamsasSeqs.get(vi).getSequence());
3576 // reading multiple views, so vamsasSeq set is a subset of JSeq
3577 multipleView = true;
3579 tmpSeq.setStart(jseq.getStart());
3580 tmpSeq.setEnd(jseq.getEnd());
3581 tmpseqs.add(tmpSeq);
3585 Sequence vamsasSeq = vamsasSeqs.get(vi);
3586 tmpSeq = new jalview.datamodel.Sequence(vamsasSeq.getName(),
3587 vamsasSeq.getSequence());
3588 tmpSeq.setDescription(vamsasSeq.getDescription());
3589 tmpSeq.setStart(jseq.getStart());
3590 tmpSeq.setEnd(jseq.getEnd());
3591 tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
3592 seqRefIds.put(vamsasSeq.getId(), tmpSeq);
3593 tmpseqs.add(tmpSeq);
3597 if (safeBoolean(jseq.isViewreference()))
3599 referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
3602 if (jseq.isHidden() != null && jseq.isHidden().booleanValue())
3604 if (hiddenSeqs == null)
3606 hiddenSeqs = new ArrayList<>();
3609 hiddenSeqs.add(tmpSeq);
3614 // Create the alignment object from the sequence set
3615 // ///////////////////////////////
3616 SequenceI[] orderedSeqs = tmpseqs
3617 .toArray(new SequenceI[tmpseqs.size()]);
3619 AlignmentI al = null;
3620 // so we must create or recover the dataset alignment before going further
3621 // ///////////////////////////////
3622 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
3624 // older jalview projects do not have a dataset - so creat alignment and
3626 al = new Alignment(orderedSeqs);
3627 al.setDataset(null);
3631 boolean isdsal = jalviewModel.getViewport().isEmpty();
3634 // we are importing a dataset record, so
3635 // recover reference to an alignment already materialsed as dataset
3636 al = getDatasetFor(vamsasSet.getDatasetId());
3640 // materialse the alignment
3641 al = new Alignment(orderedSeqs);
3645 addDatasetRef(vamsasSet.getDatasetId(), al);
3648 // finally, verify all data in vamsasSet is actually present in al
3649 // passing on flag indicating if it is actually a stored dataset
3650 recoverDatasetFor(vamsasSet, al, isdsal, uniqueSeqSetId);
3653 if (referenceseqForView != null)
3655 al.setSeqrep(referenceseqForView);
3657 // / Add the alignment properties
3658 for (int i = 0; i < vamsasSet.getSequenceSetProperties().size(); i++)
3660 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties()
3662 al.setProperty(ssp.getKey(), ssp.getValue());
3665 // ///////////////////////////////
3667 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
3670 // load sequence features, database references and any associated PDB
3671 // structures for the alignment
3673 // prior to 2.10, this part would only be executed the first time a
3674 // sequence was encountered, but not afterwards.
3675 // now, for 2.10 projects, this is also done if the xml doc includes
3676 // dataset sequences not actually present in any particular view.
3678 for (int i = 0; i < vamsasSeqs.size(); i++)
3680 JSeq jseq = jseqs.get(i);
3681 if (jseq.getFeatures().size() > 0)
3683 List<Feature> features = jseq.getFeatures();
3684 for (int f = 0; f < features.size(); f++)
3686 Feature feat = features.get(f);
3687 SequenceFeature sf = new SequenceFeature(feat.getType(),
3688 feat.getDescription(), feat.getBegin(), feat.getEnd(),
3689 safeFloat(feat.getScore()), feat.getFeatureGroup());
3690 sf.setStatus(feat.getStatus());
3693 * load any feature attributes - include map-valued attributes
3695 Map<String, Map<String, String>> mapAttributes = new HashMap<>();
3696 for (int od = 0; od < feat.getOtherData().size(); od++)
3698 OtherData keyValue = feat.getOtherData().get(od);
3699 String attributeName = keyValue.getKey();
3700 String attributeValue = keyValue.getValue();
3701 if (attributeName.startsWith("LINK"))
3703 sf.addLink(attributeValue);
3707 String subAttribute = keyValue.getKey2();
3708 if (subAttribute == null)
3710 // simple string-valued attribute
3711 sf.setValue(attributeName, attributeValue);
3715 // attribute 'key' has sub-attribute 'key2'
3716 if (!mapAttributes.containsKey(attributeName))
3718 mapAttributes.put(attributeName, new HashMap<>());
3720 mapAttributes.get(attributeName).put(subAttribute,
3725 for (Entry<String, Map<String, String>> mapAttribute : mapAttributes
3728 sf.setValue(mapAttribute.getKey(), mapAttribute.getValue());
3731 // adds feature to datasequence's feature set (since Jalview 2.10)
3732 al.getSequenceAt(i).addSequenceFeature(sf);
3735 if (vamsasSeqs.get(i).getDBRef().size() > 0)
3737 // adds dbrefs to datasequence's set (since Jalview 2.10)
3739 al.getSequenceAt(i).getDatasetSequence() == null
3740 ? al.getSequenceAt(i)
3741 : al.getSequenceAt(i).getDatasetSequence(),
3744 if (jseq.getPdbids().size() > 0)
3746 List<Pdbids> ids = jseq.getPdbids();
3747 for (int p = 0; p < ids.size(); p++)
3749 Pdbids pdbid = ids.get(p);
3750 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
3751 entry.setId(pdbid.getId());
3752 if (pdbid.getType() != null)
3754 if (PDBEntry.Type.getType(pdbid.getType()) != null)
3756 entry.setType(PDBEntry.Type.getType(pdbid.getType()));
3760 entry.setType(PDBEntry.Type.FILE);
3763 // jprovider is null when executing 'New View'
3764 if (pdbid.getFile() != null && jprovider != null)
3766 if (!pdbloaded.containsKey(pdbid.getFile()))
3768 entry.setFile(loadPDBFile(jprovider, pdbid.getId(),
3773 entry.setFile(pdbloaded.get(pdbid.getId()).toString());
3777 if (pdbid.getPdbentryItem() != null)
3779 for (PdbentryItem item : pdbid.getPdbentryItem())
3781 for (Property pr : item.getProperty())
3783 entry.setProperty(pr.getName(), pr.getValue());
3788 for (Property prop : pdbid.getProperty())
3790 entry.setProperty(prop.getName(), prop.getValue());
3792 StructureSelectionManager
3793 .getStructureSelectionManager(Desktop.instance)
3794 .registerPDBEntry(entry);
3795 // adds PDBEntry to datasequence's set (since Jalview 2.10)
3796 if (al.getSequenceAt(i).getDatasetSequence() != null)
3798 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
3802 al.getSequenceAt(i).addPDBId(entry);
3807 } // end !multipleview
3809 // ///////////////////////////////
3810 // LOAD SEQUENCE MAPPINGS
3812 if (vamsasSet.getAlcodonFrame().size() > 0)
3814 // TODO Potentially this should only be done once for all views of an
3816 List<AlcodonFrame> alc = vamsasSet.getAlcodonFrame();
3817 for (int i = 0; i < alc.size(); i++)
3819 AlignedCodonFrame cf = new AlignedCodonFrame();
3820 if (alc.get(i).getAlcodMap().size() > 0)
3822 List<AlcodMap> maps = alc.get(i).getAlcodMap();
3823 for (int m = 0; m < maps.size(); m++)
3825 AlcodMap map = maps.get(m);
3826 SequenceI dnaseq = seqRefIds.get(map.getDnasq());
3828 jalview.datamodel.Mapping mapping = null;
3829 // attach to dna sequence reference.
3830 if (map.getMapping() != null)
3832 mapping = addMapping(map.getMapping());
3833 if (dnaseq != null && mapping.getTo() != null)
3835 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
3841 .add(newAlcodMapRef(map.getDnasq(), cf, mapping));
3845 al.addCodonFrame(cf);
3850 // ////////////////////////////////
3852 List<JvAnnotRow> autoAlan = new ArrayList<>();
3855 * store any annotations which forward reference a group's ID
3857 Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
3859 if (vamsasSet.getAnnotation().size()/*Count()*/ > 0)
3861 List<Annotation> an = vamsasSet.getAnnotation();
3863 for (int i = 0; i < an.size(); i++)
3865 Annotation annotation = an.get(i);
3868 * test if annotation is automatically calculated for this view only
3870 boolean autoForView = false;
3871 if (annotation.getLabel().equals("Quality")
3872 || annotation.getLabel().equals("Conservation")
3873 || annotation.getLabel().equals("Consensus"))
3875 // Kludge for pre 2.5 projects which lacked the autocalculated flag
3877 // JAXB has no has() test; schema defaults value to false
3878 // if (!annotation.hasAutoCalculated())
3880 // annotation.setAutoCalculated(true);
3883 if (autoForView || annotation.isAutoCalculated())
3885 // remove ID - we don't recover annotation from other views for
3886 // view-specific annotation
3887 annotation.setId(null);
3890 // set visibility for other annotation in this view
3891 String annotationId = annotation.getId();
3892 if (annotationId != null && annotationIds.containsKey(annotationId))
3894 AlignmentAnnotation jda = annotationIds.get(annotationId);
3895 // in principle Visible should always be true for annotation displayed
3896 // in multiple views
3897 if (annotation.isVisible() != null)
3899 jda.visible = annotation.isVisible();
3902 al.addAnnotation(jda);
3906 // Construct new annotation from model.
3907 List<AnnotationElement> ae = annotation.getAnnotationElement();
3908 jalview.datamodel.Annotation[] anot = null;
3909 java.awt.Color firstColour = null;
3911 if (!annotation.isScoreOnly())
3913 anot = new jalview.datamodel.Annotation[al.getWidth()];
3914 for (int aa = 0; aa < ae.size() && aa < anot.length; aa++)
3916 AnnotationElement annElement = ae.get(aa);
3917 anpos = annElement.getPosition();
3919 if (anpos >= anot.length)
3924 float value = safeFloat(annElement.getValue());
3925 anot[anpos] = new jalview.datamodel.Annotation(
3926 annElement.getDisplayCharacter(),
3927 annElement.getDescription(),
3928 (annElement.getSecondaryStructure() == null
3929 || annElement.getSecondaryStructure()
3933 .getSecondaryStructure()
3936 anot[anpos].colour = new Color(safeInt(annElement.getColour()));
3937 if (firstColour == null)
3939 firstColour = anot[anpos].colour;
3943 jalview.datamodel.AlignmentAnnotation jaa = null;
3945 if (annotation.isGraph())
3947 float llim = 0, hlim = 0;
3948 // if (autoForView || an[i].isAutoCalculated()) {
3951 jaa = new jalview.datamodel.AlignmentAnnotation(
3952 annotation.getLabel(), annotation.getDescription(), anot,
3953 llim, hlim, safeInt(annotation.getGraphType()));
3955 jaa.graphGroup = safeInt(annotation.getGraphGroup());
3956 jaa._linecolour = firstColour;
3957 if (annotation.getThresholdLine() != null)
3959 jaa.setThreshold(new jalview.datamodel.GraphLine(
3960 safeFloat(annotation.getThresholdLine().getValue()),
3961 annotation.getThresholdLine().getLabel(),
3962 new java.awt.Color(safeInt(
3963 annotation.getThresholdLine().getColour()))));
3965 if (autoForView || annotation.isAutoCalculated())
3967 // Hardwire the symbol display line to ensure that labels for
3968 // histograms are displayed
3974 jaa = new jalview.datamodel.AlignmentAnnotation(
3975 annotation.getLabel(), annotation.getDescription(), anot);
3976 jaa._linecolour = firstColour;
3978 // register new annotation
3979 if (annotation.getId() != null)
3981 annotationIds.put(annotation.getId(), jaa);
3982 jaa.annotationId = annotation.getId();
3984 // recover sequence association
3985 String sequenceRef = annotation.getSequenceRef();
3986 if (sequenceRef != null)
3988 // from 2.9 sequenceRef is to sequence id (JAL-1781)
3989 SequenceI sequence = seqRefIds.get(sequenceRef);
3990 if (sequence == null)
3992 // in pre-2.9 projects sequence ref is to sequence name
3993 sequence = al.findName(sequenceRef);
3995 if (sequence != null)
3997 jaa.createSequenceMapping(sequence, 1, true);
3998 sequence.addAlignmentAnnotation(jaa);
4001 // and make a note of any group association
4002 if (annotation.getGroupRef() != null
4003 && annotation.getGroupRef().length() > 0)
4005 List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
4006 .get(annotation.getGroupRef());
4009 aal = new ArrayList<>();
4010 groupAnnotRefs.put(annotation.getGroupRef(), aal);
4015 if (annotation.getScore() != null)
4017 jaa.setScore(annotation.getScore().doubleValue());
4019 if (annotation.isVisible() != null)
4021 jaa.visible = annotation.isVisible().booleanValue();
4024 if (annotation.isCentreColLabels() != null)
4026 jaa.centreColLabels = annotation.isCentreColLabels()
4030 if (annotation.isScaleColLabels() != null)
4032 jaa.scaleColLabel = annotation.isScaleColLabels().booleanValue();
4034 if (annotation.isAutoCalculated())
4036 // newer files have an 'autoCalculated' flag and store calculation
4037 // state in viewport properties
4038 jaa.autoCalculated = true; // means annotation will be marked for
4039 // update at end of load.
4041 if (annotation.getGraphHeight() != null)
4043 jaa.graphHeight = annotation.getGraphHeight().intValue();
4045 jaa.belowAlignment = annotation.isBelowAlignment();
4046 jaa.setCalcId(annotation.getCalcId());
4047 if (annotation.getProperty().size() > 0)
4049 for (jalview.xml.binding.jalview.Property prop : annotation
4052 jaa.setProperty(prop.getName(), prop.getValue());
4055 if (jaa.graph == AlignmentAnnotation.CONTACT_MAP)
4057 if (annotation.getContactmatrix() != null
4058 && annotation.getContactmatrix().size() > 0)
4060 for (MatrixType xmlmat : annotation.getContactmatrix())
4062 if (PAEContactMatrix.PAEMATRIX.equals(xmlmat.getType()))
4064 if (!xmlmat.getRows().equals(xmlmat.getCols()))
4066 Console.error("Can't handle non square PAE Matrices");
4070 float[][] elements = ContactMatrix
4071 .fromFloatStringToContacts(xmlmat.getElements(),
4072 xmlmat.getCols().intValue(),
4073 xmlmat.getRows().intValue());
4074 jalview.util.MapList mapping = null;
4075 if (xmlmat.getMapping() != null)
4077 MapListType m = xmlmat.getMapping();
4078 // Mapping m = dr.getMapping();
4079 int fr[] = new int[m.getMapListFrom().size() * 2];
4080 Iterator<MapListFrom> from = m.getMapListFrom()
4081 .iterator();// enumerateMapListFrom();
4082 for (int _i = 0; from.hasNext(); _i += 2)
4084 MapListFrom mf = from.next();
4085 fr[_i] = mf.getStart();
4086 fr[_i + 1] = mf.getEnd();
4088 int fto[] = new int[m.getMapListTo().size() * 2];
4089 Iterator<MapListTo> to = m.getMapListTo().iterator();// enumerateMapListTo();
4090 for (int _i = 0; to.hasNext(); _i += 2)
4092 MapListTo mf = to.next();
4093 fto[_i] = mf.getStart();
4094 fto[_i + 1] = mf.getEnd();
4097 mapping = new jalview.util.MapList(fr, fto,
4098 m.getMapFromUnit().intValue(),
4099 m.getMapToUnit().intValue());
4101 List<BitSet> newgroups = new ArrayList<BitSet>();
4102 if (xmlmat.getGroups().size() > 0)
4104 for (String sgroup : xmlmat.getGroups())
4106 newgroups.add(deStringifyBitset(sgroup));
4109 String nwk = xmlmat.getNewick().size() > 0
4110 ? xmlmat.getNewick().get(0)
4112 if (xmlmat.getNewick().size() > 1)
4115 "Ignoring additional clusterings for contact matrix");
4117 String treeMethod = xmlmat.getTreeMethod();
4118 double thresh = xmlmat.getCutHeight() != null
4119 ? xmlmat.getCutHeight()
4121 GroupSet grpset = new GroupSet();
4122 grpset.restoreGroups(newgroups, treeMethod, nwk, thresh);
4123 PAEContactMatrix newpae = new PAEContactMatrix(
4124 jaa.sequenceRef, mapping, elements, grpset);
4125 jaa.sequenceRef.addContactListFor(jaa, newpae);
4130 Console.error("Ignoring CONTACT_MAP annotation with type "
4131 + xmlmat.getType());
4137 if (jaa.autoCalculated)
4139 autoAlan.add(new JvAnnotRow(i, jaa));
4142 // if (!autoForView)
4144 // add autocalculated group annotation and any user created annotation
4146 al.addAnnotation(jaa);
4150 // ///////////////////////
4152 // Create alignment markup and styles for this view
4153 if (jalviewModel.getJGroup().size() > 0)
4155 List<JGroup> groups = jalviewModel.getJGroup();
4156 boolean addAnnotSchemeGroup = false;
4157 for (int i = 0; i < groups.size(); i++)
4159 JGroup jGroup = groups.get(i);
4160 ColourSchemeI cs = null;
4161 if (jGroup.getColour() != null)
4163 if (jGroup.getColour().startsWith("ucs"))
4165 cs = getUserColourScheme(jalviewModel, jGroup.getColour());
4167 else if (jGroup.getColour().equals("AnnotationColourGradient")
4168 && jGroup.getAnnotationColours() != null)
4170 addAnnotSchemeGroup = true;
4174 cs = ColourSchemeProperty.getColourScheme(null, al,
4175 jGroup.getColour());
4178 int pidThreshold = safeInt(jGroup.getPidThreshold());
4180 Vector<SequenceI> seqs = new Vector<>();
4182 for (int s = 0; s < jGroup.getSeq().size(); s++)
4184 String seqId = jGroup.getSeq().get(s);
4185 SequenceI ts = seqRefIds.get(seqId);
4189 seqs.addElement(ts);
4193 if (seqs.size() < 1)
4198 SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
4199 safeBoolean(jGroup.isDisplayBoxes()),
4200 safeBoolean(jGroup.isDisplayText()),
4201 safeBoolean(jGroup.isColourText()),
4202 safeInt(jGroup.getStart()), safeInt(jGroup.getEnd()));
4203 sg.getGroupColourScheme().setThreshold(pidThreshold, true);
4204 sg.getGroupColourScheme()
4205 .setConservationInc(safeInt(jGroup.getConsThreshold()));
4206 sg.setOutlineColour(new Color(safeInt(jGroup.getOutlineColour())));
4208 sg.textColour = new Color(safeInt(jGroup.getTextCol1()));
4209 sg.textColour2 = new Color(safeInt(jGroup.getTextCol2()));
4210 sg.setShowNonconserved(safeBoolean(jGroup.isShowUnconserved()));
4211 sg.thresholdTextColour = safeInt(jGroup.getTextColThreshold());
4212 // attributes with a default in the schema are never null
4213 sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
4214 sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
4215 sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
4216 sg.setIgnoreGapsConsensus(jGroup.isIgnoreGapsinConsensus());
4217 if (jGroup.getConsThreshold() != null
4218 && jGroup.getConsThreshold().intValue() != 0)
4220 Conservation c = new Conservation("All", sg.getSequences(null), 0,
4223 c.verdict(false, 25);
4224 sg.cs.setConservation(c);
4227 if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
4229 // re-instate unique group/annotation row reference
4230 List<AlignmentAnnotation> jaal = groupAnnotRefs
4231 .get(jGroup.getId());
4234 for (AlignmentAnnotation jaa : jaal)
4237 if (jaa.autoCalculated)
4239 // match up and try to set group autocalc alignment row for this
4241 if (jaa.label.startsWith("Consensus for "))
4243 sg.setConsensus(jaa);
4245 // match up and try to set group autocalc alignment row for this
4247 if (jaa.label.startsWith("Conservation for "))
4249 sg.setConservationRow(jaa);
4256 if (addAnnotSchemeGroup)
4258 // reconstruct the annotation colourscheme
4260 constructAnnotationColour(jGroup.getAnnotationColours(),
4261 null, al, jalviewModel, false));
4267 // only dataset in this model, so just return.
4270 // ///////////////////////////////
4273 AlignFrame af = null;
4274 AlignViewport av = null;
4275 // now check to see if we really need to create a new viewport.
4276 if (multipleView && viewportsAdded.size() == 0)
4278 // We recovered an alignment for which a viewport already exists.
4279 // TODO: fix up any settings necessary for overlaying stored state onto
4280 // state recovered from another document. (may not be necessary).
4281 // we may need a binding from a viewport in memory to one recovered from
4283 // and then recover its containing af to allow the settings to be applied.
4284 // TODO: fix for vamsas demo
4285 jalview.bin.Console.errPrintln(
4286 "About to recover a viewport for existing alignment: Sequence set ID is "
4288 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
4289 if (seqsetobj != null)
4291 if (seqsetobj instanceof String)
4293 uniqueSeqSetId = (String) seqsetobj;
4294 jalview.bin.Console.errPrintln(
4295 "Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
4300 jalview.bin.Console.errPrintln(
4301 "Warning : Collision between sequence set ID string and existing jalview object mapping.");
4307 * indicate that annotation colours are applied across all groups (pre
4308 * Jalview 2.8.1 behaviour)
4310 boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan("2.8.1",
4311 jalviewModel.getVersion());
4313 AlignmentPanel ap = null;
4314 boolean isnewview = true;
4317 // Check to see if this alignment already has a view id == viewId
4318 jalview.gui.AlignmentPanel views[] = Desktop
4319 .getAlignmentPanels(uniqueSeqSetId);
4320 if (views != null && views.length > 0)
4322 for (int v = 0; v < views.length; v++)
4324 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
4326 // recover the existing alignpanel, alignframe, viewport
4327 af = views[v].alignFrame;
4330 // TODO: could even skip resetting view settings if we don't want to
4331 // change the local settings from other jalview processes
4340 af = loadViewport(file, jseqs, hiddenSeqs, al, jalviewModel, view,
4341 uniqueSeqSetId, viewId, autoAlan);
4342 av = af.getViewport();
4347 * Load any trees, PDB structures and viewers, Overview
4349 * Not done if flag is false (when this method is used for New View)
4351 if (loadTreesAndStructures)
4353 loadTrees(jalviewModel, view, af, av, ap);
4354 loadPCAViewers(jalviewModel, ap);
4355 loadPDBStructures(jprovider, jseqs, af, ap);
4356 loadRnaViewers(jprovider, jseqs, ap);
4357 loadOverview(view, jalviewModel.getVersion(), af);
4359 // and finally return.
4364 * Load Overview window, restoring colours, 'show hidden regions' flag, title
4365 * and geometry as saved
4370 protected void loadOverview(Viewport view, String version, AlignFrame af)
4372 if (!isVersionStringLaterThan("2.11.3", version)
4373 && view.getOverview() == null)
4378 * first close any Overview that was opened automatically
4379 * (if so configured in Preferences) so that the view is
4380 * restored in the same state as saved
4382 af.alignPanel.closeOverviewPanel();
4384 Overview overview = view.getOverview();
4385 if (overview != null)
4387 OverviewPanel overviewPanel = af
4388 .openOverviewPanel(overview.isShowHidden());
4389 overviewPanel.setTitle(overview.getTitle());
4390 overviewPanel.setFrameBounds(overview.getXpos(), overview.getYpos(),
4391 overview.getWidth(), overview.getHeight());
4392 Color gap = new Color(overview.getGapColour());
4393 Color residue = new Color(overview.getResidueColour());
4394 Color hidden = new Color(overview.getHiddenColour());
4395 overviewPanel.getCanvas().setColours(gap, residue, hidden);
4400 * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
4401 * panel is restored from separate jar entries, two (gapped and trimmed) per
4402 * sequence and secondary structure.
4404 * Currently each viewer shows just one sequence and structure (gapped and
4405 * trimmed), however this method is designed to support multiple sequences or
4406 * structures in viewers if wanted in future.
4412 private void loadRnaViewers(jarInputStreamProvider jprovider,
4413 List<JSeq> jseqs, AlignmentPanel ap)
4416 * scan the sequences for references to viewers; create each one the first
4417 * time it is referenced, add Rna models to existing viewers
4419 for (JSeq jseq : jseqs)
4421 for (int i = 0; i < jseq.getRnaViewer().size(); i++)
4423 RnaViewer viewer = jseq.getRnaViewer().get(i);
4424 AppVarna appVarna = findOrCreateVarnaViewer(viewer, uniqueSetSuffix,
4427 for (int j = 0; j < viewer.getSecondaryStructure().size(); j++)
4429 SecondaryStructure ss = viewer.getSecondaryStructure().get(j);
4430 SequenceI seq = seqRefIds.get(jseq.getId());
4431 AlignmentAnnotation ann = this.annotationIds
4432 .get(ss.getAnnotationId());
4435 * add the structure to the Varna display (with session state copied
4436 * from the jar to a temporary file)
4438 boolean gapped = safeBoolean(ss.isGapped());
4439 String rnaTitle = ss.getTitle();
4440 String sessionState = ss.getViewerState();
4441 String tempStateFile = copyJarEntry(jprovider, sessionState,
4443 RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
4444 appVarna.addModelSession(rna, rnaTitle, tempStateFile);
4446 appVarna.setInitialSelection(safeInt(viewer.getSelectedRna()));
4452 * Locate and return an already instantiated matching AppVarna, or create one
4456 * @param viewIdSuffix
4460 protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
4461 String viewIdSuffix, AlignmentPanel ap)
4464 * on each load a suffix is appended to the saved viewId, to avoid conflicts
4465 * if load is repeated
4467 String postLoadId = viewer.getViewId() + viewIdSuffix;
4468 for (JInternalFrame frame : getAllFrames())
4470 if (frame instanceof AppVarna)
4472 AppVarna varna = (AppVarna) frame;
4473 if (postLoadId.equals(varna.getViewId()))
4475 // this viewer is already instantiated
4476 // could in future here add ap as another 'parent' of the
4477 // AppVarna window; currently just 1-to-many
4484 * viewer not found - make it
4486 RnaViewerModel model = new RnaViewerModel(postLoadId, viewer.getTitle(),
4487 safeInt(viewer.getXpos()), safeInt(viewer.getYpos()),
4488 safeInt(viewer.getWidth()), safeInt(viewer.getHeight()),
4489 safeInt(viewer.getDividerLocation()));
4490 AppVarna varna = new AppVarna(model, ap);
4496 * Load any saved trees
4504 protected void loadTrees(JalviewModel jm, Viewport view, AlignFrame af,
4505 AlignViewport av, AlignmentPanel ap)
4507 // TODO result of automated refactoring - are all these parameters needed?
4510 for (int t = 0; t < jm.getTree().size(); t++)
4513 Tree tree = jm.getTree().get(t);
4515 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
4518 if (tree.isColumnWise())
4520 AlignmentAnnotation aa = annotationIds
4521 .get(tree.getColumnReference());
4525 "Null alignment annotation when restoring columnwise tree");
4527 tp = af.showColumnWiseTree(new NewickFile(tree.getNewick()), aa,
4528 tree.getTitle(), safeInt(tree.getWidth()),
4529 safeInt(tree.getHeight()), safeInt(tree.getXpos()),
4530 safeInt(tree.getYpos()));
4535 tp = af.showNewickTree(new NewickFile(tree.getNewick()),
4536 tree.getTitle(), safeInt(tree.getWidth()),
4537 safeInt(tree.getHeight()), safeInt(tree.getXpos()),
4538 safeInt(tree.getYpos()));
4540 if (tree.getId() != null)
4542 // perhaps bind the tree id to something ?
4547 // update local tree attributes ?
4548 // TODO: should check if tp has been manipulated by user - if so its
4549 // settings shouldn't be modified
4550 tp.setTitle(tree.getTitle());
4551 tp.setBounds(new Rectangle(safeInt(tree.getXpos()),
4552 safeInt(tree.getYpos()), safeInt(tree.getWidth()),
4553 safeInt(tree.getHeight())));
4554 tp.setViewport(av); // af.viewport;
4555 // TODO: verify 'associate with all views' works still
4556 tp.getTreeCanvas().setViewport(av); // af.viewport;
4557 tp.getTreeCanvas().setAssociatedPanel(ap); // af.alignPanel;
4559 tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
4563 "There was a problem recovering stored Newick tree: \n"
4564 + tree.getNewick());
4568 tp.fitToWindow.setState(safeBoolean(tree.isFitToWindow()));
4569 tp.fitToWindow_actionPerformed(null);
4571 if (tree.getFontName() != null)
4574 new Font(tree.getFontName(), safeInt(tree.getFontStyle()),
4575 safeInt(tree.getFontSize())));
4580 new Font(view.getFontName(), safeInt(view.getFontStyle()),
4581 safeInt(view.getFontSize())));
4584 tp.showPlaceholders(safeBoolean(tree.isMarkUnlinked()));
4585 tp.showBootstrap(safeBoolean(tree.isShowBootstrap()));
4586 tp.showDistances(safeBoolean(tree.isShowDistances()));
4588 tp.getTreeCanvas().setThreshold(safeFloat(tree.getThreshold()));
4590 if (safeBoolean(tree.isCurrentTree()))
4592 af.getViewport().setCurrentTree(tp.getTree());
4596 } catch (Exception ex)
4598 ex.printStackTrace();
4603 * Load and link any saved structure viewers.
4610 protected void loadPDBStructures(jarInputStreamProvider jprovider,
4611 List<JSeq> jseqs, AlignFrame af, AlignmentPanel ap)
4614 * Run through all PDB ids on the alignment, and collect mappings between
4615 * distinct view ids and all sequences referring to that view.
4617 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
4619 for (int i = 0; i < jseqs.size(); i++)
4621 JSeq jseq = jseqs.get(i);
4622 if (jseq.getPdbids().size() > 0)
4624 List<Pdbids> ids = jseq.getPdbids();
4625 for (int p = 0; p < ids.size(); p++)
4627 Pdbids pdbid = ids.get(p);
4628 final int structureStateCount = pdbid.getStructureState().size();
4629 for (int s = 0; s < structureStateCount; s++)
4631 // check to see if we haven't already created this structure view
4632 final StructureState structureState = pdbid.getStructureState()
4634 String sviewid = (structureState.getViewId() == null) ? null
4635 : structureState.getViewId() + uniqueSetSuffix;
4636 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
4637 // Originally : pdbid.getFile()
4638 // : TODO: verify external PDB file recovery still works in normal
4639 // jalview project load
4641 loadPDBFile(jprovider, pdbid.getId(), pdbid.getFile()));
4642 jpdb.setId(pdbid.getId());
4644 int x = safeInt(structureState.getXpos());
4645 int y = safeInt(structureState.getYpos());
4646 int width = safeInt(structureState.getWidth());
4647 int height = safeInt(structureState.getHeight());
4649 // Probably don't need to do this anymore...
4650 // Desktop.desktop.getComponentAt(x, y);
4651 // TODO: NOW: check that this recovers the PDB file correctly.
4652 String pdbFile = loadPDBFile(jprovider, pdbid.getId(),
4654 jalview.datamodel.SequenceI seq = seqRefIds
4655 .get(jseq.getId() + "");
4656 if (sviewid == null)
4658 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width + ","
4661 if (!structureViewers.containsKey(sviewid))
4663 String viewerType = structureState.getType();
4664 if (viewerType == null) // pre Jalview 2.9
4666 viewerType = ViewerType.JMOL.toString();
4668 structureViewers.put(sviewid,
4669 new StructureViewerModel(x, y, width, height, false,
4670 false, true, structureState.getViewId(),
4672 // Legacy pre-2.7 conversion JAL-823 :
4673 // do not assume any view has to be linked for colour by
4677 // assemble String[] { pdb files }, String[] { id for each
4678 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
4679 // seqs_file 2}, boolean[] {
4680 // linkAlignPanel,superposeWithAlignpanel}} from hash
4681 StructureViewerModel jmoldat = structureViewers.get(sviewid);
4682 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
4683 || structureState.isAlignwithAlignPanel());
4686 * Default colour by linked panel to false if not specified (e.g.
4687 * for pre-2.7 projects)
4689 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
4690 colourWithAlignPanel |= structureState.isColourwithAlignPanel();
4691 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
4694 * Default colour by viewer to true if not specified (e.g. for
4697 boolean colourByViewer = jmoldat.isColourByViewer();
4698 colourByViewer &= structureState.isColourByJmol();
4699 jmoldat.setColourByViewer(colourByViewer);
4701 if (jmoldat.getStateData().length() < structureState.getValue()
4702 /*Content()*/.length())
4704 jmoldat.setStateData(structureState.getValue());// Content());
4706 if (pdbid.getFile() != null)
4708 File mapkey = new File(pdbid.getFile());
4709 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
4710 if (seqstrmaps == null)
4712 jmoldat.getFileData().put(mapkey,
4713 seqstrmaps = jmoldat.new StructureData(pdbFile,
4716 if (!seqstrmaps.getSeqList().contains(seq))
4718 seqstrmaps.getSeqList().add(seq);
4724 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");
4725 Console.warn(errorMessage);
4731 // Instantiate the associated structure views
4732 for (Entry<String, StructureViewerModel> entry : structureViewers
4737 createOrLinkStructureViewer(entry, af, ap, jprovider);
4738 } catch (Exception e)
4740 jalview.bin.Console.errPrintln(
4741 "Error loading structure viewer: " + e.getMessage());
4742 // failed - try the next one
4754 protected void createOrLinkStructureViewer(
4755 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
4756 AlignmentPanel ap, jarInputStreamProvider jprovider)
4758 final StructureViewerModel stateData = viewerData.getValue();
4761 * Search for any viewer windows already open from other alignment views
4762 * that exactly match the stored structure state
4764 StructureViewerBase comp = findMatchingViewer(viewerData);
4768 linkStructureViewer(ap, comp, stateData);
4772 String type = stateData.getType();
4775 ViewerType viewerType = ViewerType.valueOf(type);
4776 createStructureViewer(viewerType, viewerData, af, jprovider);
4777 } catch (IllegalArgumentException | NullPointerException e)
4779 // TODO JAL-3619 show error dialog / offer an alternative viewer
4780 Console.error("Invalid structure viewer type: " + type);
4785 * Generates a name for the entry in the project jar file to hold state
4786 * information for a structure viewer
4791 protected String getViewerJarEntryName(String viewId)
4793 return VIEWER_PREFIX + viewId;
4797 * Returns any open frame that matches given structure viewer data. The match
4798 * is based on the unique viewId, or (for older project versions) the frame's
4804 protected StructureViewerBase findMatchingViewer(
4805 Entry<String, StructureViewerModel> viewerData)
4807 final String sviewid = viewerData.getKey();
4808 final StructureViewerModel svattrib = viewerData.getValue();
4809 StructureViewerBase comp = null;
4810 JInternalFrame[] frames = getAllFrames();
4811 for (JInternalFrame frame : frames)
4813 if (frame instanceof StructureViewerBase)
4816 * Post jalview 2.4 schema includes structure view id
4818 if (sviewid != null && ((StructureViewerBase) frame).getViewId()
4821 comp = (StructureViewerBase) frame;
4822 break; // break added in 2.9
4825 * Otherwise test for matching position and size of viewer frame
4827 else if (frame.getX() == svattrib.getX()
4828 && frame.getY() == svattrib.getY()
4829 && frame.getHeight() == svattrib.getHeight()
4830 && frame.getWidth() == svattrib.getWidth())
4832 comp = (StructureViewerBase) frame;
4833 // no break in faint hope of an exact match on viewId
4841 * Link an AlignmentPanel to an existing structure viewer.
4846 * @param useinViewerSuperpos
4847 * @param usetoColourbyseq
4848 * @param viewerColouring
4850 protected void linkStructureViewer(AlignmentPanel ap,
4851 StructureViewerBase viewer, StructureViewerModel stateData)
4853 // NOTE: if the jalview project is part of a shared session then
4854 // view synchronization should/could be done here.
4856 final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
4857 final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
4858 final boolean viewerColouring = stateData.isColourByViewer();
4859 Map<File, StructureData> oldFiles = stateData.getFileData();
4862 * Add mapping for sequences in this view to an already open viewer
4864 final AAStructureBindingModel binding = viewer.getBinding();
4865 for (File id : oldFiles.keySet())
4867 // add this and any other pdb files that should be present in the
4869 StructureData filedat = oldFiles.get(id);
4870 String pdbFile = filedat.getFilePath();
4871 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
4872 binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE,
4874 binding.addSequenceForStructFile(pdbFile, seq);
4876 // and add the AlignmentPanel's reference to the view panel
4877 viewer.addAlignmentPanel(ap);
4878 if (useinViewerSuperpos)
4880 viewer.useAlignmentPanelForSuperposition(ap);
4884 viewer.excludeAlignmentPanelForSuperposition(ap);
4886 if (usetoColourbyseq)
4888 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
4892 viewer.excludeAlignmentPanelForColourbyseq(ap);
4897 * Get all frames within the Desktop.
4901 protected JInternalFrame[] getAllFrames()
4903 JInternalFrame[] frames = null;
4904 // TODO is this necessary - is it safe - risk of hanging?
4909 frames = Desktop.desktop.getAllFrames();
4910 } catch (ArrayIndexOutOfBoundsException e)
4912 // occasional No such child exceptions are thrown here...
4916 } catch (InterruptedException f)
4920 } while (frames == null);
4925 * Answers true if 'version' is equal to or later than 'supported', where each
4926 * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
4927 * changes. Development and test values for 'version' are leniently treated
4931 * - minimum version we are comparing against
4933 * - version of data being processsed
4934 * @return true if version is equal to or later than supported
4936 public static boolean isVersionStringLaterThan(String supported,
4939 if (supported == null || version == null
4940 || version.equalsIgnoreCase("DEVELOPMENT BUILD")
4941 || version.equalsIgnoreCase("Test")
4942 || version.equalsIgnoreCase("AUTOMATED BUILD"))
4944 jalview.bin.Console.errPrintln("Assuming project file with "
4945 + (version == null ? "null" : version)
4946 + " is compatible with Jalview version " + supported);
4951 return StringUtils.compareVersions(version, supported, "b") >= 0;
4955 Vector<JalviewStructureDisplayI> newStructureViewers = null;
4957 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
4959 if (newStructureViewers != null)
4961 sview.getBinding().setFinishedLoadingFromArchive(false);
4962 newStructureViewers.add(sview);
4966 protected void setLoadingFinishedForNewStructureViewers()
4968 if (newStructureViewers != null)
4970 for (JalviewStructureDisplayI sview : newStructureViewers)
4972 sview.getBinding().setFinishedLoadingFromArchive(true);
4974 newStructureViewers.clear();
4975 newStructureViewers = null;
4979 AlignFrame loadViewport(String file, List<JSeq> JSEQ,
4980 List<SequenceI> hiddenSeqs, AlignmentI al, JalviewModel jm,
4981 Viewport view, String uniqueSeqSetId, String viewId,
4982 List<JvAnnotRow> autoAlan)
4984 AlignFrame af = null;
4985 af = new AlignFrame(al, safeInt(view.getWidth()),
4986 safeInt(view.getHeight()), uniqueSeqSetId, viewId)
4990 // protected void processKeyEvent(java.awt.event.KeyEvent e) {
4991 // jalview.bin.Console.outPrintln("Jalview2XML AF " + e);
4992 // super.processKeyEvent(e);
4999 af.setFileName(file, FileFormat.Jalview);
5001 final AlignViewport viewport = af.getViewport();
5002 for (int i = 0; i < JSEQ.size(); i++)
5004 int colour = safeInt(JSEQ.get(i).getColour());
5005 viewport.setSequenceColour(viewport.getAlignment().getSequenceAt(i),
5011 viewport.setColourByReferenceSeq(true);
5012 viewport.setDisplayReferenceSeq(true);
5015 viewport.setGatherViewsHere(safeBoolean(view.isGatheredViews()));
5017 if (view.getSequenceSetId() != null)
5019 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
5021 viewport.setSequenceSetId(uniqueSeqSetId);
5024 // propagate shared settings to this new view
5025 viewport.setHistoryList(av.getHistoryList());
5026 viewport.setRedoList(av.getRedoList());
5030 viewportsAdded.put(uniqueSeqSetId, viewport);
5032 // TODO: check if this method can be called repeatedly without
5033 // side-effects if alignpanel already registered.
5034 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
5036 // apply Hidden regions to view.
5037 if (hiddenSeqs != null)
5039 for (int s = 0; s < JSEQ.size(); s++)
5041 SequenceGroup hidden = new SequenceGroup();
5042 boolean isRepresentative = false;
5043 for (int r = 0; r < JSEQ.get(s).getHiddenSequences().size(); r++)
5045 isRepresentative = true;
5046 SequenceI sequenceToHide = al
5047 .getSequenceAt(JSEQ.get(s).getHiddenSequences().get(r));
5048 hidden.addSequence(sequenceToHide, false);
5049 // remove from hiddenSeqs list so we don't try to hide it twice
5050 hiddenSeqs.remove(sequenceToHide);
5052 if (isRepresentative)
5054 SequenceI representativeSequence = al.getSequenceAt(s);
5055 hidden.addSequence(representativeSequence, false);
5056 viewport.hideRepSequences(representativeSequence, hidden);
5060 SequenceI[] hseqs = hiddenSeqs
5061 .toArray(new SequenceI[hiddenSeqs.size()]);
5062 viewport.hideSequence(hseqs);
5065 // recover view properties and display parameters
5067 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
5068 viewport.setAbovePIDThreshold(safeBoolean(view.isPidSelected()));
5069 final int pidThreshold = safeInt(view.getPidThreshold());
5070 viewport.setThreshold(pidThreshold);
5072 viewport.setColourText(safeBoolean(view.isShowColourText()));
5074 viewport.setConservationSelected(
5075 safeBoolean(view.isConservationSelected()));
5076 viewport.setIncrement(safeInt(view.getConsThreshold()));
5077 viewport.setShowJVSuffix(safeBoolean(view.isShowFullId()));
5078 viewport.setRightAlignIds(safeBoolean(view.isRightAlignIds()));
5080 new Font(view.getFontName(), safeInt(view.getFontStyle()),
5081 safeInt(view.getFontSize())),
5082 (view.getCharWidth() != null) ? false : true);
5083 if (view.getCharWidth() != null)
5085 viewport.setCharWidth(view.getCharWidth());
5086 viewport.setCharHeight(view.getCharHeight());
5088 ViewStyleI vs = viewport.getViewStyle();
5089 vs.setScaleProteinAsCdna(view.isScaleProteinAsCdna());
5090 viewport.setViewStyle(vs);
5091 // TODO: allow custom charWidth/Heights to be restored by updating them
5092 // after setting font - which means set above to false
5093 viewport.setRenderGaps(safeBoolean(view.isRenderGaps()));
5094 viewport.setWrapAlignment(safeBoolean(view.isWrapAlignment()));
5095 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
5097 viewport.setShowBoxes(safeBoolean(view.isShowBoxes()));
5099 viewport.setShowText(safeBoolean(view.isShowText()));
5101 viewport.setTextColour(new Color(safeInt(view.getTextCol1())));
5102 viewport.setTextColour2(new Color(safeInt(view.getTextCol2())));
5103 viewport.setThresholdTextColour(safeInt(view.getTextColThreshold()));
5104 viewport.setShowUnconserved(view.isShowUnconserved());
5105 viewport.getRanges().setStartRes(safeInt(view.getStartRes()));
5107 if (view.getViewName() != null)
5109 viewport.setViewName(view.getViewName());
5110 af.setInitialTabVisible();
5112 af.setBounds(safeInt(view.getXpos()), safeInt(view.getYpos()),
5113 safeInt(view.getWidth()), safeInt(view.getHeight()));
5114 af.alignPanel.fontChanged(); // make sure font is updated *before* we set ID width
5115 // startSeq set in af.alignPanel.updateLayout below
5116 af.alignPanel.updateLayout();
5117 ColourSchemeI cs = null;
5118 // apply colourschemes
5119 if (view.getBgColour() != null)
5121 if (view.getBgColour().startsWith("ucs"))
5123 cs = getUserColourScheme(jm, view.getBgColour());
5125 else if (view.getBgColour().startsWith("Annotation"))
5127 AnnotationColourScheme viewAnnColour = view.getAnnotationColours();
5128 cs = constructAnnotationColour(viewAnnColour, af, al, jm, true);
5135 cs = ColourSchemeProperty.getColourScheme(af.getViewport(), al,
5136 view.getBgColour());
5141 * turn off 'alignment colour applies to all groups'
5142 * while restoring global colour scheme
5144 viewport.setColourAppliesToAllGroups(false);
5145 viewport.setGlobalColourScheme(cs);
5146 viewport.getResidueShading().setThreshold(pidThreshold,
5147 view.isIgnoreGapsinConsensus());
5148 viewport.getResidueShading()
5149 .setConsensus(viewport.getSequenceConsensusHash());
5150 if (safeBoolean(view.isConservationSelected()) && cs != null)
5152 viewport.getResidueShading()
5153 .setConservationInc(safeInt(view.getConsThreshold()));
5155 af.changeColour(cs);
5156 viewport.setColourAppliesToAllGroups(true);
5158 viewport.setShowSequenceFeatures(
5159 safeBoolean(view.isShowSequenceFeatures()));
5161 viewport.setCentreColumnLabels(view.isCentreColumnLabels());
5162 viewport.setIgnoreGapsConsensus(view.isIgnoreGapsinConsensus(), null);
5163 viewport.setFollowHighlight(view.isFollowHighlight());
5164 viewport.followSelection = view.isFollowSelection();
5165 viewport.setShowConsensusHistogram(view.isShowConsensusHistogram());
5166 viewport.setShowSequenceLogo(view.isShowSequenceLogo());
5167 viewport.setNormaliseSequenceLogo(view.isNormaliseSequenceLogo());
5168 viewport.setShowDBRefs(safeBoolean(view.isShowDbRefTooltip()));
5169 viewport.setShowNPFeats(safeBoolean(view.isShowNPfeatureTooltip()));
5170 viewport.setShowGroupConsensus(view.isShowGroupConsensus());
5171 viewport.setShowGroupConservation(view.isShowGroupConservation());
5172 viewport.setShowComplementFeatures(view.isShowComplementFeatures());
5173 viewport.setShowComplementFeaturesOnTop(
5174 view.isShowComplementFeaturesOnTop());
5176 // recover feature settings
5177 if (jm.getFeatureSettings() != null)
5179 FeatureRendererModel fr = af.alignPanel.getSeqPanel().seqCanvas
5180 .getFeatureRenderer();
5181 FeaturesDisplayed fdi;
5182 viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
5183 String[] renderOrder = new String[jm.getFeatureSettings().getSetting()
5185 Map<String, FeatureColourI> featureColours = new Hashtable<>();
5186 Map<String, Float> featureOrder = new Hashtable<>();
5188 for (int fs = 0; fs < jm.getFeatureSettings().getSetting()
5191 Setting setting = jm.getFeatureSettings().getSetting().get(fs);
5192 String featureType = setting.getType();
5195 * restore feature filters (if any)
5197 jalview.xml.binding.jalview.FeatureMatcherSet filters = setting
5199 if (filters != null)
5201 FeatureMatcherSetI filter = Jalview2XML.parseFilter(featureType,
5203 if (!filter.isEmpty())
5205 fr.setFeatureFilter(featureType, filter);
5210 * restore feature colour scheme
5212 Color maxColour = new Color(setting.getColour());
5213 if (setting.getMincolour() != null)
5216 * minColour is always set unless a simple colour
5217 * (including for colour by label though it doesn't use it)
5219 Color minColour = new Color(setting.getMincolour().intValue());
5220 Color noValueColour = minColour;
5221 NoValueColour noColour = setting.getNoValueColour();
5222 if (noColour == NoValueColour.NONE)
5224 noValueColour = null;
5226 else if (noColour == NoValueColour.MAX)
5228 noValueColour = maxColour;
5230 float min = safeFloat(safeFloat(setting.getMin()));
5231 float max = setting.getMax() == null ? 1f
5232 : setting.getMax().floatValue();
5233 FeatureColourI gc = new FeatureColour(maxColour, minColour,
5234 maxColour, noValueColour, min, max);
5235 if (setting.getAttributeName().size() > 0)
5237 gc.setAttributeName(setting.getAttributeName().toArray(
5238 new String[setting.getAttributeName().size()]));
5240 if (setting.getThreshold() != null)
5242 gc.setThreshold(setting.getThreshold().floatValue());
5243 int threshstate = safeInt(setting.getThreshstate());
5244 // -1 = None, 0 = Below, 1 = Above threshold
5245 if (threshstate == 0)
5247 gc.setBelowThreshold(true);
5249 else if (threshstate == 1)
5251 gc.setAboveThreshold(true);
5254 gc.setAutoScaled(true); // default
5255 if (setting.isAutoScale() != null)
5257 gc.setAutoScaled(setting.isAutoScale());
5259 if (setting.isColourByLabel() != null)
5261 gc.setColourByLabel(setting.isColourByLabel());
5263 // and put in the feature colour table.
5264 featureColours.put(featureType, gc);
5268 featureColours.put(featureType, new FeatureColour(maxColour));
5270 renderOrder[fs] = featureType;
5271 if (setting.getOrder() != null)
5273 featureOrder.put(featureType, setting.getOrder().floatValue());
5277 featureOrder.put(featureType, Float.valueOf(
5278 fs / jm.getFeatureSettings().getSetting().size()));
5280 if (safeBoolean(setting.isDisplay()))
5282 fdi.setVisible(featureType);
5285 Map<String, Boolean> fgtable = new Hashtable<>();
5286 for (int gs = 0; gs < jm.getFeatureSettings().getGroup().size(); gs++)
5288 Group grp = jm.getFeatureSettings().getGroup().get(gs);
5289 fgtable.put(grp.getName(), Boolean.valueOf(grp.isDisplay()));
5291 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
5292 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
5293 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
5294 FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
5295 fgtable, featureColours, 1.0f, featureOrder);
5296 fr.transferSettings(frs);
5299 if (view.getHiddenColumns().size() > 0)
5301 for (int c = 0; c < view.getHiddenColumns().size(); c++)
5303 final HiddenColumns hc = view.getHiddenColumns().get(c);
5304 viewport.hideColumns(safeInt(hc.getStart()),
5305 safeInt(hc.getEnd()) /* +1 */);
5308 if (view.getCalcIdParam() != null)
5310 for (CalcIdParam calcIdParam : view.getCalcIdParam())
5312 if (calcIdParam != null)
5314 if (recoverCalcIdParam(calcIdParam, viewport))
5319 Console.warn("Couldn't recover parameters for "
5320 + calcIdParam.getCalcId());
5325 af.setMenusFromViewport(viewport);
5326 af.setTitle(view.getTitle());
5327 // TODO: we don't need to do this if the viewport is aready visible.
5329 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
5330 * has a 'cdna/protein complement' view, in which case save it in order to
5331 * populate a SplitFrame once all views have been read in.
5333 String complementaryViewId = view.getComplementId();
5334 if (complementaryViewId == null)
5336 Desktop.addInternalFrame(af, view.getTitle(),
5337 safeInt(view.getWidth()), safeInt(view.getHeight()));
5338 // recompute any autoannotation
5339 af.alignPanel.updateAnnotation(false, true);
5340 reorderAutoannotation(af, al, autoAlan);
5341 af.alignPanel.alignmentChanged();
5345 splitFrameCandidates.put(view, af);
5352 * Reads saved data to restore Colour by Annotation settings
5354 * @param viewAnnColour
5358 * @param checkGroupAnnColour
5361 private ColourSchemeI constructAnnotationColour(
5362 AnnotationColourScheme viewAnnColour, AlignFrame af,
5363 AlignmentI al, JalviewModel model, boolean checkGroupAnnColour)
5365 boolean propagateAnnColour = false;
5366 AlignmentI annAlignment = af != null ? af.getViewport().getAlignment()
5368 if (checkGroupAnnColour && al.getGroups() != null
5369 && al.getGroups().size() > 0)
5371 // pre 2.8.1 behaviour
5372 // check to see if we should transfer annotation colours
5373 propagateAnnColour = true;
5374 for (SequenceGroup sg : al.getGroups())
5376 if (sg.getColourScheme() instanceof AnnotationColourGradient)
5378 propagateAnnColour = false;
5384 * 2.10.2- : saved annotationId is AlignmentAnnotation.annotationId
5386 String annotationId = viewAnnColour.getAnnotation();
5387 AlignmentAnnotation matchedAnnotation = annotationIds.get(annotationId);
5390 * pre 2.10.2: saved annotationId is AlignmentAnnotation.label
5392 if (matchedAnnotation == null
5393 && annAlignment.getAlignmentAnnotation() != null)
5395 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
5398 .equals(annAlignment.getAlignmentAnnotation()[i].label))
5400 matchedAnnotation = annAlignment.getAlignmentAnnotation()[i];
5405 if (matchedAnnotation == null)
5408 .errPrintln("Failed to match annotation colour scheme for "
5412 // belt-and-braces create a threshold line if the
5413 // colourscheme needs one but the matchedAnnotation doesn't have one
5414 if (safeInt(viewAnnColour.getAboveThreshold()) != 0
5415 && matchedAnnotation.getThreshold() == null)
5417 matchedAnnotation.setThreshold(
5418 new GraphLine(safeFloat(viewAnnColour.getThreshold()),
5419 "Threshold", Color.black));
5422 AnnotationColourGradient cs = null;
5423 if (viewAnnColour.getColourScheme().equals("None"))
5425 cs = new AnnotationColourGradient(matchedAnnotation,
5426 new Color(safeInt(viewAnnColour.getMinColour())),
5427 new Color(safeInt(viewAnnColour.getMaxColour())),
5428 safeInt(viewAnnColour.getAboveThreshold()));
5430 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
5432 cs = new AnnotationColourGradient(matchedAnnotation,
5433 getUserColourScheme(model, viewAnnColour.getColourScheme()),
5434 safeInt(viewAnnColour.getAboveThreshold()));
5438 cs = new AnnotationColourGradient(matchedAnnotation,
5439 ColourSchemeProperty.getColourScheme(af.getViewport(), al,
5440 viewAnnColour.getColourScheme()),
5441 safeInt(viewAnnColour.getAboveThreshold()));
5444 boolean perSequenceOnly = safeBoolean(viewAnnColour.isPerSequence());
5445 boolean useOriginalColours = safeBoolean(
5446 viewAnnColour.isPredefinedColours());
5447 cs.setSeqAssociated(perSequenceOnly);
5448 cs.setPredefinedColours(useOriginalColours);
5450 if (propagateAnnColour && al.getGroups() != null)
5452 // Also use these settings for all the groups
5453 for (int g = 0; g < al.getGroups().size(); g++)
5455 SequenceGroup sg = al.getGroups().get(g);
5456 if (sg.getGroupColourScheme() == null)
5461 AnnotationColourGradient groupScheme = new AnnotationColourGradient(
5462 matchedAnnotation, sg.getColourScheme(),
5463 safeInt(viewAnnColour.getAboveThreshold()));
5464 sg.setColourScheme(groupScheme);
5465 groupScheme.setSeqAssociated(perSequenceOnly);
5466 groupScheme.setPredefinedColours(useOriginalColours);
5472 private void reorderAutoannotation(AlignFrame af, AlignmentI al,
5473 List<JvAnnotRow> autoAlan)
5475 // copy over visualization settings for autocalculated annotation in the
5477 if (al.getAlignmentAnnotation() != null)
5480 * Kludge for magic autoannotation names (see JAL-811)
5482 String[] magicNames = new String[] { "Consensus", "Quality",
5484 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
5485 Hashtable<String, JvAnnotRow> visan = new Hashtable<>();
5486 for (String nm : magicNames)
5488 visan.put(nm, nullAnnot);
5490 for (JvAnnotRow auan : autoAlan)
5492 visan.put(auan.template.label
5493 + (auan.template.getCalcId() == null ? ""
5494 : "\t" + auan.template.getCalcId()),
5497 int hSize = al.getAlignmentAnnotation().length;
5498 List<JvAnnotRow> reorder = new ArrayList<>();
5499 // work through any autoCalculated annotation already on the view
5500 // removing it if it should be placed in a different location on the
5501 // annotation panel.
5502 List<String> remains = new ArrayList<>(visan.keySet());
5503 for (int h = 0; h < hSize; h++)
5505 jalview.datamodel.AlignmentAnnotation jalan = al
5506 .getAlignmentAnnotation()[h];
5507 if (jalan.autoCalculated)
5510 JvAnnotRow valan = visan.get(k = jalan.label);
5511 if (jalan.getCalcId() != null)
5513 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
5518 // delete the auto calculated row from the alignment
5519 al.deleteAnnotation(jalan, false);
5523 if (valan != nullAnnot)
5525 if (jalan != valan.template)
5527 // newly created autoannotation row instance
5528 // so keep a reference to the visible annotation row
5529 // and copy over all relevant attributes
5530 if (valan.template.graphHeight >= 0)
5533 jalan.graphHeight = valan.template.graphHeight;
5535 jalan.visible = valan.template.visible;
5537 reorder.add(new JvAnnotRow(valan.order, jalan));
5542 // Add any (possibly stale) autocalculated rows that were not appended to
5543 // the view during construction
5544 for (String other : remains)
5546 JvAnnotRow othera = visan.get(other);
5547 if (othera != nullAnnot && othera.template.getCalcId() != null
5548 && othera.template.getCalcId().length() > 0)
5550 reorder.add(othera);
5553 // now put the automatic annotation in its correct place
5554 int s = 0, srt[] = new int[reorder.size()];
5555 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
5556 for (JvAnnotRow jvar : reorder)
5559 srt[s++] = jvar.order;
5562 jalview.util.QuickSort.sort(srt, rws);
5563 // and re-insert the annotation at its correct position
5564 for (JvAnnotRow jvar : rws)
5566 al.addAnnotation(jvar.template, jvar.order);
5568 af.alignPanel.adjustAnnotationHeight();
5572 Hashtable skipList = null;
5575 * TODO remove this method
5578 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
5579 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
5580 * throw new Error("Implementation Error. No skipList defined for this
5581 * Jalview2XML instance."); } return (AlignFrame)
5582 * skipList.get(view.getSequenceSetId()); }
5586 * Check if the Jalview view contained in object should be skipped or not.
5589 * @return true if view's sequenceSetId is a key in skipList
5591 private boolean skipViewport(JalviewModel object)
5593 if (skipList == null)
5597 String id = object.getViewport().get(0).getSequenceSetId();
5598 if (skipList.containsKey(id))
5600 Console.debug("Skipping seuqence set id " + id);
5606 public void addToSkipList(AlignFrame af)
5608 if (skipList == null)
5610 skipList = new Hashtable();
5612 skipList.put(af.getViewport().getSequenceSetId(), af);
5615 public void clearSkipList()
5617 if (skipList != null)
5624 private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
5625 boolean ignoreUnrefed, String uniqueSeqSetId)
5627 jalview.datamodel.AlignmentI ds = getDatasetFor(
5628 vamsasSet.getDatasetId());
5629 AlignmentI xtant_ds = ds;
5630 if (xtant_ds == null)
5632 // good chance we are about to create a new dataset, but check if we've
5633 // seen some of the dataset sequence IDs before.
5634 // TODO: skip this check if we are working with project generated by
5635 // version 2.11 or later
5636 xtant_ds = checkIfHasDataset(vamsasSet.getSequence());
5637 if (xtant_ds != null)
5640 addDatasetRef(vamsasSet.getDatasetId(), ds);
5643 Vector<SequenceI> dseqs = null;
5646 // recovering an alignment View
5647 AlignmentI seqSetDS = getDatasetFor(UNIQSEQSETID + uniqueSeqSetId);
5648 if (seqSetDS != null)
5650 if (ds != null && ds != seqSetDS)
5653 "JAL-3171 regression: Overwriting a dataset reference for an alignment"
5654 + " - CDS/Protein crossreference data may be lost");
5655 if (xtant_ds != null)
5657 // This can only happen if the unique sequence set ID was bound to a
5658 // dataset that did not contain any of the sequences in the view
5659 // currently being restored.
5661 "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.");
5665 addDatasetRef(vamsasSet.getDatasetId(), ds);
5670 // try even harder to restore dataset
5671 AlignmentI xtantDS = checkIfHasDataset(vamsasSet.getSequence());
5672 // create a list of new dataset sequences
5673 dseqs = new Vector<>();
5675 for (int i = 0, iSize = vamsasSet.getSequence().size(); i < iSize; i++)
5677 Sequence vamsasSeq = vamsasSet.getSequence().get(i);
5678 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed, i);
5680 // create a new dataset
5683 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
5684 dseqs.copyInto(dsseqs);
5685 ds = new jalview.datamodel.Alignment(dsseqs);
5686 Console.debug("Created new dataset " + vamsasSet.getDatasetId()
5687 + " for alignment " + System.identityHashCode(al));
5688 addDatasetRef(vamsasSet.getDatasetId(), ds);
5690 // set the dataset for the newly imported alignment.
5691 if (al.getDataset() == null && !ignoreUnrefed)
5694 // register dataset for the alignment's uniqueSeqSetId for legacy projects
5695 addDatasetRef(UNIQSEQSETID + uniqueSeqSetId, ds);
5697 updateSeqDatasetBinding(vamsasSet.getSequence(), ds);
5701 * XML dataset sequence ID to materialised dataset reference
5703 HashMap<String, AlignmentI> seqToDataset = new HashMap<>();
5706 * @return the first materialised dataset reference containing a dataset
5707 * sequence referenced in the given view
5709 * - sequences from the view
5711 AlignmentI checkIfHasDataset(List<Sequence> list)
5713 for (Sequence restoredSeq : list)
5715 AlignmentI datasetFor = seqToDataset.get(restoredSeq.getDsseqid());
5716 if (datasetFor != null)
5725 * Register ds as the containing dataset for the dataset sequences referenced
5726 * by sequences in list
5729 * - sequences in a view
5732 void updateSeqDatasetBinding(List<Sequence> list, AlignmentI ds)
5734 for (Sequence restoredSeq : list)
5736 AlignmentI prevDS = seqToDataset.put(restoredSeq.getDsseqid(), ds);
5737 if (prevDS != null && prevDS != ds)
5739 Console.warn("Dataset sequence appears in many datasets: "
5740 + restoredSeq.getDsseqid());
5741 // TODO: try to merge!
5749 * sequence definition to create/merge dataset sequence for
5753 * vector to add new dataset sequence to
5754 * @param ignoreUnrefed
5755 * - when true, don't create new sequences from vamsasSeq if it's id
5756 * doesn't already have an asssociated Jalview sequence.
5758 * - used to reorder the sequence in the alignment according to the
5759 * vamsasSeq array ordering, to preserve ordering of dataset
5761 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
5762 AlignmentI ds, Vector<SequenceI> dseqs, boolean ignoreUnrefed,
5765 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
5767 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
5768 boolean reorder = false;
5769 SequenceI dsq = null;
5770 if (sq != null && sq.getDatasetSequence() != null)
5772 dsq = sq.getDatasetSequence();
5778 if (sq == null && ignoreUnrefed)
5782 String sqid = vamsasSeq.getDsseqid();
5785 // need to create or add a new dataset sequence reference to this sequence
5788 dsq = seqRefIds.get(sqid);
5793 // make a new dataset sequence
5794 dsq = sq.createDatasetSequence();
5797 // make up a new dataset reference for this sequence
5798 sqid = seqHash(dsq);
5800 dsq.setVamsasId(uniqueSetSuffix + sqid);
5801 seqRefIds.put(sqid, dsq);
5806 dseqs.addElement(dsq);
5811 ds.addSequence(dsq);
5817 { // make this dataset sequence sq's dataset sequence
5818 sq.setDatasetSequence(dsq);
5819 // and update the current dataset alignment
5824 if (!dseqs.contains(dsq))
5831 if (ds.findIndex(dsq) < 0)
5833 ds.addSequence(dsq);
5840 // TODO: refactor this as a merge dataset sequence function
5841 // now check that sq (the dataset sequence) sequence really is the union of
5842 // all references to it
5843 // boolean pre = sq.getStart() < dsq.getStart();
5844 // boolean post = sq.getEnd() > dsq.getEnd();
5848 // StringBuffer sb = new StringBuffer();
5849 String newres = jalview.analysis.AlignSeq.extractGaps(
5850 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
5851 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
5852 && newres.length() > dsq.getLength())
5854 // Update with the longer sequence.
5858 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
5859 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
5860 * sb.append(newres.substring(newres.length() - sq.getEnd() -
5861 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
5863 dsq.setSequence(newres);
5865 // TODO: merges will never happen if we 'know' we have the real dataset
5866 // sequence - this should be detected when id==dssid
5867 jalview.bin.Console.errPrintln(
5868 "DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
5869 // + (pre ? "prepended" : "") + " "
5870 // + (post ? "appended" : ""));
5875 // sequence refs are identical. We may need to update the existing dataset
5876 // alignment with this one, though.
5877 if (ds != null && dseqs == null)
5879 int opos = ds.findIndex(dsq);
5880 SequenceI tseq = null;
5881 if (opos != -1 && vseqpos != opos)
5883 // remove from old position
5884 ds.deleteSequence(dsq);
5886 if (vseqpos < ds.getHeight())
5888 if (vseqpos != opos)
5890 // save sequence at destination position
5891 tseq = ds.getSequenceAt(vseqpos);
5892 ds.replaceSequenceAt(vseqpos, dsq);
5893 ds.addSequence(tseq);
5898 ds.addSequence(dsq);
5905 * TODO use AlignmentI here and in related methods - needs
5906 * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
5908 Hashtable<String, AlignmentI> datasetIds = null;
5910 IdentityHashMap<AlignmentI, String> dataset2Ids = null;
5912 private AlignmentI getDatasetFor(String datasetId)
5914 if (datasetIds == null)
5916 datasetIds = new Hashtable<>();
5919 if (datasetIds.containsKey(datasetId))
5921 return datasetIds.get(datasetId);
5926 private void addDatasetRef(String datasetId, AlignmentI dataset)
5928 if (datasetIds == null)
5930 datasetIds = new Hashtable<>();
5932 datasetIds.put(datasetId, dataset);
5936 * make a new dataset ID for this jalview dataset alignment
5941 private String getDatasetIdRef(AlignmentI dataset)
5943 if (dataset.getDataset() != null)
5946 "Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
5948 String datasetId = makeHashCode(dataset, null);
5949 if (datasetId == null)
5951 // make a new datasetId and record it
5952 if (dataset2Ids == null)
5954 dataset2Ids = new IdentityHashMap<>();
5958 datasetId = dataset2Ids.get(dataset);
5960 if (datasetId == null)
5962 datasetId = "ds" + dataset2Ids.size() + 1;
5963 dataset2Ids.put(dataset, datasetId);
5970 * Add any saved DBRefEntry's to the sequence. An entry flagged as 'locus' is
5971 * constructed as a special subclass GeneLocus.
5973 * @param datasetSequence
5976 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
5978 for (int d = 0; d < sequence.getDBRef().size(); d++)
5980 DBRef dr = sequence.getDBRef().get(d);
5984 entry = new GeneLocus(dr.getSource(), dr.getVersion(),
5985 dr.getAccessionId());
5989 entry = new DBRefEntry(dr.getSource(), dr.getVersion(),
5990 dr.getAccessionId());
5992 if (dr.getMapping() != null)
5994 entry.setMap(addMapping(dr.getMapping()));
5996 entry.setCanonical(dr.isCanonical());
5997 datasetSequence.addDBRef(entry);
6001 private jalview.datamodel.Mapping addMapping(Mapping m)
6003 SequenceI dsto = null;
6004 // Mapping m = dr.getMapping();
6005 int fr[] = new int[m.getMapListFrom().size() * 2];
6006 Iterator<MapListFrom> from = m.getMapListFrom().iterator();// enumerateMapListFrom();
6007 for (int _i = 0; from.hasNext(); _i += 2)
6009 MapListFrom mf = from.next();
6010 fr[_i] = mf.getStart();
6011 fr[_i + 1] = mf.getEnd();
6013 int fto[] = new int[m.getMapListTo().size() * 2];
6014 Iterator<MapListTo> to = m.getMapListTo().iterator();// enumerateMapListTo();
6015 for (int _i = 0; to.hasNext(); _i += 2)
6017 MapListTo mf = to.next();
6018 fto[_i] = mf.getStart();
6019 fto[_i + 1] = mf.getEnd();
6021 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto, fr,
6022 fto, m.getMapFromUnit().intValue(),
6023 m.getMapToUnit().intValue());
6026 * (optional) choice of dseqFor or Sequence
6028 if (m.getDseqFor() != null)
6030 String dsfor = m.getDseqFor();
6031 if (seqRefIds.containsKey(dsfor))
6036 jmap.setTo(seqRefIds.get(dsfor));
6040 frefedSequence.add(newMappingRef(dsfor, jmap));
6043 else if (m.getSequence() != null)
6046 * local sequence definition
6048 Sequence ms = m.getSequence();
6049 SequenceI djs = null;
6050 String sqid = ms.getDsseqid();
6051 if (sqid != null && sqid.length() > 0)
6054 * recover dataset sequence
6056 djs = seqRefIds.get(sqid);
6060 jalview.bin.Console.errPrintln(
6061 "Warning - making up dataset sequence id for DbRef sequence map reference");
6062 sqid = ((Object) ms).toString(); // make up a new hascode for
6063 // undefined dataset sequence hash
6064 // (unlikely to happen)
6070 * make a new dataset sequence and add it to refIds hash
6072 djs = new jalview.datamodel.Sequence(ms.getName(),
6074 djs.setStart(jmap.getMap().getToLowest());
6075 djs.setEnd(jmap.getMap().getToHighest());
6076 djs.setVamsasId(uniqueSetSuffix + sqid);
6078 incompleteSeqs.put(sqid, djs);
6079 seqRefIds.put(sqid, djs);
6082 Console.debug("about to recurse on addDBRefs.");
6091 * Provides a 'copy' of an alignment view (on action New View) by 'saving' the
6092 * view as XML (but not to file), and then reloading it
6097 public AlignmentPanel copyAlignPanel(AlignmentPanel ap)
6100 JalviewModel jm = saveState(ap, null, null, null);
6103 jm.getVamsasModel().getSequenceSet().get(0).getDatasetId(),
6104 ap.getAlignment().getDataset());
6106 uniqueSetSuffix = "";
6107 // jm.getJalviewModelSequence().getViewport(0).setId(null);
6108 jm.getViewport().get(0).setId(null);
6109 // we don't overwrite the view we just copied
6111 if (this.frefedSequence == null)
6113 frefedSequence = new Vector<>();
6116 viewportsAdded.clear();
6118 AlignFrame af = loadFromObject(jm, null, false, null);
6119 af.getAlignPanels().clear();
6120 af.closeMenuItem_actionPerformed(true);
6123 * if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
6124 * i<ap.av.getAlignment().getAlignmentAnnotation().length; i++) {
6125 * if(!ap.av.getAlignment().getAlignmentAnnotation()[i].autoCalculated) {
6126 * af.alignPanel.av.getAlignment().getAlignmentAnnotation()[i] =
6127 * ap.av.getAlignment().getAlignmentAnnotation()[i]; } } }
6130 return af.alignPanel;
6133 private Hashtable jvids2vobj;
6136 * set the object to ID mapping tables used to write/recover objects and XML
6137 * ID strings for the jalview project. If external tables are provided then
6138 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
6139 * object goes out of scope. - also populates the datasetIds hashtable with
6140 * alignment objects containing dataset sequences
6143 * Map from ID strings to jalview datamodel
6145 * Map from jalview datamodel to ID strings
6149 public void setObjectMappingTables(Hashtable vobj2jv,
6150 IdentityHashMap jv2vobj)
6152 this.jv2vobj = jv2vobj;
6153 this.vobj2jv = vobj2jv;
6154 Iterator ds = jv2vobj.keySet().iterator();
6156 while (ds.hasNext())
6158 Object jvobj = ds.next();
6159 id = jv2vobj.get(jvobj).toString();
6160 if (jvobj instanceof jalview.datamodel.Alignment)
6162 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
6164 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
6167 else if (jvobj instanceof jalview.datamodel.Sequence)
6169 // register sequence object so the XML parser can recover it.
6170 if (seqRefIds == null)
6172 seqRefIds = new HashMap<>();
6174 if (seqsToIds == null)
6176 seqsToIds = new IdentityHashMap<>();
6178 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
6179 seqsToIds.put((SequenceI) jvobj, id);
6181 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
6184 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
6185 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
6186 if (jvann.annotationId == null)
6188 jvann.annotationId = anid;
6190 if (!jvann.annotationId.equals(anid))
6192 // TODO verify that this is the correct behaviour
6193 Console.warn("Overriding Annotation ID for " + anid
6194 + " from different id : " + jvann.annotationId);
6195 jvann.annotationId = anid;
6198 else if (jvobj instanceof String)
6200 if (jvids2vobj == null)
6202 jvids2vobj = new Hashtable();
6203 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
6208 Console.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
6214 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
6215 * objects created from the project archive. If string is null (default for
6216 * construction) then suffix will be set automatically.
6220 public void setUniqueSetSuffix(String string)
6222 uniqueSetSuffix = string;
6227 * uses skipList2 as the skipList for skipping views on sequence sets
6228 * associated with keys in the skipList
6232 public void setSkipList(Hashtable skipList2)
6234 skipList = skipList2;
6238 * Reads the jar entry of given name and returns its contents, or null if the
6239 * entry is not found.
6242 * @param jarEntryName
6245 protected String readJarEntry(jarInputStreamProvider jprovider,
6246 String jarEntryName)
6248 String result = null;
6249 BufferedReader in = null;
6254 * Reopen the jar input stream and traverse its entries to find a matching
6257 JarInputStream jin = jprovider.getJarInputStream();
6258 JarEntry entry = null;
6261 entry = jin.getNextJarEntry();
6262 } while (entry != null && !entry.getName().equals(jarEntryName));
6266 StringBuilder out = new StringBuilder(256);
6267 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
6270 while ((data = in.readLine()) != null)
6274 result = out.toString();
6279 "Couldn't find entry in Jalview Jar for " + jarEntryName);
6281 } catch (Exception ex)
6283 ex.printStackTrace();
6291 } catch (IOException e)
6302 * Returns an incrementing counter (0, 1, 2...)
6306 private synchronized int nextCounter()
6312 * Loads any saved PCA viewers
6317 protected void loadPCAViewers(JalviewModel model, AlignmentPanel ap)
6321 List<PcaViewer> pcaviewers = model.getPcaViewer();
6322 for (PcaViewer viewer : pcaviewers)
6324 String modelName = viewer.getScoreModelName();
6325 SimilarityParamsI params = new SimilarityParams(
6326 viewer.isIncludeGappedColumns(), viewer.isMatchGaps(),
6327 viewer.isIncludeGaps(),
6328 viewer.isDenominateByShortestLength());
6331 * create the panel (without computing the PCA)
6333 PCAPanel panel = new PCAPanel(ap, modelName, params);
6335 panel.setTitle(viewer.getTitle());
6336 panel.setBounds(new Rectangle(viewer.getXpos(), viewer.getYpos(),
6337 viewer.getWidth(), viewer.getHeight()));
6339 boolean showLabels = viewer.isShowLabels();
6340 panel.setShowLabels(showLabels);
6341 panel.getRotatableCanvas().setShowLabels(showLabels);
6342 panel.getRotatableCanvas()
6343 .setBgColour(new Color(viewer.getBgColour()));
6344 panel.getRotatableCanvas()
6345 .setApplyToAllViews(viewer.isLinkToAllViews());
6348 * load PCA output data
6350 ScoreModelI scoreModel = ScoreModels.getInstance()
6351 .getScoreModel(modelName, ap);
6352 PCA pca = new PCA(null, scoreModel, params);
6353 PcaDataType pcaData = viewer.getPcaData();
6355 MatrixI pairwise = loadDoubleMatrix(pcaData.getPairwiseMatrix());
6356 pca.setPairwiseScores(pairwise);
6358 MatrixI triDiag = loadDoubleMatrix(pcaData.getTridiagonalMatrix());
6359 pca.setTridiagonal(triDiag);
6361 MatrixI result = loadDoubleMatrix(pcaData.getEigenMatrix());
6362 pca.setEigenmatrix(result);
6364 panel.getPcaModel().setPCA(pca);
6367 * we haven't saved the input data! (JAL-2647 to do)
6369 panel.setInputData(null);
6372 * add the sequence points for the PCA display
6374 List<jalview.datamodel.SequencePoint> seqPoints = new ArrayList<>();
6375 for (SequencePoint sp : viewer.getSequencePoint())
6377 String seqId = sp.getSequenceRef();
6378 SequenceI seq = seqRefIds.get(seqId);
6381 throw new IllegalStateException(
6382 "Unmatched seqref for PCA: " + seqId);
6384 Point pt = new Point(sp.getXPos(), sp.getYPos(), sp.getZPos());
6385 jalview.datamodel.SequencePoint seqPoint = new jalview.datamodel.SequencePoint(
6387 seqPoints.add(seqPoint);
6389 panel.getRotatableCanvas().setPoints(seqPoints, seqPoints.size());
6392 * set min-max ranges and scale after setPoints (which recomputes them)
6394 panel.getRotatableCanvas().setScaleFactor(viewer.getScaleFactor());
6395 SeqPointMin spMin = viewer.getSeqPointMin();
6396 float[] min = new float[] { spMin.getXPos(), spMin.getYPos(),
6398 SeqPointMax spMax = viewer.getSeqPointMax();
6399 float[] max = new float[] { spMax.getXPos(), spMax.getYPos(),
6401 panel.getRotatableCanvas().setSeqMinMax(min, max);
6403 // todo: hold points list in PCAModel only
6404 panel.getPcaModel().setSequencePoints(seqPoints);
6406 panel.setSelectedDimensionIndex(viewer.getXDim(), X);
6407 panel.setSelectedDimensionIndex(viewer.getYDim(), Y);
6408 panel.setSelectedDimensionIndex(viewer.getZDim(), Z);
6410 // is this duplication needed?
6411 panel.setTop(seqPoints.size() - 1);
6412 panel.getPcaModel().setTop(seqPoints.size() - 1);
6415 * add the axes' end points for the display
6417 for (int i = 0; i < 3; i++)
6419 Axis axis = viewer.getAxis().get(i);
6420 panel.getRotatableCanvas().getAxisEndPoints()[i] = new Point(
6421 axis.getXPos(), axis.getYPos(), axis.getZPos());
6424 Desktop.addInternalFrame(panel, MessageManager.formatMessage(
6425 "label.calc_title", "PCA", modelName), 475, 450);
6427 } catch (Exception ex)
6429 Console.error("Error loading PCA: " + ex.toString());
6434 * Creates a new structure viewer window
6441 protected void createStructureViewer(ViewerType viewerType,
6442 final Entry<String, StructureViewerModel> viewerData,
6443 AlignFrame af, jarInputStreamProvider jprovider)
6445 final StructureViewerModel viewerModel = viewerData.getValue();
6446 String sessionFilePath = null;
6448 if (viewerType == ViewerType.JMOL)
6450 sessionFilePath = rewriteJmolSession(viewerModel, jprovider);
6454 String viewerJarEntryName = getViewerJarEntryName(
6455 viewerModel.getViewId());
6456 sessionFilePath = copyJarEntry(jprovider, viewerJarEntryName,
6457 "viewerSession", ".tmp");
6459 final String sessionPath = sessionFilePath;
6460 final String sviewid = viewerData.getKey();
6463 SwingUtilities.invokeAndWait(new Runnable()
6468 JalviewStructureDisplayI sview = null;
6471 sview = StructureViewer.createView(viewerType, af.alignPanel,
6472 viewerModel, sessionPath, sviewid);
6473 addNewStructureViewer(sview);
6474 } catch (OutOfMemoryError ex)
6476 new OOMWarning("Restoring structure view for " + viewerType,
6477 (OutOfMemoryError) ex.getCause());
6478 if (sview != null && sview.isVisible())
6480 sview.closeViewer(false);
6481 sview.setVisible(false);
6487 } catch (InvocationTargetException | InterruptedException ex)
6489 Console.warn("Unexpected error when opening " + viewerType
6490 + " structure viewer", ex);
6495 * Rewrites a Jmol session script, saves it to a temporary file, and returns
6496 * the path of the file. "load file" commands are rewritten to change the
6497 * original PDB file names to those created as the Jalview project is loaded.
6503 private String rewriteJmolSession(StructureViewerModel svattrib,
6504 jarInputStreamProvider jprovider)
6506 String state = svattrib.getStateData(); // Jalview < 2.9
6507 if (state == null || state.isEmpty()) // Jalview >= 2.9
6509 String jarEntryName = getViewerJarEntryName(svattrib.getViewId());
6510 state = readJarEntry(jprovider, jarEntryName);
6512 // TODO or simpler? for each key in oldFiles,
6513 // replace key.getPath() in state with oldFiles.get(key).getFilePath()
6514 // (allowing for different path escapings)
6515 StringBuilder rewritten = new StringBuilder(state.length());
6516 int cp = 0, ncp, ecp;
6517 Map<File, StructureData> oldFiles = svattrib.getFileData();
6518 while ((ncp = state.indexOf("load ", cp)) > -1)
6522 // look for next filename in load statement
6523 rewritten.append(state.substring(cp,
6524 ncp = (state.indexOf("\"", ncp + 1) + 1)));
6525 String oldfilenam = state.substring(ncp,
6526 ecp = state.indexOf("\"", ncp));
6527 // recover the new mapping data for this old filename
6528 // have to normalize filename - since Jmol and jalview do
6529 // filename translation differently.
6530 StructureData filedat = oldFiles.get(new File(oldfilenam));
6531 if (filedat == null)
6533 String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
6534 filedat = oldFiles.get(new File(reformatedOldFilename));
6536 rewritten.append(Platform.escapeBackslashes(filedat.getFilePath()));
6537 rewritten.append("\"");
6538 cp = ecp + 1; // advance beyond last \" and set cursor so we can
6539 // look for next file statement.
6540 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
6544 // just append rest of state
6545 rewritten.append(state.substring(cp));
6549 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
6550 rewritten = new StringBuilder(state);
6551 rewritten.append("; load append ");
6552 for (File id : oldFiles.keySet())
6554 // add pdb files that should be present in the viewer
6555 StructureData filedat = oldFiles.get(id);
6556 rewritten.append(" \"").append(filedat.getFilePath()).append("\"");
6558 rewritten.append(";");
6561 if (rewritten.length() == 0)
6565 final String history = "history = ";
6566 int historyIndex = rewritten.indexOf(history);
6567 if (historyIndex > -1)
6570 * change "history = [true|false];" to "history = [1|0];"
6572 historyIndex += history.length();
6573 String val = rewritten.substring(historyIndex, historyIndex + 5);
6574 if (val.startsWith("true"))
6576 rewritten.replace(historyIndex, historyIndex + 4, "1");
6578 else if (val.startsWith("false"))
6580 rewritten.replace(historyIndex, historyIndex + 5, "0");
6586 File tmp = File.createTempFile("viewerSession", ".tmp");
6587 try (OutputStream os = new FileOutputStream(tmp))
6589 InputStream is = new ByteArrayInputStream(
6590 rewritten.toString().getBytes());
6592 return tmp.getAbsolutePath();
6594 } catch (IOException e)
6596 Console.error("Error restoring Jmol session: " + e.toString());
6602 * Populates an XML model of the feature colour scheme for one feature type
6604 * @param featureType
6608 public static Colour marshalColour(String featureType,
6609 FeatureColourI fcol)
6611 Colour col = new Colour();
6612 if (fcol.isSimpleColour())
6614 col.setRGB(Format.getHexString(fcol.getColour()));
6618 col.setRGB(Format.getHexString(fcol.getMaxColour()));
6619 col.setMin(fcol.getMin());
6620 col.setMax(fcol.getMax());
6621 col.setMinRGB(jalview.util.Format.getHexString(fcol.getMinColour()));
6622 col.setAutoScale(fcol.isAutoScaled());
6623 col.setThreshold(fcol.getThreshold());
6624 col.setColourByLabel(fcol.isColourByLabel());
6625 col.setThreshType(fcol.isAboveThreshold() ? ThresholdType.ABOVE
6626 : (fcol.isBelowThreshold() ? ThresholdType.BELOW
6627 : ThresholdType.NONE));
6628 if (fcol.isColourByAttribute())
6630 final String[] attName = fcol.getAttributeName();
6631 col.getAttributeName().add(attName[0]);
6632 if (attName.length > 1)
6634 col.getAttributeName().add(attName[1]);
6637 Color noColour = fcol.getNoColour();
6638 if (noColour == null)
6640 col.setNoValueColour(NoValueColour.NONE);
6642 else if (noColour == fcol.getMaxColour())
6644 col.setNoValueColour(NoValueColour.MAX);
6648 col.setNoValueColour(NoValueColour.MIN);
6651 col.setName(featureType);
6656 * Populates an XML model of the feature filter(s) for one feature type
6658 * @param firstMatcher
6659 * the first (or only) match condition)
6661 * remaining match conditions (if any)
6663 * if true, conditions are and-ed, else or-ed
6665 public static jalview.xml.binding.jalview.FeatureMatcherSet marshalFilter(
6666 FeatureMatcherI firstMatcher, Iterator<FeatureMatcherI> filters,
6669 jalview.xml.binding.jalview.FeatureMatcherSet result = new jalview.xml.binding.jalview.FeatureMatcherSet();
6671 if (filters.hasNext())
6676 CompoundMatcher compound = new CompoundMatcher();
6677 compound.setAnd(and);
6678 jalview.xml.binding.jalview.FeatureMatcherSet matcher1 = marshalFilter(
6679 firstMatcher, Collections.emptyIterator(), and);
6680 // compound.addMatcherSet(matcher1);
6681 compound.getMatcherSet().add(matcher1);
6682 FeatureMatcherI nextMatcher = filters.next();
6683 jalview.xml.binding.jalview.FeatureMatcherSet matcher2 = marshalFilter(
6684 nextMatcher, filters, and);
6685 // compound.addMatcherSet(matcher2);
6686 compound.getMatcherSet().add(matcher2);
6687 result.setCompoundMatcher(compound);
6692 * single condition matcher
6694 // MatchCondition matcherModel = new MatchCondition();
6695 jalview.xml.binding.jalview.FeatureMatcher matcherModel = new jalview.xml.binding.jalview.FeatureMatcher();
6696 matcherModel.setCondition(
6697 firstMatcher.getMatcher().getCondition().getStableName());
6698 matcherModel.setValue(firstMatcher.getMatcher().getPattern());
6699 if (firstMatcher.isByAttribute())
6701 matcherModel.setBy(FilterBy.BY_ATTRIBUTE);
6702 // matcherModel.setAttributeName(firstMatcher.getAttribute());
6703 String[] attName = firstMatcher.getAttribute();
6704 matcherModel.getAttributeName().add(attName[0]); // attribute
6705 if (attName.length > 1)
6707 matcherModel.getAttributeName().add(attName[1]); // sub-attribute
6710 else if (firstMatcher.isByLabel())
6712 matcherModel.setBy(FilterBy.BY_LABEL);
6714 else if (firstMatcher.isByScore())
6716 matcherModel.setBy(FilterBy.BY_SCORE);
6718 result.setMatchCondition(matcherModel);
6725 * Loads one XML model of a feature filter to a Jalview object
6727 * @param featureType
6728 * @param matcherSetModel
6731 public static FeatureMatcherSetI parseFilter(String featureType,
6732 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel)
6734 FeatureMatcherSetI result = new FeatureMatcherSet();
6737 parseFilterConditions(result, matcherSetModel, true);
6738 } catch (IllegalStateException e)
6740 // mixing AND and OR conditions perhaps
6741 jalview.bin.Console.errPrintln(
6742 String.format("Error reading filter conditions for '%s': %s",
6743 featureType, e.getMessage()));
6744 // return as much as was parsed up to the error
6751 * Adds feature match conditions to matcherSet as unmarshalled from XML
6752 * (possibly recursively for compound conditions)
6755 * @param matcherSetModel
6757 * if true, multiple conditions are AND-ed, else they are OR-ed
6758 * @throws IllegalStateException
6759 * if AND and OR conditions are mixed
6761 protected static void parseFilterConditions(FeatureMatcherSetI matcherSet,
6762 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel,
6765 jalview.xml.binding.jalview.FeatureMatcher mc = matcherSetModel
6766 .getMatchCondition();
6772 FilterBy filterBy = mc.getBy();
6773 Condition cond = Condition.fromString(mc.getCondition());
6774 String pattern = mc.getValue();
6775 FeatureMatcherI matchCondition = null;
6776 if (filterBy == FilterBy.BY_LABEL)
6778 matchCondition = FeatureMatcher.byLabel(cond, pattern);
6780 else if (filterBy == FilterBy.BY_SCORE)
6782 matchCondition = FeatureMatcher.byScore(cond, pattern);
6785 else if (filterBy == FilterBy.BY_ATTRIBUTE)
6787 final List<String> attributeName = mc.getAttributeName();
6788 String[] attNames = attributeName
6789 .toArray(new String[attributeName.size()]);
6790 matchCondition = FeatureMatcher.byAttribute(cond, pattern,
6795 * note this throws IllegalStateException if AND-ing to a
6796 * previously OR-ed compound condition, or vice versa
6800 matcherSet.and(matchCondition);
6804 matcherSet.or(matchCondition);
6810 * compound condition
6812 List<jalview.xml.binding.jalview.FeatureMatcherSet> matchers = matcherSetModel
6813 .getCompoundMatcher().getMatcherSet();
6814 boolean anded = matcherSetModel.getCompoundMatcher().isAnd();
6815 if (matchers.size() == 2)
6817 parseFilterConditions(matcherSet, matchers.get(0), anded);
6818 parseFilterConditions(matcherSet, matchers.get(1), anded);
6823 .errPrintln("Malformed compound filter condition");
6829 * Loads one XML model of a feature colour to a Jalview object
6831 * @param colourModel
6834 public static FeatureColourI parseColour(Colour colourModel)
6836 FeatureColourI colour = null;
6838 if (colourModel.getMax() != null)
6840 Color mincol = null;
6841 Color maxcol = null;
6842 Color noValueColour = null;
6846 mincol = new Color(Integer.parseInt(colourModel.getMinRGB(), 16));
6847 maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6848 } catch (Exception e)
6850 Console.warn("Couldn't parse out graduated feature color.", e);
6853 NoValueColour noCol = colourModel.getNoValueColour();
6854 if (noCol == NoValueColour.MIN)
6856 noValueColour = mincol;
6858 else if (noCol == NoValueColour.MAX)
6860 noValueColour = maxcol;
6863 colour = new FeatureColour(maxcol, mincol, maxcol, noValueColour,
6864 safeFloat(colourModel.getMin()),
6865 safeFloat(colourModel.getMax()));
6866 final List<String> attributeName = colourModel.getAttributeName();
6867 String[] attributes = attributeName
6868 .toArray(new String[attributeName.size()]);
6869 if (attributes != null && attributes.length > 0)
6871 colour.setAttributeName(attributes);
6873 if (colourModel.isAutoScale() != null)
6875 colour.setAutoScaled(colourModel.isAutoScale().booleanValue());
6877 if (colourModel.isColourByLabel() != null)
6879 colour.setColourByLabel(
6880 colourModel.isColourByLabel().booleanValue());
6882 if (colourModel.getThreshold() != null)
6884 colour.setThreshold(colourModel.getThreshold().floatValue());
6886 ThresholdType ttyp = colourModel.getThreshType();
6887 if (ttyp == ThresholdType.ABOVE)
6889 colour.setAboveThreshold(true);
6891 else if (ttyp == ThresholdType.BELOW)
6893 colour.setBelowThreshold(true);
6898 Color color = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6899 colour = new FeatureColour(color);
6905 public static void setStateSavedUpToDate(boolean s)
6907 Console.debug("Setting overall stateSavedUpToDate to " + s);
6908 stateSavedUpToDate = s;
6911 public static boolean stateSavedUpToDate()
6913 Console.debug("Returning overall stateSavedUpToDate value: "
6914 + stateSavedUpToDate);
6915 return stateSavedUpToDate;
6918 public static boolean allSavedUpToDate()
6920 if (stateSavedUpToDate()) // nothing happened since last project save
6923 AlignFrame[] frames = Desktop.getAlignFrames();
6926 for (int i = 0; i < frames.length; i++)
6928 if (frames[i] == null)
6930 if (!frames[i].getViewport().savedUpToDate())
6931 return false; // at least one alignment is not individually saved
6937 // used for debugging and tests
6938 private static int debugDelaySave = 20;
6940 public static void setDebugDelaySave(int n)