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.datamodel.AlignedCodonFrame;
90 import jalview.datamodel.Alignment;
91 import jalview.datamodel.AlignmentAnnotation;
92 import jalview.datamodel.AlignmentI;
93 import jalview.datamodel.ContactMatrix;
94 import jalview.datamodel.ContactMatrixI;
95 import jalview.datamodel.DBRefEntry;
96 import jalview.datamodel.GeneLocus;
97 import jalview.datamodel.GraphLine;
98 import jalview.datamodel.GroupSet;
99 import jalview.datamodel.PDBEntry;
100 import jalview.datamodel.Point;
101 import jalview.datamodel.RnaViewerModel;
102 import jalview.datamodel.SequenceFeature;
103 import jalview.datamodel.SequenceGroup;
104 import jalview.datamodel.SequenceI;
105 import jalview.datamodel.StructureViewerModel;
106 import jalview.datamodel.StructureViewerModel.StructureData;
107 import jalview.datamodel.features.FeatureMatcher;
108 import jalview.datamodel.features.FeatureMatcherI;
109 import jalview.datamodel.features.FeatureMatcherSet;
110 import jalview.datamodel.features.FeatureMatcherSetI;
111 import jalview.ext.varna.RnaModel;
112 import jalview.gui.AlignFrame;
113 import jalview.gui.AlignViewport;
114 import jalview.gui.AlignmentPanel;
115 import jalview.gui.AppVarna;
116 import jalview.gui.Desktop;
117 import jalview.gui.JvOptionPane;
118 import jalview.gui.OOMWarning;
119 import jalview.gui.OverviewPanel;
120 import jalview.gui.PCAPanel;
121 import jalview.gui.PaintRefresher;
122 import jalview.gui.SplitFrame;
123 import jalview.gui.StructureViewer;
124 import jalview.gui.StructureViewer.ViewerType;
125 import jalview.gui.StructureViewerBase;
126 import jalview.gui.TreePanel;
127 import jalview.io.BackupFiles;
128 import jalview.io.DataSourceType;
129 import jalview.io.FileFormat;
130 import jalview.io.NewickFile;
131 import jalview.math.Matrix;
132 import jalview.math.MatrixI;
133 import jalview.renderer.ResidueShaderI;
134 import jalview.schemes.AnnotationColourGradient;
135 import jalview.schemes.ColourSchemeI;
136 import jalview.schemes.ColourSchemeProperty;
137 import jalview.schemes.FeatureColour;
138 import jalview.schemes.ResidueProperties;
139 import jalview.schemes.UserColourScheme;
140 import jalview.structure.StructureSelectionManager;
141 import jalview.structures.models.AAStructureBindingModel;
142 import jalview.util.Format;
143 import jalview.util.HttpUtils;
144 import jalview.util.MessageManager;
145 import jalview.util.Platform;
146 import jalview.util.StringUtils;
147 import jalview.util.jarInputStreamProvider;
148 import jalview.util.matcher.Condition;
149 import jalview.viewmodel.AlignmentViewport;
150 import jalview.viewmodel.PCAModel;
151 import jalview.viewmodel.ViewportRanges;
152 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
153 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
154 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
155 import jalview.ws.datamodel.MappableContactMatrixI;
156 import jalview.ws.datamodel.alphafold.PAEContactMatrix;
157 import jalview.ws.jws2.Jws2Discoverer;
158 import jalview.ws.jws2.dm.AAConSettings;
159 import jalview.ws.jws2.jabaws2.Jws2Instance;
160 import jalview.ws.params.ArgumentI;
161 import jalview.ws.params.AutoCalcSetting;
162 import jalview.ws.params.WsParamSetI;
163 import jalview.xml.binding.jalview.AlcodonFrame;
164 import jalview.xml.binding.jalview.AlcodonFrame.AlcodMap;
165 import jalview.xml.binding.jalview.Annotation;
166 import jalview.xml.binding.jalview.Annotation.ThresholdLine;
167 import jalview.xml.binding.jalview.AnnotationColourScheme;
168 import jalview.xml.binding.jalview.AnnotationElement;
169 import jalview.xml.binding.jalview.DoubleMatrix;
170 import jalview.xml.binding.jalview.DoubleVector;
171 import jalview.xml.binding.jalview.Feature;
172 import jalview.xml.binding.jalview.Feature.OtherData;
173 import jalview.xml.binding.jalview.FeatureMatcherSet.CompoundMatcher;
174 import jalview.xml.binding.jalview.FilterBy;
175 import jalview.xml.binding.jalview.JalviewModel;
176 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings;
177 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Group;
178 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Setting;
179 import jalview.xml.binding.jalview.JalviewModel.JGroup;
180 import jalview.xml.binding.jalview.JalviewModel.JSeq;
181 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids;
182 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids.StructureState;
183 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer;
184 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer.SecondaryStructure;
185 import jalview.xml.binding.jalview.JalviewModel.PcaViewer;
186 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.Axis;
187 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SeqPointMax;
188 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SeqPointMin;
189 import jalview.xml.binding.jalview.JalviewModel.PcaViewer.SequencePoint;
190 import jalview.xml.binding.jalview.JalviewModel.Tree;
191 import jalview.xml.binding.jalview.JalviewModel.UserColours;
192 import jalview.xml.binding.jalview.JalviewModel.Viewport;
193 import jalview.xml.binding.jalview.JalviewModel.Viewport.CalcIdParam;
194 import jalview.xml.binding.jalview.JalviewModel.Viewport.HiddenColumns;
195 import jalview.xml.binding.jalview.JalviewModel.Viewport.Overview;
196 import jalview.xml.binding.jalview.JalviewUserColours;
197 import jalview.xml.binding.jalview.JalviewUserColours.Colour;
198 import jalview.xml.binding.jalview.MapListType;
199 import jalview.xml.binding.jalview.MapListType.MapListFrom;
200 import jalview.xml.binding.jalview.MapListType.MapListTo;
201 import jalview.xml.binding.jalview.Mapping;
202 import jalview.xml.binding.jalview.MatrixType;
203 import jalview.xml.binding.jalview.NoValueColour;
204 import jalview.xml.binding.jalview.ObjectFactory;
205 import jalview.xml.binding.jalview.PcaDataType;
206 import jalview.xml.binding.jalview.Pdbentry.Property;
207 import jalview.xml.binding.jalview.Sequence;
208 import jalview.xml.binding.jalview.Sequence.DBRef;
209 import jalview.xml.binding.jalview.SequenceSet;
210 import jalview.xml.binding.jalview.SequenceSet.SequenceSetProperties;
211 import jalview.xml.binding.jalview.ThresholdType;
212 import jalview.xml.binding.jalview.VAMSAS;
215 * Write out the current jalview desktop state as a Jalview XML stream.
217 * Note: the vamsas objects referred to here are primitive versions of the
218 * VAMSAS project schema elements - they are not the same and most likely never
222 * @version $Revision: 1.134 $
224 public class Jalview2XML
227 // BH 2018 we add the .jvp binary extension to J2S so that
228 // it will declare that binary when we do the file save from the browser
232 Platform.addJ2SBinaryType(".jvp?");
235 private static final String VIEWER_PREFIX = "viewer_";
237 private static final String RNA_PREFIX = "rna_";
239 private static final String UTF_8 = "UTF-8";
242 * used in decision if quit confirmation should be issued
244 private static boolean stateSavedUpToDate = false;
247 * prefix for recovering datasets for alignments with multiple views where
248 * non-existent dataset IDs were written for some views
250 private static final String UNIQSEQSETID = "uniqueSeqSetId.";
252 // use this with nextCounter() to make unique names for entities
253 private int counter = 0;
256 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
257 * of sequence objects are created.
259 IdentityHashMap<SequenceI, String> seqsToIds = null;
262 * jalview XML Sequence ID to jalview sequence object reference (both dataset
263 * and alignment sequences. Populated as XML reps of sequence objects are
266 Map<String, SequenceI> seqRefIds = null;
268 Map<String, SequenceI> incompleteSeqs = null;
270 List<SeqFref> frefedSequence = null;
272 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
275 * Map of reconstructed AlignFrame objects that appear to have come from
276 * SplitFrame objects (have a dna/protein complement view).
278 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
281 * Map from displayed rna structure models to their saved session state jar
284 private Map<RnaModel, String> rnaSessions = new HashMap<>();
287 * A helper method for safely using the value of an optional attribute that
288 * may be null if not present in the XML. Answers the boolean value, or false
294 public static boolean safeBoolean(Boolean b)
296 return b == null ? false : b.booleanValue();
300 * A helper method for safely using the value of an optional attribute that
301 * may be null if not present in the XML. Answers the integer value, or zero
307 public static int safeInt(Integer i)
309 return i == null ? 0 : i.intValue();
313 * A helper method for safely using the value of an optional attribute that
314 * may be null if not present in the XML. Answers the float value, or zero if
320 public static float safeFloat(Float f)
322 return f == null ? 0f : f.floatValue();
326 * create/return unique hash string for sq
329 * @return new or existing unique string for sq
331 String seqHash(SequenceI sq)
333 if (seqsToIds == null)
337 if (seqsToIds.containsKey(sq))
339 return seqsToIds.get(sq);
343 // create sequential key
344 String key = "sq" + (seqsToIds.size() + 1);
345 key = makeHashCode(sq, key); // check we don't have an external reference
347 seqsToIds.put(sq, key);
354 if (seqsToIds == null)
356 seqsToIds = new IdentityHashMap<>();
358 if (seqRefIds == null)
360 seqRefIds = new HashMap<>();
362 if (incompleteSeqs == null)
364 incompleteSeqs = new HashMap<>();
366 if (frefedSequence == null)
368 frefedSequence = new ArrayList<>();
376 public Jalview2XML(boolean raiseGUI)
378 this.raiseGUI = raiseGUI;
382 * base class for resolving forward references to sequences by their ID
387 abstract class SeqFref
393 public SeqFref(String _sref, String type)
399 public String getSref()
404 public SequenceI getSrefSeq()
406 return seqRefIds.get(sref);
409 public boolean isResolvable()
411 return seqRefIds.get(sref) != null;
414 public SequenceI getSrefDatasetSeq()
416 SequenceI sq = seqRefIds.get(sref);
419 while (sq.getDatasetSequence() != null)
421 sq = sq.getDatasetSequence();
428 * @return true if the forward reference was fully resolved
430 abstract boolean resolve();
433 public String toString()
435 return type + " reference to " + sref;
440 * create forward reference for a mapping
446 public SeqFref newMappingRef(final String sref,
447 final jalview.datamodel.Mapping _jmap)
449 SeqFref fref = new SeqFref(sref, "Mapping")
451 public jalview.datamodel.Mapping jmap = _jmap;
456 SequenceI seq = getSrefDatasetSeq();
468 public SeqFref newAlcodMapRef(final String sref,
469 final AlignedCodonFrame _cf,
470 final jalview.datamodel.Mapping _jmap)
473 SeqFref fref = new SeqFref(sref, "Codon Frame")
475 AlignedCodonFrame cf = _cf;
477 public jalview.datamodel.Mapping mp = _jmap;
480 public boolean isResolvable()
482 return super.isResolvable() && mp.getTo() != null;
488 SequenceI seq = getSrefDatasetSeq();
493 cf.addMap(seq, mp.getTo(), mp.getMap());
500 public void resolveFrefedSequences()
502 Iterator<SeqFref> nextFref = frefedSequence.iterator();
503 int toresolve = frefedSequence.size();
504 int unresolved = 0, failedtoresolve = 0;
505 while (nextFref.hasNext())
507 SeqFref ref = nextFref.next();
508 if (ref.isResolvable())
520 } catch (Exception x)
523 "IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
536 System.err.println("Jalview Project Import: There were " + unresolved
537 + " forward references left unresolved on the stack.");
539 if (failedtoresolve > 0)
541 System.err.println("SERIOUS! " + failedtoresolve
542 + " resolvable forward references failed to resolve.");
544 if (incompleteSeqs != null && incompleteSeqs.size() > 0)
547 "Jalview Project Import: There are " + incompleteSeqs.size()
548 + " sequences which may have incomplete metadata.");
549 if (incompleteSeqs.size() < 10)
551 for (SequenceI s : incompleteSeqs.values())
553 System.err.println(s.toString());
559 "Too many to report. Skipping output of incomplete sequences.");
565 * This maintains a map of viewports, the key being the seqSetId. Important to
566 * set historyItem and redoList for multiple views
568 Map<String, AlignViewport> viewportsAdded = new HashMap<>();
570 Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
572 String uniqueSetSuffix = "";
575 * List of pdbfiles added to Jar
577 List<String> pdbfiles = null;
579 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
580 public void saveState(File statefile)
582 FileOutputStream fos = null;
587 fos = new FileOutputStream(statefile);
589 JarOutputStream jout = new JarOutputStream(fos);
593 } catch (Exception e)
595 Console.error("Couln't write Jalview state to " + statefile, e);
596 // TODO: inform user of the problem - they need to know if their data was
598 if (errorMessage == null)
600 errorMessage = "Did't write Jalview Archive to output file '"
601 + statefile + "' - See console error log for details";
605 errorMessage += "(Didn't write Jalview Archive to output file '"
616 } catch (IOException e)
626 * Writes a jalview project archive to the given Jar output stream.
630 public void saveState(JarOutputStream jout)
632 AlignFrame[] frames = Desktop.getAlignFrames();
634 setStateSavedUpToDate(true);
636 if (Cache.getDefault("DEBUG_DELAY_SAVE", false))
638 int n = debugDelaySave;
642 Console.debug("***** debugging save sleep " + i + "/" + n);
646 } catch (InterruptedException e)
648 // TODO Auto-generated catch block
659 saveAllFrames(Arrays.asList(frames), jout);
663 * core method for storing state for a set of AlignFrames.
666 * - frames involving all data to be exported (including containing
669 * - project output stream
671 private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
673 Hashtable<String, AlignFrame> dsses = new Hashtable<>();
676 * ensure cached data is clear before starting
678 // todo tidy up seqRefIds, seqsToIds initialisation / reset
680 splitFrameCandidates.clear();
685 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
686 // //////////////////////////////////////////////////
688 List<String> shortNames = new ArrayList<>();
689 List<String> viewIds = new ArrayList<>();
692 for (int i = frames.size() - 1; i > -1; i--)
694 AlignFrame af = frames.get(i);
696 if (skipList != null && skipList
697 .containsKey(af.getViewport().getSequenceSetId()))
702 String shortName = makeFilename(af, shortNames);
704 int apSize = af.getAlignPanels().size();
706 for (int ap = 0; ap < apSize; ap++)
708 AlignmentPanel apanel = (AlignmentPanel) af.getAlignPanels()
710 String fileName = apSize == 1 ? shortName : ap + shortName;
711 if (!fileName.endsWith(".xml"))
713 fileName = fileName + ".xml";
716 saveState(apanel, fileName, jout, viewIds);
718 String dssid = getDatasetIdRef(
719 af.getViewport().getAlignment().getDataset());
720 if (!dsses.containsKey(dssid))
722 dsses.put(dssid, af);
727 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
733 } catch (Exception foo)
737 } catch (Exception ex)
739 // TODO: inform user of the problem - they need to know if their data was
741 if (errorMessage == null)
743 errorMessage = "Couldn't write Jalview Archive - see error output for details";
745 ex.printStackTrace();
750 * Generates a distinct file name, based on the title of the AlignFrame, by
751 * appending _n for increasing n until an unused name is generated. The new
752 * name (without its extension) is added to the list.
756 * @return the generated name, with .xml extension
758 protected String makeFilename(AlignFrame af, List<String> namesUsed)
760 String shortName = af.getTitle();
762 if (shortName.indexOf(File.separatorChar) > -1)
764 shortName = shortName
765 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
770 while (namesUsed.contains(shortName))
772 if (shortName.endsWith("_" + (count - 1)))
774 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
777 shortName = shortName.concat("_" + count);
781 namesUsed.add(shortName);
783 if (!shortName.endsWith(".xml"))
785 shortName = shortName + ".xml";
790 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
791 public boolean saveAlignment(AlignFrame af, String jarFile,
796 // create backupfiles object and get new temp filename destination
797 boolean doBackup = BackupFiles.getEnabled();
798 BackupFiles backupfiles = doBackup ? new BackupFiles(jarFile) : null;
799 FileOutputStream fos = new FileOutputStream(
800 doBackup ? backupfiles.getTempFilePath() : jarFile);
802 if (Cache.getDefault("DEBUG_DELAY_SAVE", false))
804 int n = debugDelaySave;
808 Console.debug("***** debugging save sleep " + i + "/" + n);
812 } catch (InterruptedException e)
814 // TODO Auto-generated catch block
821 JarOutputStream jout = new JarOutputStream(fos);
822 List<AlignFrame> frames = new ArrayList<>();
824 // resolve splitframes
825 if (af.getViewport().getCodingComplement() != null)
827 frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
833 saveAllFrames(frames, jout);
837 } catch (Exception foo)
841 boolean success = true;
845 backupfiles.setWriteSuccess(success);
846 success = backupfiles.rollBackupsAndRenameTempFile();
850 } catch (Exception ex)
852 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
853 ex.printStackTrace();
858 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
859 String fileName, JarOutputStream jout)
862 for (String dssids : dsses.keySet())
864 AlignFrame _af = dsses.get(dssids);
865 String jfileName = fileName + " Dataset for " + _af.getTitle();
866 if (!jfileName.endsWith(".xml"))
868 jfileName = jfileName + ".xml";
870 saveState(_af.alignPanel, jfileName, true, jout, null);
875 * create a JalviewModel from an alignment view and marshall it to a
879 * panel to create jalview model for
881 * name of alignment panel written to output stream
888 public JalviewModel saveState(AlignmentPanel ap, String fileName,
889 JarOutputStream jout, List<String> viewIds)
891 return saveState(ap, fileName, false, jout, viewIds);
895 * create a JalviewModel from an alignment view and marshall it to a
899 * panel to create jalview model for
901 * name of alignment panel written to output stream
903 * when true, only write the dataset for the alignment, not the data
904 * associated with the view.
910 public JalviewModel saveState(AlignmentPanel ap, String fileName,
911 boolean storeDS, JarOutputStream jout, List<String> viewIds)
915 viewIds = new ArrayList<>();
920 List<UserColourScheme> userColours = new ArrayList<>();
922 AlignViewport av = ap.av;
923 ViewportRanges vpRanges = av.getRanges();
925 final ObjectFactory objectFactory = new ObjectFactory();
926 JalviewModel object = objectFactory.createJalviewModel();
927 object.setVamsasModel(new VAMSAS());
929 // object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
932 GregorianCalendar c = new GregorianCalendar();
933 DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
934 XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(c);// gregorianCalendar);
935 object.setCreationDate(now);
936 } catch (DatatypeConfigurationException e)
938 System.err.println("error writing date: " + e.toString());
940 object.setVersion(Cache.getDefault("VERSION", "Development Build"));
943 * rjal is full height alignment, jal is actual alignment with full metadata
944 * but excludes hidden sequences.
946 jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
948 if (av.hasHiddenRows())
950 rjal = jal.getHiddenSequences().getFullAlignment();
953 SequenceSet vamsasSet = new SequenceSet();
955 // JalviewModelSequence jms = new JalviewModelSequence();
957 vamsasSet.setGapChar(jal.getGapCharacter() + "");
959 if (jal.getDataset() != null)
961 // dataset id is the dataset's hashcode
962 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
965 // switch jal and the dataset
966 jal = jal.getDataset();
970 if (jal.getProperties() != null)
972 Enumeration en = jal.getProperties().keys();
973 while (en.hasMoreElements())
975 String key = en.nextElement().toString();
976 SequenceSetProperties ssp = new SequenceSetProperties();
978 ssp.setValue(jal.getProperties().get(key).toString());
979 // vamsasSet.addSequenceSetProperties(ssp);
980 vamsasSet.getSequenceSetProperties().add(ssp);
985 Set<String> calcIdSet = new HashSet<>();
986 // record the set of vamsas sequence XML POJO we create.
987 HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
989 for (final SequenceI jds : rjal.getSequences())
991 final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
992 : jds.getDatasetSequence();
993 String id = seqHash(jds);
994 if (vamsasSetIds.get(id) == null)
996 if (seqRefIds.get(id) != null && !storeDS)
998 // This happens for two reasons: 1. multiple views are being
1000 // 2. the hashCode has collided with another sequence's code. This
1002 // HAPPEN! (PF00072.15.stk does this)
1003 // JBPNote: Uncomment to debug writing out of files that do not read
1004 // back in due to ArrayOutOfBoundExceptions.
1005 // System.err.println("vamsasSeq backref: "+id+"");
1006 // System.err.println(jds.getName()+"
1007 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
1008 // System.err.println("Hashcode: "+seqHash(jds));
1009 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
1010 // System.err.println(rsq.getName()+"
1011 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
1012 // System.err.println("Hashcode: "+seqHash(rsq));
1016 vamsasSeq = createVamsasSequence(id, jds);
1017 // vamsasSet.addSequence(vamsasSeq);
1018 vamsasSet.getSequence().add(vamsasSeq);
1019 vamsasSetIds.put(id, vamsasSeq);
1020 seqRefIds.put(id, jds);
1024 jseq.setStart(jds.getStart());
1025 jseq.setEnd(jds.getEnd());
1026 jseq.setColour(av.getSequenceColour(jds).getRGB());
1028 jseq.setId(id); // jseq id should be a string not a number
1031 // Store any sequences this sequence represents
1032 if (av.hasHiddenRows())
1034 // use rjal, contains the full height alignment
1036 av.getAlignment().getHiddenSequences().isHidden(jds));
1038 if (av.isHiddenRepSequence(jds))
1040 jalview.datamodel.SequenceI[] reps = av
1041 .getRepresentedSequences(jds).getSequencesInOrder(rjal);
1043 for (int h = 0; h < reps.length; h++)
1047 // jseq.addHiddenSequences(rjal.findIndex(reps[h]));
1048 jseq.getHiddenSequences().add(rjal.findIndex(reps[h]));
1053 // mark sequence as reference - if it is the reference for this view
1054 if (jal.hasSeqrep())
1056 jseq.setViewreference(jds == jal.getSeqrep());
1060 // TODO: omit sequence features from each alignment view's XML dump if we
1061 // are storing dataset
1062 List<SequenceFeature> sfs = jds.getSequenceFeatures();
1063 for (SequenceFeature sf : sfs)
1065 // Features features = new Features();
1066 Feature features = new Feature();
1068 features.setBegin(sf.getBegin());
1069 features.setEnd(sf.getEnd());
1070 features.setDescription(sf.getDescription());
1071 features.setType(sf.getType());
1072 features.setFeatureGroup(sf.getFeatureGroup());
1073 features.setScore(sf.getScore());
1074 if (sf.links != null)
1076 for (int l = 0; l < sf.links.size(); l++)
1078 OtherData keyValue = new OtherData();
1079 keyValue.setKey("LINK_" + l);
1080 keyValue.setValue(sf.links.elementAt(l).toString());
1081 // features.addOtherData(keyValue);
1082 features.getOtherData().add(keyValue);
1085 if (sf.otherDetails != null)
1088 * save feature attributes, which may be simple strings or
1089 * map valued (have sub-attributes)
1091 for (Entry<String, Object> entry : sf.otherDetails.entrySet())
1093 String key = entry.getKey();
1094 Object value = entry.getValue();
1095 if (value instanceof Map<?, ?>)
1097 for (Entry<String, Object> subAttribute : ((Map<String, Object>) value)
1100 OtherData otherData = new OtherData();
1101 otherData.setKey(key);
1102 otherData.setKey2(subAttribute.getKey());
1103 otherData.setValue(subAttribute.getValue().toString());
1104 // features.addOtherData(otherData);
1105 features.getOtherData().add(otherData);
1110 OtherData otherData = new OtherData();
1111 otherData.setKey(key);
1112 otherData.setValue(value.toString());
1113 // features.addOtherData(otherData);
1114 features.getOtherData().add(otherData);
1119 // jseq.addFeatures(features);
1120 jseq.getFeatures().add(features);
1123 if (jdatasq.getAllPDBEntries() != null)
1125 Enumeration<PDBEntry> en = jdatasq.getAllPDBEntries().elements();
1126 while (en.hasMoreElements())
1128 Pdbids pdb = new Pdbids();
1129 jalview.datamodel.PDBEntry entry = en.nextElement();
1131 String pdbId = entry.getId();
1133 pdb.setType(entry.getType());
1136 * Store any structure views associated with this sequence. This
1137 * section copes with duplicate entries in the project, so a dataset
1138 * only view *should* be coped with sensibly.
1140 // This must have been loaded, is it still visible?
1141 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1142 String matchedFile = null;
1143 for (int f = frames.length - 1; f > -1; f--)
1145 if (frames[f] instanceof StructureViewerBase)
1147 StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
1148 matchedFile = saveStructureViewer(ap, jds, pdb, entry,
1149 viewIds, matchedFile, viewFrame);
1151 * Only store each structure viewer's state once in the project
1152 * jar. First time through only (storeDS==false)
1154 String viewId = viewFrame.getViewId();
1155 String viewerType = viewFrame.getViewerType().toString();
1156 if (!storeDS && !viewIds.contains(viewId))
1158 viewIds.add(viewId);
1159 File viewerState = viewFrame.saveSession();
1160 if (viewerState != null)
1162 copyFileToJar(jout, viewerState.getPath(),
1163 getViewerJarEntryName(viewId), viewerType);
1168 "Failed to save viewer state for " + viewerType);
1174 if (matchedFile != null || entry.getFile() != null)
1176 if (entry.getFile() != null)
1179 matchedFile = entry.getFile();
1181 pdb.setFile(matchedFile); // entry.getFile());
1182 if (pdbfiles == null)
1184 pdbfiles = new ArrayList<>();
1187 if (!pdbfiles.contains(pdbId))
1189 pdbfiles.add(pdbId);
1190 copyFileToJar(jout, matchedFile, pdbId, pdbId);
1194 Enumeration<String> props = entry.getProperties();
1195 if (props.hasMoreElements())
1197 // PdbentryItem item = new PdbentryItem();
1198 while (props.hasMoreElements())
1200 Property prop = new Property();
1201 String key = props.nextElement();
1203 prop.setValue(entry.getProperty(key).toString());
1204 // item.addProperty(prop);
1205 pdb.getProperty().add(prop);
1207 // pdb.addPdbentryItem(item);
1210 // jseq.addPdbids(pdb);
1211 jseq.getPdbids().add(pdb);
1215 saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
1217 // jms.addJSeq(jseq);
1218 object.getJSeq().add(jseq);
1221 if (!storeDS && av.hasHiddenRows())
1223 jal = av.getAlignment();
1227 if (storeDS && jal.getCodonFrames() != null)
1229 List<AlignedCodonFrame> jac = jal.getCodonFrames();
1230 for (AlignedCodonFrame acf : jac)
1232 AlcodonFrame alc = new AlcodonFrame();
1233 if (acf.getProtMappings() != null
1234 && acf.getProtMappings().length > 0)
1236 boolean hasMap = false;
1237 SequenceI[] dnas = acf.getdnaSeqs();
1238 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1239 for (int m = 0; m < pmaps.length; m++)
1241 AlcodMap alcmap = new AlcodMap();
1242 alcmap.setDnasq(seqHash(dnas[m]));
1244 createVamsasMapping(pmaps[m], dnas[m], null, false));
1245 // alc.addAlcodMap(alcmap);
1246 alc.getAlcodMap().add(alcmap);
1251 // vamsasSet.addAlcodonFrame(alc);
1252 vamsasSet.getAlcodonFrame().add(alc);
1255 // TODO: delete this ? dead code from 2.8.3->2.9 ?
1257 // AlcodonFrame alc = new AlcodonFrame();
1258 // vamsasSet.addAlcodonFrame(alc);
1259 // for (int p = 0; p < acf.aaWidth; p++)
1261 // Alcodon cmap = new Alcodon();
1262 // if (acf.codons[p] != null)
1264 // // Null codons indicate a gapped column in the translated peptide
1266 // cmap.setPos1(acf.codons[p][0]);
1267 // cmap.setPos2(acf.codons[p][1]);
1268 // cmap.setPos3(acf.codons[p][2]);
1270 // alc.addAlcodon(cmap);
1272 // if (acf.getProtMappings() != null
1273 // && acf.getProtMappings().length > 0)
1275 // SequenceI[] dnas = acf.getdnaSeqs();
1276 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1277 // for (int m = 0; m < pmaps.length; m++)
1279 // AlcodMap alcmap = new AlcodMap();
1280 // alcmap.setDnasq(seqHash(dnas[m]));
1281 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1283 // alc.addAlcodMap(alcmap);
1290 // /////////////////////////////////
1291 if (!storeDS && av.getCurrentTree() != null)
1293 // FIND ANY ASSOCIATED TREES
1294 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
1295 if (Desktop.desktop != null)
1297 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1299 for (int t = 0; t < frames.length; t++)
1301 if (frames[t] instanceof TreePanel)
1303 TreePanel tp = (TreePanel) frames[t];
1305 if (tp.getTreeCanvas().getViewport().getAlignment() == jal)
1307 JalviewModel.Tree tree = new JalviewModel.Tree();
1308 tree.setTitle(tp.getTitle());
1309 tree.setCurrentTree((av.getCurrentTree() == tp.getTree()));
1310 tree.setNewick(tp.getTree().print());
1311 tree.setThreshold(tp.getTreeCanvas().getThreshold());
1313 tree.setFitToWindow(tp.fitToWindow.getState());
1314 tree.setFontName(tp.getTreeFont().getName());
1315 tree.setFontSize(tp.getTreeFont().getSize());
1316 tree.setFontStyle(tp.getTreeFont().getStyle());
1317 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
1319 tree.setShowBootstrap(tp.bootstrapMenu.getState());
1320 tree.setShowDistances(tp.distanceMenu.getState());
1322 tree.setHeight(tp.getHeight());
1323 tree.setWidth(tp.getWidth());
1324 tree.setXpos(tp.getX());
1325 tree.setYpos(tp.getY());
1326 tree.setId(makeHashCode(tp, null));
1327 tree.setLinkToAllViews(
1328 tp.getTreeCanvas().isApplyToAllViews());
1331 if (tp.isColumnWise())
1333 tree.setColumnWise(true);
1334 String annId = tp.getAssocAnnotation().annotationId;
1335 tree.setColumnReference(annId);
1337 // jms.addTree(tree);
1338 object.getTree().add(tree);
1348 if (!storeDS && Desktop.desktop != null)
1350 for (JInternalFrame frame : Desktop.desktop.getAllFrames())
1352 if (frame instanceof PCAPanel)
1354 PCAPanel panel = (PCAPanel) frame;
1355 if (panel.getAlignViewport().getAlignment() == jal)
1357 savePCA(panel, object);
1365 * store forward refs from an annotationRow to any groups
1367 IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
1370 for (SequenceI sq : jal.getSequences())
1372 // Store annotation on dataset sequences only
1373 AlignmentAnnotation[] aa = sq.getAnnotation();
1374 if (aa != null && aa.length > 0)
1376 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1383 if (jal.getAlignmentAnnotation() != null)
1385 // Store the annotation shown on the alignment.
1386 AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
1387 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1392 if (jal.getGroups() != null)
1394 JGroup[] groups = new JGroup[jal.getGroups().size()];
1396 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
1398 JGroup jGroup = new JGroup();
1399 groups[++i] = jGroup;
1401 jGroup.setStart(sg.getStartRes());
1402 jGroup.setEnd(sg.getEndRes());
1403 jGroup.setName(sg.getName());
1404 if (groupRefs.containsKey(sg))
1406 // group has references so set its ID field
1407 jGroup.setId(groupRefs.get(sg));
1409 ColourSchemeI colourScheme = sg.getColourScheme();
1410 if (colourScheme != null)
1412 ResidueShaderI groupColourScheme = sg.getGroupColourScheme();
1413 if (groupColourScheme.conservationApplied())
1415 jGroup.setConsThreshold(groupColourScheme.getConservationInc());
1417 if (colourScheme instanceof jalview.schemes.UserColourScheme)
1419 jGroup.setColour(setUserColourScheme(colourScheme,
1420 userColours, object));
1424 jGroup.setColour(colourScheme.getSchemeName());
1427 else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
1429 jGroup.setColour("AnnotationColourGradient");
1430 jGroup.setAnnotationColours(constructAnnotationColours(
1431 (jalview.schemes.AnnotationColourGradient) colourScheme,
1432 userColours, object));
1434 else if (colourScheme instanceof jalview.schemes.UserColourScheme)
1437 setUserColourScheme(colourScheme, userColours, object));
1441 jGroup.setColour(colourScheme.getSchemeName());
1444 jGroup.setPidThreshold(groupColourScheme.getThreshold());
1447 jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
1448 jGroup.setDisplayBoxes(sg.getDisplayBoxes());
1449 jGroup.setDisplayText(sg.getDisplayText());
1450 jGroup.setColourText(sg.getColourText());
1451 jGroup.setTextCol1(sg.textColour.getRGB());
1452 jGroup.setTextCol2(sg.textColour2.getRGB());
1453 jGroup.setTextColThreshold(sg.thresholdTextColour);
1454 jGroup.setShowUnconserved(sg.getShowNonconserved());
1455 jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1456 jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
1457 jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
1458 jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1459 for (SequenceI seq : sg.getSequences())
1461 // jGroup.addSeq(seqHash(seq));
1462 jGroup.getSeq().add(seqHash(seq));
1466 // jms.setJGroup(groups);
1468 for (JGroup grp : groups)
1470 object.getJGroup().add(grp);
1475 // /////////SAVE VIEWPORT
1476 Viewport view = new Viewport();
1477 view.setTitle(ap.alignFrame.getTitle());
1478 view.setSequenceSetId(
1479 makeHashCode(av.getSequenceSetId(), av.getSequenceSetId()));
1480 view.setId(av.getViewId());
1481 if (av.getCodingComplement() != null)
1483 view.setComplementId(av.getCodingComplement().getViewId());
1485 view.setViewName(av.getViewName());
1486 view.setGatheredViews(av.isGatherViewsHere());
1488 Rectangle size = ap.av.getExplodedGeometry();
1489 Rectangle position = size;
1492 size = ap.alignFrame.getBounds();
1493 if (av.getCodingComplement() != null)
1495 position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
1503 view.setXpos(position.x);
1504 view.setYpos(position.y);
1506 view.setWidth(size.width);
1507 view.setHeight(size.height);
1509 view.setStartRes(vpRanges.getStartRes());
1510 view.setStartSeq(vpRanges.getStartSeq());
1512 OverviewPanel ov = ap.getOverviewPanel();
1515 Overview overview = new Overview();
1516 overview.setTitle(ov.getTitle());
1517 Rectangle bounds = ov.getFrameBounds();
1518 overview.setXpos(bounds.x);
1519 overview.setYpos(bounds.y);
1520 overview.setWidth(bounds.width);
1521 overview.setHeight(bounds.height);
1522 overview.setShowHidden(ov.isShowHiddenRegions());
1523 overview.setGapColour(ov.getCanvas().getGapColour().getRGB());
1524 overview.setResidueColour(
1525 ov.getCanvas().getResidueColour().getRGB());
1526 overview.setHiddenColour(ov.getCanvas().getHiddenColour().getRGB());
1527 view.setOverview(overview);
1529 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1531 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1532 userColours, object));
1535 .getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1537 AnnotationColourScheme ac = constructAnnotationColours(
1538 (jalview.schemes.AnnotationColourGradient) av
1539 .getGlobalColourScheme(),
1540 userColours, object);
1542 view.setAnnotationColours(ac);
1543 view.setBgColour("AnnotationColourGradient");
1547 view.setBgColour(ColourSchemeProperty
1548 .getColourName(av.getGlobalColourScheme()));
1551 ResidueShaderI vcs = av.getResidueShading();
1552 ColourSchemeI cs = av.getGlobalColourScheme();
1556 if (vcs.conservationApplied())
1558 view.setConsThreshold(vcs.getConservationInc());
1559 if (cs instanceof jalview.schemes.UserColourScheme)
1561 view.setBgColour(setUserColourScheme(cs, userColours, object));
1564 view.setPidThreshold(vcs.getThreshold());
1567 view.setConservationSelected(av.getConservationSelected());
1568 view.setPidSelected(av.getAbovePIDThreshold());
1569 view.setCharHeight(av.getCharHeight());
1570 view.setCharWidth(av.getCharWidth());
1571 final Font font = av.getFont();
1572 view.setFontName(font.getName());
1573 view.setFontSize(font.getSize());
1574 view.setFontStyle(font.getStyle());
1575 view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
1576 view.setRenderGaps(av.isRenderGaps());
1577 view.setShowAnnotation(av.isShowAnnotation());
1578 view.setShowBoxes(av.getShowBoxes());
1579 view.setShowColourText(av.getColourText());
1580 view.setShowFullId(av.getShowJVSuffix());
1581 view.setRightAlignIds(av.isRightAlignIds());
1582 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1583 view.setShowText(av.getShowText());
1584 view.setShowUnconserved(av.getShowUnconserved());
1585 view.setWrapAlignment(av.getWrapAlignment());
1586 view.setTextCol1(av.getTextColour().getRGB());
1587 view.setTextCol2(av.getTextColour2().getRGB());
1588 view.setTextColThreshold(av.getThresholdTextColour());
1589 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1590 view.setShowSequenceLogo(av.isShowSequenceLogo());
1591 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1592 view.setShowGroupConsensus(av.isShowGroupConsensus());
1593 view.setShowGroupConservation(av.isShowGroupConservation());
1594 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1595 view.setShowDbRefTooltip(av.isShowDBRefs());
1596 view.setFollowHighlight(av.isFollowHighlight());
1597 view.setFollowSelection(av.followSelection);
1598 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1599 view.setShowComplementFeatures(av.isShowComplementFeatures());
1600 view.setShowComplementFeaturesOnTop(
1601 av.isShowComplementFeaturesOnTop());
1602 if (av.getFeaturesDisplayed() != null)
1604 FeatureSettings fs = new FeatureSettings();
1606 FeatureRendererModel fr = ap.getSeqPanel().seqCanvas
1607 .getFeatureRenderer();
1608 String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
1610 Vector<String> settingsAdded = new Vector<>();
1611 if (renderOrder != null)
1613 for (String featureType : renderOrder)
1615 FeatureSettings.Setting setting = new FeatureSettings.Setting();
1616 setting.setType(featureType);
1619 * save any filter for the feature type
1621 FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
1624 Iterator<FeatureMatcherI> filters = filter.getMatchers()
1626 FeatureMatcherI firstFilter = filters.next();
1627 setting.setMatcherSet(Jalview2XML.marshalFilter(firstFilter,
1628 filters, filter.isAnded()));
1632 * save colour scheme for the feature type
1634 FeatureColourI fcol = fr.getFeatureStyle(featureType);
1635 if (!fcol.isSimpleColour())
1637 setting.setColour(fcol.getMaxColour().getRGB());
1638 setting.setMincolour(fcol.getMinColour().getRGB());
1639 setting.setMin(fcol.getMin());
1640 setting.setMax(fcol.getMax());
1641 setting.setColourByLabel(fcol.isColourByLabel());
1642 if (fcol.isColourByAttribute())
1644 String[] attName = fcol.getAttributeName();
1645 setting.getAttributeName().add(attName[0]);
1646 if (attName.length > 1)
1648 setting.getAttributeName().add(attName[1]);
1651 setting.setAutoScale(fcol.isAutoScaled());
1652 setting.setThreshold(fcol.getThreshold());
1653 Color noColour = fcol.getNoColour();
1654 if (noColour == null)
1656 setting.setNoValueColour(NoValueColour.NONE);
1658 else if (noColour.equals(fcol.getMaxColour()))
1660 setting.setNoValueColour(NoValueColour.MAX);
1664 setting.setNoValueColour(NoValueColour.MIN);
1666 // -1 = No threshold, 0 = Below, 1 = Above
1667 setting.setThreshstate(fcol.isAboveThreshold() ? 1
1668 : (fcol.isBelowThreshold() ? 0 : -1));
1672 setting.setColour(fcol.getColour().getRGB());
1676 av.getFeaturesDisplayed().isVisible(featureType));
1677 float rorder = fr.getOrder(featureType);
1680 setting.setOrder(rorder);
1682 /// fs.addSetting(setting);
1683 fs.getSetting().add(setting);
1684 settingsAdded.addElement(featureType);
1688 // is groups actually supposed to be a map here ?
1689 Iterator<String> en = fr.getFeatureGroups().iterator();
1690 Vector<String> groupsAdded = new Vector<>();
1691 while (en.hasNext())
1693 String grp = en.next();
1694 if (groupsAdded.contains(grp))
1698 Group g = new Group();
1700 g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
1703 fs.getGroup().add(g);
1704 groupsAdded.addElement(grp);
1706 // jms.setFeatureSettings(fs);
1707 object.setFeatureSettings(fs);
1710 if (av.hasHiddenColumns())
1712 jalview.datamodel.HiddenColumns hidden = av.getAlignment()
1713 .getHiddenColumns();
1717 "REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1721 Iterator<int[]> hiddenRegions = hidden.iterator();
1722 while (hiddenRegions.hasNext())
1724 int[] region = hiddenRegions.next();
1725 HiddenColumns hc = new HiddenColumns();
1726 hc.setStart(region[0]);
1727 hc.setEnd(region[1]);
1728 // view.addHiddenColumns(hc);
1729 view.getHiddenColumns().add(hc);
1733 if (calcIdSet.size() > 0)
1735 for (String calcId : calcIdSet)
1737 if (calcId.trim().length() > 0)
1739 CalcIdParam cidp = createCalcIdParam(calcId, av);
1740 // Some calcIds have no parameters.
1743 // view.addCalcIdParam(cidp);
1744 view.getCalcIdParam().add(cidp);
1750 // jms.addViewport(view);
1751 object.getViewport().add(view);
1753 // object.setJalviewModelSequence(jms);
1754 // object.getVamsasModel().addSequenceSet(vamsasSet);
1755 object.getVamsasModel().getSequenceSet().add(vamsasSet);
1757 if (jout != null && fileName != null)
1759 // We may not want to write the object to disk,
1760 // eg we can copy the alignViewport to a new view object
1761 // using save and then load
1764 fileName = fileName.replace('\\', '/');
1765 System.out.println("Writing jar entry " + fileName);
1766 JarEntry entry = new JarEntry(fileName);
1767 jout.putNextEntry(entry);
1768 PrintWriter pout = new PrintWriter(
1769 new OutputStreamWriter(jout, UTF_8));
1770 JAXBContext jaxbContext = JAXBContext
1771 .newInstance(JalviewModel.class);
1772 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
1774 // output pretty printed
1775 // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1776 jaxbMarshaller.marshal(
1777 new ObjectFactory().createJalviewModel(object), pout);
1779 // jaxbMarshaller.marshal(object, pout);
1780 // marshaller.marshal(object);
1783 } catch (Exception ex)
1785 // TODO: raise error in GUI if marshalling failed.
1786 System.err.println("Error writing Jalview project");
1787 ex.printStackTrace();
1794 * Writes PCA viewer attributes and computed values to an XML model object and
1795 * adds it to the JalviewModel. Any exceptions are reported by logging.
1797 protected void savePCA(PCAPanel panel, JalviewModel object)
1801 PcaViewer viewer = new PcaViewer();
1802 viewer.setHeight(panel.getHeight());
1803 viewer.setWidth(panel.getWidth());
1804 viewer.setXpos(panel.getX());
1805 viewer.setYpos(panel.getY());
1806 viewer.setTitle(panel.getTitle());
1807 PCAModel pcaModel = panel.getPcaModel();
1808 viewer.setScoreModelName(pcaModel.getScoreModelName());
1809 viewer.setXDim(panel.getSelectedDimensionIndex(X));
1810 viewer.setYDim(panel.getSelectedDimensionIndex(Y));
1811 viewer.setZDim(panel.getSelectedDimensionIndex(Z));
1813 panel.getRotatableCanvas().getBackgroundColour().getRGB());
1814 viewer.setScaleFactor(panel.getRotatableCanvas().getScaleFactor());
1815 float[] spMin = panel.getRotatableCanvas().getSeqMin();
1816 SeqPointMin spmin = new SeqPointMin();
1817 spmin.setXPos(spMin[0]);
1818 spmin.setYPos(spMin[1]);
1819 spmin.setZPos(spMin[2]);
1820 viewer.setSeqPointMin(spmin);
1821 float[] spMax = panel.getRotatableCanvas().getSeqMax();
1822 SeqPointMax spmax = new SeqPointMax();
1823 spmax.setXPos(spMax[0]);
1824 spmax.setYPos(spMax[1]);
1825 spmax.setZPos(spMax[2]);
1826 viewer.setSeqPointMax(spmax);
1827 viewer.setShowLabels(panel.getRotatableCanvas().isShowLabels());
1828 viewer.setLinkToAllViews(
1829 panel.getRotatableCanvas().isApplyToAllViews());
1830 SimilarityParamsI sp = pcaModel.getSimilarityParameters();
1831 viewer.setIncludeGaps(sp.includeGaps());
1832 viewer.setMatchGaps(sp.matchGaps());
1833 viewer.setIncludeGappedColumns(sp.includeGappedColumns());
1834 viewer.setDenominateByShortestLength(sp.denominateByShortestLength());
1837 * sequence points on display
1839 for (jalview.datamodel.SequencePoint spt : pcaModel
1840 .getSequencePoints())
1842 SequencePoint point = new SequencePoint();
1843 point.setSequenceRef(seqHash(spt.getSequence()));
1844 point.setXPos(spt.coord.x);
1845 point.setYPos(spt.coord.y);
1846 point.setZPos(spt.coord.z);
1847 viewer.getSequencePoint().add(point);
1851 * (end points of) axes on display
1853 for (Point p : panel.getRotatableCanvas().getAxisEndPoints())
1856 Axis axis = new Axis();
1860 viewer.getAxis().add(axis);
1864 * raw PCA data (note we are not restoring PCA inputs here -
1865 * alignment view, score model, similarity parameters)
1867 PcaDataType data = new PcaDataType();
1868 viewer.setPcaData(data);
1869 PCA pca = pcaModel.getPcaData();
1871 DoubleMatrix pm = new DoubleMatrix();
1872 saveDoubleMatrix(pca.getPairwiseScores(), pm);
1873 data.setPairwiseMatrix(pm);
1875 DoubleMatrix tm = new DoubleMatrix();
1876 saveDoubleMatrix(pca.getTridiagonal(), tm);
1877 data.setTridiagonalMatrix(tm);
1879 DoubleMatrix eigenMatrix = new DoubleMatrix();
1880 data.setEigenMatrix(eigenMatrix);
1881 saveDoubleMatrix(pca.getEigenmatrix(), eigenMatrix);
1883 object.getPcaViewer().add(viewer);
1884 } catch (Throwable t)
1886 Console.error("Error saving PCA: " + t.getMessage());
1891 * Stores values from a matrix into an XML element, including (if present) the
1896 * @see #loadDoubleMatrix(DoubleMatrix)
1898 protected void saveDoubleMatrix(MatrixI m, DoubleMatrix xmlMatrix)
1900 xmlMatrix.setRows(m.height());
1901 xmlMatrix.setColumns(m.width());
1902 for (int i = 0; i < m.height(); i++)
1904 DoubleVector row = new DoubleVector();
1905 for (int j = 0; j < m.width(); j++)
1907 row.getV().add(m.getValue(i, j));
1909 xmlMatrix.getRow().add(row);
1911 if (m.getD() != null)
1913 DoubleVector dVector = new DoubleVector();
1914 for (double d : m.getD())
1916 dVector.getV().add(d);
1918 xmlMatrix.setD(dVector);
1920 if (m.getE() != null)
1922 DoubleVector eVector = new DoubleVector();
1923 for (double e : m.getE())
1925 eVector.getV().add(e);
1927 xmlMatrix.setE(eVector);
1932 * Loads XML matrix data into a new Matrix object, including the D and/or E
1933 * vectors (if present)
1937 * @see Jalview2XML#saveDoubleMatrix(MatrixI, DoubleMatrix)
1939 protected MatrixI loadDoubleMatrix(DoubleMatrix mData)
1941 int rows = mData.getRows();
1942 double[][] vals = new double[rows][];
1944 for (int i = 0; i < rows; i++)
1946 List<Double> dVector = mData.getRow().get(i).getV();
1947 vals[i] = new double[dVector.size()];
1949 for (Double d : dVector)
1955 MatrixI m = new Matrix(vals);
1957 if (mData.getD() != null)
1959 List<Double> dVector = mData.getD().getV();
1960 double[] vec = new double[dVector.size()];
1962 for (Double d : dVector)
1968 if (mData.getE() != null)
1970 List<Double> dVector = mData.getE().getV();
1971 double[] vec = new double[dVector.size()];
1973 for (Double d : dVector)
1984 * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
1985 * for each viewer, with
1987 * <li>viewer geometry (position, size, split pane divider location)</li>
1988 * <li>index of the selected structure in the viewer (currently shows gapped
1990 * <li>the id of the annotation holding RNA secondary structure</li>
1991 * <li>(currently only one SS is shown per viewer, may be more in future)</li>
1993 * Varna viewer state is also written out (in native Varna XML) to separate
1994 * project jar entries. A separate entry is written for each RNA structure
1995 * displayed, with the naming convention
1997 * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
2005 * @param storeDataset
2007 protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
2008 final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
2009 boolean storeDataset)
2011 if (Desktop.desktop == null)
2015 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2016 for (int f = frames.length - 1; f > -1; f--)
2018 if (frames[f] instanceof AppVarna)
2020 AppVarna varna = (AppVarna) frames[f];
2022 * link the sequence to every viewer that is showing it and is linked to
2023 * its alignment panel
2025 if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
2027 String viewId = varna.getViewId();
2028 RnaViewer rna = new RnaViewer();
2029 rna.setViewId(viewId);
2030 rna.setTitle(varna.getTitle());
2031 rna.setXpos(varna.getX());
2032 rna.setYpos(varna.getY());
2033 rna.setWidth(varna.getWidth());
2034 rna.setHeight(varna.getHeight());
2035 rna.setDividerLocation(varna.getDividerLocation());
2036 rna.setSelectedRna(varna.getSelectedIndex());
2037 // jseq.addRnaViewer(rna);
2038 jseq.getRnaViewer().add(rna);
2041 * Store each Varna panel's state once in the project per sequence.
2042 * First time through only (storeDataset==false)
2044 // boolean storeSessions = false;
2045 // String sequenceViewId = viewId + seqsToIds.get(jds);
2046 // if (!storeDataset && !viewIds.contains(sequenceViewId))
2048 // viewIds.add(sequenceViewId);
2049 // storeSessions = true;
2051 for (RnaModel model : varna.getModels())
2053 if (model.seq == jds)
2056 * VARNA saves each view (sequence or alignment secondary
2057 * structure, gapped or trimmed) as a separate XML file
2059 String jarEntryName = rnaSessions.get(model);
2060 if (jarEntryName == null)
2063 String varnaStateFile = varna.getStateInfo(model.rna);
2064 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
2065 copyFileToJar(jout, varnaStateFile, jarEntryName, "Varna");
2066 rnaSessions.put(model, jarEntryName);
2068 SecondaryStructure ss = new SecondaryStructure();
2069 String annotationId = varna.getAnnotation(jds).annotationId;
2070 ss.setAnnotationId(annotationId);
2071 ss.setViewerState(jarEntryName);
2072 ss.setGapped(model.gapped);
2073 ss.setTitle(model.title);
2074 // rna.addSecondaryStructure(ss);
2075 rna.getSecondaryStructure().add(ss);
2084 * Copy the contents of a file to a new entry added to the output jar
2088 * @param jarEntryName
2090 * additional identifying info to log to the console
2092 protected void copyFileToJar(JarOutputStream jout, String infilePath,
2093 String jarEntryName, String msg)
2095 try (InputStream is = new FileInputStream(infilePath))
2097 File file = new File(infilePath);
2098 if (file.exists() && jout != null)
2101 "Writing jar entry " + jarEntryName + " (" + msg + ")");
2102 jout.putNextEntry(new JarEntry(jarEntryName));
2105 // dis = new DataInputStream(new FileInputStream(file));
2106 // byte[] data = new byte[(int) file.length()];
2107 // dis.readFully(data);
2108 // writeJarEntry(jout, jarEntryName, data);
2110 } catch (Exception ex)
2112 ex.printStackTrace();
2117 * Copies input to output, in 4K buffers; handles any data (text or binary)
2121 * @throws IOException
2123 protected void copyAll(InputStream in, OutputStream out)
2126 byte[] buffer = new byte[4096];
2128 while ((bytesRead = in.read(buffer)) != -1)
2130 out.write(buffer, 0, bytesRead);
2135 * Save the state of a structure viewer
2140 * the archive XML element under which to save the state
2143 * @param matchedFile
2147 protected String saveStructureViewer(AlignmentPanel ap, SequenceI jds,
2148 Pdbids pdb, PDBEntry entry, List<String> viewIds,
2149 String matchedFile, StructureViewerBase viewFrame)
2151 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
2154 * Look for any bindings for this viewer to the PDB file of interest
2155 * (including part matches excluding chain id)
2157 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
2159 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
2160 final String pdbId = pdbentry.getId();
2161 if (!pdbId.equals(entry.getId()) && !(entry.getId().length() > 4
2162 && entry.getId().toLowerCase(Locale.ROOT)
2163 .startsWith(pdbId.toLowerCase(Locale.ROOT))))
2166 * not interested in a binding to a different PDB entry here
2170 if (matchedFile == null)
2172 matchedFile = pdbentry.getFile();
2174 else if (!matchedFile.equals(pdbentry.getFile()))
2177 "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
2178 + pdbentry.getFile());
2182 // can get at it if the ID
2183 // match is ambiguous (e.g.
2186 for (int smap = 0; smap < viewFrame.getBinding()
2187 .getSequence()[peid].length; smap++)
2189 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
2190 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
2192 StructureState state = new StructureState();
2193 state.setVisible(true);
2194 state.setXpos(viewFrame.getX());
2195 state.setYpos(viewFrame.getY());
2196 state.setWidth(viewFrame.getWidth());
2197 state.setHeight(viewFrame.getHeight());
2198 final String viewId = viewFrame.getViewId();
2199 state.setViewId(viewId);
2200 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
2201 state.setColourwithAlignPanel(viewFrame.isUsedForColourBy(ap));
2202 state.setColourByJmol(viewFrame.isColouredByViewer());
2203 state.setType(viewFrame.getViewerType().toString());
2204 // pdb.addStructureState(state);
2205 pdb.getStructureState().add(state);
2213 * Populates the AnnotationColourScheme xml for save. This captures the
2214 * settings of the options in the 'Colour by Annotation' dialog.
2217 * @param userColours
2221 private AnnotationColourScheme constructAnnotationColours(
2222 AnnotationColourGradient acg, List<UserColourScheme> userColours,
2225 AnnotationColourScheme ac = new AnnotationColourScheme();
2226 ac.setAboveThreshold(acg.getAboveThreshold());
2227 ac.setThreshold(acg.getAnnotationThreshold());
2228 // 2.10.2 save annotationId (unique) not annotation label
2229 ac.setAnnotation(acg.getAnnotation().annotationId);
2230 if (acg.getBaseColour() instanceof UserColourScheme)
2233 setUserColourScheme(acg.getBaseColour(), userColours, jm));
2238 ColourSchemeProperty.getColourName(acg.getBaseColour()));
2241 ac.setMaxColour(acg.getMaxColour().getRGB());
2242 ac.setMinColour(acg.getMinColour().getRGB());
2243 ac.setPerSequence(acg.isSeqAssociated());
2244 ac.setPredefinedColours(acg.isPredefinedColours());
2248 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
2249 IdentityHashMap<SequenceGroup, String> groupRefs,
2250 AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
2251 SequenceSet vamsasSet)
2254 for (int i = 0; i < aa.length; i++)
2256 Annotation an = new Annotation();
2258 AlignmentAnnotation annotation = aa[i];
2259 if (annotation.annotationId != null)
2261 annotationIds.put(annotation.annotationId, annotation);
2264 an.setId(annotation.annotationId);
2266 an.setVisible(annotation.visible);
2268 an.setDescription(annotation.description);
2270 if (annotation.sequenceRef != null)
2272 // 2.9 JAL-1781 xref on sequence id rather than name
2273 an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
2275 if (annotation.groupRef != null)
2277 String groupIdr = groupRefs.get(annotation.groupRef);
2278 if (groupIdr == null)
2280 // make a locally unique String
2281 groupRefs.put(annotation.groupRef,
2282 groupIdr = ("" + System.currentTimeMillis()
2283 + annotation.groupRef.getName()
2284 + groupRefs.size()));
2286 an.setGroupRef(groupIdr.toString());
2289 // store all visualization attributes for annotation
2290 an.setGraphHeight(annotation.graphHeight);
2291 an.setCentreColLabels(annotation.centreColLabels);
2292 an.setScaleColLabels(annotation.scaleColLabel);
2293 an.setShowAllColLabels(annotation.showAllColLabels);
2294 an.setBelowAlignment(annotation.belowAlignment);
2296 if (annotation.graph > 0)
2299 an.setGraphType(annotation.graph);
2300 an.setGraphGroup(annotation.graphGroup);
2301 if (annotation.getThreshold() != null)
2303 ThresholdLine line = new ThresholdLine();
2304 line.setLabel(annotation.getThreshold().label);
2305 line.setValue(annotation.getThreshold().value);
2306 line.setColour(annotation.getThreshold().colour.getRGB());
2307 an.setThresholdLine(line);
2309 if (annotation.graph == AlignmentAnnotation.CONTACT_MAP)
2311 if (annotation.sequenceRef.getContactMaps() != null)
2313 ContactMatrixI cm = annotation.sequenceRef
2314 .getContactMatrixFor(annotation);
2317 MatrixType xmlmat = new MatrixType();
2318 xmlmat.setType(cm.getType());
2319 xmlmat.setRows(BigInteger.valueOf(cm.getWidth()));
2320 xmlmat.setCols(BigInteger.valueOf(cm.getHeight()));
2321 // consider using an opaque to/from -> allow instance to control
2322 // its representation ?
2323 xmlmat.setElements(ContactMatrix.contactToFloatString(cm));
2326 for (BitSet gp : cm.getGroups())
2328 xmlmat.getGroups().add(stringifyBitset(gp));
2333 // provenance object for tree ?
2334 xmlmat.getNewick().add(cm.getNewick());
2335 xmlmat.setTreeMethod(cm.getTreeMethod());
2337 if (cm.hasCutHeight())
2339 xmlmat.setCutHeight(cm.getCutHeight());
2341 // set/get properties
2342 if (cm instanceof MappableContactMatrixI)
2344 jalview.util.MapList mlst = ((MappableContactMatrixI) cm)
2345 .getMapFor(annotation.sequenceRef);
2348 MapListType mp = new MapListType();
2349 List<int[]> r = mlst.getFromRanges();
2350 for (int[] range : r)
2352 MapListFrom mfrom = new MapListFrom();
2353 mfrom.setStart(range[0]);
2354 mfrom.setEnd(range[1]);
2355 // mp.addMapListFrom(mfrom);
2356 mp.getMapListFrom().add(mfrom);
2358 r = mlst.getToRanges();
2359 for (int[] range : r)
2361 MapListTo mto = new MapListTo();
2362 mto.setStart(range[0]);
2363 mto.setEnd(range[1]);
2364 // mp.addMapListTo(mto);
2365 mp.getMapListTo().add(mto);
2368 BigInteger.valueOf(mlst.getFromRatio()));
2369 mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
2370 xmlmat.setMapping(mp);
2374 an.getContactmatrix().add(xmlmat);
2384 an.setLabel(annotation.label);
2386 if (annotation == av.getAlignmentQualityAnnot()
2387 || annotation == av.getAlignmentConservationAnnotation()
2388 || annotation == av.getAlignmentConsensusAnnotation()
2389 || annotation.autoCalculated)
2391 // new way of indicating autocalculated annotation -
2392 an.setAutoCalculated(annotation.autoCalculated);
2394 if (annotation.hasScore())
2396 an.setScore(annotation.getScore());
2399 if (annotation.getCalcId() != null)
2401 calcIdSet.add(annotation.getCalcId());
2402 an.setCalcId(annotation.getCalcId());
2404 if (annotation.hasProperties())
2406 for (String pr : annotation.getProperties())
2408 jalview.xml.binding.jalview.Property prop = new jalview.xml.binding.jalview.Property();
2410 prop.setValue(annotation.getProperty(pr));
2411 an.getProperty().add(prop);
2415 AnnotationElement ae;
2416 if (annotation.annotations != null)
2418 an.setScoreOnly(false);
2419 for (int a = 0; a < annotation.annotations.length; a++)
2421 if ((annotation == null) || (annotation.annotations[a] == null))
2426 ae = new AnnotationElement();
2427 if (annotation.annotations[a].description != null)
2429 ae.setDescription(annotation.annotations[a].description);
2431 if (annotation.annotations[a].displayCharacter != null)
2433 ae.setDisplayCharacter(
2434 annotation.annotations[a].displayCharacter);
2437 if (!Float.isNaN(annotation.annotations[a].value))
2439 ae.setValue(annotation.annotations[a].value);
2443 if (annotation.annotations[a].secondaryStructure > ' ')
2445 ae.setSecondaryStructure(
2446 annotation.annotations[a].secondaryStructure + "");
2449 if (annotation.annotations[a].colour != null
2450 && annotation.annotations[a].colour != java.awt.Color.black)
2452 ae.setColour(annotation.annotations[a].colour.getRGB());
2455 // an.addAnnotationElement(ae);
2456 an.getAnnotationElement().add(ae);
2457 if (annotation.autoCalculated)
2459 // only write one non-null entry into the annotation row -
2460 // sufficient to get the visualization attributes necessary to
2468 an.setScoreOnly(true);
2470 if (!storeDS || (storeDS && !annotation.autoCalculated))
2472 // skip autocalculated annotation - these are only provided for
2474 // vamsasSet.addAnnotation(an);
2475 vamsasSet.getAnnotation().add(an);
2481 private String stringifyBitset(BitSet gp)
2483 StringBuilder sb = new StringBuilder();
2484 for (long val : gp.toLongArray())
2486 if (sb.length() > 0)
2492 return sb.toString();
2495 private BitSet deStringifyBitset(String stringified)
2497 if ("".equals(stringified) || stringified == null)
2499 return new BitSet();
2501 String[] longvals = stringified.split(",");
2502 long[] newlongvals = new long[longvals.length];
2503 for (int lv = 0; lv < longvals.length; lv++)
2507 newlongvals[lv] = Long.valueOf(longvals[lv]);
2508 } catch (Exception x)
2510 errorMessage += "Couldn't destringify bitset from: '" + stringified
2512 newlongvals[lv] = 0;
2515 return BitSet.valueOf(newlongvals);
2519 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
2521 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
2522 if (settings != null)
2524 CalcIdParam vCalcIdParam = new CalcIdParam();
2525 vCalcIdParam.setCalcId(calcId);
2526 // vCalcIdParam.addServiceURL(settings.getServiceURI());
2527 vCalcIdParam.getServiceURL().add(settings.getServiceURI());
2528 // generic URI allowing a third party to resolve another instance of the
2529 // service used for this calculation
2530 for (String url : settings.getServiceURLs())
2532 // vCalcIdParam.addServiceURL(urls);
2533 vCalcIdParam.getServiceURL().add(url);
2535 vCalcIdParam.setVersion("1.0");
2536 if (settings.getPreset() != null)
2538 WsParamSetI setting = settings.getPreset();
2539 vCalcIdParam.setName(setting.getName());
2540 vCalcIdParam.setDescription(setting.getDescription());
2544 vCalcIdParam.setName("");
2545 vCalcIdParam.setDescription("Last used parameters");
2547 // need to be able to recover 1) settings 2) user-defined presets or
2548 // recreate settings from preset 3) predefined settings provided by
2549 // service - or settings that can be transferred (or discarded)
2550 vCalcIdParam.setParameters(
2551 settings.getWsParamFile().replace("\n", "|\\n|"));
2552 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
2553 // todo - decide if updateImmediately is needed for any projects.
2555 return vCalcIdParam;
2560 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
2563 if (calcIdParam.getVersion().equals("1.0"))
2565 final String[] calcIds = calcIdParam.getServiceURL()
2566 .toArray(new String[0]);
2567 Jws2Instance service = Jws2Discoverer.getDiscoverer()
2568 .getPreferredServiceFor(calcIds);
2569 if (service != null)
2571 WsParamSetI parmSet = null;
2574 parmSet = service.getParamStore().parseServiceParameterFile(
2575 calcIdParam.getName(), calcIdParam.getDescription(),
2577 calcIdParam.getParameters().replace("|\\n|", "\n"));
2578 } catch (IOException x)
2580 Console.warn("Couldn't parse parameter data for "
2581 + calcIdParam.getCalcId(), x);
2584 List<ArgumentI> argList = null;
2585 if (calcIdParam.getName().length() > 0)
2587 parmSet = service.getParamStore()
2588 .getPreset(calcIdParam.getName());
2589 if (parmSet != null)
2591 // TODO : check we have a good match with settings in AACon -
2592 // otherwise we'll need to create a new preset
2597 argList = parmSet.getArguments();
2600 AAConSettings settings = new AAConSettings(
2601 calcIdParam.isAutoUpdate(), service, parmSet, argList);
2602 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
2603 calcIdParam.isNeedsUpdate());
2609 "Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
2613 throw new Error(MessageManager.formatMessage(
2614 "error.unsupported_version_calcIdparam", new Object[]
2615 { calcIdParam.toString() }));
2619 * External mapping between jalview objects and objects yielding a valid and
2620 * unique object ID string. This is null for normal Jalview project IO, but
2621 * non-null when a jalview project is being read or written as part of a
2624 IdentityHashMap jv2vobj = null;
2627 * Construct a unique ID for jvobj using either existing bindings or if none
2628 * exist, the result of the hashcode call for the object.
2631 * jalview data object
2632 * @return unique ID for referring to jvobj
2634 private String makeHashCode(Object jvobj, String altCode)
2636 if (jv2vobj != null)
2638 Object id = jv2vobj.get(jvobj);
2641 return id.toString();
2643 // check string ID mappings
2644 if (jvids2vobj != null && jvobj instanceof String)
2646 id = jvids2vobj.get(jvobj);
2650 return id.toString();
2652 // give up and warn that something has gone wrong
2654 "Cannot find ID for object in external mapping : " + jvobj);
2660 * return local jalview object mapped to ID, if it exists
2664 * @return null or object bound to idcode
2666 private Object retrieveExistingObj(String idcode)
2668 if (idcode != null && vobj2jv != null)
2670 return vobj2jv.get(idcode);
2676 * binding from ID strings from external mapping table to jalview data model
2679 private Hashtable vobj2jv;
2681 private Sequence createVamsasSequence(String id, SequenceI jds)
2683 return createVamsasSequence(true, id, jds, null);
2686 private Sequence createVamsasSequence(boolean recurse, String id,
2687 SequenceI jds, SequenceI parentseq)
2689 Sequence vamsasSeq = new Sequence();
2690 vamsasSeq.setId(id);
2691 vamsasSeq.setName(jds.getName());
2692 vamsasSeq.setSequence(jds.getSequenceAsString());
2693 vamsasSeq.setDescription(jds.getDescription());
2694 List<DBRefEntry> dbrefs = null;
2695 if (jds.getDatasetSequence() != null)
2697 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
2701 // seqId==dsseqid so we can tell which sequences really are
2702 // dataset sequences only
2703 vamsasSeq.setDsseqid(id);
2704 dbrefs = jds.getDBRefs();
2705 if (parentseq == null)
2712 * save any dbrefs; special subclass GeneLocus is flagged as 'locus'
2716 for (int d = 0, nd = dbrefs.size(); d < nd; d++)
2718 DBRef dbref = new DBRef();
2719 DBRefEntry ref = dbrefs.get(d);
2720 dbref.setSource(ref.getSource());
2721 dbref.setVersion(ref.getVersion());
2722 dbref.setAccessionId(ref.getAccessionId());
2723 dbref.setCanonical(ref.isCanonical());
2724 if (ref instanceof GeneLocus)
2726 dbref.setLocus(true);
2730 Mapping mp = createVamsasMapping(ref.getMap(), parentseq, jds,
2732 dbref.setMapping(mp);
2734 vamsasSeq.getDBRef().add(dbref);
2740 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
2741 SequenceI parentseq, SequenceI jds, boolean recurse)
2744 if (jmp.getMap() != null)
2748 jalview.util.MapList mlst = jmp.getMap();
2749 List<int[]> r = mlst.getFromRanges();
2750 for (int[] range : r)
2752 MapListFrom mfrom = new MapListFrom();
2753 mfrom.setStart(range[0]);
2754 mfrom.setEnd(range[1]);
2755 // mp.addMapListFrom(mfrom);
2756 mp.getMapListFrom().add(mfrom);
2758 r = mlst.getToRanges();
2759 for (int[] range : r)
2761 MapListTo mto = new MapListTo();
2762 mto.setStart(range[0]);
2763 mto.setEnd(range[1]);
2764 // mp.addMapListTo(mto);
2765 mp.getMapListTo().add(mto);
2767 mp.setMapFromUnit(BigInteger.valueOf(mlst.getFromRatio()));
2768 mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
2769 if (jmp.getTo() != null)
2771 // MappingChoice mpc = new MappingChoice();
2773 // check/create ID for the sequence referenced by getTo()
2776 SequenceI ps = null;
2777 if (parentseq != jmp.getTo()
2778 && parentseq.getDatasetSequence() != jmp.getTo())
2780 // chaining dbref rather than a handshaking one
2781 jmpid = seqHash(ps = jmp.getTo());
2785 jmpid = seqHash(ps = parentseq);
2787 // mpc.setDseqFor(jmpid);
2788 mp.setDseqFor(jmpid);
2789 if (!seqRefIds.containsKey(jmpid))
2791 Console.debug("creatign new DseqFor ID");
2792 seqRefIds.put(jmpid, ps);
2796 Console.debug("reusing DseqFor ID");
2799 // mp.setMappingChoice(mpc);
2805 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
2806 List<UserColourScheme> userColours, JalviewModel jm)
2809 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
2810 boolean newucs = false;
2811 if (!userColours.contains(ucs))
2813 userColours.add(ucs);
2816 id = "ucs" + userColours.indexOf(ucs);
2819 // actually create the scheme's entry in the XML model
2820 java.awt.Color[] colours = ucs.getColours();
2821 UserColours uc = new UserColours();
2822 // UserColourScheme jbucs = new UserColourScheme();
2823 JalviewUserColours jbucs = new JalviewUserColours();
2825 for (int i = 0; i < colours.length; i++)
2827 Colour col = new Colour();
2828 col.setName(ResidueProperties.aa[i]);
2829 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2830 // jbucs.addColour(col);
2831 jbucs.getColour().add(col);
2833 if (ucs.getLowerCaseColours() != null)
2835 colours = ucs.getLowerCaseColours();
2836 for (int i = 0; i < colours.length; i++)
2838 Colour col = new Colour();
2839 col.setName(ResidueProperties.aa[i].toLowerCase(Locale.ROOT));
2840 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2841 // jbucs.addColour(col);
2842 jbucs.getColour().add(col);
2847 uc.setUserColourScheme(jbucs);
2848 // jm.addUserColours(uc);
2849 jm.getUserColours().add(uc);
2855 jalview.schemes.UserColourScheme getUserColourScheme(JalviewModel jm,
2858 List<UserColours> uc = jm.getUserColours();
2859 UserColours colours = null;
2861 for (int i = 0; i < uc.length; i++)
2863 if (uc[i].getId().equals(id))
2870 for (UserColours c : uc)
2872 if (c.getId().equals(id))
2879 java.awt.Color[] newColours = new java.awt.Color[24];
2881 for (int i = 0; i < 24; i++)
2883 newColours[i] = new java.awt.Color(Integer.parseInt(
2884 // colours.getUserColourScheme().getColour(i).getRGB(), 16));
2885 colours.getUserColourScheme().getColour().get(i).getRGB(),
2889 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
2892 if (colours.getUserColourScheme().getColour().size()/*Count()*/ > 24)
2894 newColours = new java.awt.Color[23];
2895 for (int i = 0; i < 23; i++)
2897 newColours[i] = new java.awt.Color(
2898 Integer.parseInt(colours.getUserColourScheme().getColour()
2899 .get(i + 24).getRGB(), 16));
2901 ucs.setLowerCaseColours(newColours);
2908 * contains last error message (if any) encountered by XML loader.
2910 String errorMessage = null;
2913 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
2914 * exceptions are raised during project XML parsing
2916 public boolean attemptversion1parse = false;
2919 * Load a jalview project archive from a jar file
2922 * - HTTP URL or filename
2924 public AlignFrame loadJalviewAlign(final Object file)
2927 jalview.gui.AlignFrame af = null;
2931 // create list to store references for any new Jmol viewers created
2932 newStructureViewers = new Vector<>();
2933 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
2934 // Workaround is to make sure caller implements the JarInputStreamProvider
2936 // so we can re-open the jar input stream for each entry.
2938 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
2939 af = loadJalviewAlign(jprovider);
2942 af.setMenusForViewport();
2944 } catch (MalformedURLException e)
2946 errorMessage = "Invalid URL format for '" + file + "'";
2952 SwingUtilities.invokeAndWait(new Runnable()
2957 setLoadingFinishedForNewStructureViewers();
2960 } catch (Exception x)
2962 System.err.println("Error loading alignment: " + x.getMessage());
2968 @SuppressWarnings("unused")
2969 private jarInputStreamProvider createjarInputStreamProvider(
2970 final Object ofile) throws MalformedURLException
2973 // BH 2018 allow for bytes already attached to File object
2976 String file = (ofile instanceof File
2977 ? ((File) ofile).getCanonicalPath()
2978 : ofile.toString());
2979 byte[] bytes = Platform.isJS() ? Platform.getFileBytes((File) ofile)
2982 errorMessage = null;
2983 uniqueSetSuffix = null;
2985 viewportsAdded.clear();
2986 frefedSequence = null;
2988 if (HttpUtils.startsWithHttpOrHttps(file))
2990 url = new URL(file);
2992 final URL _url = url;
2993 return new jarInputStreamProvider()
2997 public JarInputStream getJarInputStream() throws IOException
3001 // System.out.println("Jalview2XML: opening byte jarInputStream for
3002 // bytes.length=" + bytes.length);
3003 return new JarInputStream(new ByteArrayInputStream(bytes));
3007 // System.out.println("Jalview2XML: opening url jarInputStream for "
3009 return new JarInputStream(_url.openStream());
3013 // System.out.println("Jalview2XML: opening file jarInputStream for
3015 return new JarInputStream(new FileInputStream(file));
3020 public String getFilename()
3025 } catch (IOException e)
3027 e.printStackTrace();
3033 * Recover jalview session from a jalview project archive. Caller may
3034 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
3035 * themselves. Any null fields will be initialised with default values,
3036 * non-null fields are left alone.
3041 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
3043 errorMessage = null;
3044 if (uniqueSetSuffix == null)
3046 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
3048 if (seqRefIds == null)
3052 AlignFrame af = null, _af = null;
3053 IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
3054 Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
3055 final String file = jprovider.getFilename();
3058 JarInputStream jin = null;
3059 JarEntry jarentry = null;
3064 jin = jprovider.getJarInputStream();
3065 for (int i = 0; i < entryCount; i++)
3067 jarentry = jin.getNextJarEntry();
3070 if (jarentry != null && jarentry.getName().endsWith(".xml"))
3072 JAXBContext jc = JAXBContext
3073 .newInstance("jalview.xml.binding.jalview");
3074 XMLStreamReader streamReader = XMLInputFactory.newInstance()
3075 .createXMLStreamReader(jin);
3076 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
3077 JAXBElement<JalviewModel> jbe = um.unmarshal(streamReader,
3078 JalviewModel.class);
3079 JalviewModel object = jbe.getValue();
3081 if (true) // !skipViewport(object))
3083 _af = loadFromObject(object, file, true, jprovider);
3084 if (_af != null && object.getViewport().size() > 0)
3085 // getJalviewModelSequence().getViewportCount() > 0)
3089 // store a reference to the first view
3092 if (_af.getViewport().isGatherViewsHere())
3094 // if this is a gathered view, keep its reference since
3095 // after gathering views, only this frame will remain
3097 gatherToThisFrame.put(_af.getViewport().getSequenceSetId(),
3100 // Save dataset to register mappings once all resolved
3101 importedDatasets.put(
3102 af.getViewport().getAlignment().getDataset(),
3103 af.getViewport().getAlignment().getDataset());
3108 else if (jarentry != null)
3110 // Some other file here.
3113 } while (jarentry != null);
3115 resolveFrefedSequences();
3116 } catch (IOException ex)
3118 ex.printStackTrace();
3119 errorMessage = "Couldn't locate Jalview XML file : " + file;
3121 "Exception whilst loading jalview XML file : " + ex + "\n");
3122 } catch (Exception ex)
3124 System.err.println("Parsing as Jalview Version 2 file failed.");
3125 ex.printStackTrace(System.err);
3126 if (attemptversion1parse)
3128 // used to attempt to parse as V1 castor-generated xml
3130 if (Desktop.instance != null)
3132 Desktop.instance.stopLoading();
3136 System.out.println("Successfully loaded archive file");
3139 ex.printStackTrace();
3142 "Exception whilst loading jalview XML file : " + ex + "\n");
3143 } catch (OutOfMemoryError e)
3145 // Don't use the OOM Window here
3146 errorMessage = "Out of memory loading jalview XML file";
3147 System.err.println("Out of memory whilst loading jalview XML file");
3148 e.printStackTrace();
3152 * Regather multiple views (with the same sequence set id) to the frame (if
3153 * any) that is flagged as the one to gather to, i.e. convert them to tabbed
3154 * views instead of separate frames. Note this doesn't restore a state where
3155 * some expanded views in turn have tabbed views - the last "first tab" read
3156 * in will play the role of gatherer for all.
3158 for (AlignFrame fr : gatherToThisFrame.values())
3160 Desktop.instance.gatherViews(fr);
3163 restoreSplitFrames();
3164 for (AlignmentI ds : importedDatasets.keySet())
3166 if (ds.getCodonFrames() != null)
3168 StructureSelectionManager
3169 .getStructureSelectionManager(Desktop.instance)
3170 .registerMappings(ds.getCodonFrames());
3173 if (errorMessage != null)
3178 if (Desktop.instance != null)
3180 Desktop.instance.stopLoading();
3187 * Try to reconstruct and display SplitFrame windows, where each contains
3188 * complementary dna and protein alignments. Done by pairing up AlignFrame
3189 * objects (created earlier) which have complementary viewport ids associated.
3191 protected void restoreSplitFrames()
3193 List<SplitFrame> gatherTo = new ArrayList<>();
3194 List<AlignFrame> addedToSplitFrames = new ArrayList<>();
3195 Map<String, AlignFrame> dna = new HashMap<>();
3198 * Identify the DNA alignments
3200 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3203 AlignFrame af = candidate.getValue();
3204 if (af.getViewport().getAlignment().isNucleotide())
3206 dna.put(candidate.getKey().getId(), af);
3211 * Try to match up the protein complements
3213 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3216 AlignFrame af = candidate.getValue();
3217 if (!af.getViewport().getAlignment().isNucleotide())
3219 String complementId = candidate.getKey().getComplementId();
3220 // only non-null complements should be in the Map
3221 if (complementId != null && dna.containsKey(complementId))
3223 final AlignFrame dnaFrame = dna.get(complementId);
3224 SplitFrame sf = createSplitFrame(dnaFrame, af);
3225 addedToSplitFrames.add(dnaFrame);
3226 addedToSplitFrames.add(af);
3227 dnaFrame.setMenusForViewport();
3228 af.setMenusForViewport();
3229 if (af.getViewport().isGatherViewsHere())
3238 * Open any that we failed to pair up (which shouldn't happen!) as
3239 * standalone AlignFrame's.
3241 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
3244 AlignFrame af = candidate.getValue();
3245 if (!addedToSplitFrames.contains(af))
3247 Viewport view = candidate.getKey();
3248 Desktop.addInternalFrame(af, view.getTitle(),
3249 safeInt(view.getWidth()), safeInt(view.getHeight()));
3250 af.setMenusForViewport();
3251 System.err.println("Failed to restore view " + view.getTitle()
3252 + " to split frame");
3257 * Gather back into tabbed views as flagged.
3259 for (SplitFrame sf : gatherTo)
3261 Desktop.instance.gatherViews(sf);
3264 splitFrameCandidates.clear();
3268 * Construct and display one SplitFrame holding DNA and protein alignments.
3271 * @param proteinFrame
3274 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
3275 AlignFrame proteinFrame)
3277 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
3278 String title = MessageManager.getString("label.linked_view_title");
3279 int width = (int) dnaFrame.getBounds().getWidth();
3280 int height = (int) (dnaFrame.getBounds().getHeight()
3281 + proteinFrame.getBounds().getHeight() + 50);
3284 * SplitFrame location is saved to both enclosed frames
3286 splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
3287 Desktop.addInternalFrame(splitFrame, title, width, height);
3290 * And compute cDNA consensus (couldn't do earlier with consensus as
3291 * mappings were not yet present)
3293 proteinFrame.getViewport().alignmentChanged(proteinFrame.alignPanel);
3299 * check errorMessage for a valid error message and raise an error box in the
3300 * GUI or write the current errorMessage to stderr and then clear the error
3303 protected void reportErrors()
3305 reportErrors(false);
3308 protected void reportErrors(final boolean saving)
3310 if (errorMessage != null)
3312 final String finalErrorMessage = errorMessage;
3315 javax.swing.SwingUtilities.invokeLater(new Runnable()
3320 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
3322 "Error " + (saving ? "saving" : "loading")
3324 JvOptionPane.WARNING_MESSAGE);
3330 System.err.println("Problem loading Jalview file: " + errorMessage);
3333 errorMessage = null;
3336 Map<String, String> alreadyLoadedPDB = new HashMap<>();
3339 * when set, local views will be updated from view stored in JalviewXML
3340 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
3341 * sync if this is set to true.
3343 private final boolean updateLocalViews = false;
3346 * Returns the path to a temporary file holding the PDB file for the given PDB
3347 * id. The first time of asking, searches for a file of that name in the
3348 * Jalview project jar, and copies it to a new temporary file. Any repeat
3349 * requests just return the path to the file previously created.
3355 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
3358 if (alreadyLoadedPDB.containsKey(pdbId))
3360 return alreadyLoadedPDB.get(pdbId).toString();
3363 String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
3365 if (tempFile != null)
3367 alreadyLoadedPDB.put(pdbId, tempFile);
3373 * Copies the jar entry of given name to a new temporary file and returns the
3374 * path to the file, or null if the entry is not found.
3377 * @param jarEntryName
3379 * a prefix for the temporary file name, must be at least three
3381 * @param suffixModel
3382 * null or original file - so new file can be given the same suffix
3386 protected String copyJarEntry(jarInputStreamProvider jprovider,
3387 String jarEntryName, String prefix, String suffixModel)
3389 String suffix = ".tmp";
3390 if (suffixModel == null)
3392 suffixModel = jarEntryName;
3394 int sfpos = suffixModel.lastIndexOf(".");
3395 if (sfpos > -1 && sfpos < (suffixModel.length() - 1))
3397 suffix = "." + suffixModel.substring(sfpos + 1);
3400 try (JarInputStream jin = jprovider.getJarInputStream())
3402 JarEntry entry = null;
3405 entry = jin.getNextJarEntry();
3406 } while (entry != null && !entry.getName().equals(jarEntryName));
3410 // in = new BufferedReader(new InputStreamReader(jin, UTF_8));
3411 File outFile = File.createTempFile(prefix, suffix);
3412 outFile.deleteOnExit();
3413 try (OutputStream os = new FileOutputStream(outFile))
3417 String t = outFile.getAbsolutePath();
3423 "Couldn't find entry in Jalview Jar for " + jarEntryName);
3425 } catch (Exception ex)
3427 ex.printStackTrace();
3433 private class JvAnnotRow
3435 public JvAnnotRow(int i, AlignmentAnnotation jaa)
3442 * persisted version of annotation row from which to take vis properties
3444 public jalview.datamodel.AlignmentAnnotation template;
3447 * original position of the annotation row in the alignment
3453 * Load alignment frame from jalview XML DOM object
3455 * @param jalviewModel
3458 * filename source string
3459 * @param loadTreesAndStructures
3460 * when false only create Viewport
3462 * data source provider
3463 * @return alignment frame created from view stored in DOM
3465 AlignFrame loadFromObject(JalviewModel jalviewModel, String file,
3466 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
3468 SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet()
3470 List<Sequence> vamsasSeqs = vamsasSet.getSequence();
3472 // JalviewModelSequence jms = object.getJalviewModelSequence();
3474 // Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
3476 Viewport view = (jalviewModel.getViewport().size() > 0)
3477 ? jalviewModel.getViewport().get(0)
3480 // ////////////////////////////////
3481 // INITIALISE ALIGNMENT SEQUENCESETID AND VIEWID
3484 // If we just load in the same jar file again, the sequenceSetId
3485 // will be the same, and we end up with multiple references
3486 // to the same sequenceSet. We must modify this id on load
3487 // so that each load of the file gives a unique id
3490 * used to resolve correct alignment dataset for alignments with multiple
3493 String uniqueSeqSetId = null;
3494 String viewId = null;
3497 uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
3498 viewId = (view.getId() == null ? null
3499 : view.getId() + uniqueSetSuffix);
3502 // ////////////////////////////////
3505 List<SequenceI> hiddenSeqs = null;
3507 List<SequenceI> tmpseqs = new ArrayList<>();
3509 boolean multipleView = false;
3510 SequenceI referenceseqForView = null;
3511 // JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
3512 List<JSeq> jseqs = jalviewModel.getJSeq();
3513 int vi = 0; // counter in vamsasSeq array
3514 for (int i = 0; i < jseqs.size(); i++)
3516 JSeq jseq = jseqs.get(i);
3517 String seqId = jseq.getId();
3519 SequenceI tmpSeq = seqRefIds.get(seqId);
3522 if (!incompleteSeqs.containsKey(seqId))
3524 // may not need this check, but keep it for at least 2.9,1 release
3525 if (tmpSeq.getStart() != jseq.getStart()
3526 || tmpSeq.getEnd() != jseq.getEnd())
3528 System.err.println(String.format(
3529 "Warning JAL-2154 regression: updating start/end for sequence %s from %d/%d to %d/%d",
3530 tmpSeq.getName(), tmpSeq.getStart(), tmpSeq.getEnd(),
3531 jseq.getStart(), jseq.getEnd()));
3536 incompleteSeqs.remove(seqId);
3538 if (vamsasSeqs.size() > vi
3539 && vamsasSeqs.get(vi).getId().equals(seqId))
3541 // most likely we are reading a dataset XML document so
3542 // update from vamsasSeq section of XML for this sequence
3543 tmpSeq.setName(vamsasSeqs.get(vi).getName());
3544 tmpSeq.setDescription(vamsasSeqs.get(vi).getDescription());
3545 tmpSeq.setSequence(vamsasSeqs.get(vi).getSequence());
3550 // reading multiple views, so vamsasSeq set is a subset of JSeq
3551 multipleView = true;
3553 tmpSeq.setStart(jseq.getStart());
3554 tmpSeq.setEnd(jseq.getEnd());
3555 tmpseqs.add(tmpSeq);
3559 Sequence vamsasSeq = vamsasSeqs.get(vi);
3560 tmpSeq = new jalview.datamodel.Sequence(vamsasSeq.getName(),
3561 vamsasSeq.getSequence());
3562 tmpSeq.setDescription(vamsasSeq.getDescription());
3563 tmpSeq.setStart(jseq.getStart());
3564 tmpSeq.setEnd(jseq.getEnd());
3565 tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
3566 seqRefIds.put(vamsasSeq.getId(), tmpSeq);
3567 tmpseqs.add(tmpSeq);
3571 if (safeBoolean(jseq.isViewreference()))
3573 referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
3576 if (jseq.isHidden() != null && jseq.isHidden().booleanValue())
3578 if (hiddenSeqs == null)
3580 hiddenSeqs = new ArrayList<>();
3583 hiddenSeqs.add(tmpSeq);
3588 // Create the alignment object from the sequence set
3589 // ///////////////////////////////
3590 SequenceI[] orderedSeqs = tmpseqs
3591 .toArray(new SequenceI[tmpseqs.size()]);
3593 AlignmentI al = null;
3594 // so we must create or recover the dataset alignment before going further
3595 // ///////////////////////////////
3596 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
3598 // older jalview projects do not have a dataset - so creat alignment and
3600 al = new Alignment(orderedSeqs);
3601 al.setDataset(null);
3605 boolean isdsal = jalviewModel.getViewport().isEmpty();
3608 // we are importing a dataset record, so
3609 // recover reference to an alignment already materialsed as dataset
3610 al = getDatasetFor(vamsasSet.getDatasetId());
3614 // materialse the alignment
3615 al = new Alignment(orderedSeqs);
3619 addDatasetRef(vamsasSet.getDatasetId(), al);
3622 // finally, verify all data in vamsasSet is actually present in al
3623 // passing on flag indicating if it is actually a stored dataset
3624 recoverDatasetFor(vamsasSet, al, isdsal, uniqueSeqSetId);
3627 if (referenceseqForView != null)
3629 al.setSeqrep(referenceseqForView);
3631 // / Add the alignment properties
3632 for (int i = 0; i < vamsasSet.getSequenceSetProperties().size(); i++)
3634 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties()
3636 al.setProperty(ssp.getKey(), ssp.getValue());
3639 // ///////////////////////////////
3641 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
3644 // load sequence features, database references and any associated PDB
3645 // structures for the alignment
3647 // prior to 2.10, this part would only be executed the first time a
3648 // sequence was encountered, but not afterwards.
3649 // now, for 2.10 projects, this is also done if the xml doc includes
3650 // dataset sequences not actually present in any particular view.
3652 for (int i = 0; i < vamsasSeqs.size(); i++)
3654 JSeq jseq = jseqs.get(i);
3655 if (jseq.getFeatures().size() > 0)
3657 List<Feature> features = jseq.getFeatures();
3658 for (int f = 0; f < features.size(); f++)
3660 Feature feat = features.get(f);
3661 SequenceFeature sf = new SequenceFeature(feat.getType(),
3662 feat.getDescription(), feat.getBegin(), feat.getEnd(),
3663 safeFloat(feat.getScore()), feat.getFeatureGroup());
3664 sf.setStatus(feat.getStatus());
3667 * load any feature attributes - include map-valued attributes
3669 Map<String, Map<String, String>> mapAttributes = new HashMap<>();
3670 for (int od = 0; od < feat.getOtherData().size(); od++)
3672 OtherData keyValue = feat.getOtherData().get(od);
3673 String attributeName = keyValue.getKey();
3674 String attributeValue = keyValue.getValue();
3675 if (attributeName.startsWith("LINK"))
3677 sf.addLink(attributeValue);
3681 String subAttribute = keyValue.getKey2();
3682 if (subAttribute == null)
3684 // simple string-valued attribute
3685 sf.setValue(attributeName, attributeValue);
3689 // attribute 'key' has sub-attribute 'key2'
3690 if (!mapAttributes.containsKey(attributeName))
3692 mapAttributes.put(attributeName, new HashMap<>());
3694 mapAttributes.get(attributeName).put(subAttribute,
3699 for (Entry<String, Map<String, String>> mapAttribute : mapAttributes
3702 sf.setValue(mapAttribute.getKey(), mapAttribute.getValue());
3705 // adds feature to datasequence's feature set (since Jalview 2.10)
3706 al.getSequenceAt(i).addSequenceFeature(sf);
3709 if (vamsasSeqs.get(i).getDBRef().size() > 0)
3711 // adds dbrefs to datasequence's set (since Jalview 2.10)
3713 al.getSequenceAt(i).getDatasetSequence() == null
3714 ? al.getSequenceAt(i)
3715 : al.getSequenceAt(i).getDatasetSequence(),
3718 if (jseq.getPdbids().size() > 0)
3720 List<Pdbids> ids = jseq.getPdbids();
3721 for (int p = 0; p < ids.size(); p++)
3723 Pdbids pdbid = ids.get(p);
3724 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
3725 entry.setId(pdbid.getId());
3726 if (pdbid.getType() != null)
3728 if (PDBEntry.Type.getType(pdbid.getType()) != null)
3730 entry.setType(PDBEntry.Type.getType(pdbid.getType()));
3734 entry.setType(PDBEntry.Type.FILE);
3737 // jprovider is null when executing 'New View'
3738 if (pdbid.getFile() != null && jprovider != null)
3740 if (!pdbloaded.containsKey(pdbid.getFile()))
3742 entry.setFile(loadPDBFile(jprovider, pdbid.getId(),
3747 entry.setFile(pdbloaded.get(pdbid.getId()).toString());
3751 if (pdbid.getPdbentryItem() != null)
3753 for (PdbentryItem item : pdbid.getPdbentryItem())
3755 for (Property pr : item.getProperty())
3757 entry.setProperty(pr.getName(), pr.getValue());
3762 for (Property prop : pdbid.getProperty())
3764 entry.setProperty(prop.getName(), prop.getValue());
3766 StructureSelectionManager
3767 .getStructureSelectionManager(Desktop.instance)
3768 .registerPDBEntry(entry);
3769 // adds PDBEntry to datasequence's set (since Jalview 2.10)
3770 if (al.getSequenceAt(i).getDatasetSequence() != null)
3772 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
3776 al.getSequenceAt(i).addPDBId(entry);
3781 } // end !multipleview
3783 // ///////////////////////////////
3784 // LOAD SEQUENCE MAPPINGS
3786 if (vamsasSet.getAlcodonFrame().size() > 0)
3788 // TODO Potentially this should only be done once for all views of an
3790 List<AlcodonFrame> alc = vamsasSet.getAlcodonFrame();
3791 for (int i = 0; i < alc.size(); i++)
3793 AlignedCodonFrame cf = new AlignedCodonFrame();
3794 if (alc.get(i).getAlcodMap().size() > 0)
3796 List<AlcodMap> maps = alc.get(i).getAlcodMap();
3797 for (int m = 0; m < maps.size(); m++)
3799 AlcodMap map = maps.get(m);
3800 SequenceI dnaseq = seqRefIds.get(map.getDnasq());
3802 jalview.datamodel.Mapping mapping = null;
3803 // attach to dna sequence reference.
3804 if (map.getMapping() != null)
3806 mapping = addMapping(map.getMapping());
3807 if (dnaseq != null && mapping.getTo() != null)
3809 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
3815 .add(newAlcodMapRef(map.getDnasq(), cf, mapping));
3819 al.addCodonFrame(cf);
3824 // ////////////////////////////////
3826 List<JvAnnotRow> autoAlan = new ArrayList<>();
3829 * store any annotations which forward reference a group's ID
3831 Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
3833 if (vamsasSet.getAnnotation().size()/*Count()*/ > 0)
3835 List<Annotation> an = vamsasSet.getAnnotation();
3837 for (int i = 0; i < an.size(); i++)
3839 Annotation annotation = an.get(i);
3842 * test if annotation is automatically calculated for this view only
3844 boolean autoForView = false;
3845 if (annotation.getLabel().equals("Quality")
3846 || annotation.getLabel().equals("Conservation")
3847 || annotation.getLabel().equals("Consensus"))
3849 // Kludge for pre 2.5 projects which lacked the autocalculated flag
3851 // JAXB has no has() test; schema defaults value to false
3852 // if (!annotation.hasAutoCalculated())
3854 // annotation.setAutoCalculated(true);
3857 if (autoForView || annotation.isAutoCalculated())
3859 // remove ID - we don't recover annotation from other views for
3860 // view-specific annotation
3861 annotation.setId(null);
3864 // set visibility for other annotation in this view
3865 String annotationId = annotation.getId();
3866 if (annotationId != null && annotationIds.containsKey(annotationId))
3868 AlignmentAnnotation jda = annotationIds.get(annotationId);
3869 // in principle Visible should always be true for annotation displayed
3870 // in multiple views
3871 if (annotation.isVisible() != null)
3873 jda.visible = annotation.isVisible();
3876 al.addAnnotation(jda);
3880 // Construct new annotation from model.
3881 List<AnnotationElement> ae = annotation.getAnnotationElement();
3882 jalview.datamodel.Annotation[] anot = null;
3883 java.awt.Color firstColour = null;
3885 if (!annotation.isScoreOnly())
3887 anot = new jalview.datamodel.Annotation[al.getWidth()];
3888 for (int aa = 0; aa < ae.size() && aa < anot.length; aa++)
3890 AnnotationElement annElement = ae.get(aa);
3891 anpos = annElement.getPosition();
3893 if (anpos >= anot.length)
3898 float value = safeFloat(annElement.getValue());
3899 anot[anpos] = new jalview.datamodel.Annotation(
3900 annElement.getDisplayCharacter(),
3901 annElement.getDescription(),
3902 (annElement.getSecondaryStructure() == null
3903 || annElement.getSecondaryStructure()
3907 .getSecondaryStructure()
3910 anot[anpos].colour = new Color(safeInt(annElement.getColour()));
3911 if (firstColour == null)
3913 firstColour = anot[anpos].colour;
3917 jalview.datamodel.AlignmentAnnotation jaa = null;
3919 if (annotation.isGraph())
3921 float llim = 0, hlim = 0;
3922 // if (autoForView || an[i].isAutoCalculated()) {
3925 jaa = new jalview.datamodel.AlignmentAnnotation(
3926 annotation.getLabel(), annotation.getDescription(), anot,
3927 llim, hlim, safeInt(annotation.getGraphType()));
3929 jaa.graphGroup = safeInt(annotation.getGraphGroup());
3930 jaa._linecolour = firstColour;
3931 if (annotation.getThresholdLine() != null)
3933 jaa.setThreshold(new jalview.datamodel.GraphLine(
3934 safeFloat(annotation.getThresholdLine().getValue()),
3935 annotation.getThresholdLine().getLabel(),
3936 new java.awt.Color(safeInt(
3937 annotation.getThresholdLine().getColour()))));
3939 if (autoForView || annotation.isAutoCalculated())
3941 // Hardwire the symbol display line to ensure that labels for
3942 // histograms are displayed
3948 jaa = new jalview.datamodel.AlignmentAnnotation(
3949 annotation.getLabel(), annotation.getDescription(), anot);
3950 jaa._linecolour = firstColour;
3952 // register new annotation
3953 if (annotation.getId() != null)
3955 annotationIds.put(annotation.getId(), jaa);
3956 jaa.annotationId = annotation.getId();
3958 // recover sequence association
3959 String sequenceRef = annotation.getSequenceRef();
3960 if (sequenceRef != null)
3962 // from 2.9 sequenceRef is to sequence id (JAL-1781)
3963 SequenceI sequence = seqRefIds.get(sequenceRef);
3964 if (sequence == null)
3966 // in pre-2.9 projects sequence ref is to sequence name
3967 sequence = al.findName(sequenceRef);
3969 if (sequence != null)
3971 jaa.createSequenceMapping(sequence, 1, true);
3972 sequence.addAlignmentAnnotation(jaa);
3975 // and make a note of any group association
3976 if (annotation.getGroupRef() != null
3977 && annotation.getGroupRef().length() > 0)
3979 List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
3980 .get(annotation.getGroupRef());
3983 aal = new ArrayList<>();
3984 groupAnnotRefs.put(annotation.getGroupRef(), aal);
3989 if (annotation.getScore() != null)
3991 jaa.setScore(annotation.getScore().doubleValue());
3993 if (annotation.isVisible() != null)
3995 jaa.visible = annotation.isVisible().booleanValue();
3998 if (annotation.isCentreColLabels() != null)
4000 jaa.centreColLabels = annotation.isCentreColLabels()
4004 if (annotation.isScaleColLabels() != null)
4006 jaa.scaleColLabel = annotation.isScaleColLabels().booleanValue();
4008 if (annotation.isAutoCalculated())
4010 // newer files have an 'autoCalculated' flag and store calculation
4011 // state in viewport properties
4012 jaa.autoCalculated = true; // means annotation will be marked for
4013 // update at end of load.
4015 if (annotation.getGraphHeight() != null)
4017 jaa.graphHeight = annotation.getGraphHeight().intValue();
4019 jaa.belowAlignment = annotation.isBelowAlignment();
4020 jaa.setCalcId(annotation.getCalcId());
4021 if (annotation.getProperty().size() > 0)
4023 for (jalview.xml.binding.jalview.Property prop : annotation
4026 jaa.setProperty(prop.getName(), prop.getValue());
4029 if (jaa.graph == AlignmentAnnotation.CONTACT_MAP)
4031 if (annotation.getContactmatrix() != null
4032 && annotation.getContactmatrix().size() > 0)
4034 for (MatrixType xmlmat : annotation.getContactmatrix())
4036 if (PAEContactMatrix.PAEMATRIX.equals(xmlmat.getType()))
4038 if (!xmlmat.getRows().equals(xmlmat.getCols()))
4040 Console.error("Can't handle non square PAE Matrices");
4044 float[][] elements = ContactMatrix
4045 .fromFloatStringToContacts(xmlmat.getElements(),
4046 xmlmat.getCols().intValue(),
4047 xmlmat.getRows().intValue());
4048 jalview.util.MapList mapping = null;
4049 if (xmlmat.getMapping() != null)
4051 MapListType m = xmlmat.getMapping();
4052 // Mapping m = dr.getMapping();
4053 int fr[] = new int[m.getMapListFrom().size() * 2];
4054 Iterator<MapListFrom> from = m.getMapListFrom()
4055 .iterator();// enumerateMapListFrom();
4056 for (int _i = 0; from.hasNext(); _i += 2)
4058 MapListFrom mf = from.next();
4059 fr[_i] = mf.getStart();
4060 fr[_i + 1] = mf.getEnd();
4062 int fto[] = new int[m.getMapListTo().size() * 2];
4063 Iterator<MapListTo> to = m.getMapListTo().iterator();// enumerateMapListTo();
4064 for (int _i = 0; to.hasNext(); _i += 2)
4066 MapListTo mf = to.next();
4067 fto[_i] = mf.getStart();
4068 fto[_i + 1] = mf.getEnd();
4071 mapping = new jalview.util.MapList(fr, fto,
4072 m.getMapFromUnit().intValue(),
4073 m.getMapToUnit().intValue());
4075 List<BitSet> newgroups = new ArrayList<BitSet>();
4076 if (xmlmat.getGroups().size() > 0)
4078 for (String sgroup : xmlmat.getGroups())
4080 newgroups.add(deStringifyBitset(sgroup));
4083 String nwk = xmlmat.getNewick().size() > 0
4084 ? xmlmat.getNewick().get(0)
4086 if (xmlmat.getNewick().size() > 1)
4089 "Ignoring additional clusterings for contact matrix");
4091 String treeMethod = xmlmat.getTreeMethod();
4092 double thresh = xmlmat.getCutHeight() != null
4093 ? xmlmat.getCutHeight()
4095 GroupSet grpset = new GroupSet();
4096 grpset.restoreGroups(newgroups, treeMethod, nwk, thresh);
4097 PAEContactMatrix newpae = new PAEContactMatrix(
4098 jaa.sequenceRef, mapping, elements, grpset);
4099 jaa.sequenceRef.addContactListFor(jaa, newpae);
4104 Console.error("Ignoring CONTACT_MAP annotation with type "
4105 + xmlmat.getType());
4111 if (jaa.autoCalculated)
4113 autoAlan.add(new JvAnnotRow(i, jaa));
4116 // if (!autoForView)
4118 // add autocalculated group annotation and any user created annotation
4120 al.addAnnotation(jaa);
4124 // ///////////////////////
4126 // Create alignment markup and styles for this view
4127 if (jalviewModel.getJGroup().size() > 0)
4129 List<JGroup> groups = jalviewModel.getJGroup();
4130 boolean addAnnotSchemeGroup = false;
4131 for (int i = 0; i < groups.size(); i++)
4133 JGroup jGroup = groups.get(i);
4134 ColourSchemeI cs = null;
4135 if (jGroup.getColour() != null)
4137 if (jGroup.getColour().startsWith("ucs"))
4139 cs = getUserColourScheme(jalviewModel, jGroup.getColour());
4141 else if (jGroup.getColour().equals("AnnotationColourGradient")
4142 && jGroup.getAnnotationColours() != null)
4144 addAnnotSchemeGroup = true;
4148 cs = ColourSchemeProperty.getColourScheme(null, al,
4149 jGroup.getColour());
4152 int pidThreshold = safeInt(jGroup.getPidThreshold());
4154 Vector<SequenceI> seqs = new Vector<>();
4156 for (int s = 0; s < jGroup.getSeq().size(); s++)
4158 String seqId = jGroup.getSeq().get(s);
4159 SequenceI ts = seqRefIds.get(seqId);
4163 seqs.addElement(ts);
4167 if (seqs.size() < 1)
4172 SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
4173 safeBoolean(jGroup.isDisplayBoxes()),
4174 safeBoolean(jGroup.isDisplayText()),
4175 safeBoolean(jGroup.isColourText()),
4176 safeInt(jGroup.getStart()), safeInt(jGroup.getEnd()));
4177 sg.getGroupColourScheme().setThreshold(pidThreshold, true);
4178 sg.getGroupColourScheme()
4179 .setConservationInc(safeInt(jGroup.getConsThreshold()));
4180 sg.setOutlineColour(new Color(safeInt(jGroup.getOutlineColour())));
4182 sg.textColour = new Color(safeInt(jGroup.getTextCol1()));
4183 sg.textColour2 = new Color(safeInt(jGroup.getTextCol2()));
4184 sg.setShowNonconserved(safeBoolean(jGroup.isShowUnconserved()));
4185 sg.thresholdTextColour = safeInt(jGroup.getTextColThreshold());
4186 // attributes with a default in the schema are never null
4187 sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
4188 sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
4189 sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
4190 sg.setIgnoreGapsConsensus(jGroup.isIgnoreGapsinConsensus());
4191 if (jGroup.getConsThreshold() != null
4192 && jGroup.getConsThreshold().intValue() != 0)
4194 Conservation c = new Conservation("All", sg.getSequences(null), 0,
4197 c.verdict(false, 25);
4198 sg.cs.setConservation(c);
4201 if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
4203 // re-instate unique group/annotation row reference
4204 List<AlignmentAnnotation> jaal = groupAnnotRefs
4205 .get(jGroup.getId());
4208 for (AlignmentAnnotation jaa : jaal)
4211 if (jaa.autoCalculated)
4213 // match up and try to set group autocalc alignment row for this
4215 if (jaa.label.startsWith("Consensus for "))
4217 sg.setConsensus(jaa);
4219 // match up and try to set group autocalc alignment row for this
4221 if (jaa.label.startsWith("Conservation for "))
4223 sg.setConservationRow(jaa);
4230 if (addAnnotSchemeGroup)
4232 // reconstruct the annotation colourscheme
4234 constructAnnotationColour(jGroup.getAnnotationColours(),
4235 null, al, jalviewModel, false));
4241 // only dataset in this model, so just return.
4244 // ///////////////////////////////
4247 AlignFrame af = null;
4248 AlignViewport av = null;
4249 // now check to see if we really need to create a new viewport.
4250 if (multipleView && viewportsAdded.size() == 0)
4252 // We recovered an alignment for which a viewport already exists.
4253 // TODO: fix up any settings necessary for overlaying stored state onto
4254 // state recovered from another document. (may not be necessary).
4255 // we may need a binding from a viewport in memory to one recovered from
4257 // and then recover its containing af to allow the settings to be applied.
4258 // TODO: fix for vamsas demo
4260 "About to recover a viewport for existing alignment: Sequence set ID is "
4262 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
4263 if (seqsetobj != null)
4265 if (seqsetobj instanceof String)
4267 uniqueSeqSetId = (String) seqsetobj;
4269 "Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
4275 "Warning : Collision between sequence set ID string and existing jalview object mapping.");
4281 * indicate that annotation colours are applied across all groups (pre
4282 * Jalview 2.8.1 behaviour)
4284 boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan("2.8.1",
4285 jalviewModel.getVersion());
4287 AlignmentPanel ap = null;
4288 boolean isnewview = true;
4291 // Check to see if this alignment already has a view id == viewId
4292 jalview.gui.AlignmentPanel views[] = Desktop
4293 .getAlignmentPanels(uniqueSeqSetId);
4294 if (views != null && views.length > 0)
4296 for (int v = 0; v < views.length; v++)
4298 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
4300 // recover the existing alignpanel, alignframe, viewport
4301 af = views[v].alignFrame;
4304 // TODO: could even skip resetting view settings if we don't want to
4305 // change the local settings from other jalview processes
4314 af = loadViewport(file, jseqs, hiddenSeqs, al, jalviewModel, view,
4315 uniqueSeqSetId, viewId, autoAlan);
4316 av = af.getViewport();
4321 * Load any trees, PDB structures and viewers, Overview
4323 * Not done if flag is false (when this method is used for New View)
4325 if (loadTreesAndStructures)
4327 loadTrees(jalviewModel, view, af, av, ap);
4328 loadPCAViewers(jalviewModel, ap);
4329 loadPDBStructures(jprovider, jseqs, af, ap);
4330 loadRnaViewers(jprovider, jseqs, ap);
4331 loadOverview(view, jalviewModel.getVersion(), af);
4333 // and finally return.
4338 * Load Overview window, restoring colours, 'show hidden regions' flag, title
4339 * and geometry as saved
4344 protected void loadOverview(Viewport view, String version, AlignFrame af)
4346 if (!isVersionStringLaterThan("2.11.3", version)
4347 && view.getOverview() == null)
4352 * first close any Overview that was opened automatically
4353 * (if so configured in Preferences) so that the view is
4354 * restored in the same state as saved
4356 af.alignPanel.closeOverviewPanel();
4358 Overview overview = view.getOverview();
4359 if (overview != null)
4361 OverviewPanel overviewPanel = af
4362 .openOverviewPanel(overview.isShowHidden());
4363 overviewPanel.setTitle(overview.getTitle());
4364 overviewPanel.setFrameBounds(overview.getXpos(), overview.getYpos(),
4365 overview.getWidth(), overview.getHeight());
4366 Color gap = new Color(overview.getGapColour());
4367 Color residue = new Color(overview.getResidueColour());
4368 Color hidden = new Color(overview.getHiddenColour());
4369 overviewPanel.getCanvas().setColours(gap, residue, hidden);
4374 * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
4375 * panel is restored from separate jar entries, two (gapped and trimmed) per
4376 * sequence and secondary structure.
4378 * Currently each viewer shows just one sequence and structure (gapped and
4379 * trimmed), however this method is designed to support multiple sequences or
4380 * structures in viewers if wanted in future.
4386 private void loadRnaViewers(jarInputStreamProvider jprovider,
4387 List<JSeq> jseqs, AlignmentPanel ap)
4390 * scan the sequences for references to viewers; create each one the first
4391 * time it is referenced, add Rna models to existing viewers
4393 for (JSeq jseq : jseqs)
4395 for (int i = 0; i < jseq.getRnaViewer().size(); i++)
4397 RnaViewer viewer = jseq.getRnaViewer().get(i);
4398 AppVarna appVarna = findOrCreateVarnaViewer(viewer, uniqueSetSuffix,
4401 for (int j = 0; j < viewer.getSecondaryStructure().size(); j++)
4403 SecondaryStructure ss = viewer.getSecondaryStructure().get(j);
4404 SequenceI seq = seqRefIds.get(jseq.getId());
4405 AlignmentAnnotation ann = this.annotationIds
4406 .get(ss.getAnnotationId());
4409 * add the structure to the Varna display (with session state copied
4410 * from the jar to a temporary file)
4412 boolean gapped = safeBoolean(ss.isGapped());
4413 String rnaTitle = ss.getTitle();
4414 String sessionState = ss.getViewerState();
4415 String tempStateFile = copyJarEntry(jprovider, sessionState,
4417 RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
4418 appVarna.addModelSession(rna, rnaTitle, tempStateFile);
4420 appVarna.setInitialSelection(safeInt(viewer.getSelectedRna()));
4426 * Locate and return an already instantiated matching AppVarna, or create one
4430 * @param viewIdSuffix
4434 protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
4435 String viewIdSuffix, AlignmentPanel ap)
4438 * on each load a suffix is appended to the saved viewId, to avoid conflicts
4439 * if load is repeated
4441 String postLoadId = viewer.getViewId() + viewIdSuffix;
4442 for (JInternalFrame frame : getAllFrames())
4444 if (frame instanceof AppVarna)
4446 AppVarna varna = (AppVarna) frame;
4447 if (postLoadId.equals(varna.getViewId()))
4449 // this viewer is already instantiated
4450 // could in future here add ap as another 'parent' of the
4451 // AppVarna window; currently just 1-to-many
4458 * viewer not found - make it
4460 RnaViewerModel model = new RnaViewerModel(postLoadId, viewer.getTitle(),
4461 safeInt(viewer.getXpos()), safeInt(viewer.getYpos()),
4462 safeInt(viewer.getWidth()), safeInt(viewer.getHeight()),
4463 safeInt(viewer.getDividerLocation()));
4464 AppVarna varna = new AppVarna(model, ap);
4470 * Load any saved trees
4478 protected void loadTrees(JalviewModel jm, Viewport view, AlignFrame af,
4479 AlignViewport av, AlignmentPanel ap)
4481 // TODO result of automated refactoring - are all these parameters needed?
4484 for (int t = 0; t < jm.getTree().size(); t++)
4487 Tree tree = jm.getTree().get(t);
4489 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
4492 if (tree.isColumnWise())
4494 AlignmentAnnotation aa = (AlignmentAnnotation) annotationIds
4495 .get(tree.getColumnReference());
4499 "Null alignment annotation when restoring columnwise tree");
4501 tp = af.showColumnWiseTree(new NewickFile(tree.getNewick()), aa,
4502 tree.getTitle(), safeInt(tree.getWidth()),
4503 safeInt(tree.getHeight()), safeInt(tree.getXpos()),
4504 safeInt(tree.getYpos()));
4509 tp = af.showNewickTree(new NewickFile(tree.getNewick()),
4510 tree.getTitle(), safeInt(tree.getWidth()),
4511 safeInt(tree.getHeight()), safeInt(tree.getXpos()),
4512 safeInt(tree.getYpos()));
4514 if (tree.getId() != null)
4516 // perhaps bind the tree id to something ?
4521 // update local tree attributes ?
4522 // TODO: should check if tp has been manipulated by user - if so its
4523 // settings shouldn't be modified
4524 tp.setTitle(tree.getTitle());
4525 tp.setBounds(new Rectangle(safeInt(tree.getXpos()),
4526 safeInt(tree.getYpos()), safeInt(tree.getWidth()),
4527 safeInt(tree.getHeight())));
4528 tp.setViewport(av); // af.viewport;
4529 // TODO: verify 'associate with all views' works still
4530 tp.getTreeCanvas().setViewport(av); // af.viewport;
4531 tp.getTreeCanvas().setAssociatedPanel(ap); // af.alignPanel;
4533 tp.getTreeCanvas().setApplyToAllViews(tree.isLinkToAllViews());
4537 "There was a problem recovering stored Newick tree: \n"
4538 + tree.getNewick());
4542 tp.fitToWindow.setState(safeBoolean(tree.isFitToWindow()));
4543 tp.fitToWindow_actionPerformed(null);
4545 if (tree.getFontName() != null)
4548 new Font(tree.getFontName(), safeInt(tree.getFontStyle()),
4549 safeInt(tree.getFontSize())));
4554 new Font(view.getFontName(), safeInt(view.getFontStyle()),
4555 safeInt(view.getFontSize())));
4558 tp.showPlaceholders(safeBoolean(tree.isMarkUnlinked()));
4559 tp.showBootstrap(safeBoolean(tree.isShowBootstrap()));
4560 tp.showDistances(safeBoolean(tree.isShowDistances()));
4562 tp.getTreeCanvas().setThreshold(safeFloat(tree.getThreshold()));
4564 if (safeBoolean(tree.isCurrentTree()))
4566 af.getViewport().setCurrentTree(tp.getTree());
4570 } catch (Exception ex)
4572 ex.printStackTrace();
4577 * Load and link any saved structure viewers.
4584 protected void loadPDBStructures(jarInputStreamProvider jprovider,
4585 List<JSeq> jseqs, AlignFrame af, AlignmentPanel ap)
4588 * Run through all PDB ids on the alignment, and collect mappings between
4589 * distinct view ids and all sequences referring to that view.
4591 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
4593 for (int i = 0; i < jseqs.size(); i++)
4595 JSeq jseq = jseqs.get(i);
4596 if (jseq.getPdbids().size() > 0)
4598 List<Pdbids> ids = jseq.getPdbids();
4599 for (int p = 0; p < ids.size(); p++)
4601 Pdbids pdbid = ids.get(p);
4602 final int structureStateCount = pdbid.getStructureState().size();
4603 for (int s = 0; s < structureStateCount; s++)
4605 // check to see if we haven't already created this structure view
4606 final StructureState structureState = pdbid.getStructureState()
4608 String sviewid = (structureState.getViewId() == null) ? null
4609 : structureState.getViewId() + uniqueSetSuffix;
4610 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
4611 // Originally : pdbid.getFile()
4612 // : TODO: verify external PDB file recovery still works in normal
4613 // jalview project load
4615 loadPDBFile(jprovider, pdbid.getId(), pdbid.getFile()));
4616 jpdb.setId(pdbid.getId());
4618 int x = safeInt(structureState.getXpos());
4619 int y = safeInt(structureState.getYpos());
4620 int width = safeInt(structureState.getWidth());
4621 int height = safeInt(structureState.getHeight());
4623 // Probably don't need to do this anymore...
4624 // Desktop.desktop.getComponentAt(x, y);
4625 // TODO: NOW: check that this recovers the PDB file correctly.
4626 String pdbFile = loadPDBFile(jprovider, pdbid.getId(),
4628 jalview.datamodel.SequenceI seq = seqRefIds
4629 .get(jseq.getId() + "");
4630 if (sviewid == null)
4632 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width + ","
4635 if (!structureViewers.containsKey(sviewid))
4637 String viewerType = structureState.getType();
4638 if (viewerType == null) // pre Jalview 2.9
4640 viewerType = ViewerType.JMOL.toString();
4642 structureViewers.put(sviewid,
4643 new StructureViewerModel(x, y, width, height, false,
4644 false, true, structureState.getViewId(),
4646 // Legacy pre-2.7 conversion JAL-823 :
4647 // do not assume any view has to be linked for colour by
4651 // assemble String[] { pdb files }, String[] { id for each
4652 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
4653 // seqs_file 2}, boolean[] {
4654 // linkAlignPanel,superposeWithAlignpanel}} from hash
4655 StructureViewerModel jmoldat = structureViewers.get(sviewid);
4656 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
4657 || structureState.isAlignwithAlignPanel());
4660 * Default colour by linked panel to false if not specified (e.g.
4661 * for pre-2.7 projects)
4663 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
4664 colourWithAlignPanel |= structureState.isColourwithAlignPanel();
4665 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
4668 * Default colour by viewer to true if not specified (e.g. for
4671 boolean colourByViewer = jmoldat.isColourByViewer();
4672 colourByViewer &= structureState.isColourByJmol();
4673 jmoldat.setColourByViewer(colourByViewer);
4675 if (jmoldat.getStateData().length() < structureState.getValue()
4676 /*Content()*/.length())
4678 jmoldat.setStateData(structureState.getValue());// Content());
4680 if (pdbid.getFile() != null)
4682 File mapkey = new File(pdbid.getFile());
4683 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
4684 if (seqstrmaps == null)
4686 jmoldat.getFileData().put(mapkey,
4687 seqstrmaps = jmoldat.new StructureData(pdbFile,
4690 if (!seqstrmaps.getSeqList().contains(seq))
4692 seqstrmaps.getSeqList().add(seq);
4698 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");
4699 Console.warn(errorMessage);
4705 // Instantiate the associated structure views
4706 for (Entry<String, StructureViewerModel> entry : structureViewers
4711 createOrLinkStructureViewer(entry, af, ap, jprovider);
4712 } catch (Exception e)
4715 "Error loading structure viewer: " + e.getMessage());
4716 // failed - try the next one
4728 protected void createOrLinkStructureViewer(
4729 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
4730 AlignmentPanel ap, jarInputStreamProvider jprovider)
4732 final StructureViewerModel stateData = viewerData.getValue();
4735 * Search for any viewer windows already open from other alignment views
4736 * that exactly match the stored structure state
4738 StructureViewerBase comp = findMatchingViewer(viewerData);
4742 linkStructureViewer(ap, comp, stateData);
4746 String type = stateData.getType();
4749 ViewerType viewerType = ViewerType.valueOf(type);
4750 createStructureViewer(viewerType, viewerData, af, jprovider);
4751 } catch (IllegalArgumentException | NullPointerException e)
4753 // TODO JAL-3619 show error dialog / offer an alternative viewer
4754 Console.error("Invalid structure viewer type: " + type);
4759 * Generates a name for the entry in the project jar file to hold state
4760 * information for a structure viewer
4765 protected String getViewerJarEntryName(String viewId)
4767 return VIEWER_PREFIX + viewId;
4771 * Returns any open frame that matches given structure viewer data. The match
4772 * is based on the unique viewId, or (for older project versions) the frame's
4778 protected StructureViewerBase findMatchingViewer(
4779 Entry<String, StructureViewerModel> viewerData)
4781 final String sviewid = viewerData.getKey();
4782 final StructureViewerModel svattrib = viewerData.getValue();
4783 StructureViewerBase comp = null;
4784 JInternalFrame[] frames = getAllFrames();
4785 for (JInternalFrame frame : frames)
4787 if (frame instanceof StructureViewerBase)
4790 * Post jalview 2.4 schema includes structure view id
4792 if (sviewid != null && ((StructureViewerBase) frame).getViewId()
4795 comp = (StructureViewerBase) frame;
4796 break; // break added in 2.9
4799 * Otherwise test for matching position and size of viewer frame
4801 else if (frame.getX() == svattrib.getX()
4802 && frame.getY() == svattrib.getY()
4803 && frame.getHeight() == svattrib.getHeight()
4804 && frame.getWidth() == svattrib.getWidth())
4806 comp = (StructureViewerBase) frame;
4807 // no break in faint hope of an exact match on viewId
4815 * Link an AlignmentPanel to an existing structure viewer.
4820 * @param useinViewerSuperpos
4821 * @param usetoColourbyseq
4822 * @param viewerColouring
4824 protected void linkStructureViewer(AlignmentPanel ap,
4825 StructureViewerBase viewer, StructureViewerModel stateData)
4827 // NOTE: if the jalview project is part of a shared session then
4828 // view synchronization should/could be done here.
4830 final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
4831 final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
4832 final boolean viewerColouring = stateData.isColourByViewer();
4833 Map<File, StructureData> oldFiles = stateData.getFileData();
4836 * Add mapping for sequences in this view to an already open viewer
4838 final AAStructureBindingModel binding = viewer.getBinding();
4839 for (File id : oldFiles.keySet())
4841 // add this and any other pdb files that should be present in the
4843 StructureData filedat = oldFiles.get(id);
4844 String pdbFile = filedat.getFilePath();
4845 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
4846 binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE,
4848 binding.addSequenceForStructFile(pdbFile, seq);
4850 // and add the AlignmentPanel's reference to the view panel
4851 viewer.addAlignmentPanel(ap);
4852 if (useinViewerSuperpos)
4854 viewer.useAlignmentPanelForSuperposition(ap);
4858 viewer.excludeAlignmentPanelForSuperposition(ap);
4860 if (usetoColourbyseq)
4862 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
4866 viewer.excludeAlignmentPanelForColourbyseq(ap);
4871 * Get all frames within the Desktop.
4875 protected JInternalFrame[] getAllFrames()
4877 JInternalFrame[] frames = null;
4878 // TODO is this necessary - is it safe - risk of hanging?
4883 frames = Desktop.desktop.getAllFrames();
4884 } catch (ArrayIndexOutOfBoundsException e)
4886 // occasional No such child exceptions are thrown here...
4890 } catch (InterruptedException f)
4894 } while (frames == null);
4899 * Answers true if 'version' is equal to or later than 'supported', where each
4900 * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
4901 * changes. Development and test values for 'version' are leniently treated
4905 * - minimum version we are comparing against
4907 * - version of data being processsed
4908 * @return true if version is equal to or later than supported
4910 public static boolean isVersionStringLaterThan(String supported,
4913 if (supported == null || version == null
4914 || version.equalsIgnoreCase("DEVELOPMENT BUILD")
4915 || version.equalsIgnoreCase("Test")
4916 || version.equalsIgnoreCase("AUTOMATED BUILD"))
4918 System.err.println("Assuming project file with "
4919 + (version == null ? "null" : version)
4920 + " is compatible with Jalview version " + supported);
4925 return StringUtils.compareVersions(version, supported, "b") >= 0;
4929 Vector<JalviewStructureDisplayI> newStructureViewers = null;
4931 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
4933 if (newStructureViewers != null)
4935 sview.getBinding().setFinishedLoadingFromArchive(false);
4936 newStructureViewers.add(sview);
4940 protected void setLoadingFinishedForNewStructureViewers()
4942 if (newStructureViewers != null)
4944 for (JalviewStructureDisplayI sview : newStructureViewers)
4946 sview.getBinding().setFinishedLoadingFromArchive(true);
4948 newStructureViewers.clear();
4949 newStructureViewers = null;
4953 AlignFrame loadViewport(String file, List<JSeq> JSEQ,
4954 List<SequenceI> hiddenSeqs, AlignmentI al, JalviewModel jm,
4955 Viewport view, String uniqueSeqSetId, String viewId,
4956 List<JvAnnotRow> autoAlan)
4958 AlignFrame af = null;
4959 af = new AlignFrame(al, safeInt(view.getWidth()),
4960 safeInt(view.getHeight()), uniqueSeqSetId, viewId)
4964 // protected void processKeyEvent(java.awt.event.KeyEvent e) {
4965 // System.out.println("Jalview2XML AF " + e);
4966 // super.processKeyEvent(e);
4973 af.setFileName(file, FileFormat.Jalview);
4975 final AlignViewport viewport = af.getViewport();
4976 for (int i = 0; i < JSEQ.size(); i++)
4978 int colour = safeInt(JSEQ.get(i).getColour());
4979 viewport.setSequenceColour(viewport.getAlignment().getSequenceAt(i),
4985 viewport.setColourByReferenceSeq(true);
4986 viewport.setDisplayReferenceSeq(true);
4989 viewport.setGatherViewsHere(safeBoolean(view.isGatheredViews()));
4991 if (view.getSequenceSetId() != null)
4993 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
4995 viewport.setSequenceSetId(uniqueSeqSetId);
4998 // propagate shared settings to this new view
4999 viewport.setHistoryList(av.getHistoryList());
5000 viewport.setRedoList(av.getRedoList());
5004 viewportsAdded.put(uniqueSeqSetId, viewport);
5006 // TODO: check if this method can be called repeatedly without
5007 // side-effects if alignpanel already registered.
5008 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
5010 // apply Hidden regions to view.
5011 if (hiddenSeqs != null)
5013 for (int s = 0; s < JSEQ.size(); s++)
5015 SequenceGroup hidden = new SequenceGroup();
5016 boolean isRepresentative = false;
5017 for (int r = 0; r < JSEQ.get(s).getHiddenSequences().size(); r++)
5019 isRepresentative = true;
5020 SequenceI sequenceToHide = al
5021 .getSequenceAt(JSEQ.get(s).getHiddenSequences().get(r));
5022 hidden.addSequence(sequenceToHide, false);
5023 // remove from hiddenSeqs list so we don't try to hide it twice
5024 hiddenSeqs.remove(sequenceToHide);
5026 if (isRepresentative)
5028 SequenceI representativeSequence = al.getSequenceAt(s);
5029 hidden.addSequence(representativeSequence, false);
5030 viewport.hideRepSequences(representativeSequence, hidden);
5034 SequenceI[] hseqs = hiddenSeqs
5035 .toArray(new SequenceI[hiddenSeqs.size()]);
5036 viewport.hideSequence(hseqs);
5039 // recover view properties and display parameters
5041 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
5042 viewport.setAbovePIDThreshold(safeBoolean(view.isPidSelected()));
5043 final int pidThreshold = safeInt(view.getPidThreshold());
5044 viewport.setThreshold(pidThreshold);
5046 viewport.setColourText(safeBoolean(view.isShowColourText()));
5048 viewport.setConservationSelected(
5049 safeBoolean(view.isConservationSelected()));
5050 viewport.setIncrement(safeInt(view.getConsThreshold()));
5051 viewport.setShowJVSuffix(safeBoolean(view.isShowFullId()));
5052 viewport.setRightAlignIds(safeBoolean(view.isRightAlignIds()));
5054 new Font(view.getFontName(), safeInt(view.getFontStyle()),
5055 safeInt(view.getFontSize())),
5056 (view.getCharWidth() != null) ? false : true);
5057 if (view.getCharWidth() != null)
5059 viewport.setCharWidth(view.getCharWidth());
5060 viewport.setCharHeight(view.getCharHeight());
5062 ViewStyleI vs = viewport.getViewStyle();
5063 vs.setScaleProteinAsCdna(view.isScaleProteinAsCdna());
5064 viewport.setViewStyle(vs);
5065 // TODO: allow custom charWidth/Heights to be restored by updating them
5066 // after setting font - which means set above to false
5067 viewport.setRenderGaps(safeBoolean(view.isRenderGaps()));
5068 viewport.setWrapAlignment(safeBoolean(view.isWrapAlignment()));
5069 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
5071 viewport.setShowBoxes(safeBoolean(view.isShowBoxes()));
5073 viewport.setShowText(safeBoolean(view.isShowText()));
5075 viewport.setTextColour(new Color(safeInt(view.getTextCol1())));
5076 viewport.setTextColour2(new Color(safeInt(view.getTextCol2())));
5077 viewport.setThresholdTextColour(safeInt(view.getTextColThreshold()));
5078 viewport.setShowUnconserved(view.isShowUnconserved());
5079 viewport.getRanges().setStartRes(safeInt(view.getStartRes()));
5081 if (view.getViewName() != null)
5083 viewport.setViewName(view.getViewName());
5084 af.setInitialTabVisible();
5086 af.setBounds(safeInt(view.getXpos()), safeInt(view.getYpos()),
5087 safeInt(view.getWidth()), safeInt(view.getHeight()));
5088 // startSeq set in af.alignPanel.updateLayout below
5089 af.alignPanel.updateLayout();
5090 ColourSchemeI cs = null;
5091 // apply colourschemes
5092 if (view.getBgColour() != null)
5094 if (view.getBgColour().startsWith("ucs"))
5096 cs = getUserColourScheme(jm, view.getBgColour());
5098 else if (view.getBgColour().startsWith("Annotation"))
5100 AnnotationColourScheme viewAnnColour = view.getAnnotationColours();
5101 cs = constructAnnotationColour(viewAnnColour, af, al, jm, true);
5108 cs = ColourSchemeProperty.getColourScheme(af.getViewport(), al,
5109 view.getBgColour());
5114 * turn off 'alignment colour applies to all groups'
5115 * while restoring global colour scheme
5117 viewport.setColourAppliesToAllGroups(false);
5118 viewport.setGlobalColourScheme(cs);
5119 viewport.getResidueShading().setThreshold(pidThreshold,
5120 view.isIgnoreGapsinConsensus());
5121 viewport.getResidueShading()
5122 .setConsensus(viewport.getSequenceConsensusHash());
5123 if (safeBoolean(view.isConservationSelected()) && cs != null)
5125 viewport.getResidueShading()
5126 .setConservationInc(safeInt(view.getConsThreshold()));
5128 af.changeColour(cs);
5129 viewport.setColourAppliesToAllGroups(true);
5131 viewport.setShowSequenceFeatures(
5132 safeBoolean(view.isShowSequenceFeatures()));
5134 viewport.setCentreColumnLabels(view.isCentreColumnLabels());
5135 viewport.setIgnoreGapsConsensus(view.isIgnoreGapsinConsensus(), null);
5136 viewport.setFollowHighlight(view.isFollowHighlight());
5137 viewport.followSelection = view.isFollowSelection();
5138 viewport.setShowConsensusHistogram(view.isShowConsensusHistogram());
5139 viewport.setShowSequenceLogo(view.isShowSequenceLogo());
5140 viewport.setNormaliseSequenceLogo(view.isNormaliseSequenceLogo());
5141 viewport.setShowDBRefs(safeBoolean(view.isShowDbRefTooltip()));
5142 viewport.setShowNPFeats(safeBoolean(view.isShowNPfeatureTooltip()));
5143 viewport.setShowGroupConsensus(view.isShowGroupConsensus());
5144 viewport.setShowGroupConservation(view.isShowGroupConservation());
5145 viewport.setShowComplementFeatures(view.isShowComplementFeatures());
5146 viewport.setShowComplementFeaturesOnTop(
5147 view.isShowComplementFeaturesOnTop());
5149 // recover feature settings
5150 if (jm.getFeatureSettings() != null)
5152 FeatureRendererModel fr = af.alignPanel.getSeqPanel().seqCanvas
5153 .getFeatureRenderer();
5154 FeaturesDisplayed fdi;
5155 viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
5156 String[] renderOrder = new String[jm.getFeatureSettings().getSetting()
5158 Map<String, FeatureColourI> featureColours = new Hashtable<>();
5159 Map<String, Float> featureOrder = new Hashtable<>();
5161 for (int fs = 0; fs < jm.getFeatureSettings().getSetting()
5164 Setting setting = jm.getFeatureSettings().getSetting().get(fs);
5165 String featureType = setting.getType();
5168 * restore feature filters (if any)
5170 jalview.xml.binding.jalview.FeatureMatcherSet filters = setting
5172 if (filters != null)
5174 FeatureMatcherSetI filter = Jalview2XML.parseFilter(featureType,
5176 if (!filter.isEmpty())
5178 fr.setFeatureFilter(featureType, filter);
5183 * restore feature colour scheme
5185 Color maxColour = new Color(setting.getColour());
5186 if (setting.getMincolour() != null)
5189 * minColour is always set unless a simple colour
5190 * (including for colour by label though it doesn't use it)
5192 Color minColour = new Color(setting.getMincolour().intValue());
5193 Color noValueColour = minColour;
5194 NoValueColour noColour = setting.getNoValueColour();
5195 if (noColour == NoValueColour.NONE)
5197 noValueColour = null;
5199 else if (noColour == NoValueColour.MAX)
5201 noValueColour = maxColour;
5203 float min = safeFloat(safeFloat(setting.getMin()));
5204 float max = setting.getMax() == null ? 1f
5205 : setting.getMax().floatValue();
5206 FeatureColourI gc = new FeatureColour(maxColour, minColour,
5207 maxColour, noValueColour, min, max);
5208 if (setting.getAttributeName().size() > 0)
5210 gc.setAttributeName(setting.getAttributeName().toArray(
5211 new String[setting.getAttributeName().size()]));
5213 if (setting.getThreshold() != null)
5215 gc.setThreshold(setting.getThreshold().floatValue());
5216 int threshstate = safeInt(setting.getThreshstate());
5217 // -1 = None, 0 = Below, 1 = Above threshold
5218 if (threshstate == 0)
5220 gc.setBelowThreshold(true);
5222 else if (threshstate == 1)
5224 gc.setAboveThreshold(true);
5227 gc.setAutoScaled(true); // default
5228 if (setting.isAutoScale() != null)
5230 gc.setAutoScaled(setting.isAutoScale());
5232 if (setting.isColourByLabel() != null)
5234 gc.setColourByLabel(setting.isColourByLabel());
5236 // and put in the feature colour table.
5237 featureColours.put(featureType, gc);
5241 featureColours.put(featureType, new FeatureColour(maxColour));
5243 renderOrder[fs] = featureType;
5244 if (setting.getOrder() != null)
5246 featureOrder.put(featureType, setting.getOrder().floatValue());
5250 featureOrder.put(featureType, Float.valueOf(
5251 fs / jm.getFeatureSettings().getSetting().size()));
5253 if (safeBoolean(setting.isDisplay()))
5255 fdi.setVisible(featureType);
5258 Map<String, Boolean> fgtable = new Hashtable<>();
5259 for (int gs = 0; gs < jm.getFeatureSettings().getGroup().size(); gs++)
5261 Group grp = jm.getFeatureSettings().getGroup().get(gs);
5262 fgtable.put(grp.getName(), Boolean.valueOf(grp.isDisplay()));
5264 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
5265 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
5266 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
5267 FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
5268 fgtable, featureColours, 1.0f, featureOrder);
5269 fr.transferSettings(frs);
5272 if (view.getHiddenColumns().size() > 0)
5274 for (int c = 0; c < view.getHiddenColumns().size(); c++)
5276 final HiddenColumns hc = view.getHiddenColumns().get(c);
5277 viewport.hideColumns(safeInt(hc.getStart()),
5278 safeInt(hc.getEnd()) /* +1 */);
5281 if (view.getCalcIdParam() != null)
5283 for (CalcIdParam calcIdParam : view.getCalcIdParam())
5285 if (calcIdParam != null)
5287 if (recoverCalcIdParam(calcIdParam, viewport))
5292 Console.warn("Couldn't recover parameters for "
5293 + calcIdParam.getCalcId());
5298 af.setMenusFromViewport(viewport);
5299 af.setTitle(view.getTitle());
5300 // TODO: we don't need to do this if the viewport is aready visible.
5302 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
5303 * has a 'cdna/protein complement' view, in which case save it in order to
5304 * populate a SplitFrame once all views have been read in.
5306 String complementaryViewId = view.getComplementId();
5307 if (complementaryViewId == null)
5309 Desktop.addInternalFrame(af, view.getTitle(),
5310 safeInt(view.getWidth()), safeInt(view.getHeight()));
5311 // recompute any autoannotation
5312 af.alignPanel.updateAnnotation(false, true);
5313 reorderAutoannotation(af, al, autoAlan);
5314 af.alignPanel.alignmentChanged();
5318 splitFrameCandidates.put(view, af);
5325 * Reads saved data to restore Colour by Annotation settings
5327 * @param viewAnnColour
5331 * @param checkGroupAnnColour
5334 private ColourSchemeI constructAnnotationColour(
5335 AnnotationColourScheme viewAnnColour, AlignFrame af,
5336 AlignmentI al, JalviewModel model, boolean checkGroupAnnColour)
5338 boolean propagateAnnColour = false;
5339 AlignmentI annAlignment = af != null ? af.getViewport().getAlignment()
5341 if (checkGroupAnnColour && al.getGroups() != null
5342 && al.getGroups().size() > 0)
5344 // pre 2.8.1 behaviour
5345 // check to see if we should transfer annotation colours
5346 propagateAnnColour = true;
5347 for (SequenceGroup sg : al.getGroups())
5349 if (sg.getColourScheme() instanceof AnnotationColourGradient)
5351 propagateAnnColour = false;
5357 * 2.10.2- : saved annotationId is AlignmentAnnotation.annotationId
5359 String annotationId = viewAnnColour.getAnnotation();
5360 AlignmentAnnotation matchedAnnotation = annotationIds.get(annotationId);
5363 * pre 2.10.2: saved annotationId is AlignmentAnnotation.label
5365 if (matchedAnnotation == null
5366 && annAlignment.getAlignmentAnnotation() != null)
5368 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
5371 .equals(annAlignment.getAlignmentAnnotation()[i].label))
5373 matchedAnnotation = annAlignment.getAlignmentAnnotation()[i];
5378 if (matchedAnnotation == null)
5380 System.err.println("Failed to match annotation colour scheme for "
5384 // belt-and-braces create a threshold line if the
5385 // colourscheme needs one but the matchedAnnotation doesn't have one
5386 if (safeInt(viewAnnColour.getAboveThreshold()) != 0
5387 && matchedAnnotation.getThreshold() == null)
5389 matchedAnnotation.setThreshold(
5390 new GraphLine(safeFloat(viewAnnColour.getThreshold()),
5391 "Threshold", Color.black));
5394 AnnotationColourGradient cs = null;
5395 if (viewAnnColour.getColourScheme().equals("None"))
5397 cs = new AnnotationColourGradient(matchedAnnotation,
5398 new Color(safeInt(viewAnnColour.getMinColour())),
5399 new Color(safeInt(viewAnnColour.getMaxColour())),
5400 safeInt(viewAnnColour.getAboveThreshold()));
5402 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
5404 cs = new AnnotationColourGradient(matchedAnnotation,
5405 getUserColourScheme(model, viewAnnColour.getColourScheme()),
5406 safeInt(viewAnnColour.getAboveThreshold()));
5410 cs = new AnnotationColourGradient(matchedAnnotation,
5411 ColourSchemeProperty.getColourScheme(af.getViewport(), al,
5412 viewAnnColour.getColourScheme()),
5413 safeInt(viewAnnColour.getAboveThreshold()));
5416 boolean perSequenceOnly = safeBoolean(viewAnnColour.isPerSequence());
5417 boolean useOriginalColours = safeBoolean(
5418 viewAnnColour.isPredefinedColours());
5419 cs.setSeqAssociated(perSequenceOnly);
5420 cs.setPredefinedColours(useOriginalColours);
5422 if (propagateAnnColour && al.getGroups() != null)
5424 // Also use these settings for all the groups
5425 for (int g = 0; g < al.getGroups().size(); g++)
5427 SequenceGroup sg = al.getGroups().get(g);
5428 if (sg.getGroupColourScheme() == null)
5433 AnnotationColourGradient groupScheme = new AnnotationColourGradient(
5434 matchedAnnotation, sg.getColourScheme(),
5435 safeInt(viewAnnColour.getAboveThreshold()));
5436 sg.setColourScheme(groupScheme);
5437 groupScheme.setSeqAssociated(perSequenceOnly);
5438 groupScheme.setPredefinedColours(useOriginalColours);
5444 private void reorderAutoannotation(AlignFrame af, AlignmentI al,
5445 List<JvAnnotRow> autoAlan)
5447 // copy over visualization settings for autocalculated annotation in the
5449 if (al.getAlignmentAnnotation() != null)
5452 * Kludge for magic autoannotation names (see JAL-811)
5454 String[] magicNames = new String[] { "Consensus", "Quality",
5456 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
5457 Hashtable<String, JvAnnotRow> visan = new Hashtable<>();
5458 for (String nm : magicNames)
5460 visan.put(nm, nullAnnot);
5462 for (JvAnnotRow auan : autoAlan)
5464 visan.put(auan.template.label
5465 + (auan.template.getCalcId() == null ? ""
5466 : "\t" + auan.template.getCalcId()),
5469 int hSize = al.getAlignmentAnnotation().length;
5470 List<JvAnnotRow> reorder = new ArrayList<>();
5471 // work through any autoCalculated annotation already on the view
5472 // removing it if it should be placed in a different location on the
5473 // annotation panel.
5474 List<String> remains = new ArrayList<>(visan.keySet());
5475 for (int h = 0; h < hSize; h++)
5477 jalview.datamodel.AlignmentAnnotation jalan = al
5478 .getAlignmentAnnotation()[h];
5479 if (jalan.autoCalculated)
5482 JvAnnotRow valan = visan.get(k = jalan.label);
5483 if (jalan.getCalcId() != null)
5485 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
5490 // delete the auto calculated row from the alignment
5491 al.deleteAnnotation(jalan, false);
5495 if (valan != nullAnnot)
5497 if (jalan != valan.template)
5499 // newly created autoannotation row instance
5500 // so keep a reference to the visible annotation row
5501 // and copy over all relevant attributes
5502 if (valan.template.graphHeight >= 0)
5505 jalan.graphHeight = valan.template.graphHeight;
5507 jalan.visible = valan.template.visible;
5509 reorder.add(new JvAnnotRow(valan.order, jalan));
5514 // Add any (possibly stale) autocalculated rows that were not appended to
5515 // the view during construction
5516 for (String other : remains)
5518 JvAnnotRow othera = visan.get(other);
5519 if (othera != nullAnnot && othera.template.getCalcId() != null
5520 && othera.template.getCalcId().length() > 0)
5522 reorder.add(othera);
5525 // now put the automatic annotation in its correct place
5526 int s = 0, srt[] = new int[reorder.size()];
5527 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
5528 for (JvAnnotRow jvar : reorder)
5531 srt[s++] = jvar.order;
5534 jalview.util.QuickSort.sort(srt, rws);
5535 // and re-insert the annotation at its correct position
5536 for (JvAnnotRow jvar : rws)
5538 al.addAnnotation(jvar.template, jvar.order);
5540 af.alignPanel.adjustAnnotationHeight();
5544 Hashtable skipList = null;
5547 * TODO remove this method
5550 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
5551 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
5552 * throw new Error("Implementation Error. No skipList defined for this
5553 * Jalview2XML instance."); } return (AlignFrame)
5554 * skipList.get(view.getSequenceSetId()); }
5558 * Check if the Jalview view contained in object should be skipped or not.
5561 * @return true if view's sequenceSetId is a key in skipList
5563 private boolean skipViewport(JalviewModel object)
5565 if (skipList == null)
5569 String id = object.getViewport().get(0).getSequenceSetId();
5570 if (skipList.containsKey(id))
5572 Console.debug("Skipping seuqence set id " + id);
5578 public void addToSkipList(AlignFrame af)
5580 if (skipList == null)
5582 skipList = new Hashtable();
5584 skipList.put(af.getViewport().getSequenceSetId(), af);
5587 public void clearSkipList()
5589 if (skipList != null)
5596 private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
5597 boolean ignoreUnrefed, String uniqueSeqSetId)
5599 jalview.datamodel.AlignmentI ds = getDatasetFor(
5600 vamsasSet.getDatasetId());
5601 AlignmentI xtant_ds = ds;
5602 if (xtant_ds == null)
5604 // good chance we are about to create a new dataset, but check if we've
5605 // seen some of the dataset sequence IDs before.
5606 // TODO: skip this check if we are working with project generated by
5607 // version 2.11 or later
5608 xtant_ds = checkIfHasDataset(vamsasSet.getSequence());
5609 if (xtant_ds != null)
5612 addDatasetRef(vamsasSet.getDatasetId(), ds);
5615 Vector<SequenceI> dseqs = null;
5618 // recovering an alignment View
5619 AlignmentI seqSetDS = getDatasetFor(UNIQSEQSETID + uniqueSeqSetId);
5620 if (seqSetDS != null)
5622 if (ds != null && ds != seqSetDS)
5625 "JAL-3171 regression: Overwriting a dataset reference for an alignment"
5626 + " - CDS/Protein crossreference data may be lost");
5627 if (xtant_ds != null)
5629 // This can only happen if the unique sequence set ID was bound to a
5630 // dataset that did not contain any of the sequences in the view
5631 // currently being restored.
5633 "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.");
5637 addDatasetRef(vamsasSet.getDatasetId(), ds);
5642 // try even harder to restore dataset
5643 AlignmentI xtantDS = checkIfHasDataset(vamsasSet.getSequence());
5644 // create a list of new dataset sequences
5645 dseqs = new Vector<>();
5647 for (int i = 0, iSize = vamsasSet.getSequence().size(); i < iSize; i++)
5649 Sequence vamsasSeq = vamsasSet.getSequence().get(i);
5650 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed, i);
5652 // create a new dataset
5655 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
5656 dseqs.copyInto(dsseqs);
5657 ds = new jalview.datamodel.Alignment(dsseqs);
5658 Console.debug("Created new dataset " + vamsasSet.getDatasetId()
5659 + " for alignment " + System.identityHashCode(al));
5660 addDatasetRef(vamsasSet.getDatasetId(), ds);
5662 // set the dataset for the newly imported alignment.
5663 if (al.getDataset() == null && !ignoreUnrefed)
5666 // register dataset for the alignment's uniqueSeqSetId for legacy projects
5667 addDatasetRef(UNIQSEQSETID + uniqueSeqSetId, ds);
5669 updateSeqDatasetBinding(vamsasSet.getSequence(), ds);
5673 * XML dataset sequence ID to materialised dataset reference
5675 HashMap<String, AlignmentI> seqToDataset = new HashMap<>();
5678 * @return the first materialised dataset reference containing a dataset
5679 * sequence referenced in the given view
5681 * - sequences from the view
5683 AlignmentI checkIfHasDataset(List<Sequence> list)
5685 for (Sequence restoredSeq : list)
5687 AlignmentI datasetFor = seqToDataset.get(restoredSeq.getDsseqid());
5688 if (datasetFor != null)
5697 * Register ds as the containing dataset for the dataset sequences referenced
5698 * by sequences in list
5701 * - sequences in a view
5704 void updateSeqDatasetBinding(List<Sequence> list, AlignmentI ds)
5706 for (Sequence restoredSeq : list)
5708 AlignmentI prevDS = seqToDataset.put(restoredSeq.getDsseqid(), ds);
5709 if (prevDS != null && prevDS != ds)
5711 Console.warn("Dataset sequence appears in many datasets: "
5712 + restoredSeq.getDsseqid());
5713 // TODO: try to merge!
5721 * sequence definition to create/merge dataset sequence for
5725 * vector to add new dataset sequence to
5726 * @param ignoreUnrefed
5727 * - when true, don't create new sequences from vamsasSeq if it's id
5728 * doesn't already have an asssociated Jalview sequence.
5730 * - used to reorder the sequence in the alignment according to the
5731 * vamsasSeq array ordering, to preserve ordering of dataset
5733 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
5734 AlignmentI ds, Vector<SequenceI> dseqs, boolean ignoreUnrefed,
5737 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
5739 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
5740 boolean reorder = false;
5741 SequenceI dsq = null;
5742 if (sq != null && sq.getDatasetSequence() != null)
5744 dsq = sq.getDatasetSequence();
5750 if (sq == null && ignoreUnrefed)
5754 String sqid = vamsasSeq.getDsseqid();
5757 // need to create or add a new dataset sequence reference to this sequence
5760 dsq = seqRefIds.get(sqid);
5765 // make a new dataset sequence
5766 dsq = sq.createDatasetSequence();
5769 // make up a new dataset reference for this sequence
5770 sqid = seqHash(dsq);
5772 dsq.setVamsasId(uniqueSetSuffix + sqid);
5773 seqRefIds.put(sqid, dsq);
5778 dseqs.addElement(dsq);
5783 ds.addSequence(dsq);
5789 { // make this dataset sequence sq's dataset sequence
5790 sq.setDatasetSequence(dsq);
5791 // and update the current dataset alignment
5796 if (!dseqs.contains(dsq))
5803 if (ds.findIndex(dsq) < 0)
5805 ds.addSequence(dsq);
5812 // TODO: refactor this as a merge dataset sequence function
5813 // now check that sq (the dataset sequence) sequence really is the union of
5814 // all references to it
5815 // boolean pre = sq.getStart() < dsq.getStart();
5816 // boolean post = sq.getEnd() > dsq.getEnd();
5820 // StringBuffer sb = new StringBuffer();
5821 String newres = jalview.analysis.AlignSeq.extractGaps(
5822 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
5823 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
5824 && newres.length() > dsq.getLength())
5826 // Update with the longer sequence.
5830 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
5831 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
5832 * sb.append(newres.substring(newres.length() - sq.getEnd() -
5833 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
5835 dsq.setSequence(newres);
5837 // TODO: merges will never happen if we 'know' we have the real dataset
5838 // sequence - this should be detected when id==dssid
5840 "DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
5841 // + (pre ? "prepended" : "") + " "
5842 // + (post ? "appended" : ""));
5847 // sequence refs are identical. We may need to update the existing dataset
5848 // alignment with this one, though.
5849 if (ds != null && dseqs == null)
5851 int opos = ds.findIndex(dsq);
5852 SequenceI tseq = null;
5853 if (opos != -1 && vseqpos != opos)
5855 // remove from old position
5856 ds.deleteSequence(dsq);
5858 if (vseqpos < ds.getHeight())
5860 if (vseqpos != opos)
5862 // save sequence at destination position
5863 tseq = ds.getSequenceAt(vseqpos);
5864 ds.replaceSequenceAt(vseqpos, dsq);
5865 ds.addSequence(tseq);
5870 ds.addSequence(dsq);
5877 * TODO use AlignmentI here and in related methods - needs
5878 * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
5880 Hashtable<String, AlignmentI> datasetIds = null;
5882 IdentityHashMap<AlignmentI, String> dataset2Ids = null;
5884 private AlignmentI getDatasetFor(String datasetId)
5886 if (datasetIds == null)
5888 datasetIds = new Hashtable<>();
5891 if (datasetIds.containsKey(datasetId))
5893 return datasetIds.get(datasetId);
5898 private void addDatasetRef(String datasetId, AlignmentI dataset)
5900 if (datasetIds == null)
5902 datasetIds = new Hashtable<>();
5904 datasetIds.put(datasetId, dataset);
5908 * make a new dataset ID for this jalview dataset alignment
5913 private String getDatasetIdRef(AlignmentI dataset)
5915 if (dataset.getDataset() != null)
5918 "Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
5920 String datasetId = makeHashCode(dataset, null);
5921 if (datasetId == null)
5923 // make a new datasetId and record it
5924 if (dataset2Ids == null)
5926 dataset2Ids = new IdentityHashMap<>();
5930 datasetId = dataset2Ids.get(dataset);
5932 if (datasetId == null)
5934 datasetId = "ds" + dataset2Ids.size() + 1;
5935 dataset2Ids.put(dataset, datasetId);
5942 * Add any saved DBRefEntry's to the sequence. An entry flagged as 'locus' is
5943 * constructed as a special subclass GeneLocus.
5945 * @param datasetSequence
5948 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
5950 for (int d = 0; d < sequence.getDBRef().size(); d++)
5952 DBRef dr = sequence.getDBRef().get(d);
5956 entry = new GeneLocus(dr.getSource(), dr.getVersion(),
5957 dr.getAccessionId());
5961 entry = new DBRefEntry(dr.getSource(), dr.getVersion(),
5962 dr.getAccessionId());
5964 if (dr.getMapping() != null)
5966 entry.setMap(addMapping(dr.getMapping()));
5968 entry.setCanonical(dr.isCanonical());
5969 datasetSequence.addDBRef(entry);
5973 private jalview.datamodel.Mapping addMapping(Mapping m)
5975 SequenceI dsto = null;
5976 // Mapping m = dr.getMapping();
5977 int fr[] = new int[m.getMapListFrom().size() * 2];
5978 Iterator<MapListFrom> from = m.getMapListFrom().iterator();// enumerateMapListFrom();
5979 for (int _i = 0; from.hasNext(); _i += 2)
5981 MapListFrom mf = from.next();
5982 fr[_i] = mf.getStart();
5983 fr[_i + 1] = mf.getEnd();
5985 int fto[] = new int[m.getMapListTo().size() * 2];
5986 Iterator<MapListTo> to = m.getMapListTo().iterator();// enumerateMapListTo();
5987 for (int _i = 0; to.hasNext(); _i += 2)
5989 MapListTo mf = to.next();
5990 fto[_i] = mf.getStart();
5991 fto[_i + 1] = mf.getEnd();
5993 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto, fr,
5994 fto, m.getMapFromUnit().intValue(),
5995 m.getMapToUnit().intValue());
5998 * (optional) choice of dseqFor or Sequence
6000 if (m.getDseqFor() != null)
6002 String dsfor = m.getDseqFor();
6003 if (seqRefIds.containsKey(dsfor))
6008 jmap.setTo(seqRefIds.get(dsfor));
6012 frefedSequence.add(newMappingRef(dsfor, jmap));
6015 else if (m.getSequence() != null)
6018 * local sequence definition
6020 Sequence ms = m.getSequence();
6021 SequenceI djs = null;
6022 String sqid = ms.getDsseqid();
6023 if (sqid != null && sqid.length() > 0)
6026 * recover dataset sequence
6028 djs = seqRefIds.get(sqid);
6033 "Warning - making up dataset sequence id for DbRef sequence map reference");
6034 sqid = ((Object) ms).toString(); // make up a new hascode for
6035 // undefined dataset sequence hash
6036 // (unlikely to happen)
6042 * make a new dataset sequence and add it to refIds hash
6044 djs = new jalview.datamodel.Sequence(ms.getName(),
6046 djs.setStart(jmap.getMap().getToLowest());
6047 djs.setEnd(jmap.getMap().getToHighest());
6048 djs.setVamsasId(uniqueSetSuffix + sqid);
6050 incompleteSeqs.put(sqid, djs);
6051 seqRefIds.put(sqid, djs);
6054 Console.debug("about to recurse on addDBRefs.");
6063 * Provides a 'copy' of an alignment view (on action New View) by 'saving' the
6064 * view as XML (but not to file), and then reloading it
6069 public AlignmentPanel copyAlignPanel(AlignmentPanel ap)
6072 JalviewModel jm = saveState(ap, null, null, null);
6075 jm.getVamsasModel().getSequenceSet().get(0).getDatasetId(),
6076 ap.getAlignment().getDataset());
6078 uniqueSetSuffix = "";
6079 // jm.getJalviewModelSequence().getViewport(0).setId(null);
6080 jm.getViewport().get(0).setId(null);
6081 // we don't overwrite the view we just copied
6083 if (this.frefedSequence == null)
6085 frefedSequence = new Vector<>();
6088 viewportsAdded.clear();
6090 AlignFrame af = loadFromObject(jm, null, false, null);
6091 af.getAlignPanels().clear();
6092 af.closeMenuItem_actionPerformed(true);
6095 * if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
6096 * i<ap.av.getAlignment().getAlignmentAnnotation().length; i++) {
6097 * if(!ap.av.getAlignment().getAlignmentAnnotation()[i].autoCalculated) {
6098 * af.alignPanel.av.getAlignment().getAlignmentAnnotation()[i] =
6099 * ap.av.getAlignment().getAlignmentAnnotation()[i]; } } }
6102 return af.alignPanel;
6105 private Hashtable jvids2vobj;
6108 * set the object to ID mapping tables used to write/recover objects and XML
6109 * ID strings for the jalview project. If external tables are provided then
6110 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
6111 * object goes out of scope. - also populates the datasetIds hashtable with
6112 * alignment objects containing dataset sequences
6115 * Map from ID strings to jalview datamodel
6117 * Map from jalview datamodel to ID strings
6121 public void setObjectMappingTables(Hashtable vobj2jv,
6122 IdentityHashMap jv2vobj)
6124 this.jv2vobj = jv2vobj;
6125 this.vobj2jv = vobj2jv;
6126 Iterator ds = jv2vobj.keySet().iterator();
6128 while (ds.hasNext())
6130 Object jvobj = ds.next();
6131 id = jv2vobj.get(jvobj).toString();
6132 if (jvobj instanceof jalview.datamodel.Alignment)
6134 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
6136 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
6139 else if (jvobj instanceof jalview.datamodel.Sequence)
6141 // register sequence object so the XML parser can recover it.
6142 if (seqRefIds == null)
6144 seqRefIds = new HashMap<>();
6146 if (seqsToIds == null)
6148 seqsToIds = new IdentityHashMap<>();
6150 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
6151 seqsToIds.put((SequenceI) jvobj, id);
6153 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
6156 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
6157 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
6158 if (jvann.annotationId == null)
6160 jvann.annotationId = anid;
6162 if (!jvann.annotationId.equals(anid))
6164 // TODO verify that this is the correct behaviour
6165 Console.warn("Overriding Annotation ID for " + anid
6166 + " from different id : " + jvann.annotationId);
6167 jvann.annotationId = anid;
6170 else if (jvobj instanceof String)
6172 if (jvids2vobj == null)
6174 jvids2vobj = new Hashtable();
6175 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
6180 Console.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
6186 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
6187 * objects created from the project archive. If string is null (default for
6188 * construction) then suffix will be set automatically.
6192 public void setUniqueSetSuffix(String string)
6194 uniqueSetSuffix = string;
6199 * uses skipList2 as the skipList for skipping views on sequence sets
6200 * associated with keys in the skipList
6204 public void setSkipList(Hashtable skipList2)
6206 skipList = skipList2;
6210 * Reads the jar entry of given name and returns its contents, or null if the
6211 * entry is not found.
6214 * @param jarEntryName
6217 protected String readJarEntry(jarInputStreamProvider jprovider,
6218 String jarEntryName)
6220 String result = null;
6221 BufferedReader in = null;
6226 * Reopen the jar input stream and traverse its entries to find a matching
6229 JarInputStream jin = jprovider.getJarInputStream();
6230 JarEntry entry = null;
6233 entry = jin.getNextJarEntry();
6234 } while (entry != null && !entry.getName().equals(jarEntryName));
6238 StringBuilder out = new StringBuilder(256);
6239 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
6242 while ((data = in.readLine()) != null)
6246 result = out.toString();
6251 "Couldn't find entry in Jalview Jar for " + jarEntryName);
6253 } catch (Exception ex)
6255 ex.printStackTrace();
6263 } catch (IOException e)
6274 * Returns an incrementing counter (0, 1, 2...)
6278 private synchronized int nextCounter()
6284 * Loads any saved PCA viewers
6289 protected void loadPCAViewers(JalviewModel model, AlignmentPanel ap)
6293 List<PcaViewer> pcaviewers = model.getPcaViewer();
6294 for (PcaViewer viewer : pcaviewers)
6296 String modelName = viewer.getScoreModelName();
6297 SimilarityParamsI params = new SimilarityParams(
6298 viewer.isIncludeGappedColumns(), viewer.isMatchGaps(),
6299 viewer.isIncludeGaps(),
6300 viewer.isDenominateByShortestLength());
6303 * create the panel (without computing the PCA)
6305 PCAPanel panel = new PCAPanel(ap, modelName, params);
6307 panel.setTitle(viewer.getTitle());
6308 panel.setBounds(new Rectangle(viewer.getXpos(), viewer.getYpos(),
6309 viewer.getWidth(), viewer.getHeight()));
6311 boolean showLabels = viewer.isShowLabels();
6312 panel.setShowLabels(showLabels);
6313 panel.getRotatableCanvas().setShowLabels(showLabels);
6314 panel.getRotatableCanvas()
6315 .setBgColour(new Color(viewer.getBgColour()));
6316 panel.getRotatableCanvas()
6317 .setApplyToAllViews(viewer.isLinkToAllViews());
6320 * load PCA output data
6322 ScoreModelI scoreModel = ScoreModels.getInstance()
6323 .getScoreModel(modelName, ap);
6324 PCA pca = new PCA(null, scoreModel, params);
6325 PcaDataType pcaData = viewer.getPcaData();
6327 MatrixI pairwise = loadDoubleMatrix(pcaData.getPairwiseMatrix());
6328 pca.setPairwiseScores(pairwise);
6330 MatrixI triDiag = loadDoubleMatrix(pcaData.getTridiagonalMatrix());
6331 pca.setTridiagonal(triDiag);
6333 MatrixI result = loadDoubleMatrix(pcaData.getEigenMatrix());
6334 pca.setEigenmatrix(result);
6336 panel.getPcaModel().setPCA(pca);
6339 * we haven't saved the input data! (JAL-2647 to do)
6341 panel.setInputData(null);
6344 * add the sequence points for the PCA display
6346 List<jalview.datamodel.SequencePoint> seqPoints = new ArrayList<>();
6347 for (SequencePoint sp : viewer.getSequencePoint())
6349 String seqId = sp.getSequenceRef();
6350 SequenceI seq = seqRefIds.get(seqId);
6353 throw new IllegalStateException(
6354 "Unmatched seqref for PCA: " + seqId);
6356 Point pt = new Point(sp.getXPos(), sp.getYPos(), sp.getZPos());
6357 jalview.datamodel.SequencePoint seqPoint = new jalview.datamodel.SequencePoint(
6359 seqPoints.add(seqPoint);
6361 panel.getRotatableCanvas().setPoints(seqPoints, seqPoints.size());
6364 * set min-max ranges and scale after setPoints (which recomputes them)
6366 panel.getRotatableCanvas().setScaleFactor(viewer.getScaleFactor());
6367 SeqPointMin spMin = viewer.getSeqPointMin();
6368 float[] min = new float[] { spMin.getXPos(), spMin.getYPos(),
6370 SeqPointMax spMax = viewer.getSeqPointMax();
6371 float[] max = new float[] { spMax.getXPos(), spMax.getYPos(),
6373 panel.getRotatableCanvas().setSeqMinMax(min, max);
6375 // todo: hold points list in PCAModel only
6376 panel.getPcaModel().setSequencePoints(seqPoints);
6378 panel.setSelectedDimensionIndex(viewer.getXDim(), X);
6379 panel.setSelectedDimensionIndex(viewer.getYDim(), Y);
6380 panel.setSelectedDimensionIndex(viewer.getZDim(), Z);
6382 // is this duplication needed?
6383 panel.setTop(seqPoints.size() - 1);
6384 panel.getPcaModel().setTop(seqPoints.size() - 1);
6387 * add the axes' end points for the display
6389 for (int i = 0; i < 3; i++)
6391 Axis axis = viewer.getAxis().get(i);
6392 panel.getRotatableCanvas().getAxisEndPoints()[i] = new Point(
6393 axis.getXPos(), axis.getYPos(), axis.getZPos());
6396 Desktop.addInternalFrame(panel, MessageManager.formatMessage(
6397 "label.calc_title", "PCA", modelName), 475, 450);
6399 } catch (Exception ex)
6401 Console.error("Error loading PCA: " + ex.toString());
6406 * Creates a new structure viewer window
6413 protected void createStructureViewer(ViewerType viewerType,
6414 final Entry<String, StructureViewerModel> viewerData,
6415 AlignFrame af, jarInputStreamProvider jprovider)
6417 final StructureViewerModel viewerModel = viewerData.getValue();
6418 String sessionFilePath = null;
6420 if (viewerType == ViewerType.JMOL)
6422 sessionFilePath = rewriteJmolSession(viewerModel, jprovider);
6426 String viewerJarEntryName = getViewerJarEntryName(
6427 viewerModel.getViewId());
6428 sessionFilePath = copyJarEntry(jprovider, viewerJarEntryName,
6429 "viewerSession", ".tmp");
6431 final String sessionPath = sessionFilePath;
6432 final String sviewid = viewerData.getKey();
6435 SwingUtilities.invokeAndWait(new Runnable()
6440 JalviewStructureDisplayI sview = null;
6443 sview = StructureViewer.createView(viewerType, af.alignPanel,
6444 viewerModel, sessionPath, sviewid);
6445 addNewStructureViewer(sview);
6446 } catch (OutOfMemoryError ex)
6448 new OOMWarning("Restoring structure view for " + viewerType,
6449 (OutOfMemoryError) ex.getCause());
6450 if (sview != null && sview.isVisible())
6452 sview.closeViewer(false);
6453 sview.setVisible(false);
6459 } catch (InvocationTargetException | InterruptedException ex)
6461 Console.warn("Unexpected error when opening " + viewerType
6462 + " structure viewer", ex);
6467 * Rewrites a Jmol session script, saves it to a temporary file, and returns
6468 * the path of the file. "load file" commands are rewritten to change the
6469 * original PDB file names to those created as the Jalview project is loaded.
6475 private String rewriteJmolSession(StructureViewerModel svattrib,
6476 jarInputStreamProvider jprovider)
6478 String state = svattrib.getStateData(); // Jalview < 2.9
6479 if (state == null || state.isEmpty()) // Jalview >= 2.9
6481 String jarEntryName = getViewerJarEntryName(svattrib.getViewId());
6482 state = readJarEntry(jprovider, jarEntryName);
6484 // TODO or simpler? for each key in oldFiles,
6485 // replace key.getPath() in state with oldFiles.get(key).getFilePath()
6486 // (allowing for different path escapings)
6487 StringBuilder rewritten = new StringBuilder(state.length());
6488 int cp = 0, ncp, ecp;
6489 Map<File, StructureData> oldFiles = svattrib.getFileData();
6490 while ((ncp = state.indexOf("load ", cp)) > -1)
6494 // look for next filename in load statement
6495 rewritten.append(state.substring(cp,
6496 ncp = (state.indexOf("\"", ncp + 1) + 1)));
6497 String oldfilenam = state.substring(ncp,
6498 ecp = state.indexOf("\"", ncp));
6499 // recover the new mapping data for this old filename
6500 // have to normalize filename - since Jmol and jalview do
6501 // filename translation differently.
6502 StructureData filedat = oldFiles.get(new File(oldfilenam));
6503 if (filedat == null)
6505 String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
6506 filedat = oldFiles.get(new File(reformatedOldFilename));
6508 rewritten.append(Platform.escapeBackslashes(filedat.getFilePath()));
6509 rewritten.append("\"");
6510 cp = ecp + 1; // advance beyond last \" and set cursor so we can
6511 // look for next file statement.
6512 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
6516 // just append rest of state
6517 rewritten.append(state.substring(cp));
6521 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
6522 rewritten = new StringBuilder(state);
6523 rewritten.append("; load append ");
6524 for (File id : oldFiles.keySet())
6526 // add pdb files that should be present in the viewer
6527 StructureData filedat = oldFiles.get(id);
6528 rewritten.append(" \"").append(filedat.getFilePath()).append("\"");
6530 rewritten.append(";");
6533 if (rewritten.length() == 0)
6537 final String history = "history = ";
6538 int historyIndex = rewritten.indexOf(history);
6539 if (historyIndex > -1)
6542 * change "history = [true|false];" to "history = [1|0];"
6544 historyIndex += history.length();
6545 String val = rewritten.substring(historyIndex, historyIndex + 5);
6546 if (val.startsWith("true"))
6548 rewritten.replace(historyIndex, historyIndex + 4, "1");
6550 else if (val.startsWith("false"))
6552 rewritten.replace(historyIndex, historyIndex + 5, "0");
6558 File tmp = File.createTempFile("viewerSession", ".tmp");
6559 try (OutputStream os = new FileOutputStream(tmp))
6561 InputStream is = new ByteArrayInputStream(
6562 rewritten.toString().getBytes());
6564 return tmp.getAbsolutePath();
6566 } catch (IOException e)
6568 Console.error("Error restoring Jmol session: " + e.toString());
6574 * Populates an XML model of the feature colour scheme for one feature type
6576 * @param featureType
6580 public static Colour marshalColour(String featureType,
6581 FeatureColourI fcol)
6583 Colour col = new Colour();
6584 if (fcol.isSimpleColour())
6586 col.setRGB(Format.getHexString(fcol.getColour()));
6590 col.setRGB(Format.getHexString(fcol.getMaxColour()));
6591 col.setMin(fcol.getMin());
6592 col.setMax(fcol.getMax());
6593 col.setMinRGB(jalview.util.Format.getHexString(fcol.getMinColour()));
6594 col.setAutoScale(fcol.isAutoScaled());
6595 col.setThreshold(fcol.getThreshold());
6596 col.setColourByLabel(fcol.isColourByLabel());
6597 col.setThreshType(fcol.isAboveThreshold() ? ThresholdType.ABOVE
6598 : (fcol.isBelowThreshold() ? ThresholdType.BELOW
6599 : ThresholdType.NONE));
6600 if (fcol.isColourByAttribute())
6602 final String[] attName = fcol.getAttributeName();
6603 col.getAttributeName().add(attName[0]);
6604 if (attName.length > 1)
6606 col.getAttributeName().add(attName[1]);
6609 Color noColour = fcol.getNoColour();
6610 if (noColour == null)
6612 col.setNoValueColour(NoValueColour.NONE);
6614 else if (noColour == fcol.getMaxColour())
6616 col.setNoValueColour(NoValueColour.MAX);
6620 col.setNoValueColour(NoValueColour.MIN);
6623 col.setName(featureType);
6628 * Populates an XML model of the feature filter(s) for one feature type
6630 * @param firstMatcher
6631 * the first (or only) match condition)
6633 * remaining match conditions (if any)
6635 * if true, conditions are and-ed, else or-ed
6637 public static jalview.xml.binding.jalview.FeatureMatcherSet marshalFilter(
6638 FeatureMatcherI firstMatcher, Iterator<FeatureMatcherI> filters,
6641 jalview.xml.binding.jalview.FeatureMatcherSet result = new jalview.xml.binding.jalview.FeatureMatcherSet();
6643 if (filters.hasNext())
6648 CompoundMatcher compound = new CompoundMatcher();
6649 compound.setAnd(and);
6650 jalview.xml.binding.jalview.FeatureMatcherSet matcher1 = marshalFilter(
6651 firstMatcher, Collections.emptyIterator(), and);
6652 // compound.addMatcherSet(matcher1);
6653 compound.getMatcherSet().add(matcher1);
6654 FeatureMatcherI nextMatcher = filters.next();
6655 jalview.xml.binding.jalview.FeatureMatcherSet matcher2 = marshalFilter(
6656 nextMatcher, filters, and);
6657 // compound.addMatcherSet(matcher2);
6658 compound.getMatcherSet().add(matcher2);
6659 result.setCompoundMatcher(compound);
6664 * single condition matcher
6666 // MatchCondition matcherModel = new MatchCondition();
6667 jalview.xml.binding.jalview.FeatureMatcher matcherModel = new jalview.xml.binding.jalview.FeatureMatcher();
6668 matcherModel.setCondition(
6669 firstMatcher.getMatcher().getCondition().getStableName());
6670 matcherModel.setValue(firstMatcher.getMatcher().getPattern());
6671 if (firstMatcher.isByAttribute())
6673 matcherModel.setBy(FilterBy.BY_ATTRIBUTE);
6674 // matcherModel.setAttributeName(firstMatcher.getAttribute());
6675 String[] attName = firstMatcher.getAttribute();
6676 matcherModel.getAttributeName().add(attName[0]); // attribute
6677 if (attName.length > 1)
6679 matcherModel.getAttributeName().add(attName[1]); // sub-attribute
6682 else if (firstMatcher.isByLabel())
6684 matcherModel.setBy(FilterBy.BY_LABEL);
6686 else if (firstMatcher.isByScore())
6688 matcherModel.setBy(FilterBy.BY_SCORE);
6690 result.setMatchCondition(matcherModel);
6697 * Loads one XML model of a feature filter to a Jalview object
6699 * @param featureType
6700 * @param matcherSetModel
6703 public static FeatureMatcherSetI parseFilter(String featureType,
6704 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel)
6706 FeatureMatcherSetI result = new FeatureMatcherSet();
6709 parseFilterConditions(result, matcherSetModel, true);
6710 } catch (IllegalStateException e)
6712 // mixing AND and OR conditions perhaps
6714 String.format("Error reading filter conditions for '%s': %s",
6715 featureType, e.getMessage()));
6716 // return as much as was parsed up to the error
6723 * Adds feature match conditions to matcherSet as unmarshalled from XML
6724 * (possibly recursively for compound conditions)
6727 * @param matcherSetModel
6729 * if true, multiple conditions are AND-ed, else they are OR-ed
6730 * @throws IllegalStateException
6731 * if AND and OR conditions are mixed
6733 protected static void parseFilterConditions(FeatureMatcherSetI matcherSet,
6734 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel,
6737 jalview.xml.binding.jalview.FeatureMatcher mc = matcherSetModel
6738 .getMatchCondition();
6744 FilterBy filterBy = mc.getBy();
6745 Condition cond = Condition.fromString(mc.getCondition());
6746 String pattern = mc.getValue();
6747 FeatureMatcherI matchCondition = null;
6748 if (filterBy == FilterBy.BY_LABEL)
6750 matchCondition = FeatureMatcher.byLabel(cond, pattern);
6752 else if (filterBy == FilterBy.BY_SCORE)
6754 matchCondition = FeatureMatcher.byScore(cond, pattern);
6757 else if (filterBy == FilterBy.BY_ATTRIBUTE)
6759 final List<String> attributeName = mc.getAttributeName();
6760 String[] attNames = attributeName
6761 .toArray(new String[attributeName.size()]);
6762 matchCondition = FeatureMatcher.byAttribute(cond, pattern,
6767 * note this throws IllegalStateException if AND-ing to a
6768 * previously OR-ed compound condition, or vice versa
6772 matcherSet.and(matchCondition);
6776 matcherSet.or(matchCondition);
6782 * compound condition
6784 List<jalview.xml.binding.jalview.FeatureMatcherSet> matchers = matcherSetModel
6785 .getCompoundMatcher().getMatcherSet();
6786 boolean anded = matcherSetModel.getCompoundMatcher().isAnd();
6787 if (matchers.size() == 2)
6789 parseFilterConditions(matcherSet, matchers.get(0), anded);
6790 parseFilterConditions(matcherSet, matchers.get(1), anded);
6794 System.err.println("Malformed compound filter condition");
6800 * Loads one XML model of a feature colour to a Jalview object
6802 * @param colourModel
6805 public static FeatureColourI parseColour(Colour colourModel)
6807 FeatureColourI colour = null;
6809 if (colourModel.getMax() != null)
6811 Color mincol = null;
6812 Color maxcol = null;
6813 Color noValueColour = null;
6817 mincol = new Color(Integer.parseInt(colourModel.getMinRGB(), 16));
6818 maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6819 } catch (Exception e)
6821 Console.warn("Couldn't parse out graduated feature color.", e);
6824 NoValueColour noCol = colourModel.getNoValueColour();
6825 if (noCol == NoValueColour.MIN)
6827 noValueColour = mincol;
6829 else if (noCol == NoValueColour.MAX)
6831 noValueColour = maxcol;
6834 colour = new FeatureColour(maxcol, mincol, maxcol, noValueColour,
6835 safeFloat(colourModel.getMin()),
6836 safeFloat(colourModel.getMax()));
6837 final List<String> attributeName = colourModel.getAttributeName();
6838 String[] attributes = attributeName
6839 .toArray(new String[attributeName.size()]);
6840 if (attributes != null && attributes.length > 0)
6842 colour.setAttributeName(attributes);
6844 if (colourModel.isAutoScale() != null)
6846 colour.setAutoScaled(colourModel.isAutoScale().booleanValue());
6848 if (colourModel.isColourByLabel() != null)
6850 colour.setColourByLabel(
6851 colourModel.isColourByLabel().booleanValue());
6853 if (colourModel.getThreshold() != null)
6855 colour.setThreshold(colourModel.getThreshold().floatValue());
6857 ThresholdType ttyp = colourModel.getThreshType();
6858 if (ttyp == ThresholdType.ABOVE)
6860 colour.setAboveThreshold(true);
6862 else if (ttyp == ThresholdType.BELOW)
6864 colour.setBelowThreshold(true);
6869 Color color = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6870 colour = new FeatureColour(color);
6876 public static void setStateSavedUpToDate(boolean s)
6878 Console.debug("Setting overall stateSavedUpToDate to " + s);
6879 stateSavedUpToDate = s;
6882 public static boolean stateSavedUpToDate()
6884 Console.debug("Returning overall stateSavedUpToDate value: "
6885 + stateSavedUpToDate);
6886 return stateSavedUpToDate;
6889 public static boolean allSavedUpToDate()
6891 if (stateSavedUpToDate()) // nothing happened since last project save
6894 AlignFrame[] frames = Desktop.getAlignFrames();
6897 for (int i = 0; i < frames.length; i++)
6899 if (frames[i] == null)
6901 if (!frames[i].getViewport().savedUpToDate())
6902 return false; // at least one alignment is not individually saved
6908 // used for debugging and tests
6909 private static int debugDelaySave = 20;
6911 public static void setDebugDelaySave(int n)