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 jalview.analysis.Conservation;
24 import jalview.api.FeatureColourI;
25 import jalview.api.ViewStyleI;
26 import jalview.api.structures.JalviewStructureDisplayI;
27 import jalview.bin.Cache;
28 import jalview.datamodel.AlignedCodonFrame;
29 import jalview.datamodel.Alignment;
30 import jalview.datamodel.AlignmentAnnotation;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.GraphLine;
33 import jalview.datamodel.PDBEntry;
34 import jalview.datamodel.RnaViewerModel;
35 import jalview.datamodel.SequenceFeature;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.datamodel.StructureViewerModel;
39 import jalview.datamodel.StructureViewerModel.StructureData;
40 import jalview.datamodel.features.FeatureMatcher;
41 import jalview.datamodel.features.FeatureMatcherI;
42 import jalview.datamodel.features.FeatureMatcherSet;
43 import jalview.datamodel.features.FeatureMatcherSetI;
44 import jalview.ext.varna.RnaModel;
45 import jalview.gui.AlignFrame;
46 import jalview.gui.AlignViewport;
47 import jalview.gui.AlignmentPanel;
48 import jalview.gui.AppVarna;
49 import jalview.gui.ChimeraViewFrame;
50 import jalview.gui.Desktop;
51 import jalview.gui.FeatureRenderer;
52 import jalview.gui.Jalview2XML_V1;
53 import jalview.gui.JvOptionPane;
54 import jalview.gui.OOMWarning;
55 import jalview.gui.PaintRefresher;
56 import jalview.gui.SplitFrame;
57 import jalview.gui.StructureViewer;
58 import jalview.gui.StructureViewer.ViewerType;
59 import jalview.gui.StructureViewerBase;
60 import jalview.gui.TreePanel;
61 import jalview.io.DataSourceType;
62 import jalview.io.FileFormat;
63 import jalview.io.NewickFile;
64 import jalview.renderer.ResidueShaderI;
65 import jalview.schemes.AnnotationColourGradient;
66 import jalview.schemes.ColourSchemeI;
67 import jalview.schemes.ColourSchemeProperty;
68 import jalview.schemes.FeatureColour;
69 import jalview.schemes.ResidueProperties;
70 import jalview.schemes.UserColourScheme;
71 import jalview.structure.StructureSelectionManager;
72 import jalview.structures.models.AAStructureBindingModel;
73 import jalview.util.Format;
74 import jalview.util.MessageManager;
75 import jalview.util.Platform;
76 import jalview.util.StringUtils;
77 import jalview.util.jarInputStreamProvider;
78 import jalview.util.matcher.Condition;
79 import jalview.viewmodel.AlignmentViewport;
80 import jalview.viewmodel.ViewportRanges;
81 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
82 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
83 import jalview.ws.jws2.Jws2Discoverer;
84 import jalview.ws.jws2.dm.AAConSettings;
85 import jalview.ws.jws2.jabaws2.Jws2Instance;
86 import jalview.ws.params.ArgumentI;
87 import jalview.ws.params.AutoCalcSetting;
88 import jalview.ws.params.WsParamSetI;
89 import jalview.xml.binding.jalview.AlcodonFrame;
90 import jalview.xml.binding.jalview.AlcodonFrame.AlcodMap;
91 import jalview.xml.binding.jalview.Annotation;
92 import jalview.xml.binding.jalview.Annotation.ThresholdLine;
93 import jalview.xml.binding.jalview.AnnotationColourScheme;
94 import jalview.xml.binding.jalview.AnnotationElement;
95 import jalview.xml.binding.jalview.Feature;
96 import jalview.xml.binding.jalview.Feature.OtherData;
97 import jalview.xml.binding.jalview.FeatureMatcherSet.CompoundMatcher;
98 import jalview.xml.binding.jalview.FilterBy;
99 import jalview.xml.binding.jalview.JalviewModel;
100 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings;
101 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Group;
102 import jalview.xml.binding.jalview.JalviewModel.FeatureSettings.Setting;
103 import jalview.xml.binding.jalview.JalviewModel.JGroup;
104 import jalview.xml.binding.jalview.JalviewModel.JSeq;
105 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids;
106 import jalview.xml.binding.jalview.JalviewModel.JSeq.Pdbids.StructureState;
107 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer;
108 import jalview.xml.binding.jalview.JalviewModel.JSeq.RnaViewer.SecondaryStructure;
109 import jalview.xml.binding.jalview.JalviewModel.Tree;
110 import jalview.xml.binding.jalview.JalviewModel.UserColours;
111 import jalview.xml.binding.jalview.JalviewModel.Viewport;
112 import jalview.xml.binding.jalview.JalviewModel.Viewport.CalcIdParam;
113 import jalview.xml.binding.jalview.JalviewModel.Viewport.HiddenColumns;
114 import jalview.xml.binding.jalview.JalviewUserColours;
115 import jalview.xml.binding.jalview.JalviewUserColours.Colour;
116 import jalview.xml.binding.jalview.MapListType.MapListFrom;
117 import jalview.xml.binding.jalview.MapListType.MapListTo;
118 import jalview.xml.binding.jalview.Mapping;
119 import jalview.xml.binding.jalview.NoValueColour;
120 import jalview.xml.binding.jalview.ObjectFactory;
121 import jalview.xml.binding.jalview.Pdbentry.Property;
122 import jalview.xml.binding.jalview.Sequence;
123 import jalview.xml.binding.jalview.Sequence.DBRef;
124 import jalview.xml.binding.jalview.SequenceSet;
125 import jalview.xml.binding.jalview.SequenceSet.SequenceSetProperties;
126 import jalview.xml.binding.jalview.ThresholdType;
127 import jalview.xml.binding.jalview.VAMSAS;
129 import java.awt.Color;
130 import java.awt.Font;
131 import java.awt.Rectangle;
132 import java.io.BufferedReader;
133 import java.io.DataInputStream;
134 import java.io.DataOutputStream;
136 import java.io.FileInputStream;
137 import java.io.FileOutputStream;
138 import java.io.IOException;
139 import java.io.InputStreamReader;
140 import java.io.OutputStreamWriter;
141 import java.io.PrintWriter;
142 import java.lang.reflect.InvocationTargetException;
143 import java.math.BigInteger;
144 import java.net.MalformedURLException;
146 import java.util.ArrayList;
147 import java.util.Arrays;
148 import java.util.Collections;
149 import java.util.Enumeration;
150 import java.util.GregorianCalendar;
151 import java.util.HashMap;
152 import java.util.HashSet;
153 import java.util.Hashtable;
154 import java.util.IdentityHashMap;
155 import java.util.Iterator;
156 import java.util.LinkedHashMap;
157 import java.util.List;
158 import java.util.Map;
159 import java.util.Map.Entry;
160 import java.util.Set;
161 import java.util.Vector;
162 import java.util.jar.JarEntry;
163 import java.util.jar.JarInputStream;
164 import java.util.jar.JarOutputStream;
166 import javax.swing.JInternalFrame;
167 import javax.swing.SwingUtilities;
168 import javax.xml.bind.JAXBContext;
169 import javax.xml.bind.JAXBElement;
170 import javax.xml.bind.Marshaller;
171 import javax.xml.datatype.DatatypeConfigurationException;
172 import javax.xml.datatype.DatatypeFactory;
173 import javax.xml.datatype.XMLGregorianCalendar;
174 import javax.xml.stream.XMLInputFactory;
175 import javax.xml.stream.XMLStreamReader;
178 * Write out the current jalview desktop state as a Jalview XML stream.
180 * Note: the vamsas objects referred to here are primitive versions of the
181 * VAMSAS project schema elements - they are not the same and most likely never
185 * @version $Revision: 1.134 $
187 public class Jalview2XML
190 // BH 2018 we add the .jvp binary extension to J2S so that
191 // it will declare that binary when we do the file save from the browser
193 private static void addJ2SBinaryType(String ext)
195 ext = "." + ext + "?";
200 * J2S._binaryTypes.push(ext);
207 addJ2SBinaryType(".jvp?");
210 private static final String VIEWER_PREFIX = "viewer_";
212 private static final String RNA_PREFIX = "rna_";
214 private static final String UTF_8 = "UTF-8";
216 // use this with nextCounter() to make unique names for entities
217 private int counter = 0;
220 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
221 * of sequence objects are created.
223 IdentityHashMap<SequenceI, String> seqsToIds = null;
226 * jalview XML Sequence ID to jalview sequence object reference (both dataset
227 * and alignment sequences. Populated as XML reps of sequence objects are
230 Map<String, SequenceI> seqRefIds = null;
232 Map<String, SequenceI> incompleteSeqs = null;
234 List<SeqFref> frefedSequence = null;
236 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
239 * Map of reconstructed AlignFrame objects that appear to have come from
240 * SplitFrame objects (have a dna/protein complement view).
242 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
245 * Map from displayed rna structure models to their saved session state jar
248 private Map<RnaModel, String> rnaSessions = new HashMap<>();
251 * A helper method for safely using the value of an optional attribute that
252 * may be null if not present in the XML. Answers the boolean value, or false
258 public static boolean safeBoolean(Boolean b)
260 return b == null ? false : b.booleanValue();
264 * A helper method for safely using the value of an optional attribute that
265 * may be null if not present in the XML. Answers the integer value, or zero
271 public static int safeInt(Integer i)
273 return i == null ? 0 : i.intValue();
277 * A helper method for safely using the value of an optional attribute that
278 * may be null if not present in the XML. Answers the float value, or zero if
284 public static float safeFloat(Float f)
286 return f == null ? 0f : f.floatValue();
290 * create/return unique hash string for sq
293 * @return new or existing unique string for sq
295 String seqHash(SequenceI sq)
297 if (seqsToIds == null)
301 if (seqsToIds.containsKey(sq))
303 return seqsToIds.get(sq);
307 // create sequential key
308 String key = "sq" + (seqsToIds.size() + 1);
309 key = makeHashCode(sq, key); // check we don't have an external reference
311 seqsToIds.put(sq, key);
318 if (seqsToIds == null)
320 seqsToIds = new IdentityHashMap<>();
322 if (seqRefIds == null)
324 seqRefIds = new HashMap<>();
326 if (incompleteSeqs == null)
328 incompleteSeqs = new HashMap<>();
330 if (frefedSequence == null)
332 frefedSequence = new ArrayList<>();
340 public Jalview2XML(boolean raiseGUI)
342 this.raiseGUI = raiseGUI;
346 * base class for resolving forward references to sequences by their ID
351 abstract class SeqFref
357 public SeqFref(String _sref, String type)
363 public String getSref()
368 public SequenceI getSrefSeq()
370 return seqRefIds.get(sref);
373 public boolean isResolvable()
375 return seqRefIds.get(sref) != null;
378 public SequenceI getSrefDatasetSeq()
380 SequenceI sq = seqRefIds.get(sref);
383 while (sq.getDatasetSequence() != null)
385 sq = sq.getDatasetSequence();
392 * @return true if the forward reference was fully resolved
394 abstract boolean resolve();
397 public String toString()
399 return type + " reference to " + sref;
404 * create forward reference for a mapping
410 public SeqFref newMappingRef(final String sref,
411 final jalview.datamodel.Mapping _jmap)
413 SeqFref fref = new SeqFref(sref, "Mapping")
415 public jalview.datamodel.Mapping jmap = _jmap;
420 SequenceI seq = getSrefDatasetSeq();
432 public SeqFref newAlcodMapRef(final String sref,
433 final AlignedCodonFrame _cf,
434 final jalview.datamodel.Mapping _jmap)
437 SeqFref fref = new SeqFref(sref, "Codon Frame")
439 AlignedCodonFrame cf = _cf;
441 public jalview.datamodel.Mapping mp = _jmap;
444 public boolean isResolvable()
446 return super.isResolvable() && mp.getTo() != null;
452 SequenceI seq = getSrefDatasetSeq();
457 cf.addMap(seq, mp.getTo(), mp.getMap());
464 public void resolveFrefedSequences()
466 Iterator<SeqFref> nextFref = frefedSequence.iterator();
467 int toresolve = frefedSequence.size();
468 int unresolved = 0, failedtoresolve = 0;
469 while (nextFref.hasNext())
471 SeqFref ref = nextFref.next();
472 if (ref.isResolvable())
484 } catch (Exception x)
487 "IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
500 System.err.println("Jalview Project Import: There were " + unresolved
501 + " forward references left unresolved on the stack.");
503 if (failedtoresolve > 0)
505 System.err.println("SERIOUS! " + failedtoresolve
506 + " resolvable forward references failed to resolve.");
508 if (incompleteSeqs != null && incompleteSeqs.size() > 0)
511 "Jalview Project Import: There are " + incompleteSeqs.size()
512 + " sequences which may have incomplete metadata.");
513 if (incompleteSeqs.size() < 10)
515 for (SequenceI s : incompleteSeqs.values())
517 System.err.println(s.toString());
523 "Too many to report. Skipping output of incomplete sequences.");
529 * This maintains a map of viewports, the key being the seqSetId. Important to
530 * set historyItem and redoList for multiple views
532 Map<String, AlignViewport> viewportsAdded = new HashMap<>();
534 Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
536 String uniqueSetSuffix = "";
539 * List of pdbfiles added to Jar
541 List<String> pdbfiles = null;
543 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
544 public void saveState(File statefile)
546 FileOutputStream fos = null;
549 fos = new FileOutputStream(statefile);
550 JarOutputStream jout = new JarOutputStream(fos);
553 } catch (Exception e)
555 // TODO: inform user of the problem - they need to know if their data was
557 if (errorMessage == null)
559 errorMessage = "Couldn't write Jalview Archive to output file '"
560 + statefile + "' - See console error log for details";
564 errorMessage += "(output file was '" + statefile + "')";
574 } catch (IOException e)
584 * Writes a jalview project archive to the given Jar output stream.
588 public void saveState(JarOutputStream jout)
590 AlignFrame[] frames = Desktop.getAlignFrames();
596 saveAllFrames(Arrays.asList(frames), jout);
600 * core method for storing state for a set of AlignFrames.
603 * - frames involving all data to be exported (including containing
606 * - project output stream
608 private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
610 Hashtable<String, AlignFrame> dsses = new Hashtable<>();
613 * ensure cached data is clear before starting
615 // todo tidy up seqRefIds, seqsToIds initialisation / reset
617 splitFrameCandidates.clear();
622 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
623 // //////////////////////////////////////////////////
625 List<String> shortNames = new ArrayList<>();
626 List<String> viewIds = new ArrayList<>();
629 for (int i = frames.size() - 1; i > -1; i--)
631 AlignFrame af = frames.get(i);
633 if (skipList != null && skipList
634 .containsKey(af.getViewport().getSequenceSetId()))
639 String shortName = makeFilename(af, shortNames);
641 int apSize = af.getAlignPanels().size();
643 for (int ap = 0; ap < apSize; ap++)
645 AlignmentPanel apanel = (AlignmentPanel) af.getAlignPanels()
647 String fileName = apSize == 1 ? shortName : ap + shortName;
648 if (!fileName.endsWith(".xml"))
650 fileName = fileName + ".xml";
653 saveState(apanel, fileName, jout, viewIds);
655 String dssid = getDatasetIdRef(
656 af.getViewport().getAlignment().getDataset());
657 if (!dsses.containsKey(dssid))
659 dsses.put(dssid, af);
664 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
670 } catch (Exception foo)
675 } catch (Exception ex)
677 // TODO: inform user of the problem - they need to know if their data was
679 if (errorMessage == null)
681 errorMessage = "Couldn't write Jalview Archive - see error output for details";
683 ex.printStackTrace();
688 * Generates a distinct file name, based on the title of the AlignFrame, by
689 * appending _n for increasing n until an unused name is generated. The new
690 * name (without its extension) is added to the list.
694 * @return the generated name, with .xml extension
696 protected String makeFilename(AlignFrame af, List<String> namesUsed)
698 String shortName = af.getTitle();
700 if (shortName.indexOf(File.separatorChar) > -1)
702 shortName = shortName
703 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
708 while (namesUsed.contains(shortName))
710 if (shortName.endsWith("_" + (count - 1)))
712 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
715 shortName = shortName.concat("_" + count);
719 namesUsed.add(shortName);
721 if (!shortName.endsWith(".xml"))
723 shortName = shortName + ".xml";
728 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
729 public boolean saveAlignment(AlignFrame af, String jarFile,
734 FileOutputStream fos = new FileOutputStream(jarFile);
735 JarOutputStream jout = new JarOutputStream(fos);
736 List<AlignFrame> frames = new ArrayList<>();
738 // resolve splitframes
739 if (af.getViewport().getCodingComplement() != null)
741 frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
747 saveAllFrames(frames, jout);
751 } catch (Exception foo)
757 } catch (Exception ex)
759 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
760 ex.printStackTrace();
765 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
766 String fileName, JarOutputStream jout)
769 for (String dssids : dsses.keySet())
771 AlignFrame _af = dsses.get(dssids);
772 String jfileName = fileName + " Dataset for " + _af.getTitle();
773 if (!jfileName.endsWith(".xml"))
775 jfileName = jfileName + ".xml";
777 saveState(_af.alignPanel, jfileName, true, jout, null);
782 * create a JalviewModel from an alignment view and marshall it to a
786 * panel to create jalview model for
788 * name of alignment panel written to output stream
795 public JalviewModel saveState(AlignmentPanel ap, String fileName,
796 JarOutputStream jout, List<String> viewIds)
798 return saveState(ap, fileName, false, jout, viewIds);
802 * create a JalviewModel from an alignment view and marshall it to a
806 * panel to create jalview model for
808 * name of alignment panel written to output stream
810 * when true, only write the dataset for the alignment, not the data
811 * associated with the view.
817 public JalviewModel saveState(AlignmentPanel ap, String fileName,
818 boolean storeDS, JarOutputStream jout, List<String> viewIds)
822 viewIds = new ArrayList<>();
827 List<UserColourScheme> userColours = new ArrayList<>();
829 AlignViewport av = ap.av;
830 ViewportRanges vpRanges = av.getRanges();
832 final ObjectFactory objectFactory = new ObjectFactory();
833 JalviewModel object = objectFactory.createJalviewModel();
834 object.setVamsasModel(new VAMSAS());
836 // object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
839 GregorianCalendar c = new GregorianCalendar();
840 DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
841 XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(c);// gregorianCalendar);
842 object.setCreationDate(now);
843 } catch (DatatypeConfigurationException e)
845 System.err.println("error writing date: " + e.toString());
848 jalview.bin.Cache.getDefault("VERSION", "Development Build"));
851 * rjal is full height alignment, jal is actual alignment with full metadata
852 * but excludes hidden sequences.
854 jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
856 if (av.hasHiddenRows())
858 rjal = jal.getHiddenSequences().getFullAlignment();
861 SequenceSet vamsasSet = new SequenceSet();
863 // JalviewModelSequence jms = new JalviewModelSequence();
865 vamsasSet.setGapChar(jal.getGapCharacter() + "");
867 if (jal.getDataset() != null)
869 // dataset id is the dataset's hashcode
870 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
873 // switch jal and the dataset
874 jal = jal.getDataset();
878 if (jal.getProperties() != null)
880 Enumeration en = jal.getProperties().keys();
881 while (en.hasMoreElements())
883 String key = en.nextElement().toString();
884 SequenceSetProperties ssp = new SequenceSetProperties();
886 ssp.setValue(jal.getProperties().get(key).toString());
887 // vamsasSet.addSequenceSetProperties(ssp);
888 vamsasSet.getSequenceSetProperties().add(ssp);
893 Set<String> calcIdSet = new HashSet<>();
894 // record the set of vamsas sequence XML POJO we create.
895 HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
897 for (final SequenceI jds : rjal.getSequences())
899 final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
900 : jds.getDatasetSequence();
901 String id = seqHash(jds);
902 if (vamsasSetIds.get(id) == null)
904 if (seqRefIds.get(id) != null && !storeDS)
906 // This happens for two reasons: 1. multiple views are being
908 // 2. the hashCode has collided with another sequence's code. This
910 // HAPPEN! (PF00072.15.stk does this)
911 // JBPNote: Uncomment to debug writing out of files that do not read
912 // back in due to ArrayOutOfBoundExceptions.
913 // System.err.println("vamsasSeq backref: "+id+"");
914 // System.err.println(jds.getName()+"
915 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
916 // System.err.println("Hashcode: "+seqHash(jds));
917 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
918 // System.err.println(rsq.getName()+"
919 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
920 // System.err.println("Hashcode: "+seqHash(rsq));
924 vamsasSeq = createVamsasSequence(id, jds);
925 // vamsasSet.addSequence(vamsasSeq);
926 vamsasSet.getSequence().add(vamsasSeq);
927 vamsasSetIds.put(id, vamsasSeq);
928 seqRefIds.put(id, jds);
932 jseq.setStart(jds.getStart());
933 jseq.setEnd(jds.getEnd());
934 jseq.setColour(av.getSequenceColour(jds).getRGB());
936 jseq.setId(id); // jseq id should be a string not a number
939 // Store any sequences this sequence represents
940 if (av.hasHiddenRows())
942 // use rjal, contains the full height alignment
944 av.getAlignment().getHiddenSequences().isHidden(jds));
946 if (av.isHiddenRepSequence(jds))
948 jalview.datamodel.SequenceI[] reps = av
949 .getRepresentedSequences(jds).getSequencesInOrder(rjal);
951 for (int h = 0; h < reps.length; h++)
955 // jseq.addHiddenSequences(rjal.findIndex(reps[h]));
956 jseq.getHiddenSequences().add(rjal.findIndex(reps[h]));
961 // mark sequence as reference - if it is the reference for this view
964 jseq.setViewreference(jds == jal.getSeqrep());
968 // TODO: omit sequence features from each alignment view's XML dump if we
969 // are storing dataset
970 List<SequenceFeature> sfs = jds.getSequenceFeatures();
971 for (SequenceFeature sf : sfs)
973 // Features features = new Features();
974 Feature features = new Feature();
976 features.setBegin(sf.getBegin());
977 features.setEnd(sf.getEnd());
978 features.setDescription(sf.getDescription());
979 features.setType(sf.getType());
980 features.setFeatureGroup(sf.getFeatureGroup());
981 features.setScore(sf.getScore());
982 if (sf.links != null)
984 for (int l = 0; l < sf.links.size(); l++)
986 OtherData keyValue = new OtherData();
987 keyValue.setKey("LINK_" + l);
988 keyValue.setValue(sf.links.elementAt(l).toString());
989 // features.addOtherData(keyValue);
990 features.getOtherData().add(keyValue);
993 if (sf.otherDetails != null)
996 * save feature attributes, which may be simple strings or
997 * map valued (have sub-attributes)
999 for (Entry<String, Object> entry : sf.otherDetails.entrySet())
1001 String key = entry.getKey();
1002 Object value = entry.getValue();
1003 if (value instanceof Map<?, ?>)
1005 for (Entry<String, Object> subAttribute : ((Map<String, Object>) value)
1008 OtherData otherData = new OtherData();
1009 otherData.setKey(key);
1010 otherData.setKey2(subAttribute.getKey());
1011 otherData.setValue(subAttribute.getValue().toString());
1012 // features.addOtherData(otherData);
1013 features.getOtherData().add(otherData);
1018 OtherData otherData = new OtherData();
1019 otherData.setKey(key);
1020 otherData.setValue(value.toString());
1021 // features.addOtherData(otherData);
1022 features.getOtherData().add(otherData);
1027 // jseq.addFeatures(features);
1028 jseq.getFeatures().add(features);
1031 if (jdatasq.getAllPDBEntries() != null)
1033 Enumeration<PDBEntry> en = jdatasq.getAllPDBEntries().elements();
1034 while (en.hasMoreElements())
1036 Pdbids pdb = new Pdbids();
1037 jalview.datamodel.PDBEntry entry = en.nextElement();
1039 String pdbId = entry.getId();
1041 pdb.setType(entry.getType());
1044 * Store any structure views associated with this sequence. This
1045 * section copes with duplicate entries in the project, so a dataset
1046 * only view *should* be coped with sensibly.
1048 // This must have been loaded, is it still visible?
1049 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1050 String matchedFile = null;
1051 for (int f = frames.length - 1; f > -1; f--)
1053 if (frames[f] instanceof StructureViewerBase)
1055 StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
1056 matchedFile = saveStructureState(ap, jds, pdb, entry, viewIds,
1057 matchedFile, viewFrame);
1059 * Only store each structure viewer's state once in the project
1060 * jar. First time through only (storeDS==false)
1062 String viewId = viewFrame.getViewId();
1063 if (!storeDS && !viewIds.contains(viewId))
1065 viewIds.add(viewId);
1068 String viewerState = viewFrame.getStateInfo();
1069 writeJarEntry(jout, getViewerJarEntryName(viewId),
1070 viewerState.getBytes());
1071 } catch (IOException e)
1074 "Error saving viewer state: " + e.getMessage());
1080 if (matchedFile != null || entry.getFile() != null)
1082 if (entry.getFile() != null)
1085 matchedFile = entry.getFile();
1087 pdb.setFile(matchedFile); // entry.getFile());
1088 if (pdbfiles == null)
1090 pdbfiles = new ArrayList<>();
1093 if (!pdbfiles.contains(pdbId))
1095 pdbfiles.add(pdbId);
1096 copyFileToJar(jout, matchedFile, pdbId);
1100 Enumeration<String> props = entry.getProperties();
1101 if (props.hasMoreElements())
1103 // PdbentryItem item = new PdbentryItem();
1104 while (props.hasMoreElements())
1106 Property prop = new Property();
1107 String key = props.nextElement();
1109 prop.setValue(entry.getProperty(key).toString());
1110 // item.addProperty(prop);
1111 pdb.getProperty().add(prop);
1113 // pdb.addPdbentryItem(item);
1116 // jseq.addPdbids(pdb);
1117 jseq.getPdbids().add(pdb);
1121 saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
1123 // jms.addJSeq(jseq);
1124 object.getJSeq().add(jseq);
1127 if (!storeDS && av.hasHiddenRows())
1129 jal = av.getAlignment();
1133 if (storeDS && jal.getCodonFrames() != null)
1135 List<AlignedCodonFrame> jac = jal.getCodonFrames();
1136 for (AlignedCodonFrame acf : jac)
1138 AlcodonFrame alc = new AlcodonFrame();
1139 if (acf.getProtMappings() != null
1140 && acf.getProtMappings().length > 0)
1142 boolean hasMap = false;
1143 SequenceI[] dnas = acf.getdnaSeqs();
1144 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1145 for (int m = 0; m < pmaps.length; m++)
1147 AlcodMap alcmap = new AlcodMap();
1148 alcmap.setDnasq(seqHash(dnas[m]));
1150 createVamsasMapping(pmaps[m], dnas[m], null, false));
1151 // alc.addAlcodMap(alcmap);
1152 alc.getAlcodMap().add(alcmap);
1157 // vamsasSet.addAlcodonFrame(alc);
1158 vamsasSet.getAlcodonFrame().add(alc);
1161 // TODO: delete this ? dead code from 2.8.3->2.9 ?
1163 // AlcodonFrame alc = new AlcodonFrame();
1164 // vamsasSet.addAlcodonFrame(alc);
1165 // for (int p = 0; p < acf.aaWidth; p++)
1167 // Alcodon cmap = new Alcodon();
1168 // if (acf.codons[p] != null)
1170 // // Null codons indicate a gapped column in the translated peptide
1172 // cmap.setPos1(acf.codons[p][0]);
1173 // cmap.setPos2(acf.codons[p][1]);
1174 // cmap.setPos3(acf.codons[p][2]);
1176 // alc.addAlcodon(cmap);
1178 // if (acf.getProtMappings() != null
1179 // && acf.getProtMappings().length > 0)
1181 // SequenceI[] dnas = acf.getdnaSeqs();
1182 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1183 // for (int m = 0; m < pmaps.length; m++)
1185 // AlcodMap alcmap = new AlcodMap();
1186 // alcmap.setDnasq(seqHash(dnas[m]));
1187 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1189 // alc.addAlcodMap(alcmap);
1196 // /////////////////////////////////
1197 if (!storeDS && av.getCurrentTree() != null)
1199 // FIND ANY ASSOCIATED TREES
1200 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
1201 if (Desktop.desktop != null)
1203 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1205 for (int t = 0; t < frames.length; t++)
1207 if (frames[t] instanceof TreePanel)
1209 TreePanel tp = (TreePanel) frames[t];
1211 if (tp.getTreeCanvas().getViewport().getAlignment() == jal)
1213 JalviewModel.Tree tree = new JalviewModel.Tree();
1214 tree.setTitle(tp.getTitle());
1215 tree.setCurrentTree((av.getCurrentTree() == tp.getTree()));
1216 tree.setNewick(tp.getTree().print());
1217 tree.setThreshold(tp.getTreeCanvas().getThreshold());
1219 tree.setFitToWindow(tp.fitToWindow.getState());
1220 tree.setFontName(tp.getTreeFont().getName());
1221 tree.setFontSize(tp.getTreeFont().getSize());
1222 tree.setFontStyle(tp.getTreeFont().getStyle());
1223 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
1225 tree.setShowBootstrap(tp.bootstrapMenu.getState());
1226 tree.setShowDistances(tp.distanceMenu.getState());
1228 tree.setHeight(tp.getHeight());
1229 tree.setWidth(tp.getWidth());
1230 tree.setXpos(tp.getX());
1231 tree.setYpos(tp.getY());
1232 tree.setId(makeHashCode(tp, null));
1233 // jms.addTree(tree);
1234 object.getTree().add(tree);
1243 * store forward refs from an annotationRow to any groups
1245 IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
1248 for (SequenceI sq : jal.getSequences())
1250 // Store annotation on dataset sequences only
1251 AlignmentAnnotation[] aa = sq.getAnnotation();
1252 if (aa != null && aa.length > 0)
1254 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1261 if (jal.getAlignmentAnnotation() != null)
1263 // Store the annotation shown on the alignment.
1264 AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
1265 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1270 if (jal.getGroups() != null)
1272 JGroup[] groups = new JGroup[jal.getGroups().size()];
1274 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
1276 JGroup jGroup = new JGroup();
1277 groups[++i] = jGroup;
1279 jGroup.setStart(sg.getStartRes());
1280 jGroup.setEnd(sg.getEndRes());
1281 jGroup.setName(sg.getName());
1282 if (groupRefs.containsKey(sg))
1284 // group has references so set its ID field
1285 jGroup.setId(groupRefs.get(sg));
1287 ColourSchemeI colourScheme = sg.getColourScheme();
1288 if (colourScheme != null)
1290 ResidueShaderI groupColourScheme = sg.getGroupColourScheme();
1291 if (groupColourScheme.conservationApplied())
1293 jGroup.setConsThreshold(groupColourScheme.getConservationInc());
1295 if (colourScheme instanceof jalview.schemes.UserColourScheme)
1298 setUserColourScheme(colourScheme, userColours,
1303 jGroup.setColour(colourScheme.getSchemeName());
1306 else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
1308 jGroup.setColour("AnnotationColourGradient");
1309 jGroup.setAnnotationColours(constructAnnotationColours(
1310 (jalview.schemes.AnnotationColourGradient) colourScheme,
1311 userColours, object));
1313 else if (colourScheme instanceof jalview.schemes.UserColourScheme)
1316 setUserColourScheme(colourScheme, userColours, object));
1320 jGroup.setColour(colourScheme.getSchemeName());
1323 jGroup.setPidThreshold(groupColourScheme.getThreshold());
1326 jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
1327 jGroup.setDisplayBoxes(sg.getDisplayBoxes());
1328 jGroup.setDisplayText(sg.getDisplayText());
1329 jGroup.setColourText(sg.getColourText());
1330 jGroup.setTextCol1(sg.textColour.getRGB());
1331 jGroup.setTextCol2(sg.textColour2.getRGB());
1332 jGroup.setTextColThreshold(sg.thresholdTextColour);
1333 jGroup.setShowUnconserved(sg.getShowNonconserved());
1334 jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1335 jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
1336 jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
1337 jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1338 for (SequenceI seq : sg.getSequences())
1340 // jGroup.addSeq(seqHash(seq));
1341 jGroup.getSeq().add(seqHash(seq));
1345 //jms.setJGroup(groups);
1347 for (JGroup grp : groups)
1349 object.getJGroup().add(grp);
1354 // /////////SAVE VIEWPORT
1355 Viewport view = new Viewport();
1356 view.setTitle(ap.alignFrame.getTitle());
1357 view.setSequenceSetId(
1358 makeHashCode(av.getSequenceSetId(), av.getSequenceSetId()));
1359 view.setId(av.getViewId());
1360 if (av.getCodingComplement() != null)
1362 view.setComplementId(av.getCodingComplement().getViewId());
1364 view.setViewName(av.getViewName());
1365 view.setGatheredViews(av.isGatherViewsHere());
1367 Rectangle size = ap.av.getExplodedGeometry();
1368 Rectangle position = size;
1371 size = ap.alignFrame.getBounds();
1372 if (av.getCodingComplement() != null)
1374 position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
1382 view.setXpos(position.x);
1383 view.setYpos(position.y);
1385 view.setWidth(size.width);
1386 view.setHeight(size.height);
1388 view.setStartRes(vpRanges.getStartRes());
1389 view.setStartSeq(vpRanges.getStartSeq());
1391 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1393 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1394 userColours, object));
1397 .getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1399 AnnotationColourScheme ac = constructAnnotationColours(
1400 (jalview.schemes.AnnotationColourGradient) av
1401 .getGlobalColourScheme(),
1402 userColours, object);
1404 view.setAnnotationColours(ac);
1405 view.setBgColour("AnnotationColourGradient");
1409 view.setBgColour(ColourSchemeProperty
1410 .getColourName(av.getGlobalColourScheme()));
1413 ResidueShaderI vcs = av.getResidueShading();
1414 ColourSchemeI cs = av.getGlobalColourScheme();
1418 if (vcs.conservationApplied())
1420 view.setConsThreshold(vcs.getConservationInc());
1421 if (cs instanceof jalview.schemes.UserColourScheme)
1423 view.setBgColour(setUserColourScheme(cs, userColours, object));
1426 view.setPidThreshold(vcs.getThreshold());
1429 view.setConservationSelected(av.getConservationSelected());
1430 view.setPidSelected(av.getAbovePIDThreshold());
1431 final Font font = av.getFont();
1432 view.setFontName(font.getName());
1433 view.setFontSize(font.getSize());
1434 view.setFontStyle(font.getStyle());
1435 view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
1436 view.setRenderGaps(av.isRenderGaps());
1437 view.setShowAnnotation(av.isShowAnnotation());
1438 view.setShowBoxes(av.getShowBoxes());
1439 view.setShowColourText(av.getColourText());
1440 view.setShowFullId(av.getShowJVSuffix());
1441 view.setRightAlignIds(av.isRightAlignIds());
1442 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1443 view.setShowText(av.getShowText());
1444 view.setShowUnconserved(av.getShowUnconserved());
1445 view.setWrapAlignment(av.getWrapAlignment());
1446 view.setTextCol1(av.getTextColour().getRGB());
1447 view.setTextCol2(av.getTextColour2().getRGB());
1448 view.setTextColThreshold(av.getThresholdTextColour());
1449 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1450 view.setShowSequenceLogo(av.isShowSequenceLogo());
1451 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1452 view.setShowGroupConsensus(av.isShowGroupConsensus());
1453 view.setShowGroupConservation(av.isShowGroupConservation());
1454 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1455 view.setShowDbRefTooltip(av.isShowDBRefs());
1456 view.setFollowHighlight(av.isFollowHighlight());
1457 view.setFollowSelection(av.followSelection);
1458 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1459 if (av.getFeaturesDisplayed() != null)
1461 FeatureSettings fs = new FeatureSettings();
1463 FeatureRenderer fr = ap.getSeqPanel().seqCanvas
1464 .getFeatureRenderer();
1465 String[] renderOrder = fr.getRenderOrder().toArray(new String[0]);
1467 Vector<String> settingsAdded = new Vector<>();
1468 if (renderOrder != null)
1470 for (String featureType : renderOrder)
1472 FeatureSettings.Setting setting = new FeatureSettings.Setting();
1473 setting.setType(featureType);
1476 * save any filter for the feature type
1478 FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
1479 if (filter != null) {
1480 Iterator<FeatureMatcherI> filters = filter.getMatchers().iterator();
1481 FeatureMatcherI firstFilter = filters.next();
1482 setting.setMatcherSet(Jalview2XML.marshalFilter(
1483 firstFilter, filters, filter.isAnded()));
1487 * save colour scheme for the feature type
1489 FeatureColourI fcol = fr.getFeatureStyle(featureType);
1490 if (!fcol.isSimpleColour())
1492 setting.setColour(fcol.getMaxColour().getRGB());
1493 setting.setMincolour(fcol.getMinColour().getRGB());
1494 setting.setMin(fcol.getMin());
1495 setting.setMax(fcol.getMax());
1496 setting.setColourByLabel(fcol.isColourByLabel());
1497 if (fcol.isColourByAttribute())
1499 String[] attName = fcol.getAttributeName();
1500 setting.getAttributeName().add(attName[0]);
1501 if (attName.length > 1)
1503 setting.getAttributeName().add(attName[1]);
1506 setting.setAutoScale(fcol.isAutoScaled());
1507 setting.setThreshold(fcol.getThreshold());
1508 Color noColour = fcol.getNoColour();
1509 if (noColour == null)
1511 setting.setNoValueColour(NoValueColour.NONE);
1513 else if (noColour.equals(fcol.getMaxColour()))
1515 setting.setNoValueColour(NoValueColour.MAX);
1519 setting.setNoValueColour(NoValueColour.MIN);
1521 // -1 = No threshold, 0 = Below, 1 = Above
1522 setting.setThreshstate(fcol.isAboveThreshold() ? 1
1523 : (fcol.isBelowThreshold() ? 0 : -1));
1527 setting.setColour(fcol.getColour().getRGB());
1531 av.getFeaturesDisplayed().isVisible(featureType));
1533 .getOrder(featureType);
1536 setting.setOrder(rorder);
1538 /// fs.addSetting(setting);
1539 fs.getSetting().add(setting);
1540 settingsAdded.addElement(featureType);
1544 // is groups actually supposed to be a map here ?
1545 Iterator<String> en = fr.getFeatureGroups().iterator();
1546 Vector<String> groupsAdded = new Vector<>();
1547 while (en.hasNext())
1549 String grp = en.next();
1550 if (groupsAdded.contains(grp))
1554 Group g = new Group();
1556 g.setDisplay(((Boolean) fr.checkGroupVisibility(grp, false))
1559 fs.getGroup().add(g);
1560 groupsAdded.addElement(grp);
1562 // jms.setFeatureSettings(fs);
1563 object.setFeatureSettings(fs);
1566 if (av.hasHiddenColumns())
1568 jalview.datamodel.HiddenColumns hidden = av.getAlignment()
1569 .getHiddenColumns();
1572 warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1576 Iterator<int[]> hiddenRegions = hidden.iterator();
1577 while (hiddenRegions.hasNext())
1579 int[] region = hiddenRegions.next();
1580 HiddenColumns hc = new HiddenColumns();
1581 hc.setStart(region[0]);
1582 hc.setEnd(region[1]);
1583 // view.addHiddenColumns(hc);
1584 view.getHiddenColumns().add(hc);
1588 if (calcIdSet.size() > 0)
1590 for (String calcId : calcIdSet)
1592 if (calcId.trim().length() > 0)
1594 CalcIdParam cidp = createCalcIdParam(calcId, av);
1595 // Some calcIds have no parameters.
1598 // view.addCalcIdParam(cidp);
1599 view.getCalcIdParam().add(cidp);
1605 // jms.addViewport(view);
1606 object.getViewport().add(view);
1608 // object.setJalviewModelSequence(jms);
1609 // object.getVamsasModel().addSequenceSet(vamsasSet);
1610 object.getVamsasModel().getSequenceSet().add(vamsasSet);
1612 if (jout != null && fileName != null)
1614 // We may not want to write the object to disk,
1615 // eg we can copy the alignViewport to a new view object
1616 // using save and then load
1619 System.out.println("Writing jar entry " + fileName);
1620 JarEntry entry = new JarEntry(fileName);
1621 jout.putNextEntry(entry);
1622 PrintWriter pout = new PrintWriter(
1623 new OutputStreamWriter(jout, UTF_8));
1624 JAXBContext jaxbContext = JAXBContext
1625 .newInstance(JalviewModel.class);
1626 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
1628 // output pretty printed
1629 // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
1630 jaxbMarshaller.marshal(
1631 new ObjectFactory().createJalviewModel(object), pout);
1633 // jaxbMarshaller.marshal(object, pout);
1634 // marshaller.marshal(object);
1637 } catch (Exception ex)
1639 // TODO: raise error in GUI if marshalling failed.
1640 System.err.println("Error writing Jalview project");
1641 ex.printStackTrace();
1648 * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
1649 * for each viewer, with
1651 * <li>viewer geometry (position, size, split pane divider location)</li>
1652 * <li>index of the selected structure in the viewer (currently shows gapped
1654 * <li>the id of the annotation holding RNA secondary structure</li>
1655 * <li>(currently only one SS is shown per viewer, may be more in future)</li>
1657 * Varna viewer state is also written out (in native Varna XML) to separate
1658 * project jar entries. A separate entry is written for each RNA structure
1659 * displayed, with the naming convention
1661 * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
1669 * @param storeDataset
1671 protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
1672 final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
1673 boolean storeDataset)
1675 if (Desktop.desktop == null)
1679 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1680 for (int f = frames.length - 1; f > -1; f--)
1682 if (frames[f] instanceof AppVarna)
1684 AppVarna varna = (AppVarna) frames[f];
1686 * link the sequence to every viewer that is showing it and is linked to
1687 * its alignment panel
1689 if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
1691 String viewId = varna.getViewId();
1692 RnaViewer rna = new RnaViewer();
1693 rna.setViewId(viewId);
1694 rna.setTitle(varna.getTitle());
1695 rna.setXpos(varna.getX());
1696 rna.setYpos(varna.getY());
1697 rna.setWidth(varna.getWidth());
1698 rna.setHeight(varna.getHeight());
1699 rna.setDividerLocation(varna.getDividerLocation());
1700 rna.setSelectedRna(varna.getSelectedIndex());
1701 // jseq.addRnaViewer(rna);
1702 jseq.getRnaViewer().add(rna);
1705 * Store each Varna panel's state once in the project per sequence.
1706 * First time through only (storeDataset==false)
1708 // boolean storeSessions = false;
1709 // String sequenceViewId = viewId + seqsToIds.get(jds);
1710 // if (!storeDataset && !viewIds.contains(sequenceViewId))
1712 // viewIds.add(sequenceViewId);
1713 // storeSessions = true;
1715 for (RnaModel model : varna.getModels())
1717 if (model.seq == jds)
1720 * VARNA saves each view (sequence or alignment secondary
1721 * structure, gapped or trimmed) as a separate XML file
1723 String jarEntryName = rnaSessions.get(model);
1724 if (jarEntryName == null)
1727 String varnaStateFile = varna.getStateInfo(model.rna);
1728 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
1729 copyFileToJar(jout, varnaStateFile, jarEntryName);
1730 rnaSessions.put(model, jarEntryName);
1732 SecondaryStructure ss = new SecondaryStructure();
1733 String annotationId = varna.getAnnotation(jds).annotationId;
1734 ss.setAnnotationId(annotationId);
1735 ss.setViewerState(jarEntryName);
1736 ss.setGapped(model.gapped);
1737 ss.setTitle(model.title);
1738 // rna.addSecondaryStructure(ss);
1739 rna.getSecondaryStructure().add(ss);
1748 * Copy the contents of a file to a new entry added to the output jar
1752 * @param jarEntryName
1754 protected void copyFileToJar(JarOutputStream jout, String infilePath,
1755 String jarEntryName)
1757 DataInputStream dis = null;
1760 File file = new File(infilePath);
1761 if (file.exists() && jout != null)
1763 dis = new DataInputStream(new FileInputStream(file));
1764 byte[] data = new byte[(int) file.length()];
1765 dis.readFully(data);
1766 writeJarEntry(jout, jarEntryName, data);
1768 } catch (Exception ex)
1770 ex.printStackTrace();
1778 } catch (IOException e)
1787 * Write the data to a new entry of given name in the output jar file
1790 * @param jarEntryName
1792 * @throws IOException
1794 protected void writeJarEntry(JarOutputStream jout, String jarEntryName,
1795 byte[] data) throws IOException
1799 System.out.println("Writing jar entry " + jarEntryName);
1800 jout.putNextEntry(new JarEntry(jarEntryName));
1801 DataOutputStream dout = new DataOutputStream(jout);
1802 dout.write(data, 0, data.length);
1809 * Save the state of a structure viewer
1814 * the archive XML element under which to save the state
1817 * @param matchedFile
1821 protected String saveStructureState(AlignmentPanel ap, SequenceI jds,
1822 Pdbids pdb, PDBEntry entry, List<String> viewIds,
1823 String matchedFile, StructureViewerBase viewFrame)
1825 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
1828 * Look for any bindings for this viewer to the PDB file of interest
1829 * (including part matches excluding chain id)
1831 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
1833 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
1834 final String pdbId = pdbentry.getId();
1835 if (!pdbId.equals(entry.getId())
1836 && !(entry.getId().length() > 4 && entry.getId().toLowerCase()
1837 .startsWith(pdbId.toLowerCase())))
1840 * not interested in a binding to a different PDB entry here
1844 if (matchedFile == null)
1846 matchedFile = pdbentry.getFile();
1848 else if (!matchedFile.equals(pdbentry.getFile()))
1851 "Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
1852 + pdbentry.getFile());
1856 // can get at it if the ID
1857 // match is ambiguous (e.g.
1860 for (int smap = 0; smap < viewFrame.getBinding()
1861 .getSequence()[peid].length; smap++)
1863 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
1864 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
1866 StructureState state = new StructureState();
1867 state.setVisible(true);
1868 state.setXpos(viewFrame.getX());
1869 state.setYpos(viewFrame.getY());
1870 state.setWidth(viewFrame.getWidth());
1871 state.setHeight(viewFrame.getHeight());
1872 final String viewId = viewFrame.getViewId();
1873 state.setViewId(viewId);
1874 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
1875 state.setColourwithAlignPanel(viewFrame.isUsedforcolourby(ap));
1876 state.setColourByJmol(viewFrame.isColouredByViewer());
1877 state.setType(viewFrame.getViewerType().toString());
1878 // pdb.addStructureState(state);
1879 pdb.getStructureState().add(state);
1887 * Populates the AnnotationColourScheme xml for save. This captures the
1888 * settings of the options in the 'Colour by Annotation' dialog.
1891 * @param userColours
1895 private AnnotationColourScheme constructAnnotationColours(
1896 AnnotationColourGradient acg, List<UserColourScheme> userColours,
1899 AnnotationColourScheme ac = new AnnotationColourScheme();
1900 ac.setAboveThreshold(acg.getAboveThreshold());
1901 ac.setThreshold(acg.getAnnotationThreshold());
1902 // 2.10.2 save annotationId (unique) not annotation label
1903 ac.setAnnotation(acg.getAnnotation().annotationId);
1904 if (acg.getBaseColour() instanceof UserColourScheme)
1907 setUserColourScheme(acg.getBaseColour(), userColours, jm));
1912 ColourSchemeProperty.getColourName(acg.getBaseColour()));
1915 ac.setMaxColour(acg.getMaxColour().getRGB());
1916 ac.setMinColour(acg.getMinColour().getRGB());
1917 ac.setPerSequence(acg.isSeqAssociated());
1918 ac.setPredefinedColours(acg.isPredefinedColours());
1922 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
1923 IdentityHashMap<SequenceGroup, String> groupRefs,
1924 AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
1925 SequenceSet vamsasSet)
1928 for (int i = 0; i < aa.length; i++)
1930 Annotation an = new Annotation();
1932 AlignmentAnnotation annotation = aa[i];
1933 if (annotation.annotationId != null)
1935 annotationIds.put(annotation.annotationId, annotation);
1938 an.setId(annotation.annotationId);
1940 an.setVisible(annotation.visible);
1942 an.setDescription(annotation.description);
1944 if (annotation.sequenceRef != null)
1946 // 2.9 JAL-1781 xref on sequence id rather than name
1947 an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
1949 if (annotation.groupRef != null)
1951 String groupIdr = groupRefs.get(annotation.groupRef);
1952 if (groupIdr == null)
1954 // make a locally unique String
1955 groupRefs.put(annotation.groupRef,
1956 groupIdr = ("" + System.currentTimeMillis()
1957 + annotation.groupRef.getName()
1958 + groupRefs.size()));
1960 an.setGroupRef(groupIdr.toString());
1963 // store all visualization attributes for annotation
1964 an.setGraphHeight(annotation.graphHeight);
1965 an.setCentreColLabels(annotation.centreColLabels);
1966 an.setScaleColLabels(annotation.scaleColLabel);
1967 an.setShowAllColLabels(annotation.showAllColLabels);
1968 an.setBelowAlignment(annotation.belowAlignment);
1970 if (annotation.graph > 0)
1973 an.setGraphType(annotation.graph);
1974 an.setGraphGroup(annotation.graphGroup);
1975 if (annotation.getThreshold() != null)
1977 ThresholdLine line = new ThresholdLine();
1978 line.setLabel(annotation.getThreshold().label);
1979 line.setValue(annotation.getThreshold().value);
1980 line.setColour(annotation.getThreshold().colour.getRGB());
1981 an.setThresholdLine(line);
1989 an.setLabel(annotation.label);
1991 if (annotation == av.getAlignmentQualityAnnot()
1992 || annotation == av.getAlignmentConservationAnnotation()
1993 || annotation == av.getAlignmentConsensusAnnotation()
1994 || annotation.autoCalculated)
1996 // new way of indicating autocalculated annotation -
1997 an.setAutoCalculated(annotation.autoCalculated);
1999 if (annotation.hasScore())
2001 an.setScore(annotation.getScore());
2004 if (annotation.getCalcId() != null)
2006 calcIdSet.add(annotation.getCalcId());
2007 an.setCalcId(annotation.getCalcId());
2009 if (annotation.hasProperties())
2011 for (String pr : annotation.getProperties())
2013 jalview.xml.binding.jalview.Annotation.Property prop = new jalview.xml.binding.jalview.Annotation.Property();
2015 prop.setValue(annotation.getProperty(pr));
2016 // an.addProperty(prop);
2017 an.getProperty().add(prop);
2021 AnnotationElement ae;
2022 if (annotation.annotations != null)
2024 an.setScoreOnly(false);
2025 for (int a = 0; a < annotation.annotations.length; a++)
2027 if ((annotation == null) || (annotation.annotations[a] == null))
2032 ae = new AnnotationElement();
2033 if (annotation.annotations[a].description != null)
2035 ae.setDescription(annotation.annotations[a].description);
2037 if (annotation.annotations[a].displayCharacter != null)
2039 ae.setDisplayCharacter(
2040 annotation.annotations[a].displayCharacter);
2043 if (!Float.isNaN(annotation.annotations[a].value))
2045 ae.setValue(annotation.annotations[a].value);
2049 if (annotation.annotations[a].secondaryStructure > ' ')
2051 ae.setSecondaryStructure(
2052 annotation.annotations[a].secondaryStructure + "");
2055 if (annotation.annotations[a].colour != null
2056 && annotation.annotations[a].colour != java.awt.Color.black)
2058 ae.setColour(annotation.annotations[a].colour.getRGB());
2061 // an.addAnnotationElement(ae);
2062 an.getAnnotationElement().add(ae);
2063 if (annotation.autoCalculated)
2065 // only write one non-null entry into the annotation row -
2066 // sufficient to get the visualization attributes necessary to
2074 an.setScoreOnly(true);
2076 if (!storeDS || (storeDS && !annotation.autoCalculated))
2078 // skip autocalculated annotation - these are only provided for
2080 // vamsasSet.addAnnotation(an);
2081 vamsasSet.getAnnotation().add(an);
2087 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
2089 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
2090 if (settings != null)
2092 CalcIdParam vCalcIdParam = new CalcIdParam();
2093 vCalcIdParam.setCalcId(calcId);
2094 // vCalcIdParam.addServiceURL(settings.getServiceURI());
2095 vCalcIdParam.getServiceURL().add(settings.getServiceURI());
2096 // generic URI allowing a third party to resolve another instance of the
2097 // service used for this calculation
2098 for (String url : settings.getServiceURLs())
2100 // vCalcIdParam.addServiceURL(urls);
2101 vCalcIdParam.getServiceURL().add(url);
2103 vCalcIdParam.setVersion("1.0");
2104 if (settings.getPreset() != null)
2106 WsParamSetI setting = settings.getPreset();
2107 vCalcIdParam.setName(setting.getName());
2108 vCalcIdParam.setDescription(setting.getDescription());
2112 vCalcIdParam.setName("");
2113 vCalcIdParam.setDescription("Last used parameters");
2115 // need to be able to recover 1) settings 2) user-defined presets or
2116 // recreate settings from preset 3) predefined settings provided by
2117 // service - or settings that can be transferred (or discarded)
2118 vCalcIdParam.setParameters(
2119 settings.getWsParamFile().replace("\n", "|\\n|"));
2120 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
2121 // todo - decide if updateImmediately is needed for any projects.
2123 return vCalcIdParam;
2128 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
2131 if (calcIdParam.getVersion().equals("1.0"))
2133 final String[] calcIds = calcIdParam.getServiceURL().toArray(new String[0]);
2134 Jws2Instance service = Jws2Discoverer.getDiscoverer()
2135 .getPreferredServiceFor(calcIds);
2136 if (service != null)
2138 WsParamSetI parmSet = null;
2141 parmSet = service.getParamStore().parseServiceParameterFile(
2142 calcIdParam.getName(), calcIdParam.getDescription(),
2144 calcIdParam.getParameters().replace("|\\n|", "\n"));
2145 } catch (IOException x)
2147 warn("Couldn't parse parameter data for "
2148 + calcIdParam.getCalcId(), x);
2151 List<ArgumentI> argList = null;
2152 if (calcIdParam.getName().length() > 0)
2154 parmSet = service.getParamStore()
2155 .getPreset(calcIdParam.getName());
2156 if (parmSet != null)
2158 // TODO : check we have a good match with settings in AACon -
2159 // otherwise we'll need to create a new preset
2164 argList = parmSet.getArguments();
2167 AAConSettings settings = new AAConSettings(
2168 calcIdParam.isAutoUpdate(), service, parmSet, argList);
2169 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
2170 calcIdParam.isNeedsUpdate());
2175 warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
2179 throw new Error(MessageManager.formatMessage(
2180 "error.unsupported_version_calcIdparam", new Object[]
2181 { calcIdParam.toString() }));
2185 * External mapping between jalview objects and objects yielding a valid and
2186 * unique object ID string. This is null for normal Jalview project IO, but
2187 * non-null when a jalview project is being read or written as part of a
2190 IdentityHashMap jv2vobj = null;
2193 * Construct a unique ID for jvobj using either existing bindings or if none
2194 * exist, the result of the hashcode call for the object.
2197 * jalview data object
2198 * @return unique ID for referring to jvobj
2200 private String makeHashCode(Object jvobj, String altCode)
2202 if (jv2vobj != null)
2204 Object id = jv2vobj.get(jvobj);
2207 return id.toString();
2209 // check string ID mappings
2210 if (jvids2vobj != null && jvobj instanceof String)
2212 id = jvids2vobj.get(jvobj);
2216 return id.toString();
2218 // give up and warn that something has gone wrong
2219 warn("Cannot find ID for object in external mapping : " + jvobj);
2225 * return local jalview object mapped to ID, if it exists
2229 * @return null or object bound to idcode
2231 private Object retrieveExistingObj(String idcode)
2233 if (idcode != null && vobj2jv != null)
2235 return vobj2jv.get(idcode);
2241 * binding from ID strings from external mapping table to jalview data model
2244 private Hashtable vobj2jv;
2246 private Sequence createVamsasSequence(String id, SequenceI jds)
2248 return createVamsasSequence(true, id, jds, null);
2251 private Sequence createVamsasSequence(boolean recurse, String id,
2252 SequenceI jds, SequenceI parentseq)
2254 Sequence vamsasSeq = new Sequence();
2255 vamsasSeq.setId(id);
2256 vamsasSeq.setName(jds.getName());
2257 vamsasSeq.setSequence(jds.getSequenceAsString());
2258 vamsasSeq.setDescription(jds.getDescription());
2259 jalview.datamodel.DBRefEntry[] dbrefs = null;
2260 if (jds.getDatasetSequence() != null)
2262 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
2266 // seqId==dsseqid so we can tell which sequences really are
2267 // dataset sequences only
2268 vamsasSeq.setDsseqid(id);
2269 dbrefs = jds.getDBRefs();
2270 if (parentseq == null)
2277 for (int d = 0; d < dbrefs.length; d++)
2279 DBRef dbref = new DBRef();
2280 dbref.setSource(dbrefs[d].getSource());
2281 dbref.setVersion(dbrefs[d].getVersion());
2282 dbref.setAccessionId(dbrefs[d].getAccessionId());
2283 if (dbrefs[d].hasMap())
2285 Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
2287 dbref.setMapping(mp);
2289 // vamsasSeq.addDBRef(dbref);
2290 vamsasSeq.getDBRef().add(dbref);
2296 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
2297 SequenceI parentseq, SequenceI jds, boolean recurse)
2300 if (jmp.getMap() != null)
2304 jalview.util.MapList mlst = jmp.getMap();
2305 List<int[]> r = mlst.getFromRanges();
2306 for (int[] range : r)
2308 MapListFrom mfrom = new MapListFrom();
2309 mfrom.setStart(range[0]);
2310 mfrom.setEnd(range[1]);
2311 // mp.addMapListFrom(mfrom);
2312 mp.getMapListFrom().add(mfrom);
2314 r = mlst.getToRanges();
2315 for (int[] range : r)
2317 MapListTo mto = new MapListTo();
2318 mto.setStart(range[0]);
2319 mto.setEnd(range[1]);
2320 // mp.addMapListTo(mto);
2321 mp.getMapListTo().add(mto);
2323 mp.setMapFromUnit(BigInteger.valueOf(mlst.getFromRatio()));
2324 mp.setMapToUnit(BigInteger.valueOf(mlst.getToRatio()));
2325 if (jmp.getTo() != null)
2327 // MappingChoice mpc = new MappingChoice();
2329 // check/create ID for the sequence referenced by getTo()
2332 SequenceI ps = null;
2333 if (parentseq != jmp.getTo()
2334 && parentseq.getDatasetSequence() != jmp.getTo())
2336 // chaining dbref rather than a handshaking one
2337 jmpid = seqHash(ps = jmp.getTo());
2341 jmpid = seqHash(ps = parentseq);
2343 // mpc.setDseqFor(jmpid);
2344 mp.setDseqFor(jmpid);
2345 if (!seqRefIds.containsKey(jmpid))
2347 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
2348 seqRefIds.put(jmpid, ps);
2352 jalview.bin.Cache.log.debug("reusing DseqFor ID");
2355 // mp.setMappingChoice(mpc);
2361 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
2362 List<UserColourScheme> userColours, JalviewModel jm)
2365 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
2366 boolean newucs = false;
2367 if (!userColours.contains(ucs))
2369 userColours.add(ucs);
2372 id = "ucs" + userColours.indexOf(ucs);
2375 // actually create the scheme's entry in the XML model
2376 java.awt.Color[] colours = ucs.getColours();
2377 UserColours uc = new UserColours();
2378 // UserColourScheme jbucs = new UserColourScheme();
2379 JalviewUserColours jbucs = new JalviewUserColours();
2381 for (int i = 0; i < colours.length; i++)
2383 Colour col = new Colour();
2384 col.setName(ResidueProperties.aa[i]);
2385 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2386 // jbucs.addColour(col);
2387 jbucs.getColour().add(col);
2389 if (ucs.getLowerCaseColours() != null)
2391 colours = ucs.getLowerCaseColours();
2392 for (int i = 0; i < colours.length; i++)
2394 Colour col = new Colour();
2395 col.setName(ResidueProperties.aa[i].toLowerCase());
2396 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2397 // jbucs.addColour(col);
2398 jbucs.getColour().add(col);
2403 uc.setUserColourScheme(jbucs);
2404 // jm.addUserColours(uc);
2405 jm.getUserColours().add(uc);
2411 jalview.schemes.UserColourScheme getUserColourScheme(
2412 JalviewModel jm, String id)
2414 List<UserColours> uc = jm.getUserColours();
2415 UserColours colours = null;
2417 for (int i = 0; i < uc.length; i++)
2419 if (uc[i].getId().equals(id))
2426 for (UserColours c : uc)
2428 if (c.getId().equals(id))
2435 java.awt.Color[] newColours = new java.awt.Color[24];
2437 for (int i = 0; i < 24; i++)
2439 newColours[i] = new java.awt.Color(Integer.parseInt(
2440 // colours.getUserColourScheme().getColour(i).getRGB(), 16));
2441 colours.getUserColourScheme().getColour().get(i).getRGB(),
2445 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
2448 if (colours.getUserColourScheme().getColour().size()/*Count()*/ > 24)
2450 newColours = new java.awt.Color[23];
2451 for (int i = 0; i < 23; i++)
2453 newColours[i] = new java.awt.Color(Integer.parseInt(
2454 colours.getUserColourScheme().getColour().get(i + 24)
2458 ucs.setLowerCaseColours(newColours);
2465 * contains last error message (if any) encountered by XML loader.
2467 String errorMessage = null;
2470 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
2471 * exceptions are raised during project XML parsing
2473 public boolean attemptversion1parse = false;
2476 * Load a jalview project archive from a jar file
2479 * - HTTP URL or filename
2481 public AlignFrame loadJalviewAlign(final String file)
2484 jalview.gui.AlignFrame af = null;
2488 // create list to store references for any new Jmol viewers created
2489 newStructureViewers = new Vector<>();
2490 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
2491 // Workaround is to make sure caller implements the JarInputStreamProvider
2493 // so we can re-open the jar input stream for each entry.
2495 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
2496 af = loadJalviewAlign(jprovider);
2499 af.setMenusForViewport();
2501 } catch (MalformedURLException e)
2503 errorMessage = "Invalid URL format for '" + file + "'";
2509 SwingUtilities.invokeAndWait(new Runnable()
2514 setLoadingFinishedForNewStructureViewers();
2517 } catch (Exception x)
2519 System.err.println("Error loading alignment: " + x.getMessage());
2525 private jarInputStreamProvider createjarInputStreamProvider(
2526 final String file) throws MalformedURLException
2529 errorMessage = null;
2530 uniqueSetSuffix = null;
2532 viewportsAdded.clear();
2533 frefedSequence = null;
2535 if (file.startsWith("http://"))
2537 url = new URL(file);
2539 final URL _url = url;
2540 return new jarInputStreamProvider()
2544 public JarInputStream getJarInputStream() throws IOException
2548 return new JarInputStream(_url.openStream());
2552 return new JarInputStream(new FileInputStream(file));
2557 public String getFilename()
2565 * Recover jalview session from a jalview project archive. Caller may
2566 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
2567 * themselves. Any null fields will be initialised with default values,
2568 * non-null fields are left alone.
2573 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
2575 errorMessage = null;
2576 if (uniqueSetSuffix == null)
2578 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
2580 if (seqRefIds == null)
2584 AlignFrame af = null, _af = null;
2585 IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
2586 Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
2587 final String file = jprovider.getFilename();
2590 JarInputStream jin = null;
2591 JarEntry jarentry = null;
2596 jin = jprovider.getJarInputStream();
2597 for (int i = 0; i < entryCount; i++)
2599 jarentry = jin.getNextJarEntry();
2602 if (jarentry != null && jarentry.getName().endsWith(".xml"))
2604 InputStreamReader in = new InputStreamReader(jin, UTF_8);
2605 // JalviewModel object = new JalviewModel();
2607 JAXBContext jc = JAXBContext
2608 .newInstance("jalview.xml.binding.jalview");
2609 XMLStreamReader streamReader = XMLInputFactory.newInstance()
2610 .createXMLStreamReader(jin);
2611 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
2612 JAXBElement<JalviewModel> jbe = um
2613 .unmarshal(streamReader, JalviewModel.class);
2614 JalviewModel object = jbe.getValue();
2617 Unmarshaller unmar = new Unmarshaller(object);
2618 unmar.setValidation(false);
2619 object = (JalviewModel) unmar.unmarshal(in);
2621 if (true) // !skipViewport(object))
2623 _af = loadFromObject(object, file, true, jprovider);
2624 if (_af != null && object.getViewport().size() > 0)
2625 // getJalviewModelSequence().getViewportCount() > 0)
2629 // store a reference to the first view
2632 if (_af.getViewport().isGatherViewsHere())
2634 // if this is a gathered view, keep its reference since
2635 // after gathering views, only this frame will remain
2637 gatherToThisFrame.put(_af.getViewport().getSequenceSetId(),
2640 // Save dataset to register mappings once all resolved
2641 importedDatasets.put(
2642 af.getViewport().getAlignment().getDataset(),
2643 af.getViewport().getAlignment().getDataset());
2648 else if (jarentry != null)
2650 // Some other file here.
2653 } while (jarentry != null);
2654 resolveFrefedSequences();
2655 } catch (IOException ex)
2657 ex.printStackTrace();
2658 errorMessage = "Couldn't locate Jalview XML file : " + file;
2660 "Exception whilst loading jalview XML file : " + ex + "\n");
2661 } catch (Exception ex)
2663 System.err.println("Parsing as Jalview Version 2 file failed.");
2664 ex.printStackTrace(System.err);
2665 if (attemptversion1parse)
2667 // Is Version 1 Jar file?
2670 af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
2671 } catch (Exception ex2)
2673 System.err.println("Exception whilst loading as jalviewXMLV1:");
2674 ex2.printStackTrace();
2678 if (Desktop.instance != null)
2680 Desktop.instance.stopLoading();
2684 System.out.println("Successfully loaded archive file");
2687 ex.printStackTrace();
2690 "Exception whilst loading jalview XML file : " + ex + "\n");
2691 } catch (OutOfMemoryError e)
2693 // Don't use the OOM Window here
2694 errorMessage = "Out of memory loading jalview XML file";
2695 System.err.println("Out of memory whilst loading jalview XML file");
2696 e.printStackTrace();
2700 * Regather multiple views (with the same sequence set id) to the frame (if
2701 * any) that is flagged as the one to gather to, i.e. convert them to tabbed
2702 * views instead of separate frames. Note this doesn't restore a state where
2703 * some expanded views in turn have tabbed views - the last "first tab" read
2704 * in will play the role of gatherer for all.
2706 for (AlignFrame fr : gatherToThisFrame.values())
2708 Desktop.instance.gatherViews(fr);
2711 restoreSplitFrames();
2712 for (AlignmentI ds : importedDatasets.keySet())
2714 if (ds.getCodonFrames() != null)
2716 StructureSelectionManager
2717 .getStructureSelectionManager(Desktop.instance)
2718 .registerMappings(ds.getCodonFrames());
2721 if (errorMessage != null)
2726 if (Desktop.instance != null)
2728 Desktop.instance.stopLoading();
2735 * Try to reconstruct and display SplitFrame windows, where each contains
2736 * complementary dna and protein alignments. Done by pairing up AlignFrame
2737 * objects (created earlier) which have complementary viewport ids associated.
2739 protected void restoreSplitFrames()
2741 List<SplitFrame> gatherTo = new ArrayList<>();
2742 List<AlignFrame> addedToSplitFrames = new ArrayList<>();
2743 Map<String, AlignFrame> dna = new HashMap<>();
2746 * Identify the DNA alignments
2748 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2751 AlignFrame af = candidate.getValue();
2752 if (af.getViewport().getAlignment().isNucleotide())
2754 dna.put(candidate.getKey().getId(), af);
2759 * Try to match up the protein complements
2761 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2764 AlignFrame af = candidate.getValue();
2765 if (!af.getViewport().getAlignment().isNucleotide())
2767 String complementId = candidate.getKey().getComplementId();
2768 // only non-null complements should be in the Map
2769 if (complementId != null && dna.containsKey(complementId))
2771 final AlignFrame dnaFrame = dna.get(complementId);
2772 SplitFrame sf = createSplitFrame(dnaFrame, af);
2773 addedToSplitFrames.add(dnaFrame);
2774 addedToSplitFrames.add(af);
2775 dnaFrame.setMenusForViewport();
2776 af.setMenusForViewport();
2777 if (af.getViewport().isGatherViewsHere())
2786 * Open any that we failed to pair up (which shouldn't happen!) as
2787 * standalone AlignFrame's.
2789 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2792 AlignFrame af = candidate.getValue();
2793 if (!addedToSplitFrames.contains(af))
2795 Viewport view = candidate.getKey();
2796 Desktop.addInternalFrame(af, view.getTitle(),
2797 safeInt(view.getWidth()), safeInt(view.getHeight()));
2798 af.setMenusForViewport();
2799 System.err.println("Failed to restore view " + view.getTitle()
2800 + " to split frame");
2805 * Gather back into tabbed views as flagged.
2807 for (SplitFrame sf : gatherTo)
2809 Desktop.instance.gatherViews(sf);
2812 splitFrameCandidates.clear();
2816 * Construct and display one SplitFrame holding DNA and protein alignments.
2819 * @param proteinFrame
2822 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
2823 AlignFrame proteinFrame)
2825 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
2826 String title = MessageManager.getString("label.linked_view_title");
2827 int width = (int) dnaFrame.getBounds().getWidth();
2828 int height = (int) (dnaFrame.getBounds().getHeight()
2829 + proteinFrame.getBounds().getHeight() + 50);
2832 * SplitFrame location is saved to both enclosed frames
2834 splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
2835 Desktop.addInternalFrame(splitFrame, title, width, height);
2838 * And compute cDNA consensus (couldn't do earlier with consensus as
2839 * mappings were not yet present)
2841 proteinFrame.getViewport().alignmentChanged(proteinFrame.alignPanel);
2847 * check errorMessage for a valid error message and raise an error box in the
2848 * GUI or write the current errorMessage to stderr and then clear the error
2851 protected void reportErrors()
2853 reportErrors(false);
2856 protected void reportErrors(final boolean saving)
2858 if (errorMessage != null)
2860 final String finalErrorMessage = errorMessage;
2863 javax.swing.SwingUtilities.invokeLater(new Runnable()
2868 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2870 "Error " + (saving ? "saving" : "loading")
2872 JvOptionPane.WARNING_MESSAGE);
2878 System.err.println("Problem loading Jalview file: " + errorMessage);
2881 errorMessage = null;
2884 Map<String, String> alreadyLoadedPDB = new HashMap<>();
2887 * when set, local views will be updated from view stored in JalviewXML
2888 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
2889 * sync if this is set to true.
2891 private final boolean updateLocalViews = false;
2894 * Returns the path to a temporary file holding the PDB file for the given PDB
2895 * id. The first time of asking, searches for a file of that name in the
2896 * Jalview project jar, and copies it to a new temporary file. Any repeat
2897 * requests just return the path to the file previously created.
2903 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
2906 if (alreadyLoadedPDB.containsKey(pdbId))
2908 return alreadyLoadedPDB.get(pdbId).toString();
2911 String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
2913 if (tempFile != null)
2915 alreadyLoadedPDB.put(pdbId, tempFile);
2921 * Copies the jar entry of given name to a new temporary file and returns the
2922 * path to the file, or null if the entry is not found.
2925 * @param jarEntryName
2927 * a prefix for the temporary file name, must be at least three
2930 * null or original file - so new file can be given the same suffix
2934 protected String copyJarEntry(jarInputStreamProvider jprovider,
2935 String jarEntryName, String prefix, String origFile)
2937 BufferedReader in = null;
2938 PrintWriter out = null;
2939 String suffix = ".tmp";
2940 if (origFile == null)
2942 origFile = jarEntryName;
2944 int sfpos = origFile.lastIndexOf(".");
2945 if (sfpos > -1 && sfpos < (origFile.length() - 3))
2947 suffix = "." + origFile.substring(sfpos + 1);
2951 JarInputStream jin = jprovider.getJarInputStream();
2953 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
2954 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
2955 * FileInputStream(jprovider)); }
2958 JarEntry entry = null;
2961 entry = jin.getNextJarEntry();
2962 } while (entry != null && !entry.getName().equals(jarEntryName));
2965 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
2966 File outFile = File.createTempFile(prefix, suffix);
2967 outFile.deleteOnExit();
2968 out = new PrintWriter(new FileOutputStream(outFile));
2971 while ((data = in.readLine()) != null)
2976 String t = outFile.getAbsolutePath();
2981 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
2983 } catch (Exception ex)
2985 ex.printStackTrace();
2993 } catch (IOException e)
3007 private class JvAnnotRow
3009 public JvAnnotRow(int i, AlignmentAnnotation jaa)
3016 * persisted version of annotation row from which to take vis properties
3018 public jalview.datamodel.AlignmentAnnotation template;
3021 * original position of the annotation row in the alignment
3027 * Load alignment frame from jalview XML DOM object
3029 * @param jalviewModel
3032 * filename source string
3033 * @param loadTreesAndStructures
3034 * when false only create Viewport
3036 * data source provider
3037 * @return alignment frame created from view stored in DOM
3039 AlignFrame loadFromObject(JalviewModel jalviewModel, String file,
3040 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
3042 SequenceSet vamsasSet = jalviewModel.getVamsasModel().getSequenceSet().get(0);
3043 List<Sequence> vamsasSeqs = vamsasSet.getSequence();
3045 // JalviewModelSequence jms = object.getJalviewModelSequence();
3047 // Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
3049 Viewport view = (jalviewModel.getViewport().size() > 0)
3050 ? jalviewModel.getViewport().get(0)
3053 // ////////////////////////////////
3056 List<SequenceI> hiddenSeqs = null;
3058 List<SequenceI> tmpseqs = new ArrayList<>();
3060 boolean multipleView = false;
3061 SequenceI referenceseqForView = null;
3062 // JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
3063 List<JSeq> jseqs = jalviewModel.getJSeq();
3064 int vi = 0; // counter in vamsasSeq array
3065 for (int i = 0; i < jseqs.size(); i++)
3067 JSeq jseq = jseqs.get(i);
3068 String seqId = jseq.getId();
3070 SequenceI tmpSeq = seqRefIds.get(seqId);
3073 if (!incompleteSeqs.containsKey(seqId))
3075 // may not need this check, but keep it for at least 2.9,1 release
3076 if (tmpSeq.getStart() != jseq.getStart()
3077 || tmpSeq.getEnd() != jseq.getEnd())
3080 "Warning JAL-2154 regression: updating start/end for sequence "
3081 + tmpSeq.toString() + " to " + jseq);
3086 incompleteSeqs.remove(seqId);
3088 if (vamsasSeqs.size() > vi
3089 && vamsasSeqs.get(vi).getId().equals(seqId))
3091 // most likely we are reading a dataset XML document so
3092 // update from vamsasSeq section of XML for this sequence
3093 tmpSeq.setName(vamsasSeqs.get(vi).getName());
3094 tmpSeq.setDescription(vamsasSeqs.get(vi).getDescription());
3095 tmpSeq.setSequence(vamsasSeqs.get(vi).getSequence());
3100 // reading multiple views, so vamsasSeq set is a subset of JSeq
3101 multipleView = true;
3103 tmpSeq.setStart(jseq.getStart());
3104 tmpSeq.setEnd(jseq.getEnd());
3105 tmpseqs.add(tmpSeq);
3109 Sequence vamsasSeq = vamsasSeqs.get(vi);
3110 tmpSeq = new jalview.datamodel.Sequence(vamsasSeq.getName(),
3111 vamsasSeq.getSequence());
3112 tmpSeq.setDescription(vamsasSeq.getDescription());
3113 tmpSeq.setStart(jseq.getStart());
3114 tmpSeq.setEnd(jseq.getEnd());
3115 tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
3116 seqRefIds.put(vamsasSeq.getId(), tmpSeq);
3117 tmpseqs.add(tmpSeq);
3121 if (safeBoolean(jseq.isViewreference()))
3123 referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
3126 if (jseq.isHidden() != null && jseq.isHidden().booleanValue())
3128 if (hiddenSeqs == null)
3130 hiddenSeqs = new ArrayList<>();
3133 hiddenSeqs.add(tmpSeq);
3138 // Create the alignment object from the sequence set
3139 // ///////////////////////////////
3140 SequenceI[] orderedSeqs = tmpseqs
3141 .toArray(new SequenceI[tmpseqs.size()]);
3143 AlignmentI al = null;
3144 // so we must create or recover the dataset alignment before going further
3145 // ///////////////////////////////
3146 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
3148 // older jalview projects do not have a dataset - so creat alignment and
3150 al = new Alignment(orderedSeqs);
3151 al.setDataset(null);
3155 boolean isdsal = jalviewModel.getViewport().isEmpty();
3158 // we are importing a dataset record, so
3159 // recover reference to an alignment already materialsed as dataset
3160 al = getDatasetFor(vamsasSet.getDatasetId());
3164 // materialse the alignment
3165 al = new Alignment(orderedSeqs);
3169 addDatasetRef(vamsasSet.getDatasetId(), al);
3172 // finally, verify all data in vamsasSet is actually present in al
3173 // passing on flag indicating if it is actually a stored dataset
3174 recoverDatasetFor(vamsasSet, al, isdsal);
3177 if (referenceseqForView != null)
3179 al.setSeqrep(referenceseqForView);
3181 // / Add the alignment properties
3182 for (int i = 0; i < vamsasSet.getSequenceSetProperties().size(); i++)
3184 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties()
3186 al.setProperty(ssp.getKey(), ssp.getValue());
3189 // ///////////////////////////////
3191 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
3194 // load sequence features, database references and any associated PDB
3195 // structures for the alignment
3197 // prior to 2.10, this part would only be executed the first time a
3198 // sequence was encountered, but not afterwards.
3199 // now, for 2.10 projects, this is also done if the xml doc includes
3200 // dataset sequences not actually present in any particular view.
3202 for (int i = 0; i < vamsasSeqs.size(); i++)
3204 JSeq jseq = jseqs.get(i);
3205 if (jseq.getFeatures().size() > 0)
3207 List<Feature> features = jseq.getFeatures();
3208 for (int f = 0; f < features.size(); f++)
3210 Feature feat = features.get(f);
3211 SequenceFeature sf = new SequenceFeature(feat.getType(),
3212 feat.getDescription(), feat.getBegin(), feat.getEnd(),
3213 safeFloat(feat.getScore()), feat.getFeatureGroup());
3214 sf.setStatus(feat.getStatus());
3217 * load any feature attributes - include map-valued attributes
3219 Map<String, Map<String, String>> mapAttributes = new HashMap<>();
3220 for (int od = 0; od < feat.getOtherData().size(); od++)
3222 OtherData keyValue = feat.getOtherData().get(od);
3223 String attributeName = keyValue.getKey();
3224 String attributeValue = keyValue.getValue();
3225 if (attributeName.startsWith("LINK"))
3227 sf.addLink(attributeValue);
3231 String subAttribute = keyValue.getKey2();
3232 if (subAttribute == null)
3234 // simple string-valued attribute
3235 sf.setValue(attributeName, attributeValue);
3239 // attribute 'key' has sub-attribute 'key2'
3240 if (!mapAttributes.containsKey(attributeName))
3242 mapAttributes.put(attributeName, new HashMap<>());
3244 mapAttributes.get(attributeName).put(subAttribute,
3249 for (Entry<String, Map<String, String>> mapAttribute : mapAttributes
3252 sf.setValue(mapAttribute.getKey(), mapAttribute.getValue());
3255 // adds feature to datasequence's feature set (since Jalview 2.10)
3256 al.getSequenceAt(i).addSequenceFeature(sf);
3259 if (vamsasSeqs.get(i).getDBRef().size() > 0)
3261 // adds dbrefs to datasequence's set (since Jalview 2.10)
3263 al.getSequenceAt(i).getDatasetSequence() == null
3264 ? al.getSequenceAt(i)
3265 : al.getSequenceAt(i).getDatasetSequence(),
3268 if (jseq.getPdbids().size() > 0)
3270 List<Pdbids> ids = jseq.getPdbids();
3271 for (int p = 0; p < ids.size(); p++)
3273 Pdbids pdbid = ids.get(p);
3274 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
3275 entry.setId(pdbid.getId());
3276 if (pdbid.getType() != null)
3278 if (PDBEntry.Type.getType(pdbid.getType()) != null)
3280 entry.setType(PDBEntry.Type.getType(pdbid.getType()));
3284 entry.setType(PDBEntry.Type.FILE);
3287 // jprovider is null when executing 'New View'
3288 if (pdbid.getFile() != null && jprovider != null)
3290 if (!pdbloaded.containsKey(pdbid.getFile()))
3292 entry.setFile(loadPDBFile(jprovider, pdbid.getId(),
3297 entry.setFile(pdbloaded.get(pdbid.getId()).toString());
3301 if (pdbid.getPdbentryItem() != null)
3303 for (PdbentryItem item : pdbid.getPdbentryItem())
3305 for (Property pr : item.getProperty())
3307 entry.setProperty(pr.getName(), pr.getValue());
3312 for (Property prop : pdbid.getProperty())
3314 entry.setProperty(prop.getName(), prop.getValue());
3316 StructureSelectionManager
3317 .getStructureSelectionManager(Desktop.instance)
3318 .registerPDBEntry(entry);
3319 // adds PDBEntry to datasequence's set (since Jalview 2.10)
3320 if (al.getSequenceAt(i).getDatasetSequence() != null)
3322 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
3326 al.getSequenceAt(i).addPDBId(entry);
3331 } // end !multipleview
3333 // ///////////////////////////////
3334 // LOAD SEQUENCE MAPPINGS
3336 if (vamsasSet.getAlcodonFrame().size() > 0)
3338 // TODO Potentially this should only be done once for all views of an
3340 List<AlcodonFrame> alc = vamsasSet.getAlcodonFrame();
3341 for (int i = 0; i < alc.size(); i++)
3343 AlignedCodonFrame cf = new AlignedCodonFrame();
3344 if (alc.get(i).getAlcodMap().size() > 0)
3346 List<AlcodMap> maps = alc.get(i).getAlcodMap();
3347 for (int m = 0; m < maps.size(); m++)
3349 AlcodMap map = maps.get(m);
3350 SequenceI dnaseq = seqRefIds.get(map.getDnasq());
3352 jalview.datamodel.Mapping mapping = null;
3353 // attach to dna sequence reference.
3354 if (map.getMapping() != null)
3356 mapping = addMapping(map.getMapping());
3357 if (dnaseq != null && mapping.getTo() != null)
3359 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
3365 newAlcodMapRef(map.getDnasq(), cf, mapping));
3369 al.addCodonFrame(cf);
3374 // ////////////////////////////////
3376 List<JvAnnotRow> autoAlan = new ArrayList<>();
3379 * store any annotations which forward reference a group's ID
3381 Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
3383 if (vamsasSet.getAnnotation().size()/*Count()*/ > 0)
3385 List<Annotation> an = vamsasSet.getAnnotation();
3387 for (int i = 0; i < an.size(); i++)
3389 Annotation annotation = an.get(i);
3392 * test if annotation is automatically calculated for this view only
3394 boolean autoForView = false;
3395 if (annotation.getLabel().equals("Quality")
3396 || annotation.getLabel().equals("Conservation")
3397 || annotation.getLabel().equals("Consensus"))
3399 // Kludge for pre 2.5 projects which lacked the autocalculated flag
3401 // JAXB has no has() test; schema defaults value to false
3402 // if (!annotation.hasAutoCalculated())
3404 // annotation.setAutoCalculated(true);
3407 if (autoForView || annotation.isAutoCalculated())
3409 // remove ID - we don't recover annotation from other views for
3410 // view-specific annotation
3411 annotation.setId(null);
3414 // set visibility for other annotation in this view
3415 String annotationId = annotation.getId();
3416 if (annotationId != null && annotationIds.containsKey(annotationId))
3418 AlignmentAnnotation jda = annotationIds.get(annotationId);
3419 // in principle Visible should always be true for annotation displayed
3420 // in multiple views
3421 if (annotation.isVisible() != null)
3423 jda.visible = annotation.isVisible();
3426 al.addAnnotation(jda);
3430 // Construct new annotation from model.
3431 List<AnnotationElement> ae = annotation.getAnnotationElement();
3432 jalview.datamodel.Annotation[] anot = null;
3433 java.awt.Color firstColour = null;
3435 if (!annotation.isScoreOnly())
3437 anot = new jalview.datamodel.Annotation[al.getWidth()];
3438 for (int aa = 0; aa < ae.size() && aa < anot.length; aa++)
3440 AnnotationElement annElement = ae.get(aa);
3441 anpos = annElement.getPosition();
3443 if (anpos >= anot.length)
3448 float value = safeFloat(annElement.getValue());
3449 anot[anpos] = new jalview.datamodel.Annotation(
3450 annElement.getDisplayCharacter(),
3451 annElement.getDescription(),
3452 (annElement.getSecondaryStructure() == null
3453 || annElement.getSecondaryStructure()
3457 .getSecondaryStructure()
3460 anot[anpos].colour = new Color(safeInt(annElement.getColour()));
3461 if (firstColour == null)
3463 firstColour = anot[anpos].colour;
3467 jalview.datamodel.AlignmentAnnotation jaa = null;
3469 if (annotation.isGraph())
3471 float llim = 0, hlim = 0;
3472 // if (autoForView || an[i].isAutoCalculated()) {
3475 jaa = new jalview.datamodel.AlignmentAnnotation(
3476 annotation.getLabel(), annotation.getDescription(), anot,
3477 llim, hlim, safeInt(annotation.getGraphType()));
3479 jaa.graphGroup = safeInt(annotation.getGraphGroup());
3480 jaa._linecolour = firstColour;
3481 if (annotation.getThresholdLine() != null)
3483 jaa.setThreshold(new jalview.datamodel.GraphLine(
3484 safeFloat(annotation.getThresholdLine().getValue()),
3485 annotation.getThresholdLine().getLabel(),
3486 new java.awt.Color(safeInt(
3487 annotation.getThresholdLine().getColour()))));
3489 if (autoForView || annotation.isAutoCalculated())
3491 // Hardwire the symbol display line to ensure that labels for
3492 // histograms are displayed
3498 jaa = new jalview.datamodel.AlignmentAnnotation(
3499 annotation.getLabel(), annotation.getDescription(), anot);
3500 jaa._linecolour = firstColour;
3502 // register new annotation
3503 if (annotation.getId() != null)
3505 annotationIds.put(annotation.getId(), jaa);
3506 jaa.annotationId = annotation.getId();
3508 // recover sequence association
3509 String sequenceRef = annotation.getSequenceRef();
3510 if (sequenceRef != null)
3512 // from 2.9 sequenceRef is to sequence id (JAL-1781)
3513 SequenceI sequence = seqRefIds.get(sequenceRef);
3514 if (sequence == null)
3516 // in pre-2.9 projects sequence ref is to sequence name
3517 sequence = al.findName(sequenceRef);
3519 if (sequence != null)
3521 jaa.createSequenceMapping(sequence, 1, true);
3522 sequence.addAlignmentAnnotation(jaa);
3525 // and make a note of any group association
3526 if (annotation.getGroupRef() != null
3527 && annotation.getGroupRef().length() > 0)
3529 List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
3530 .get(annotation.getGroupRef());
3533 aal = new ArrayList<>();
3534 groupAnnotRefs.put(annotation.getGroupRef(), aal);
3539 if (annotation.getScore() != null)
3541 jaa.setScore(annotation.getScore().doubleValue());
3543 if (annotation.isVisible() != null)
3545 jaa.visible = annotation.isVisible().booleanValue();
3548 if (annotation.isCentreColLabels() != null)
3550 jaa.centreColLabels = annotation.isCentreColLabels()
3554 if (annotation.isScaleColLabels() != null)
3556 jaa.scaleColLabel = annotation.isScaleColLabels().booleanValue();
3558 if (annotation.isAutoCalculated())
3560 // newer files have an 'autoCalculated' flag and store calculation
3561 // state in viewport properties
3562 jaa.autoCalculated = true; // means annotation will be marked for
3563 // update at end of load.
3565 if (annotation.getGraphHeight() != null)
3567 jaa.graphHeight = annotation.getGraphHeight().intValue();
3569 jaa.belowAlignment = annotation.isBelowAlignment();
3570 jaa.setCalcId(annotation.getCalcId());
3571 if (annotation.getProperty().size() > 0)
3573 for (Annotation.Property prop : annotation
3576 jaa.setProperty(prop.getName(), prop.getValue());
3579 if (jaa.autoCalculated)
3581 autoAlan.add(new JvAnnotRow(i, jaa));
3584 // if (!autoForView)
3586 // add autocalculated group annotation and any user created annotation
3588 al.addAnnotation(jaa);
3592 // ///////////////////////
3594 // Create alignment markup and styles for this view
3595 if (jalviewModel.getJGroup().size() > 0)
3597 List<JGroup> groups = jalviewModel.getJGroup();
3598 boolean addAnnotSchemeGroup = false;
3599 for (int i = 0; i < groups.size(); i++)
3601 JGroup jGroup = groups.get(i);
3602 ColourSchemeI cs = null;
3603 if (jGroup.getColour() != null)
3605 if (jGroup.getColour().startsWith("ucs"))
3607 cs = getUserColourScheme(jalviewModel, jGroup.getColour());
3609 else if (jGroup.getColour().equals("AnnotationColourGradient")
3610 && jGroup.getAnnotationColours() != null)
3612 addAnnotSchemeGroup = true;
3616 cs = ColourSchemeProperty.getColourScheme(al,
3617 jGroup.getColour());
3620 int pidThreshold = safeInt(jGroup.getPidThreshold());
3622 Vector<SequenceI> seqs = new Vector<>();
3624 for (int s = 0; s < jGroup.getSeq().size(); s++)
3626 String seqId = jGroup.getSeq().get(s);
3627 SequenceI ts = seqRefIds.get(seqId);
3631 seqs.addElement(ts);
3635 if (seqs.size() < 1)
3640 SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
3641 safeBoolean(jGroup.isDisplayBoxes()),
3642 safeBoolean(jGroup.isDisplayText()),
3643 safeBoolean(jGroup.isColourText()),
3644 safeInt(jGroup.getStart()), safeInt(jGroup.getEnd()));
3645 sg.getGroupColourScheme().setThreshold(pidThreshold, true);
3646 sg.getGroupColourScheme()
3647 .setConservationInc(safeInt(jGroup.getConsThreshold()));
3648 sg.setOutlineColour(new Color(safeInt(jGroup.getOutlineColour())));
3650 sg.textColour = new Color(safeInt(jGroup.getTextCol1()));
3651 sg.textColour2 = new Color(safeInt(jGroup.getTextCol2()));
3652 sg.setShowNonconserved(safeBoolean(jGroup.isShowUnconserved()));
3653 sg.thresholdTextColour = safeInt(jGroup.getTextColThreshold());
3654 // attributes with a default in the schema are never null
3655 sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
3656 sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
3657 sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
3658 sg.setIgnoreGapsConsensus(jGroup.isIgnoreGapsinConsensus());
3659 if (jGroup.getConsThreshold() != null
3660 && jGroup.getConsThreshold().intValue() != 0)
3662 Conservation c = new Conservation("All", sg.getSequences(null), 0,
3665 c.verdict(false, 25);
3666 sg.cs.setConservation(c);
3669 if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
3671 // re-instate unique group/annotation row reference
3672 List<AlignmentAnnotation> jaal = groupAnnotRefs
3673 .get(jGroup.getId());
3676 for (AlignmentAnnotation jaa : jaal)
3679 if (jaa.autoCalculated)
3681 // match up and try to set group autocalc alignment row for this
3683 if (jaa.label.startsWith("Consensus for "))
3685 sg.setConsensus(jaa);
3687 // match up and try to set group autocalc alignment row for this
3689 if (jaa.label.startsWith("Conservation for "))
3691 sg.setConservationRow(jaa);
3698 if (addAnnotSchemeGroup)
3700 // reconstruct the annotation colourscheme
3701 sg.setColourScheme(constructAnnotationColour(
3702 jGroup.getAnnotationColours(), null, al, jalviewModel, false));
3708 // only dataset in this model, so just return.
3711 // ///////////////////////////////
3714 // If we just load in the same jar file again, the sequenceSetId
3715 // will be the same, and we end up with multiple references
3716 // to the same sequenceSet. We must modify this id on load
3717 // so that each load of the file gives a unique id
3718 String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
3719 String viewId = (view.getId() == null ? null
3720 : view.getId() + uniqueSetSuffix);
3721 AlignFrame af = null;
3722 AlignViewport av = null;
3723 // now check to see if we really need to create a new viewport.
3724 if (multipleView && viewportsAdded.size() == 0)
3726 // We recovered an alignment for which a viewport already exists.
3727 // TODO: fix up any settings necessary for overlaying stored state onto
3728 // state recovered from another document. (may not be necessary).
3729 // we may need a binding from a viewport in memory to one recovered from
3731 // and then recover its containing af to allow the settings to be applied.
3732 // TODO: fix for vamsas demo
3734 "About to recover a viewport for existing alignment: Sequence set ID is "
3736 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
3737 if (seqsetobj != null)
3739 if (seqsetobj instanceof String)
3741 uniqueSeqSetId = (String) seqsetobj;
3743 "Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
3749 "Warning : Collision between sequence set ID string and existing jalview object mapping.");
3755 * indicate that annotation colours are applied across all groups (pre
3756 * Jalview 2.8.1 behaviour)
3758 boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan("2.8.1",
3759 jalviewModel.getVersion());
3761 AlignmentPanel ap = null;
3762 boolean isnewview = true;
3765 // Check to see if this alignment already has a view id == viewId
3766 jalview.gui.AlignmentPanel views[] = Desktop
3767 .getAlignmentPanels(uniqueSeqSetId);
3768 if (views != null && views.length > 0)
3770 for (int v = 0; v < views.length; v++)
3772 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
3774 // recover the existing alignpanel, alignframe, viewport
3775 af = views[v].alignFrame;
3778 // TODO: could even skip resetting view settings if we don't want to
3779 // change the local settings from other jalview processes
3788 af = loadViewport(file, jseqs, hiddenSeqs, al, jalviewModel, view,
3789 uniqueSeqSetId, viewId, autoAlan);
3790 av = af.getViewport();
3795 * Load any trees, PDB structures and viewers
3797 * Not done if flag is false (when this method is used for New View)
3799 if (loadTreesAndStructures)
3801 loadTrees(jalviewModel, view, af, av, ap);
3802 loadPDBStructures(jprovider, jseqs, af, ap);
3803 loadRnaViewers(jprovider, jseqs, ap);
3805 // and finally return.
3810 * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
3811 * panel is restored from separate jar entries, two (gapped and trimmed) per
3812 * sequence and secondary structure.
3814 * Currently each viewer shows just one sequence and structure (gapped and
3815 * trimmed), however this method is designed to support multiple sequences or
3816 * structures in viewers if wanted in future.
3822 private void loadRnaViewers(jarInputStreamProvider jprovider,
3823 List<JSeq> jseqs, AlignmentPanel ap)
3826 * scan the sequences for references to viewers; create each one the first
3827 * time it is referenced, add Rna models to existing viewers
3829 for (JSeq jseq : jseqs)
3831 for (int i = 0; i < jseq.getRnaViewer().size(); i++)
3833 RnaViewer viewer = jseq.getRnaViewer().get(i);
3834 AppVarna appVarna = findOrCreateVarnaViewer(viewer, uniqueSetSuffix,
3837 for (int j = 0; j < viewer.getSecondaryStructure().size(); j++)
3839 SecondaryStructure ss = viewer.getSecondaryStructure().get(j);
3840 SequenceI seq = seqRefIds.get(jseq.getId());
3841 AlignmentAnnotation ann = this.annotationIds
3842 .get(ss.getAnnotationId());
3845 * add the structure to the Varna display (with session state copied
3846 * from the jar to a temporary file)
3848 boolean gapped = safeBoolean(ss.isGapped());
3849 String rnaTitle = ss.getTitle();
3850 String sessionState = ss.getViewerState();
3851 String tempStateFile = copyJarEntry(jprovider, sessionState,
3853 RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
3854 appVarna.addModelSession(rna, rnaTitle, tempStateFile);
3856 appVarna.setInitialSelection(safeInt(viewer.getSelectedRna()));
3862 * Locate and return an already instantiated matching AppVarna, or create one
3866 * @param viewIdSuffix
3870 protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
3871 String viewIdSuffix, AlignmentPanel ap)
3874 * on each load a suffix is appended to the saved viewId, to avoid conflicts
3875 * if load is repeated
3877 String postLoadId = viewer.getViewId() + viewIdSuffix;
3878 for (JInternalFrame frame : getAllFrames())
3880 if (frame instanceof AppVarna)
3882 AppVarna varna = (AppVarna) frame;
3883 if (postLoadId.equals(varna.getViewId()))
3885 // this viewer is already instantiated
3886 // could in future here add ap as another 'parent' of the
3887 // AppVarna window; currently just 1-to-many
3894 * viewer not found - make it
3896 RnaViewerModel model = new RnaViewerModel(postLoadId, viewer.getTitle(),
3897 safeInt(viewer.getXpos()), safeInt(viewer.getYpos()),
3898 safeInt(viewer.getWidth()), safeInt(viewer.getHeight()),
3899 safeInt(viewer.getDividerLocation()));
3900 AppVarna varna = new AppVarna(model, ap);
3906 * Load any saved trees
3914 protected void loadTrees(JalviewModel jm, Viewport view,
3915 AlignFrame af, AlignViewport av, AlignmentPanel ap)
3917 // TODO result of automated refactoring - are all these parameters needed?
3920 for (int t = 0; t < jm.getTree().size(); t++)
3923 Tree tree = jm.getTree().get(t);
3925 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
3928 tp = af.showNewickTree(new NewickFile(tree.getNewick()),
3929 tree.getTitle(), safeInt(tree.getWidth()),
3930 safeInt(tree.getHeight()), safeInt(tree.getXpos()),
3931 safeInt(tree.getYpos()));
3932 if (tree.getId() != null)
3934 // perhaps bind the tree id to something ?
3939 // update local tree attributes ?
3940 // TODO: should check if tp has been manipulated by user - if so its
3941 // settings shouldn't be modified
3942 tp.setTitle(tree.getTitle());
3943 tp.setBounds(new Rectangle(safeInt(tree.getXpos()),
3944 safeInt(tree.getYpos()), safeInt(tree.getWidth()),
3945 safeInt(tree.getHeight())));
3946 tp.setViewport(av); // af.viewport;
3947 // TODO: verify 'associate with all views' works still
3948 tp.getTreeCanvas().setViewport(av); // af.viewport;
3949 tp.getTreeCanvas().setAssociatedPanel(ap); // af.alignPanel;
3954 warn("There was a problem recovering stored Newick tree: \n"
3955 + tree.getNewick());
3959 tp.fitToWindow.setState(safeBoolean(tree.isFitToWindow()));
3960 tp.fitToWindow_actionPerformed(null);
3962 if (tree.getFontName() != null)
3965 new Font(tree.getFontName(), safeInt(tree.getFontStyle()),
3966 safeInt(tree.getFontSize())));
3971 new Font(view.getFontName(), safeInt(view.getFontStyle()),
3972 safeInt(view.getFontSize())));
3975 tp.showPlaceholders(safeBoolean(tree.isMarkUnlinked()));
3976 tp.showBootstrap(safeBoolean(tree.isShowBootstrap()));
3977 tp.showDistances(safeBoolean(tree.isShowDistances()));
3979 tp.getTreeCanvas().setThreshold(safeFloat(tree.getThreshold()));
3981 if (safeBoolean(tree.isCurrentTree()))
3983 af.getViewport().setCurrentTree(tp.getTree());
3987 } catch (Exception ex)
3989 ex.printStackTrace();
3994 * Load and link any saved structure viewers.
4001 protected void loadPDBStructures(jarInputStreamProvider jprovider,
4002 List<JSeq> jseqs, AlignFrame af, AlignmentPanel ap)
4005 * Run through all PDB ids on the alignment, and collect mappings between
4006 * distinct view ids and all sequences referring to that view.
4008 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
4010 for (int i = 0; i < jseqs.size(); i++)
4012 JSeq jseq = jseqs.get(i);
4013 if (jseq.getPdbids().size() > 0)
4015 List<Pdbids> ids = jseq.getPdbids();
4016 for (int p = 0; p < ids.size(); p++)
4018 Pdbids pdbid = ids.get(p);
4019 final int structureStateCount = pdbid.getStructureState().size();
4020 for (int s = 0; s < structureStateCount; s++)
4022 // check to see if we haven't already created this structure view
4023 final StructureState structureState = pdbid
4024 .getStructureState().get(s);
4025 String sviewid = (structureState.getViewId() == null) ? null
4026 : structureState.getViewId() + uniqueSetSuffix;
4027 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
4028 // Originally : pdbid.getFile()
4029 // : TODO: verify external PDB file recovery still works in normal
4030 // jalview project load
4032 loadPDBFile(jprovider, pdbid.getId(), pdbid.getFile()));
4033 jpdb.setId(pdbid.getId());
4035 int x = safeInt(structureState.getXpos());
4036 int y = safeInt(structureState.getYpos());
4037 int width = safeInt(structureState.getWidth());
4038 int height = safeInt(structureState.getHeight());
4040 // Probably don't need to do this anymore...
4041 // Desktop.desktop.getComponentAt(x, y);
4042 // TODO: NOW: check that this recovers the PDB file correctly.
4043 String pdbFile = loadPDBFile(jprovider, pdbid.getId(),
4045 jalview.datamodel.SequenceI seq = seqRefIds
4046 .get(jseq.getId() + "");
4047 if (sviewid == null)
4049 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width + ","
4052 if (!structureViewers.containsKey(sviewid))
4054 structureViewers.put(sviewid,
4055 new StructureViewerModel(x, y, width, height, false,
4056 false, true, structureState.getViewId(),
4057 structureState.getType()));
4058 // Legacy pre-2.7 conversion JAL-823 :
4059 // do not assume any view has to be linked for colour by
4063 // assemble String[] { pdb files }, String[] { id for each
4064 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
4065 // seqs_file 2}, boolean[] {
4066 // linkAlignPanel,superposeWithAlignpanel}} from hash
4067 StructureViewerModel jmoldat = structureViewers.get(sviewid);
4068 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
4069 || structureState.isAlignwithAlignPanel());
4072 * Default colour by linked panel to false if not specified (e.g.
4073 * for pre-2.7 projects)
4075 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
4076 colourWithAlignPanel |= structureState.isColourwithAlignPanel();
4077 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
4080 * Default colour by viewer to true if not specified (e.g. for
4083 boolean colourByViewer = jmoldat.isColourByViewer();
4084 colourByViewer &= structureState.isColourByJmol();
4085 jmoldat.setColourByViewer(colourByViewer);
4087 if (jmoldat.getStateData().length() < structureState
4088 .getValue()/*Content()*/.length())
4090 jmoldat.setStateData(structureState.getValue());// Content());
4092 if (pdbid.getFile() != null)
4094 File mapkey = new File(pdbid.getFile());
4095 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
4096 if (seqstrmaps == null)
4098 jmoldat.getFileData().put(mapkey,
4099 seqstrmaps = jmoldat.new StructureData(pdbFile,
4102 if (!seqstrmaps.getSeqList().contains(seq))
4104 seqstrmaps.getSeqList().add(seq);
4110 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");
4117 // Instantiate the associated structure views
4118 for (Entry<String, StructureViewerModel> entry : structureViewers
4123 createOrLinkStructureViewer(entry, af, ap, jprovider);
4124 } catch (Exception e)
4127 "Error loading structure viewer: " + e.getMessage());
4128 // failed - try the next one
4140 protected void createOrLinkStructureViewer(
4141 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
4142 AlignmentPanel ap, jarInputStreamProvider jprovider)
4144 final StructureViewerModel stateData = viewerData.getValue();
4147 * Search for any viewer windows already open from other alignment views
4148 * that exactly match the stored structure state
4150 StructureViewerBase comp = findMatchingViewer(viewerData);
4154 linkStructureViewer(ap, comp, stateData);
4159 * From 2.9: stateData.type contains JMOL or CHIMERA, data is in jar entry
4160 * "viewer_"+stateData.viewId
4162 if (ViewerType.CHIMERA.toString().equals(stateData.getType()))
4164 createChimeraViewer(viewerData, af, jprovider);
4169 * else Jmol (if pre-2.9, stateData contains JMOL state string)
4171 createJmolViewer(viewerData, af, jprovider);
4176 * Create a new Chimera viewer.
4182 protected void createChimeraViewer(
4183 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
4184 jarInputStreamProvider jprovider)
4186 StructureViewerModel data = viewerData.getValue();
4187 String chimeraSessionFile = data.getStateData();
4190 * Copy Chimera session from jar entry "viewer_"+viewId to a temporary file
4192 * NB this is the 'saved' viewId as in the project file XML, _not_ the
4193 * 'uniquified' sviewid used to reconstruct the viewer here
4195 String viewerJarEntryName = getViewerJarEntryName(data.getViewId());
4196 chimeraSessionFile = copyJarEntry(jprovider, viewerJarEntryName,
4199 Set<Entry<File, StructureData>> fileData = data.getFileData()
4201 List<PDBEntry> pdbs = new ArrayList<>();
4202 List<SequenceI[]> allseqs = new ArrayList<>();
4203 for (Entry<File, StructureData> pdb : fileData)
4205 String filePath = pdb.getValue().getFilePath();
4206 String pdbId = pdb.getValue().getPdbId();
4207 // pdbs.add(new PDBEntry(filePath, pdbId));
4208 pdbs.add(new PDBEntry(pdbId, null, PDBEntry.Type.PDB, filePath));
4209 final List<SequenceI> seqList = pdb.getValue().getSeqList();
4210 SequenceI[] seqs = seqList.toArray(new SequenceI[seqList.size()]);
4214 boolean colourByChimera = data.isColourByViewer();
4215 boolean colourBySequence = data.isColourWithAlignPanel();
4217 // TODO use StructureViewer as a factory here, see JAL-1761
4218 final PDBEntry[] pdbArray = pdbs.toArray(new PDBEntry[pdbs.size()]);
4219 final SequenceI[][] seqsArray = allseqs
4220 .toArray(new SequenceI[allseqs.size()][]);
4221 String newViewId = viewerData.getKey();
4223 ChimeraViewFrame cvf = new ChimeraViewFrame(chimeraSessionFile,
4224 af.alignPanel, pdbArray, seqsArray, colourByChimera,
4225 colourBySequence, newViewId);
4226 cvf.setSize(data.getWidth(), data.getHeight());
4227 cvf.setLocation(data.getX(), data.getY());
4231 * Create a new Jmol window. First parse the Jmol state to translate filenames
4232 * loaded into the view, and record the order in which files are shown in the
4233 * Jmol view, so we can add the sequence mappings in same order.
4239 protected void createJmolViewer(
4240 final Entry<String, StructureViewerModel> viewerData,
4241 AlignFrame af, jarInputStreamProvider jprovider)
4243 final StructureViewerModel svattrib = viewerData.getValue();
4244 String state = svattrib.getStateData();
4247 * Pre-2.9: state element value is the Jmol state string
4249 * 2.9+: @type is "JMOL", state data is in a Jar file member named "viewer_"
4252 if (ViewerType.JMOL.toString().equals(svattrib.getType()))
4254 state = readJarEntry(jprovider,
4255 getViewerJarEntryName(svattrib.getViewId()));
4258 List<String> pdbfilenames = new ArrayList<>();
4259 List<SequenceI[]> seqmaps = new ArrayList<>();
4260 List<String> pdbids = new ArrayList<>();
4261 StringBuilder newFileLoc = new StringBuilder(64);
4262 int cp = 0, ncp, ecp;
4263 Map<File, StructureData> oldFiles = svattrib.getFileData();
4264 while ((ncp = state.indexOf("load ", cp)) > -1)
4268 // look for next filename in load statement
4269 newFileLoc.append(state.substring(cp,
4270 ncp = (state.indexOf("\"", ncp + 1) + 1)));
4271 String oldfilenam = state.substring(ncp,
4272 ecp = state.indexOf("\"", ncp));
4273 // recover the new mapping data for this old filename
4274 // have to normalize filename - since Jmol and jalview do
4276 // translation differently.
4277 StructureData filedat = oldFiles.get(new File(oldfilenam));
4278 if (filedat == null)
4280 String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
4281 filedat = oldFiles.get(new File(reformatedOldFilename));
4283 newFileLoc.append(Platform.escapeString(filedat.getFilePath()));
4284 pdbfilenames.add(filedat.getFilePath());
4285 pdbids.add(filedat.getPdbId());
4286 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4287 newFileLoc.append("\"");
4288 cp = ecp + 1; // advance beyond last \" and set cursor so we can
4289 // look for next file statement.
4290 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
4294 // just append rest of state
4295 newFileLoc.append(state.substring(cp));
4299 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
4300 newFileLoc = new StringBuilder(state);
4301 newFileLoc.append("; load append ");
4302 for (File id : oldFiles.keySet())
4304 // add this and any other pdb files that should be present in
4306 StructureData filedat = oldFiles.get(id);
4307 newFileLoc.append(filedat.getFilePath());
4308 pdbfilenames.add(filedat.getFilePath());
4309 pdbids.add(filedat.getPdbId());
4310 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4311 newFileLoc.append(" \"");
4312 newFileLoc.append(filedat.getFilePath());
4313 newFileLoc.append("\"");
4316 newFileLoc.append(";");
4319 if (newFileLoc.length() == 0)
4323 int histbug = newFileLoc.indexOf("history = ");
4327 * change "history = [true|false];" to "history = [1|0];"
4330 int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";", histbug);
4331 String val = (diff == -1) ? null
4332 : newFileLoc.substring(histbug, diff);
4333 if (val != null && val.length() >= 4)
4335 if (val.contains("e")) // eh? what can it be?
4337 if (val.trim().equals("true"))
4345 newFileLoc.replace(histbug, diff, val);
4350 final String[] pdbf = pdbfilenames
4351 .toArray(new String[pdbfilenames.size()]);
4352 final String[] id = pdbids.toArray(new String[pdbids.size()]);
4353 final SequenceI[][] sq = seqmaps
4354 .toArray(new SequenceI[seqmaps.size()][]);
4355 final String fileloc = newFileLoc.toString();
4356 final String sviewid = viewerData.getKey();
4357 final AlignFrame alf = af;
4358 final Rectangle rect = new Rectangle(svattrib.getX(), svattrib.getY(),
4359 svattrib.getWidth(), svattrib.getHeight());
4362 javax.swing.SwingUtilities.invokeAndWait(new Runnable()
4367 JalviewStructureDisplayI sview = null;
4370 sview = new StructureViewer(
4371 alf.alignPanel.getStructureSelectionManager())
4372 .createView(StructureViewer.ViewerType.JMOL,
4373 pdbf, id, sq, alf.alignPanel, svattrib,
4374 fileloc, rect, sviewid);
4375 addNewStructureViewer(sview);
4376 } catch (OutOfMemoryError ex)
4378 new OOMWarning("restoring structure view for PDB id " + id,
4379 (OutOfMemoryError) ex.getCause());
4380 if (sview != null && sview.isVisible())
4382 sview.closeViewer(false);
4383 sview.setVisible(false);
4389 } catch (InvocationTargetException ex)
4391 warn("Unexpected error when opening Jmol view.", ex);
4393 } catch (InterruptedException e)
4395 // e.printStackTrace();
4401 * Generates a name for the entry in the project jar file to hold state
4402 * information for a structure viewer
4407 protected String getViewerJarEntryName(String viewId)
4409 return VIEWER_PREFIX + viewId;
4413 * Returns any open frame that matches given structure viewer data. The match
4414 * is based on the unique viewId, or (for older project versions) the frame's
4420 protected StructureViewerBase findMatchingViewer(
4421 Entry<String, StructureViewerModel> viewerData)
4423 final String sviewid = viewerData.getKey();
4424 final StructureViewerModel svattrib = viewerData.getValue();
4425 StructureViewerBase comp = null;
4426 JInternalFrame[] frames = getAllFrames();
4427 for (JInternalFrame frame : frames)
4429 if (frame instanceof StructureViewerBase)
4432 * Post jalview 2.4 schema includes structure view id
4434 if (sviewid != null && ((StructureViewerBase) frame).getViewId()
4437 comp = (StructureViewerBase) frame;
4438 break; // break added in 2.9
4441 * Otherwise test for matching position and size of viewer frame
4443 else if (frame.getX() == svattrib.getX()
4444 && frame.getY() == svattrib.getY()
4445 && frame.getHeight() == svattrib.getHeight()
4446 && frame.getWidth() == svattrib.getWidth())
4448 comp = (StructureViewerBase) frame;
4449 // no break in faint hope of an exact match on viewId
4457 * Link an AlignmentPanel to an existing structure viewer.
4462 * @param useinViewerSuperpos
4463 * @param usetoColourbyseq
4464 * @param viewerColouring
4466 protected void linkStructureViewer(AlignmentPanel ap,
4467 StructureViewerBase viewer, StructureViewerModel stateData)
4469 // NOTE: if the jalview project is part of a shared session then
4470 // view synchronization should/could be done here.
4472 final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
4473 final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
4474 final boolean viewerColouring = stateData.isColourByViewer();
4475 Map<File, StructureData> oldFiles = stateData.getFileData();
4478 * Add mapping for sequences in this view to an already open viewer
4480 final AAStructureBindingModel binding = viewer.getBinding();
4481 for (File id : oldFiles.keySet())
4483 // add this and any other pdb files that should be present in the
4485 StructureData filedat = oldFiles.get(id);
4486 String pdbFile = filedat.getFilePath();
4487 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
4488 binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE,
4490 binding.addSequenceForStructFile(pdbFile, seq);
4492 // and add the AlignmentPanel's reference to the view panel
4493 viewer.addAlignmentPanel(ap);
4494 if (useinViewerSuperpos)
4496 viewer.useAlignmentPanelForSuperposition(ap);
4500 viewer.excludeAlignmentPanelForSuperposition(ap);
4502 if (usetoColourbyseq)
4504 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
4508 viewer.excludeAlignmentPanelForColourbyseq(ap);
4513 * Get all frames within the Desktop.
4517 protected JInternalFrame[] getAllFrames()
4519 JInternalFrame[] frames = null;
4520 // TODO is this necessary - is it safe - risk of hanging?
4525 frames = Desktop.desktop.getAllFrames();
4526 } catch (ArrayIndexOutOfBoundsException e)
4528 // occasional No such child exceptions are thrown here...
4532 } catch (InterruptedException f)
4536 } while (frames == null);
4541 * Answers true if 'version' is equal to or later than 'supported', where each
4542 * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
4543 * changes. Development and test values for 'version' are leniently treated
4547 * - minimum version we are comparing against
4549 * - version of data being processsed
4552 public static boolean isVersionStringLaterThan(String supported,
4555 if (supported == null || version == null
4556 || version.equalsIgnoreCase("DEVELOPMENT BUILD")
4557 || version.equalsIgnoreCase("Test")
4558 || version.equalsIgnoreCase("AUTOMATED BUILD"))
4560 System.err.println("Assuming project file with "
4561 + (version == null ? "null" : version)
4562 + " is compatible with Jalview version " + supported);
4567 return StringUtils.compareVersions(version, supported, "b") >= 0;
4571 Vector<JalviewStructureDisplayI> newStructureViewers = null;
4573 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
4575 if (newStructureViewers != null)
4577 sview.getBinding().setFinishedLoadingFromArchive(false);
4578 newStructureViewers.add(sview);
4582 protected void setLoadingFinishedForNewStructureViewers()
4584 if (newStructureViewers != null)
4586 for (JalviewStructureDisplayI sview : newStructureViewers)
4588 sview.getBinding().setFinishedLoadingFromArchive(true);
4590 newStructureViewers.clear();
4591 newStructureViewers = null;
4595 AlignFrame loadViewport(String file, List<JSeq> JSEQ,
4596 List<SequenceI> hiddenSeqs, AlignmentI al,
4597 JalviewModel jm, Viewport view, String uniqueSeqSetId,
4598 String viewId, List<JvAnnotRow> autoAlan)
4600 AlignFrame af = null;
4601 af = new AlignFrame(al, safeInt(view.getWidth()),
4602 safeInt(view.getHeight()), uniqueSeqSetId, viewId);
4604 af.setFileName(file, FileFormat.Jalview);
4606 final AlignViewport viewport = af.getViewport();
4607 for (int i = 0; i < JSEQ.size(); i++)
4609 int colour = safeInt(JSEQ.get(i).getColour());
4610 viewport.setSequenceColour(viewport.getAlignment().getSequenceAt(i),
4616 viewport.setColourByReferenceSeq(true);
4617 viewport.setDisplayReferenceSeq(true);
4620 viewport.setGatherViewsHere(safeBoolean(view.isGatheredViews()));
4622 if (view.getSequenceSetId() != null)
4624 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
4626 viewport.setSequenceSetId(uniqueSeqSetId);
4629 // propagate shared settings to this new view
4630 viewport.setHistoryList(av.getHistoryList());
4631 viewport.setRedoList(av.getRedoList());
4635 viewportsAdded.put(uniqueSeqSetId, viewport);
4637 // TODO: check if this method can be called repeatedly without
4638 // side-effects if alignpanel already registered.
4639 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
4641 // apply Hidden regions to view.
4642 if (hiddenSeqs != null)
4644 for (int s = 0; s < JSEQ.size(); s++)
4646 SequenceGroup hidden = new SequenceGroup();
4647 boolean isRepresentative = false;
4648 for (int r = 0; r < JSEQ.get(s).getHiddenSequences().size(); r++)
4650 isRepresentative = true;
4651 SequenceI sequenceToHide = al
4652 .getSequenceAt(JSEQ.get(s).getHiddenSequences().get(r));
4653 hidden.addSequence(sequenceToHide, false);
4654 // remove from hiddenSeqs list so we don't try to hide it twice
4655 hiddenSeqs.remove(sequenceToHide);
4657 if (isRepresentative)
4659 SequenceI representativeSequence = al.getSequenceAt(s);
4660 hidden.addSequence(representativeSequence, false);
4661 viewport.hideRepSequences(representativeSequence, hidden);
4665 SequenceI[] hseqs = hiddenSeqs
4666 .toArray(new SequenceI[hiddenSeqs.size()]);
4667 viewport.hideSequence(hseqs);
4670 // recover view properties and display parameters
4672 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
4673 viewport.setAbovePIDThreshold(safeBoolean(view.isPidSelected()));
4674 final int pidThreshold = safeInt(view.getPidThreshold());
4675 viewport.setThreshold(pidThreshold);
4677 viewport.setColourText(safeBoolean(view.isShowColourText()));
4680 .setConservationSelected(
4681 safeBoolean(view.isConservationSelected()));
4682 viewport.setIncrement(safeInt(view.getConsThreshold()));
4683 viewport.setShowJVSuffix(safeBoolean(view.isShowFullId()));
4684 viewport.setRightAlignIds(safeBoolean(view.isRightAlignIds()));
4685 viewport.setFont(new Font(view.getFontName(),
4686 safeInt(view.getFontStyle()), safeInt(view.getFontSize())),
4688 ViewStyleI vs = viewport.getViewStyle();
4689 vs.setScaleProteinAsCdna(view.isScaleProteinAsCdna());
4690 viewport.setViewStyle(vs);
4691 // TODO: allow custom charWidth/Heights to be restored by updating them
4692 // after setting font - which means set above to false
4693 viewport.setRenderGaps(safeBoolean(view.isRenderGaps()));
4694 viewport.setWrapAlignment(safeBoolean(view.isWrapAlignment()));
4695 viewport.setShowAnnotation(safeBoolean(view.isShowAnnotation()));
4697 viewport.setShowBoxes(safeBoolean(view.isShowBoxes()));
4699 viewport.setShowText(safeBoolean(view.isShowText()));
4701 viewport.setTextColour(new Color(safeInt(view.getTextCol1())));
4702 viewport.setTextColour2(new Color(safeInt(view.getTextCol2())));
4703 viewport.setThresholdTextColour(safeInt(view.getTextColThreshold()));
4704 viewport.setShowUnconserved(view.isShowUnconserved());
4705 viewport.getRanges().setStartRes(safeInt(view.getStartRes()));
4707 if (view.getViewName() != null)
4709 viewport.setViewName(view.getViewName());
4710 af.setInitialTabVisible();
4712 af.setBounds(safeInt(view.getXpos()), safeInt(view.getYpos()),
4713 safeInt(view.getWidth()), safeInt(view.getHeight()));
4714 // startSeq set in af.alignPanel.updateLayout below
4715 af.alignPanel.updateLayout();
4716 ColourSchemeI cs = null;
4717 // apply colourschemes
4718 if (view.getBgColour() != null)
4720 if (view.getBgColour().startsWith("ucs"))
4722 cs = getUserColourScheme(jm, view.getBgColour());
4724 else if (view.getBgColour().startsWith("Annotation"))
4726 AnnotationColourScheme viewAnnColour = view.getAnnotationColours();
4727 cs = constructAnnotationColour(viewAnnColour, af, al, jm, true);
4734 cs = ColourSchemeProperty.getColourScheme(al, view.getBgColour());
4738 viewport.setGlobalColourScheme(cs);
4739 viewport.getResidueShading().setThreshold(pidThreshold,
4740 view.isIgnoreGapsinConsensus());
4741 viewport.getResidueShading()
4742 .setConsensus(viewport.getSequenceConsensusHash());
4743 viewport.setColourAppliesToAllGroups(false);
4745 if (safeBoolean(view.isConservationSelected()) && cs != null)
4747 viewport.getResidueShading()
4748 .setConservationInc(safeInt(view.getConsThreshold()));
4751 af.changeColour(cs);
4753 viewport.setColourAppliesToAllGroups(true);
4756 .setShowSequenceFeatures(
4757 safeBoolean(view.isShowSequenceFeatures()));
4759 viewport.setCentreColumnLabels(view.isCentreColumnLabels());
4760 viewport.setIgnoreGapsConsensus(view.isIgnoreGapsinConsensus(), null);
4761 viewport.setFollowHighlight(view.isFollowHighlight());
4762 viewport.followSelection = view.isFollowSelection();
4763 viewport.setShowConsensusHistogram(view.isShowConsensusHistogram());
4764 viewport.setShowSequenceLogo(view.isShowSequenceLogo());
4765 viewport.setNormaliseSequenceLogo(view.isNormaliseSequenceLogo());
4766 viewport.setShowDBRefs(safeBoolean(view.isShowDbRefTooltip()));
4767 viewport.setShowNPFeats(safeBoolean(view.isShowNPfeatureTooltip()));
4768 viewport.setShowGroupConsensus(view.isShowGroupConsensus());
4769 viewport.setShowGroupConservation(view.isShowGroupConservation());
4771 // recover feature settings
4772 if (jm.getFeatureSettings() != null)
4774 FeatureRenderer fr = af.alignPanel.getSeqPanel().seqCanvas
4775 .getFeatureRenderer();
4776 FeaturesDisplayed fdi;
4777 viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
4778 String[] renderOrder = new String[jm.getFeatureSettings()
4779 .getSetting().size()];
4780 Map<String, FeatureColourI> featureColours = new Hashtable<>();
4781 Map<String, Float> featureOrder = new Hashtable<>();
4783 for (int fs = 0; fs < jm.getFeatureSettings()
4784 .getSetting().size(); fs++)
4786 Setting setting = jm.getFeatureSettings().getSetting().get(fs);
4787 String featureType = setting.getType();
4790 * restore feature filters (if any)
4792 jalview.xml.binding.jalview.FeatureMatcherSet filters = setting
4794 if (filters != null)
4796 FeatureMatcherSetI filter = Jalview2XML
4797 .parseFilter(featureType, filters);
4798 if (!filter.isEmpty())
4800 fr.setFeatureFilter(featureType, filter);
4805 * restore feature colour scheme
4807 Color maxColour = new Color(setting.getColour());
4808 if (setting.getMincolour() != null)
4811 * minColour is always set unless a simple colour
4812 * (including for colour by label though it doesn't use it)
4814 Color minColour = new Color(setting.getMincolour().intValue());
4815 Color noValueColour = minColour;
4816 NoValueColour noColour = setting.getNoValueColour();
4817 if (noColour == NoValueColour.NONE)
4819 noValueColour = null;
4821 else if (noColour == NoValueColour.MAX)
4823 noValueColour = maxColour;
4825 float min = safeFloat(safeFloat(setting.getMin()));
4826 float max = setting.getMax() == null ? 1f
4827 : setting.getMax().floatValue();
4828 FeatureColourI gc = new FeatureColour(minColour, maxColour,
4829 noValueColour, min, max);
4830 if (setting.getAttributeName().size() > 0)
4832 gc.setAttributeName(setting.getAttributeName().toArray(
4833 new String[setting.getAttributeName().size()]));
4835 if (setting.getThreshold() != null)
4837 gc.setThreshold(setting.getThreshold().floatValue());
4838 int threshstate = safeInt(setting.getThreshstate());
4839 // -1 = None, 0 = Below, 1 = Above threshold
4840 if (threshstate == 0)
4842 gc.setBelowThreshold(true);
4844 else if (threshstate == 1)
4846 gc.setAboveThreshold(true);
4849 gc.setAutoScaled(true); // default
4850 if (setting.isAutoScale() != null)
4852 gc.setAutoScaled(setting.isAutoScale());
4854 if (setting.isColourByLabel() != null)
4856 gc.setColourByLabel(setting.isColourByLabel());
4858 // and put in the feature colour table.
4859 featureColours.put(featureType, gc);
4863 featureColours.put(featureType,
4864 new FeatureColour(maxColour));
4866 renderOrder[fs] = featureType;
4867 if (setting.getOrder() != null)
4869 featureOrder.put(featureType, setting.getOrder().floatValue());
4873 featureOrder.put(featureType, new Float(
4874 fs / jm.getFeatureSettings().getSetting().size()));
4876 if (safeBoolean(setting.isDisplay()))
4878 fdi.setVisible(featureType);
4881 Map<String, Boolean> fgtable = new Hashtable<>();
4882 for (int gs = 0; gs < jm.getFeatureSettings().getGroup().size(); gs++)
4884 Group grp = jm.getFeatureSettings().getGroup().get(gs);
4885 fgtable.put(grp.getName(), new Boolean(grp.isDisplay()));
4887 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
4888 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
4889 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
4890 FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
4891 fgtable, featureColours, 1.0f, featureOrder);
4892 fr.transferSettings(frs);
4895 if (view.getHiddenColumns().size() > 0)
4897 for (int c = 0; c < view.getHiddenColumns().size(); c++)
4899 final HiddenColumns hc = view.getHiddenColumns().get(c);
4900 viewport.hideColumns(safeInt(hc.getStart()),
4901 safeInt(hc.getEnd()) /* +1 */);
4904 if (view.getCalcIdParam() != null)
4906 for (CalcIdParam calcIdParam : view.getCalcIdParam())
4908 if (calcIdParam != null)
4910 if (recoverCalcIdParam(calcIdParam, viewport))
4915 warn("Couldn't recover parameters for "
4916 + calcIdParam.getCalcId());
4921 af.setMenusFromViewport(viewport);
4922 af.setTitle(view.getTitle());
4923 // TODO: we don't need to do this if the viewport is aready visible.
4925 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
4926 * has a 'cdna/protein complement' view, in which case save it in order to
4927 * populate a SplitFrame once all views have been read in.
4929 String complementaryViewId = view.getComplementId();
4930 if (complementaryViewId == null)
4932 Desktop.addInternalFrame(af, view.getTitle(),
4933 safeInt(view.getWidth()), safeInt(view.getHeight()));
4934 // recompute any autoannotation
4935 af.alignPanel.updateAnnotation(false, true);
4936 reorderAutoannotation(af, al, autoAlan);
4937 af.alignPanel.alignmentChanged();
4941 splitFrameCandidates.put(view, af);
4947 * Reads saved data to restore Colour by Annotation settings
4949 * @param viewAnnColour
4953 * @param checkGroupAnnColour
4956 private ColourSchemeI constructAnnotationColour(
4957 AnnotationColourScheme viewAnnColour, AlignFrame af,
4958 AlignmentI al, JalviewModel model, boolean checkGroupAnnColour)
4960 boolean propagateAnnColour = false;
4961 AlignmentI annAlignment = af != null ? af.getViewport().getAlignment()
4963 if (checkGroupAnnColour && al.getGroups() != null
4964 && al.getGroups().size() > 0)
4966 // pre 2.8.1 behaviour
4967 // check to see if we should transfer annotation colours
4968 propagateAnnColour = true;
4969 for (SequenceGroup sg : al.getGroups())
4971 if (sg.getColourScheme() instanceof AnnotationColourGradient)
4973 propagateAnnColour = false;
4979 * 2.10.2- : saved annotationId is AlignmentAnnotation.annotationId
4981 String annotationId = viewAnnColour.getAnnotation();
4982 AlignmentAnnotation matchedAnnotation = annotationIds.get(annotationId);
4985 * pre 2.10.2: saved annotationId is AlignmentAnnotation.label
4987 if (matchedAnnotation == null
4988 && annAlignment.getAlignmentAnnotation() != null)
4990 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
4993 .equals(annAlignment.getAlignmentAnnotation()[i].label))
4995 matchedAnnotation = annAlignment.getAlignmentAnnotation()[i];
5000 if (matchedAnnotation == null)
5002 System.err.println("Failed to match annotation colour scheme for "
5006 if (matchedAnnotation.getThreshold() == null)
5008 matchedAnnotation.setThreshold(
5009 new GraphLine(safeFloat(viewAnnColour.getThreshold()),
5010 "Threshold", Color.black));
5013 AnnotationColourGradient cs = null;
5014 if (viewAnnColour.getColourScheme().equals("None"))
5016 cs = new AnnotationColourGradient(matchedAnnotation,
5017 new Color(safeInt(viewAnnColour.getMinColour())),
5018 new Color(safeInt(viewAnnColour.getMaxColour())),
5019 safeInt(viewAnnColour.getAboveThreshold()));
5021 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
5023 cs = new AnnotationColourGradient(matchedAnnotation,
5024 getUserColourScheme(model, viewAnnColour.getColourScheme()),
5025 safeInt(viewAnnColour.getAboveThreshold()));
5029 cs = new AnnotationColourGradient(matchedAnnotation,
5030 ColourSchemeProperty.getColourScheme(al,
5031 viewAnnColour.getColourScheme()),
5032 safeInt(viewAnnColour.getAboveThreshold()));
5035 boolean perSequenceOnly = safeBoolean(viewAnnColour.isPerSequence());
5036 boolean useOriginalColours = safeBoolean(
5037 viewAnnColour.isPredefinedColours());
5038 cs.setSeqAssociated(perSequenceOnly);
5039 cs.setPredefinedColours(useOriginalColours);
5041 if (propagateAnnColour && al.getGroups() != null)
5043 // Also use these settings for all the groups
5044 for (int g = 0; g < al.getGroups().size(); g++)
5046 SequenceGroup sg = al.getGroups().get(g);
5047 if (sg.getGroupColourScheme() == null)
5052 AnnotationColourGradient groupScheme = new AnnotationColourGradient(
5053 matchedAnnotation, sg.getColourScheme(),
5054 safeInt(viewAnnColour.getAboveThreshold()));
5055 sg.setColourScheme(groupScheme);
5056 groupScheme.setSeqAssociated(perSequenceOnly);
5057 groupScheme.setPredefinedColours(useOriginalColours);
5063 private void reorderAutoannotation(AlignFrame af, AlignmentI al,
5064 List<JvAnnotRow> autoAlan)
5066 // copy over visualization settings for autocalculated annotation in the
5068 if (al.getAlignmentAnnotation() != null)
5071 * Kludge for magic autoannotation names (see JAL-811)
5073 String[] magicNames = new String[] { "Consensus", "Quality",
5075 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
5076 Hashtable<String, JvAnnotRow> visan = new Hashtable<>();
5077 for (String nm : magicNames)
5079 visan.put(nm, nullAnnot);
5081 for (JvAnnotRow auan : autoAlan)
5083 visan.put(auan.template.label
5084 + (auan.template.getCalcId() == null ? ""
5085 : "\t" + auan.template.getCalcId()),
5088 int hSize = al.getAlignmentAnnotation().length;
5089 List<JvAnnotRow> reorder = new ArrayList<>();
5090 // work through any autoCalculated annotation already on the view
5091 // removing it if it should be placed in a different location on the
5092 // annotation panel.
5093 List<String> remains = new ArrayList<>(visan.keySet());
5094 for (int h = 0; h < hSize; h++)
5096 jalview.datamodel.AlignmentAnnotation jalan = al
5097 .getAlignmentAnnotation()[h];
5098 if (jalan.autoCalculated)
5101 JvAnnotRow valan = visan.get(k = jalan.label);
5102 if (jalan.getCalcId() != null)
5104 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
5109 // delete the auto calculated row from the alignment
5110 al.deleteAnnotation(jalan, false);
5114 if (valan != nullAnnot)
5116 if (jalan != valan.template)
5118 // newly created autoannotation row instance
5119 // so keep a reference to the visible annotation row
5120 // and copy over all relevant attributes
5121 if (valan.template.graphHeight >= 0)
5124 jalan.graphHeight = valan.template.graphHeight;
5126 jalan.visible = valan.template.visible;
5128 reorder.add(new JvAnnotRow(valan.order, jalan));
5133 // Add any (possibly stale) autocalculated rows that were not appended to
5134 // the view during construction
5135 for (String other : remains)
5137 JvAnnotRow othera = visan.get(other);
5138 if (othera != nullAnnot && othera.template.getCalcId() != null
5139 && othera.template.getCalcId().length() > 0)
5141 reorder.add(othera);
5144 // now put the automatic annotation in its correct place
5145 int s = 0, srt[] = new int[reorder.size()];
5146 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
5147 for (JvAnnotRow jvar : reorder)
5150 srt[s++] = jvar.order;
5153 jalview.util.QuickSort.sort(srt, rws);
5154 // and re-insert the annotation at its correct position
5155 for (JvAnnotRow jvar : rws)
5157 al.addAnnotation(jvar.template, jvar.order);
5159 af.alignPanel.adjustAnnotationHeight();
5163 Hashtable skipList = null;
5166 * TODO remove this method
5169 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
5170 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
5171 * throw new Error("Implementation Error. No skipList defined for this
5172 * Jalview2XML instance."); } return (AlignFrame)
5173 * skipList.get(view.getSequenceSetId()); }
5177 * Check if the Jalview view contained in object should be skipped or not.
5180 * @return true if view's sequenceSetId is a key in skipList
5182 private boolean skipViewport(JalviewModel object)
5184 if (skipList == null)
5188 String id = object.getViewport().get(0).getSequenceSetId();
5189 if (skipList.containsKey(id))
5191 if (Cache.log != null && Cache.log.isDebugEnabled())
5193 Cache.log.debug("Skipping seuqence set id " + id);
5200 public void addToSkipList(AlignFrame af)
5202 if (skipList == null)
5204 skipList = new Hashtable();
5206 skipList.put(af.getViewport().getSequenceSetId(), af);
5209 public void clearSkipList()
5211 if (skipList != null)
5218 private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
5219 boolean ignoreUnrefed)
5221 jalview.datamodel.AlignmentI ds = getDatasetFor(
5222 vamsasSet.getDatasetId());
5223 Vector dseqs = null;
5226 // create a list of new dataset sequences
5227 dseqs = new Vector();
5229 for (int i = 0, iSize = vamsasSet.getSequence().size(); i < iSize; i++)
5231 Sequence vamsasSeq = vamsasSet.getSequence().get(i);
5232 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed, i);
5234 // create a new dataset
5237 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
5238 dseqs.copyInto(dsseqs);
5239 ds = new jalview.datamodel.Alignment(dsseqs);
5240 debug("Created new dataset " + vamsasSet.getDatasetId()
5241 + " for alignment " + System.identityHashCode(al));
5242 addDatasetRef(vamsasSet.getDatasetId(), ds);
5244 // set the dataset for the newly imported alignment.
5245 if (al.getDataset() == null && !ignoreUnrefed)
5254 * sequence definition to create/merge dataset sequence for
5258 * vector to add new dataset sequence to
5259 * @param ignoreUnrefed
5260 * - when true, don't create new sequences from vamsasSeq if it's id
5261 * doesn't already have an asssociated Jalview sequence.
5263 * - used to reorder the sequence in the alignment according to the
5264 * vamsasSeq array ordering, to preserve ordering of dataset
5266 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
5267 AlignmentI ds, Vector dseqs, boolean ignoreUnrefed, int vseqpos)
5269 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
5271 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
5272 boolean reorder = false;
5273 SequenceI dsq = null;
5274 if (sq != null && sq.getDatasetSequence() != null)
5276 dsq = sq.getDatasetSequence();
5282 if (sq == null && ignoreUnrefed)
5286 String sqid = vamsasSeq.getDsseqid();
5289 // need to create or add a new dataset sequence reference to this sequence
5292 dsq = seqRefIds.get(sqid);
5297 // make a new dataset sequence
5298 dsq = sq.createDatasetSequence();
5301 // make up a new dataset reference for this sequence
5302 sqid = seqHash(dsq);
5304 dsq.setVamsasId(uniqueSetSuffix + sqid);
5305 seqRefIds.put(sqid, dsq);
5310 dseqs.addElement(dsq);
5315 ds.addSequence(dsq);
5321 { // make this dataset sequence sq's dataset sequence
5322 sq.setDatasetSequence(dsq);
5323 // and update the current dataset alignment
5328 if (!dseqs.contains(dsq))
5335 if (ds.findIndex(dsq) < 0)
5337 ds.addSequence(dsq);
5344 // TODO: refactor this as a merge dataset sequence function
5345 // now check that sq (the dataset sequence) sequence really is the union of
5346 // all references to it
5347 // boolean pre = sq.getStart() < dsq.getStart();
5348 // boolean post = sq.getEnd() > dsq.getEnd();
5352 // StringBuffer sb = new StringBuffer();
5353 String newres = jalview.analysis.AlignSeq.extractGaps(
5354 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
5355 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
5356 && newres.length() > dsq.getLength())
5358 // Update with the longer sequence.
5362 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
5363 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
5364 * sb.append(newres.substring(newres.length() - sq.getEnd() -
5365 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
5367 dsq.setSequence(newres);
5369 // TODO: merges will never happen if we 'know' we have the real dataset
5370 // sequence - this should be detected when id==dssid
5372 "DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
5373 // + (pre ? "prepended" : "") + " "
5374 // + (post ? "appended" : ""));
5379 // sequence refs are identical. We may need to update the existing dataset
5380 // alignment with this one, though.
5381 if (ds != null && dseqs == null)
5383 int opos = ds.findIndex(dsq);
5384 SequenceI tseq = null;
5385 if (opos != -1 && vseqpos != opos)
5387 // remove from old position
5388 ds.deleteSequence(dsq);
5390 if (vseqpos < ds.getHeight())
5392 if (vseqpos != opos)
5394 // save sequence at destination position
5395 tseq = ds.getSequenceAt(vseqpos);
5396 ds.replaceSequenceAt(vseqpos, dsq);
5397 ds.addSequence(tseq);
5402 ds.addSequence(dsq);
5409 * TODO use AlignmentI here and in related methods - needs
5410 * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
5412 Hashtable<String, AlignmentI> datasetIds = null;
5414 IdentityHashMap<AlignmentI, String> dataset2Ids = null;
5416 private AlignmentI getDatasetFor(String datasetId)
5418 if (datasetIds == null)
5420 datasetIds = new Hashtable<>();
5423 if (datasetIds.containsKey(datasetId))
5425 return datasetIds.get(datasetId);
5430 private void addDatasetRef(String datasetId, AlignmentI dataset)
5432 if (datasetIds == null)
5434 datasetIds = new Hashtable<>();
5436 datasetIds.put(datasetId, dataset);
5440 * make a new dataset ID for this jalview dataset alignment
5445 private String getDatasetIdRef(AlignmentI dataset)
5447 if (dataset.getDataset() != null)
5449 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
5451 String datasetId = makeHashCode(dataset, null);
5452 if (datasetId == null)
5454 // make a new datasetId and record it
5455 if (dataset2Ids == null)
5457 dataset2Ids = new IdentityHashMap<>();
5461 datasetId = dataset2Ids.get(dataset);
5463 if (datasetId == null)
5465 datasetId = "ds" + dataset2Ids.size() + 1;
5466 dataset2Ids.put(dataset, datasetId);
5472 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
5474 for (int d = 0; d < sequence.getDBRef().size(); d++)
5476 DBRef dr = sequence.getDBRef().get(d);
5477 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
5478 dr.getSource(), dr.getVersion(), dr.getAccessionId());
5479 if (dr.getMapping() != null)
5481 entry.setMap(addMapping(dr.getMapping()));
5483 datasetSequence.addDBRef(entry);
5487 private jalview.datamodel.Mapping addMapping(Mapping m)
5489 SequenceI dsto = null;
5490 // Mapping m = dr.getMapping();
5491 int fr[] = new int[m.getMapListFrom().size() * 2];
5492 Iterator<MapListFrom> from = m.getMapListFrom().iterator();// enumerateMapListFrom();
5493 for (int _i = 0; from.hasNext(); _i += 2)
5495 MapListFrom mf = from.next();
5496 fr[_i] = mf.getStart();
5497 fr[_i + 1] = mf.getEnd();
5499 int fto[] = new int[m.getMapListTo().size() * 2];
5500 Iterator<MapListTo> to = m.getMapListTo().iterator();// enumerateMapListTo();
5501 for (int _i = 0; to.hasNext(); _i += 2)
5503 MapListTo mf = to.next();
5504 fto[_i] = mf.getStart();
5505 fto[_i + 1] = mf.getEnd();
5507 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto, fr,
5508 fto, m.getMapFromUnit().intValue(),
5509 m.getMapToUnit().intValue());
5510 // if (m.getMappingChoice() != null)
5512 // MappingChoice mc = m.getMappingChoice();
5513 if (m.getDseqFor() != null)
5515 String dsfor = m.getDseqFor();
5516 if (seqRefIds.containsKey(dsfor))
5521 jmap.setTo(seqRefIds.get(dsfor));
5525 frefedSequence.add(newMappingRef(dsfor, jmap));
5531 * local sequence definition
5533 Sequence ms = m.getSequence();
5534 SequenceI djs = null;
5535 String sqid = ms.getDsseqid();
5536 if (sqid != null && sqid.length() > 0)
5539 * recover dataset sequence
5541 djs = seqRefIds.get(sqid);
5546 "Warning - making up dataset sequence id for DbRef sequence map reference");
5547 sqid = ((Object) ms).toString(); // make up a new hascode for
5548 // undefined dataset sequence hash
5549 // (unlikely to happen)
5555 * make a new dataset sequence and add it to refIds hash
5557 djs = new jalview.datamodel.Sequence(ms.getName(),
5559 djs.setStart(jmap.getMap().getToLowest());
5560 djs.setEnd(jmap.getMap().getToHighest());
5561 djs.setVamsasId(uniqueSetSuffix + sqid);
5563 incompleteSeqs.put(sqid, djs);
5564 seqRefIds.put(sqid, djs);
5567 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
5576 * Provides a 'copy' of an alignment view (on action New View) by 'saving' the
5577 * view as XML (but not to file), and then reloading it
5582 public AlignmentPanel copyAlignPanel(AlignmentPanel ap)
5585 JalviewModel jm = saveState(ap, null, null, null);
5587 uniqueSetSuffix = "";
5588 // jm.getJalviewModelSequence().getViewport(0).setId(null);
5589 jm.getViewport().get(0).setId(null);
5590 // we don't overwrite the view we just copied
5592 if (this.frefedSequence == null)
5594 frefedSequence = new Vector<>();
5597 viewportsAdded.clear();
5599 AlignFrame af = loadFromObject(jm, null, false, null);
5600 af.getAlignPanels().clear();
5601 af.closeMenuItem_actionPerformed(true);
5604 * if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
5605 * i<ap.av.getAlignment().getAlignmentAnnotation().length; i++) {
5606 * if(!ap.av.getAlignment().getAlignmentAnnotation()[i].autoCalculated) {
5607 * af.alignPanel.av.getAlignment().getAlignmentAnnotation()[i] =
5608 * ap.av.getAlignment().getAlignmentAnnotation()[i]; } } }
5611 return af.alignPanel;
5614 private Hashtable jvids2vobj;
5616 private void warn(String msg)
5621 private void warn(String msg, Exception e)
5623 if (Cache.log != null)
5627 Cache.log.warn(msg, e);
5631 Cache.log.warn(msg);
5636 System.err.println("Warning: " + msg);
5639 e.printStackTrace();
5644 private void debug(String string)
5646 debug(string, null);
5649 private void debug(String msg, Exception e)
5651 if (Cache.log != null)
5655 Cache.log.debug(msg, e);
5659 Cache.log.debug(msg);
5664 System.err.println("Warning: " + msg);
5667 e.printStackTrace();
5673 * set the object to ID mapping tables used to write/recover objects and XML
5674 * ID strings for the jalview project. If external tables are provided then
5675 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
5676 * object goes out of scope. - also populates the datasetIds hashtable with
5677 * alignment objects containing dataset sequences
5680 * Map from ID strings to jalview datamodel
5682 * Map from jalview datamodel to ID strings
5686 public void setObjectMappingTables(Hashtable vobj2jv,
5687 IdentityHashMap jv2vobj)
5689 this.jv2vobj = jv2vobj;
5690 this.vobj2jv = vobj2jv;
5691 Iterator ds = jv2vobj.keySet().iterator();
5693 while (ds.hasNext())
5695 Object jvobj = ds.next();
5696 id = jv2vobj.get(jvobj).toString();
5697 if (jvobj instanceof jalview.datamodel.Alignment)
5699 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
5701 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
5704 else if (jvobj instanceof jalview.datamodel.Sequence)
5706 // register sequence object so the XML parser can recover it.
5707 if (seqRefIds == null)
5709 seqRefIds = new HashMap<>();
5711 if (seqsToIds == null)
5713 seqsToIds = new IdentityHashMap<>();
5715 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
5716 seqsToIds.put((SequenceI) jvobj, id);
5718 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
5721 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
5722 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
5723 if (jvann.annotationId == null)
5725 jvann.annotationId = anid;
5727 if (!jvann.annotationId.equals(anid))
5729 // TODO verify that this is the correct behaviour
5730 this.warn("Overriding Annotation ID for " + anid
5731 + " from different id : " + jvann.annotationId);
5732 jvann.annotationId = anid;
5735 else if (jvobj instanceof String)
5737 if (jvids2vobj == null)
5739 jvids2vobj = new Hashtable();
5740 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
5745 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
5751 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
5752 * objects created from the project archive. If string is null (default for
5753 * construction) then suffix will be set automatically.
5757 public void setUniqueSetSuffix(String string)
5759 uniqueSetSuffix = string;
5764 * uses skipList2 as the skipList for skipping views on sequence sets
5765 * associated with keys in the skipList
5769 public void setSkipList(Hashtable skipList2)
5771 skipList = skipList2;
5775 * Reads the jar entry of given name and returns its contents, or null if the
5776 * entry is not found.
5779 * @param jarEntryName
5782 protected String readJarEntry(jarInputStreamProvider jprovider,
5783 String jarEntryName)
5785 String result = null;
5786 BufferedReader in = null;
5791 * Reopen the jar input stream and traverse its entries to find a matching
5794 JarInputStream jin = jprovider.getJarInputStream();
5795 JarEntry entry = null;
5798 entry = jin.getNextJarEntry();
5799 } while (entry != null && !entry.getName().equals(jarEntryName));
5803 StringBuilder out = new StringBuilder(256);
5804 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
5807 while ((data = in.readLine()) != null)
5811 result = out.toString();
5815 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
5817 } catch (Exception ex)
5819 ex.printStackTrace();
5827 } catch (IOException e)
5838 * Returns an incrementing counter (0, 1, 2...)
5842 private synchronized int nextCounter()
5848 * Populates an XML model of the feature colour scheme for one feature type
5850 * @param featureType
5854 public static Colour marshalColour(
5855 String featureType, FeatureColourI fcol)
5857 Colour col = new Colour();
5858 if (fcol.isSimpleColour())
5860 col.setRGB(Format.getHexString(fcol.getColour()));
5864 col.setRGB(Format.getHexString(fcol.getMaxColour()));
5865 col.setMin(fcol.getMin());
5866 col.setMax(fcol.getMax());
5867 col.setMinRGB(jalview.util.Format.getHexString(fcol.getMinColour()));
5868 col.setAutoScale(fcol.isAutoScaled());
5869 col.setThreshold(fcol.getThreshold());
5870 col.setColourByLabel(fcol.isColourByLabel());
5871 col.setThreshType(fcol.isAboveThreshold() ? ThresholdType.ABOVE
5872 : (fcol.isBelowThreshold() ? ThresholdType.BELOW
5873 : ThresholdType.NONE));
5874 if (fcol.isColourByAttribute())
5876 final String[] attName = fcol.getAttributeName();
5877 col.getAttributeName().add(attName[0]);
5878 if (attName.length > 1)
5880 col.getAttributeName().add(attName[1]);
5883 Color noColour = fcol.getNoColour();
5884 if (noColour == null)
5886 col.setNoValueColour(NoValueColour.NONE);
5888 else if (noColour == fcol.getMaxColour())
5890 col.setNoValueColour(NoValueColour.MAX);
5894 col.setNoValueColour(NoValueColour.MIN);
5897 col.setName(featureType);
5902 * Populates an XML model of the feature filter(s) for one feature type
5904 * @param firstMatcher
5905 * the first (or only) match condition)
5907 * remaining match conditions (if any)
5909 * if true, conditions are and-ed, else or-ed
5911 public static jalview.xml.binding.jalview.FeatureMatcherSet marshalFilter(
5912 FeatureMatcherI firstMatcher, Iterator<FeatureMatcherI> filters,
5915 jalview.xml.binding.jalview.FeatureMatcherSet result = new jalview.xml.binding.jalview.FeatureMatcherSet();
5917 if (filters.hasNext())
5922 CompoundMatcher compound = new CompoundMatcher();
5923 compound.setAnd(and);
5924 jalview.xml.binding.jalview.FeatureMatcherSet matcher1 = marshalFilter(
5925 firstMatcher, Collections.emptyIterator(), and);
5926 // compound.addMatcherSet(matcher1);
5927 compound.getMatcherSet().add(matcher1);
5928 FeatureMatcherI nextMatcher = filters.next();
5929 jalview.xml.binding.jalview.FeatureMatcherSet matcher2 = marshalFilter(
5930 nextMatcher, filters, and);
5931 // compound.addMatcherSet(matcher2);
5932 compound.getMatcherSet().add(matcher2);
5933 result.setCompoundMatcher(compound);
5938 * single condition matcher
5940 // MatchCondition matcherModel = new MatchCondition();
5941 jalview.xml.binding.jalview.FeatureMatcher matcherModel = new jalview.xml.binding.jalview.FeatureMatcher();
5942 matcherModel.setCondition(
5943 firstMatcher.getMatcher().getCondition().getStableName());
5944 matcherModel.setValue(firstMatcher.getMatcher().getPattern());
5945 if (firstMatcher.isByAttribute())
5947 matcherModel.setBy(FilterBy.BY_ATTRIBUTE);
5948 // matcherModel.setAttributeName(firstMatcher.getAttribute());
5949 String[] attName = firstMatcher.getAttribute();
5950 matcherModel.getAttributeName().add(attName[0]); // attribute
5951 if (attName.length > 1)
5953 matcherModel.getAttributeName().add(attName[1]); // sub-attribute
5956 else if (firstMatcher.isByLabel())
5958 matcherModel.setBy(FilterBy.BY_LABEL);
5960 else if (firstMatcher.isByScore())
5962 matcherModel.setBy(FilterBy.BY_SCORE);
5964 result.setMatchCondition(matcherModel);
5971 * Loads one XML model of a feature filter to a Jalview object
5973 * @param featureType
5974 * @param matcherSetModel
5977 public static FeatureMatcherSetI parseFilter(
5979 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel)
5981 FeatureMatcherSetI result = new FeatureMatcherSet();
5984 parseFilterConditions(result, matcherSetModel, true);
5985 } catch (IllegalStateException e)
5987 // mixing AND and OR conditions perhaps
5989 String.format("Error reading filter conditions for '%s': %s",
5990 featureType, e.getMessage()));
5991 // return as much as was parsed up to the error
5998 * Adds feature match conditions to matcherSet as unmarshalled from XML
5999 * (possibly recursively for compound conditions)
6002 * @param matcherSetModel
6004 * if true, multiple conditions are AND-ed, else they are OR-ed
6005 * @throws IllegalStateException
6006 * if AND and OR conditions are mixed
6008 protected static void parseFilterConditions(
6009 FeatureMatcherSetI matcherSet,
6010 jalview.xml.binding.jalview.FeatureMatcherSet matcherSetModel,
6013 jalview.xml.binding.jalview.FeatureMatcher mc = matcherSetModel
6014 .getMatchCondition();
6020 FilterBy filterBy = mc.getBy();
6021 Condition cond = Condition.fromString(mc.getCondition());
6022 String pattern = mc.getValue();
6023 FeatureMatcherI matchCondition = null;
6024 if (filterBy == FilterBy.BY_LABEL)
6026 matchCondition = FeatureMatcher.byLabel(cond, pattern);
6028 else if (filterBy == FilterBy.BY_SCORE)
6030 matchCondition = FeatureMatcher.byScore(cond, pattern);
6033 else if (filterBy == FilterBy.BY_ATTRIBUTE)
6035 final List<String> attributeName = mc.getAttributeName();
6036 String[] attNames = attributeName
6037 .toArray(new String[attributeName.size()]);
6038 matchCondition = FeatureMatcher.byAttribute(cond, pattern,
6043 * note this throws IllegalStateException if AND-ing to a
6044 * previously OR-ed compound condition, or vice versa
6048 matcherSet.and(matchCondition);
6052 matcherSet.or(matchCondition);
6058 * compound condition
6060 List<jalview.xml.binding.jalview.FeatureMatcherSet> matchers = matcherSetModel
6061 .getCompoundMatcher().getMatcherSet();
6062 boolean anded = matcherSetModel.getCompoundMatcher().isAnd();
6063 if (matchers.size() == 2)
6065 parseFilterConditions(matcherSet, matchers.get(0), anded);
6066 parseFilterConditions(matcherSet, matchers.get(1), anded);
6070 System.err.println("Malformed compound filter condition");
6076 * Loads one XML model of a feature colour to a Jalview object
6078 * @param colourModel
6081 public static FeatureColourI parseColour(Colour colourModel)
6083 FeatureColourI colour = null;
6085 if (colourModel.getMax() != null)
6087 Color mincol = null;
6088 Color maxcol = null;
6089 Color noValueColour = null;
6093 mincol = new Color(Integer.parseInt(colourModel.getMinRGB(), 16));
6094 maxcol = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6095 } catch (Exception e)
6097 Cache.log.warn("Couldn't parse out graduated feature color.", e);
6100 NoValueColour noCol = colourModel.getNoValueColour();
6101 if (noCol == NoValueColour.MIN)
6103 noValueColour = mincol;
6105 else if (noCol == NoValueColour.MAX)
6107 noValueColour = maxcol;
6110 colour = new FeatureColour(mincol, maxcol, noValueColour,
6111 safeFloat(colourModel.getMin()),
6112 safeFloat(colourModel.getMax()));
6113 final List<String> attributeName = colourModel.getAttributeName();
6114 String[] attributes = attributeName
6115 .toArray(new String[attributeName.size()]);
6116 if (attributes != null && attributes.length > 0)
6118 colour.setAttributeName(attributes);
6120 if (colourModel.isAutoScale() != null)
6122 colour.setAutoScaled(colourModel.isAutoScale().booleanValue());
6124 if (colourModel.isColourByLabel() != null)
6126 colour.setColourByLabel(
6127 colourModel.isColourByLabel().booleanValue());
6129 if (colourModel.getThreshold() != null)
6131 colour.setThreshold(colourModel.getThreshold().floatValue());
6133 ThresholdType ttyp = colourModel.getThreshType();
6134 if (ttyp == ThresholdType.ABOVE)
6136 colour.setAboveThreshold(true);
6138 else if (ttyp == ThresholdType.BELOW)
6140 colour.setBelowThreshold(true);
6145 Color color = new Color(Integer.parseInt(colourModel.getRGB(), 16));
6146 colour = new FeatureColour(color);