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.
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.ext.varna.RnaModel;
41 import jalview.gui.StructureViewer.ViewerType;
42 import jalview.io.DataSourceType;
43 import jalview.io.FileFormat;
44 import jalview.renderer.ResidueShaderI;
45 import jalview.schemabinding.version2.AlcodMap;
46 import jalview.schemabinding.version2.AlcodonFrame;
47 import jalview.schemabinding.version2.Annotation;
48 import jalview.schemabinding.version2.AnnotationColours;
49 import jalview.schemabinding.version2.AnnotationElement;
50 import jalview.schemabinding.version2.CalcIdParam;
51 import jalview.schemabinding.version2.DBRef;
52 import jalview.schemabinding.version2.Features;
53 import jalview.schemabinding.version2.Group;
54 import jalview.schemabinding.version2.HiddenColumns;
55 import jalview.schemabinding.version2.JGroup;
56 import jalview.schemabinding.version2.JSeq;
57 import jalview.schemabinding.version2.JalviewModel;
58 import jalview.schemabinding.version2.JalviewModelSequence;
59 import jalview.schemabinding.version2.MapListFrom;
60 import jalview.schemabinding.version2.MapListTo;
61 import jalview.schemabinding.version2.Mapping;
62 import jalview.schemabinding.version2.MappingChoice;
63 import jalview.schemabinding.version2.OtherData;
64 import jalview.schemabinding.version2.PdbentryItem;
65 import jalview.schemabinding.version2.Pdbids;
66 import jalview.schemabinding.version2.Property;
67 import jalview.schemabinding.version2.RnaViewer;
68 import jalview.schemabinding.version2.SecondaryStructure;
69 import jalview.schemabinding.version2.Sequence;
70 import jalview.schemabinding.version2.SequenceSet;
71 import jalview.schemabinding.version2.SequenceSetProperties;
72 import jalview.schemabinding.version2.Setting;
73 import jalview.schemabinding.version2.StructureState;
74 import jalview.schemabinding.version2.ThresholdLine;
75 import jalview.schemabinding.version2.Tree;
76 import jalview.schemabinding.version2.UserColours;
77 import jalview.schemabinding.version2.Viewport;
78 import jalview.schemes.AnnotationColourGradient;
79 import jalview.schemes.ColourSchemeI;
80 import jalview.schemes.ColourSchemeProperty;
81 import jalview.schemes.FeatureColour;
82 import jalview.schemes.ResidueProperties;
83 import jalview.schemes.UserColourScheme;
84 import jalview.structure.StructureSelectionManager;
85 import jalview.structures.models.AAStructureBindingModel;
86 import jalview.util.MessageManager;
87 import jalview.util.Platform;
88 import jalview.util.StringUtils;
89 import jalview.util.jarInputStreamProvider;
90 import jalview.viewmodel.AlignmentViewport;
91 import jalview.viewmodel.ViewportRanges;
92 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
93 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
94 import jalview.ws.jws2.Jws2Discoverer;
95 import jalview.ws.jws2.dm.AAConSettings;
96 import jalview.ws.jws2.jabaws2.Jws2Instance;
97 import jalview.ws.params.ArgumentI;
98 import jalview.ws.params.AutoCalcSetting;
99 import jalview.ws.params.WsParamSetI;
101 import java.awt.Color;
102 import java.awt.Rectangle;
103 import java.io.BufferedReader;
104 import java.io.DataInputStream;
105 import java.io.DataOutputStream;
107 import java.io.FileInputStream;
108 import java.io.FileOutputStream;
109 import java.io.IOException;
110 import java.io.InputStreamReader;
111 import java.io.OutputStreamWriter;
112 import java.io.PrintWriter;
113 import java.lang.reflect.InvocationTargetException;
114 import java.net.MalformedURLException;
116 import java.util.ArrayList;
117 import java.util.Arrays;
118 import java.util.Enumeration;
119 import java.util.HashMap;
120 import java.util.HashSet;
121 import java.util.Hashtable;
122 import java.util.IdentityHashMap;
123 import java.util.Iterator;
124 import java.util.LinkedHashMap;
125 import java.util.List;
126 import java.util.Map;
127 import java.util.Map.Entry;
128 import java.util.Set;
129 import java.util.Vector;
130 import java.util.jar.JarEntry;
131 import java.util.jar.JarInputStream;
132 import java.util.jar.JarOutputStream;
134 import javax.swing.JInternalFrame;
135 import javax.swing.SwingUtilities;
137 import org.exolab.castor.xml.Marshaller;
138 import org.exolab.castor.xml.Unmarshaller;
141 * Write out the current jalview desktop state as a Jalview XML stream.
143 * Note: the vamsas objects referred to here are primitive versions of the
144 * VAMSAS project schema elements - they are not the same and most likely never
148 * @version $Revision: 1.134 $
150 public class Jalview2XML
152 private static final String VIEWER_PREFIX = "viewer_";
154 private static final String RNA_PREFIX = "rna_";
156 private static final String UTF_8 = "UTF-8";
158 // use this with nextCounter() to make unique names for entities
159 private int counter = 0;
162 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
163 * of sequence objects are created.
165 IdentityHashMap<SequenceI, String> seqsToIds = null;
168 * jalview XML Sequence ID to jalview sequence object reference (both dataset
169 * and alignment sequences. Populated as XML reps of sequence objects are
172 Map<String, SequenceI> seqRefIds = null;
174 Map<String, SequenceI> incompleteSeqs = null;
176 List<SeqFref> frefedSequence = null;
178 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
181 * Map of reconstructed AlignFrame objects that appear to have come from
182 * SplitFrame objects (have a dna/protein complement view).
184 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<>();
187 * Map from displayed rna structure models to their saved session state jar
190 private Map<RnaModel, String> rnaSessions = new HashMap<>();
193 * create/return unique hash string for sq
196 * @return new or existing unique string for sq
198 String seqHash(SequenceI sq)
200 if (seqsToIds == null)
204 if (seqsToIds.containsKey(sq))
206 return seqsToIds.get(sq);
210 // create sequential key
211 String key = "sq" + (seqsToIds.size() + 1);
212 key = makeHashCode(sq, key); // check we don't have an external reference
214 seqsToIds.put(sq, key);
223 if (seqRefIds != null)
227 if (seqsToIds != null)
231 if (incompleteSeqs != null)
233 incompleteSeqs.clear();
241 warn("clearSeqRefs called when _cleartables was not set. Doing nothing.");
242 // seqRefIds = new Hashtable();
243 // seqsToIds = new IdentityHashMap();
249 if (seqsToIds == null)
251 seqsToIds = new IdentityHashMap<>();
253 if (seqRefIds == null)
255 seqRefIds = new HashMap<>();
257 if (incompleteSeqs == null)
259 incompleteSeqs = new HashMap<>();
261 if (frefedSequence == null)
263 frefedSequence = new ArrayList<>();
271 public Jalview2XML(boolean raiseGUI)
273 this.raiseGUI = raiseGUI;
277 * base class for resolving forward references to sequences by their ID
282 abstract class SeqFref
288 public SeqFref(String _sref, String type)
294 public String getSref()
299 public SequenceI getSrefSeq()
301 return seqRefIds.get(sref);
304 public boolean isResolvable()
306 return seqRefIds.get(sref) != null;
309 public SequenceI getSrefDatasetSeq()
311 SequenceI sq = seqRefIds.get(sref);
314 while (sq.getDatasetSequence() != null)
316 sq = sq.getDatasetSequence();
323 * @return true if the forward reference was fully resolved
325 abstract boolean resolve();
328 public String toString()
330 return type + " reference to " + sref;
335 * create forward reference for a mapping
341 public SeqFref newMappingRef(final String sref,
342 final jalview.datamodel.Mapping _jmap)
344 SeqFref fref = new SeqFref(sref, "Mapping")
346 public jalview.datamodel.Mapping jmap = _jmap;
351 SequenceI seq = getSrefDatasetSeq();
363 public SeqFref newAlcodMapRef(final String sref,
364 final AlignedCodonFrame _cf, final jalview.datamodel.Mapping _jmap)
367 SeqFref fref = new SeqFref(sref, "Codon Frame")
369 AlignedCodonFrame cf = _cf;
371 public jalview.datamodel.Mapping mp = _jmap;
374 public boolean isResolvable()
376 return super.isResolvable() && mp.getTo() != null;
382 SequenceI seq = getSrefDatasetSeq();
387 cf.addMap(seq, mp.getTo(), mp.getMap());
394 public void resolveFrefedSequences()
396 Iterator<SeqFref> nextFref = frefedSequence.iterator();
397 int toresolve = frefedSequence.size();
398 int unresolved = 0, failedtoresolve = 0;
399 while (nextFref.hasNext())
401 SeqFref ref = nextFref.next();
402 if (ref.isResolvable())
414 } catch (Exception x)
417 .println("IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
430 System.err.println("Jalview Project Import: There were " + unresolved
431 + " forward references left unresolved on the stack.");
433 if (failedtoresolve > 0)
435 System.err.println("SERIOUS! " + failedtoresolve
436 + " resolvable forward references failed to resolve.");
438 if (incompleteSeqs != null && incompleteSeqs.size() > 0)
440 System.err.println("Jalview Project Import: There are "
441 + incompleteSeqs.size()
442 + " sequences which may have incomplete metadata.");
443 if (incompleteSeqs.size() < 10)
445 for (SequenceI s : incompleteSeqs.values())
447 System.err.println(s.toString());
453 .println("Too many to report. Skipping output of incomplete sequences.");
459 * This maintains a map of viewports, the key being the seqSetId. Important to
460 * set historyItem and redoList for multiple views
462 Map<String, AlignViewport> viewportsAdded = new HashMap<>();
464 Map<String, AlignmentAnnotation> annotationIds = new HashMap<>();
466 String uniqueSetSuffix = "";
469 * List of pdbfiles added to Jar
471 List<String> pdbfiles = null;
473 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
474 public void saveState(File statefile)
476 FileOutputStream fos = null;
479 fos = new FileOutputStream(statefile);
480 JarOutputStream jout = new JarOutputStream(fos);
483 } catch (Exception e)
485 // TODO: inform user of the problem - they need to know if their data was
487 if (errorMessage == null)
489 errorMessage = "Couldn't write Jalview Archive to output file '"
490 + statefile + "' - See console error log for details";
494 errorMessage += "(output file was '" + statefile + "')";
504 } catch (IOException e)
514 * Writes a jalview project archive to the given Jar output stream.
518 public void saveState(JarOutputStream jout)
520 AlignFrame[] frames = Desktop.getAlignFrames();
526 saveAllFrames(Arrays.asList(frames), jout);
530 * core method for storing state for a set of AlignFrames.
533 * - frames involving all data to be exported (including containing
536 * - project output stream
538 private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
540 Hashtable<String, AlignFrame> dsses = new Hashtable<>();
543 * ensure cached data is clear before starting
545 // todo tidy up seqRefIds, seqsToIds initialisation / reset
547 splitFrameCandidates.clear();
552 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
553 // //////////////////////////////////////////////////
555 List<String> shortNames = new ArrayList<>();
556 List<String> viewIds = new ArrayList<>();
559 for (int i = frames.size() - 1; i > -1; i--)
561 AlignFrame af = frames.get(i);
565 .containsKey(af.getViewport().getSequenceSetId()))
570 String shortName = makeFilename(af, shortNames);
572 int ap, apSize = af.alignPanels.size();
574 for (ap = 0; ap < apSize; ap++)
576 AlignmentPanel apanel = af.alignPanels.get(ap);
577 String fileName = apSize == 1 ? shortName : ap + shortName;
578 if (!fileName.endsWith(".xml"))
580 fileName = fileName + ".xml";
583 saveState(apanel, fileName, jout, viewIds);
585 String dssid = getDatasetIdRef(af.getViewport().getAlignment()
587 if (!dsses.containsKey(dssid))
589 dsses.put(dssid, af);
594 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
600 } catch (Exception foo)
605 } catch (Exception ex)
607 // TODO: inform user of the problem - they need to know if their data was
609 if (errorMessage == null)
611 errorMessage = "Couldn't write Jalview Archive - see error output for details";
613 ex.printStackTrace();
618 * Generates a distinct file name, based on the title of the AlignFrame, by
619 * appending _n for increasing n until an unused name is generated. The new
620 * name (without its extension) is added to the list.
624 * @return the generated name, with .xml extension
626 protected String makeFilename(AlignFrame af, List<String> namesUsed)
628 String shortName = af.getTitle();
630 if (shortName.indexOf(File.separatorChar) > -1)
632 shortName = shortName.substring(shortName
633 .lastIndexOf(File.separatorChar) + 1);
638 while (namesUsed.contains(shortName))
640 if (shortName.endsWith("_" + (count - 1)))
642 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
645 shortName = shortName.concat("_" + count);
649 namesUsed.add(shortName);
651 if (!shortName.endsWith(".xml"))
653 shortName = shortName + ".xml";
658 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
659 public boolean saveAlignment(AlignFrame af, String jarFile,
664 FileOutputStream fos = new FileOutputStream(jarFile);
665 JarOutputStream jout = new JarOutputStream(fos);
666 List<AlignFrame> frames = new ArrayList<>();
668 // resolve splitframes
669 if (af.getViewport().getCodingComplement() != null)
671 frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
677 saveAllFrames(frames, jout);
681 } catch (Exception foo)
687 } catch (Exception ex)
689 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
690 ex.printStackTrace();
695 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
696 String fileName, JarOutputStream jout)
699 for (String dssids : dsses.keySet())
701 AlignFrame _af = dsses.get(dssids);
702 String jfileName = fileName + " Dataset for " + _af.getTitle();
703 if (!jfileName.endsWith(".xml"))
705 jfileName = jfileName + ".xml";
707 saveState(_af.alignPanel, jfileName, true, jout, null);
712 * create a JalviewModel from an alignment view and marshall it to a
716 * panel to create jalview model for
718 * name of alignment panel written to output stream
725 public JalviewModel saveState(AlignmentPanel ap, String fileName,
726 JarOutputStream jout, List<String> viewIds)
728 return saveState(ap, fileName, false, jout, viewIds);
732 * create a JalviewModel from an alignment view and marshall it to a
736 * panel to create jalview model for
738 * name of alignment panel written to output stream
740 * when true, only write the dataset for the alignment, not the data
741 * associated with the view.
747 public JalviewModel saveState(AlignmentPanel ap, String fileName,
748 boolean storeDS, JarOutputStream jout, List<String> viewIds)
752 viewIds = new ArrayList<>();
757 List<UserColourScheme> userColours = new ArrayList<>();
759 AlignViewport av = ap.av;
760 ViewportRanges vpRanges = av.getRanges();
762 JalviewModel object = new JalviewModel();
763 object.setVamsasModel(new jalview.schemabinding.version2.VamsasModel());
765 object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
766 object.setVersion(jalview.bin.Cache.getDefault("VERSION",
767 "Development Build"));
770 * rjal is full height alignment, jal is actual alignment with full metadata
771 * but excludes hidden sequences.
773 jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
775 if (av.hasHiddenRows())
777 rjal = jal.getHiddenSequences().getFullAlignment();
780 SequenceSet vamsasSet = new SequenceSet();
782 JalviewModelSequence jms = new JalviewModelSequence();
784 vamsasSet.setGapChar(jal.getGapCharacter() + "");
786 if (jal.getDataset() != null)
788 // dataset id is the dataset's hashcode
789 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
792 // switch jal and the dataset
793 jal = jal.getDataset();
797 if (jal.getProperties() != null)
799 Enumeration en = jal.getProperties().keys();
800 while (en.hasMoreElements())
802 String key = en.nextElement().toString();
803 SequenceSetProperties ssp = new SequenceSetProperties();
805 ssp.setValue(jal.getProperties().get(key).toString());
806 vamsasSet.addSequenceSetProperties(ssp);
811 Set<String> calcIdSet = new HashSet<>();
812 // record the set of vamsas sequence XML POJO we create.
813 HashMap<String, Sequence> vamsasSetIds = new HashMap<>();
815 for (final SequenceI jds : rjal.getSequences())
817 final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
818 : jds.getDatasetSequence();
819 String id = seqHash(jds);
820 if (vamsasSetIds.get(id) == null)
822 if (seqRefIds.get(id) != null && !storeDS)
824 // This happens for two reasons: 1. multiple views are being
826 // 2. the hashCode has collided with another sequence's code. This
828 // HAPPEN! (PF00072.15.stk does this)
829 // JBPNote: Uncomment to debug writing out of files that do not read
830 // back in due to ArrayOutOfBoundExceptions.
831 // System.err.println("vamsasSeq backref: "+id+"");
832 // System.err.println(jds.getName()+"
833 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
834 // System.err.println("Hashcode: "+seqHash(jds));
835 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
836 // System.err.println(rsq.getName()+"
837 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
838 // System.err.println("Hashcode: "+seqHash(rsq));
842 vamsasSeq = createVamsasSequence(id, jds);
843 vamsasSet.addSequence(vamsasSeq);
844 vamsasSetIds.put(id, vamsasSeq);
845 seqRefIds.put(id, jds);
849 jseq.setStart(jds.getStart());
850 jseq.setEnd(jds.getEnd());
851 jseq.setColour(av.getSequenceColour(jds).getRGB());
853 jseq.setId(id); // jseq id should be a string not a number
856 // Store any sequences this sequence represents
857 if (av.hasHiddenRows())
859 // use rjal, contains the full height alignment
860 jseq.setHidden(av.getAlignment().getHiddenSequences()
863 if (av.isHiddenRepSequence(jds))
865 jalview.datamodel.SequenceI[] reps = av
866 .getRepresentedSequences(jds).getSequencesInOrder(rjal);
868 for (int h = 0; h < reps.length; h++)
872 jseq.addHiddenSequences(rjal.findIndex(reps[h]));
877 // mark sequence as reference - if it is the reference for this view
880 jseq.setViewreference(jds == jal.getSeqrep());
884 // TODO: omit sequence features from each alignment view's XML dump if we
885 // are storing dataset
886 List<jalview.datamodel.SequenceFeature> sfs = jds
887 .getSequenceFeatures();
888 for (SequenceFeature sf : sfs)
890 Features features = new Features();
892 features.setBegin(sf.getBegin());
893 features.setEnd(sf.getEnd());
894 features.setDescription(sf.getDescription());
895 features.setType(sf.getType());
896 features.setFeatureGroup(sf.getFeatureGroup());
897 features.setScore(sf.getScore());
898 if (sf.links != null)
900 for (int l = 0; l < sf.links.size(); l++)
902 OtherData keyValue = new OtherData();
903 keyValue.setKey("LINK_" + l);
904 keyValue.setValue(sf.links.elementAt(l).toString());
905 features.addOtherData(keyValue);
908 if (sf.otherDetails != null)
911 Iterator<String> keys = sf.otherDetails.keySet().iterator();
912 while (keys.hasNext())
915 OtherData keyValue = new OtherData();
916 keyValue.setKey(key);
917 keyValue.setValue(sf.otherDetails.get(key).toString());
918 features.addOtherData(keyValue);
922 jseq.addFeatures(features);
925 if (jdatasq.getAllPDBEntries() != null)
927 Enumeration en = jdatasq.getAllPDBEntries().elements();
928 while (en.hasMoreElements())
930 Pdbids pdb = new Pdbids();
931 jalview.datamodel.PDBEntry entry = (jalview.datamodel.PDBEntry) en
934 String pdbId = entry.getId();
936 pdb.setType(entry.getType());
939 * Store any structure views associated with this sequence. This
940 * section copes with duplicate entries in the project, so a dataset
941 * only view *should* be coped with sensibly.
943 // This must have been loaded, is it still visible?
944 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
945 String matchedFile = null;
946 for (int f = frames.length - 1; f > -1; f--)
948 if (frames[f] instanceof StructureViewerBase)
950 StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
951 matchedFile = saveStructureState(ap, jds, pdb, entry,
952 viewIds, matchedFile, viewFrame);
954 * Only store each structure viewer's state once in the project
955 * jar. First time through only (storeDS==false)
957 String viewId = viewFrame.getViewId();
958 if (!storeDS && !viewIds.contains(viewId))
963 String viewerState = viewFrame.getStateInfo();
964 writeJarEntry(jout, getViewerJarEntryName(viewId),
965 viewerState.getBytes());
966 } catch (IOException e)
968 System.err.println("Error saving viewer state: "
975 if (matchedFile != null || entry.getFile() != null)
977 if (entry.getFile() != null)
980 matchedFile = entry.getFile();
982 pdb.setFile(matchedFile); // entry.getFile());
983 if (pdbfiles == null)
985 pdbfiles = new ArrayList<>();
988 if (!pdbfiles.contains(pdbId))
991 copyFileToJar(jout, matchedFile, pdbId);
995 Enumeration<String> props = entry.getProperties();
996 if (props.hasMoreElements())
998 PdbentryItem item = new PdbentryItem();
999 while (props.hasMoreElements())
1001 Property prop = new Property();
1002 String key = props.nextElement();
1004 prop.setValue(entry.getProperty(key).toString());
1005 item.addProperty(prop);
1007 pdb.addPdbentryItem(item);
1010 jseq.addPdbids(pdb);
1014 saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
1019 if (!storeDS && av.hasHiddenRows())
1021 jal = av.getAlignment();
1025 if (storeDS && jal.getCodonFrames() != null)
1027 List<AlignedCodonFrame> jac = jal.getCodonFrames();
1028 for (AlignedCodonFrame acf : jac)
1030 AlcodonFrame alc = new AlcodonFrame();
1031 if (acf.getProtMappings() != null
1032 && acf.getProtMappings().length > 0)
1034 boolean hasMap = false;
1035 SequenceI[] dnas = acf.getdnaSeqs();
1036 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1037 for (int m = 0; m < pmaps.length; m++)
1039 AlcodMap alcmap = new AlcodMap();
1040 alcmap.setDnasq(seqHash(dnas[m]));
1041 alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1043 alc.addAlcodMap(alcmap);
1048 vamsasSet.addAlcodonFrame(alc);
1051 // TODO: delete this ? dead code from 2.8.3->2.9 ?
1053 // AlcodonFrame alc = new AlcodonFrame();
1054 // vamsasSet.addAlcodonFrame(alc);
1055 // for (int p = 0; p < acf.aaWidth; p++)
1057 // Alcodon cmap = new Alcodon();
1058 // if (acf.codons[p] != null)
1060 // // Null codons indicate a gapped column in the translated peptide
1062 // cmap.setPos1(acf.codons[p][0]);
1063 // cmap.setPos2(acf.codons[p][1]);
1064 // cmap.setPos3(acf.codons[p][2]);
1066 // alc.addAlcodon(cmap);
1068 // if (acf.getProtMappings() != null
1069 // && acf.getProtMappings().length > 0)
1071 // SequenceI[] dnas = acf.getdnaSeqs();
1072 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1073 // for (int m = 0; m < pmaps.length; m++)
1075 // AlcodMap alcmap = new AlcodMap();
1076 // alcmap.setDnasq(seqHash(dnas[m]));
1077 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1079 // alc.addAlcodMap(alcmap);
1086 // /////////////////////////////////
1087 if (!storeDS && av.currentTree != null)
1089 // FIND ANY ASSOCIATED TREES
1090 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
1091 if (Desktop.desktop != null)
1093 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1095 for (int t = 0; t < frames.length; t++)
1097 if (frames[t] instanceof TreePanel)
1099 TreePanel tp = (TreePanel) frames[t];
1101 if (tp.treeCanvas.av.getAlignment() == jal)
1103 Tree tree = new Tree();
1104 tree.setTitle(tp.getTitle());
1105 tree.setCurrentTree((av.currentTree == tp.getTree()));
1106 tree.setNewick(tp.getTree().print());
1107 tree.setThreshold(tp.treeCanvas.threshold);
1109 tree.setFitToWindow(tp.fitToWindow.getState());
1110 tree.setFontName(tp.getTreeFont().getName());
1111 tree.setFontSize(tp.getTreeFont().getSize());
1112 tree.setFontStyle(tp.getTreeFont().getStyle());
1113 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
1115 tree.setShowBootstrap(tp.bootstrapMenu.getState());
1116 tree.setShowDistances(tp.distanceMenu.getState());
1118 tree.setHeight(tp.getHeight());
1119 tree.setWidth(tp.getWidth());
1120 tree.setXpos(tp.getX());
1121 tree.setYpos(tp.getY());
1122 tree.setId(makeHashCode(tp, null));
1132 * store forward refs from an annotationRow to any groups
1134 IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<>();
1137 for (SequenceI sq : jal.getSequences())
1139 // Store annotation on dataset sequences only
1140 AlignmentAnnotation[] aa = sq.getAnnotation();
1141 if (aa != null && aa.length > 0)
1143 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1150 if (jal.getAlignmentAnnotation() != null)
1152 // Store the annotation shown on the alignment.
1153 AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
1154 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1159 if (jal.getGroups() != null)
1161 JGroup[] groups = new JGroup[jal.getGroups().size()];
1163 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
1165 JGroup jGroup = new JGroup();
1166 groups[++i] = jGroup;
1168 jGroup.setStart(sg.getStartRes());
1169 jGroup.setEnd(sg.getEndRes());
1170 jGroup.setName(sg.getName());
1171 if (groupRefs.containsKey(sg))
1173 // group has references so set its ID field
1174 jGroup.setId(groupRefs.get(sg));
1176 ColourSchemeI colourScheme = sg.getColourScheme();
1177 if (colourScheme != null)
1179 ResidueShaderI groupColourScheme = sg
1180 .getGroupColourScheme();
1181 if (groupColourScheme.conservationApplied())
1183 jGroup.setConsThreshold(groupColourScheme.getConservationInc());
1185 if (colourScheme instanceof jalview.schemes.UserColourScheme)
1187 jGroup.setColour(setUserColourScheme(colourScheme,
1192 jGroup.setColour(colourScheme.getSchemeName());
1195 else if (colourScheme instanceof jalview.schemes.AnnotationColourGradient)
1197 jGroup.setColour("AnnotationColourGradient");
1198 jGroup.setAnnotationColours(constructAnnotationColours(
1199 (jalview.schemes.AnnotationColourGradient) colourScheme,
1202 else if (colourScheme instanceof jalview.schemes.UserColourScheme)
1204 jGroup.setColour(setUserColourScheme(colourScheme,
1209 jGroup.setColour(colourScheme.getSchemeName());
1212 jGroup.setPidThreshold(groupColourScheme.getThreshold());
1215 jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
1216 jGroup.setDisplayBoxes(sg.getDisplayBoxes());
1217 jGroup.setDisplayText(sg.getDisplayText());
1218 jGroup.setColourText(sg.getColourText());
1219 jGroup.setTextCol1(sg.textColour.getRGB());
1220 jGroup.setTextCol2(sg.textColour2.getRGB());
1221 jGroup.setTextColThreshold(sg.thresholdTextColour);
1222 jGroup.setShowUnconserved(sg.getShowNonconserved());
1223 jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1224 jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
1225 jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
1226 jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1227 for (SequenceI seq : sg.getSequences())
1229 jGroup.addSeq(seqHash(seq));
1233 jms.setJGroup(groups);
1237 // /////////SAVE VIEWPORT
1238 Viewport view = new Viewport();
1239 view.setTitle(ap.alignFrame.getTitle());
1240 view.setSequenceSetId(makeHashCode(av.getSequenceSetId(),
1241 av.getSequenceSetId()));
1242 view.setId(av.getViewId());
1243 if (av.getCodingComplement() != null)
1245 view.setComplementId(av.getCodingComplement().getViewId());
1247 view.setViewName(av.viewName);
1248 view.setGatheredViews(av.isGatherViewsHere());
1250 Rectangle size = ap.av.getExplodedGeometry();
1251 Rectangle position = size;
1254 size = ap.alignFrame.getBounds();
1255 if (av.getCodingComplement() != null)
1257 position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
1265 view.setXpos(position.x);
1266 view.setYpos(position.y);
1268 view.setWidth(size.width);
1269 view.setHeight(size.height);
1271 view.setStartRes(vpRanges.getStartRes());
1272 view.setStartSeq(vpRanges.getStartSeq());
1274 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1276 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1279 else if (av.getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1281 AnnotationColours ac = constructAnnotationColours(
1282 (jalview.schemes.AnnotationColourGradient) av
1283 .getGlobalColourScheme(),
1286 view.setAnnotationColours(ac);
1287 view.setBgColour("AnnotationColourGradient");
1291 view.setBgColour(ColourSchemeProperty.getColourName(av
1292 .getGlobalColourScheme()));
1295 ResidueShaderI vcs = av.getResidueShading();
1296 ColourSchemeI cs = av.getGlobalColourScheme();
1300 if (vcs.conservationApplied())
1302 view.setConsThreshold(vcs.getConservationInc());
1303 if (cs instanceof jalview.schemes.UserColourScheme)
1305 view.setBgColour(setUserColourScheme(cs, userColours, jms));
1308 view.setPidThreshold(vcs.getThreshold());
1311 view.setConservationSelected(av.getConservationSelected());
1312 view.setPidSelected(av.getAbovePIDThreshold());
1313 view.setFontName(av.font.getName());
1314 view.setFontSize(av.font.getSize());
1315 view.setFontStyle(av.font.getStyle());
1316 view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
1317 view.setRenderGaps(av.isRenderGaps());
1318 view.setShowAnnotation(av.isShowAnnotation());
1319 view.setShowBoxes(av.getShowBoxes());
1320 view.setShowColourText(av.getColourText());
1321 view.setShowFullId(av.getShowJVSuffix());
1322 view.setRightAlignIds(av.isRightAlignIds());
1323 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1324 view.setShowText(av.getShowText());
1325 view.setShowUnconserved(av.getShowUnconserved());
1326 view.setWrapAlignment(av.getWrapAlignment());
1327 view.setTextCol1(av.getTextColour().getRGB());
1328 view.setTextCol2(av.getTextColour2().getRGB());
1329 view.setTextColThreshold(av.getThresholdTextColour());
1330 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1331 view.setShowSequenceLogo(av.isShowSequenceLogo());
1332 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1333 view.setShowGroupConsensus(av.isShowGroupConsensus());
1334 view.setShowGroupConservation(av.isShowGroupConservation());
1335 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1336 view.setShowDbRefTooltip(av.isShowDBRefs());
1337 view.setFollowHighlight(av.isFollowHighlight());
1338 view.setFollowSelection(av.followSelection);
1339 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1340 if (av.getFeaturesDisplayed() != null)
1342 jalview.schemabinding.version2.FeatureSettings fs = new jalview.schemabinding.version2.FeatureSettings();
1344 String[] renderOrder = ap.getSeqPanel().seqCanvas
1345 .getFeatureRenderer().getRenderOrder()
1346 .toArray(new String[0]);
1348 Vector<String> settingsAdded = new Vector<>();
1349 if (renderOrder != null)
1351 for (String featureType : renderOrder)
1353 FeatureColourI fcol = ap.getSeqPanel().seqCanvas
1354 .getFeatureRenderer().getFeatureStyle(featureType);
1355 Setting setting = new Setting();
1356 setting.setType(featureType);
1357 if (!fcol.isSimpleColour())
1359 setting.setColour(fcol.getMaxColour().getRGB());
1360 setting.setMincolour(fcol.getMinColour().getRGB());
1361 setting.setMin(fcol.getMin());
1362 setting.setMax(fcol.getMax());
1363 setting.setColourByLabel(fcol.isColourByLabel());
1364 setting.setAutoScale(fcol.isAutoScaled());
1365 setting.setThreshold(fcol.getThreshold());
1366 // -1 = No threshold, 0 = Below, 1 = Above
1367 setting.setThreshstate(fcol.isAboveThreshold() ? 1 : (fcol
1368 .isBelowThreshold() ? 0 : -1));
1372 setting.setColour(fcol.getColour().getRGB());
1375 setting.setDisplay(av.getFeaturesDisplayed().isVisible(
1377 float rorder = ap.getSeqPanel().seqCanvas.getFeatureRenderer()
1378 .getOrder(featureType);
1381 setting.setOrder(rorder);
1383 fs.addSetting(setting);
1384 settingsAdded.addElement(featureType);
1388 // is groups actually supposed to be a map here ?
1389 Iterator<String> en = ap.getSeqPanel().seqCanvas
1390 .getFeatureRenderer().getFeatureGroups().iterator();
1391 Vector<String> groupsAdded = new Vector<>();
1392 while (en.hasNext())
1394 String grp = en.next();
1395 if (groupsAdded.contains(grp))
1399 Group g = new Group();
1401 g.setDisplay(((Boolean) ap.getSeqPanel().seqCanvas
1402 .getFeatureRenderer().checkGroupVisibility(grp, false))
1405 groupsAdded.addElement(grp);
1407 jms.setFeatureSettings(fs);
1410 if (av.hasHiddenColumns())
1412 jalview.datamodel.HiddenColumns hidden = av.getAlignment()
1413 .getHiddenColumns();
1416 warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1420 ArrayList<int[]> hiddenRegions = hidden
1421 .getHiddenColumnsCopy();
1422 for (int[] region : hiddenRegions)
1424 HiddenColumns hc = new HiddenColumns();
1425 hc.setStart(region[0]);
1426 hc.setEnd(region[1]);
1427 view.addHiddenColumns(hc);
1431 if (calcIdSet.size() > 0)
1433 for (String calcId : calcIdSet)
1435 if (calcId.trim().length() > 0)
1437 CalcIdParam cidp = createCalcIdParam(calcId, av);
1438 // Some calcIds have no parameters.
1441 view.addCalcIdParam(cidp);
1447 jms.addViewport(view);
1449 object.setJalviewModelSequence(jms);
1450 object.getVamsasModel().addSequenceSet(vamsasSet);
1452 if (jout != null && fileName != null)
1454 // We may not want to write the object to disk,
1455 // eg we can copy the alignViewport to a new view object
1456 // using save and then load
1459 System.out.println("Writing jar entry " + fileName);
1460 JarEntry entry = new JarEntry(fileName);
1461 jout.putNextEntry(entry);
1462 PrintWriter pout = new PrintWriter(new OutputStreamWriter(jout,
1464 Marshaller marshaller = new Marshaller(pout);
1465 marshaller.marshal(object);
1468 } catch (Exception ex)
1470 // TODO: raise error in GUI if marshalling failed.
1471 ex.printStackTrace();
1478 * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
1479 * for each viewer, with
1481 * <li>viewer geometry (position, size, split pane divider location)</li>
1482 * <li>index of the selected structure in the viewer (currently shows gapped
1484 * <li>the id of the annotation holding RNA secondary structure</li>
1485 * <li>(currently only one SS is shown per viewer, may be more in future)</li>
1487 * Varna viewer state is also written out (in native Varna XML) to separate
1488 * project jar entries. A separate entry is written for each RNA structure
1489 * displayed, with the naming convention
1491 * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
1499 * @param storeDataset
1501 protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
1502 final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
1503 boolean storeDataset)
1505 if (Desktop.desktop == null)
1509 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1510 for (int f = frames.length - 1; f > -1; f--)
1512 if (frames[f] instanceof AppVarna)
1514 AppVarna varna = (AppVarna) frames[f];
1516 * link the sequence to every viewer that is showing it and is linked to
1517 * its alignment panel
1519 if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
1521 String viewId = varna.getViewId();
1522 RnaViewer rna = new RnaViewer();
1523 rna.setViewId(viewId);
1524 rna.setTitle(varna.getTitle());
1525 rna.setXpos(varna.getX());
1526 rna.setYpos(varna.getY());
1527 rna.setWidth(varna.getWidth());
1528 rna.setHeight(varna.getHeight());
1529 rna.setDividerLocation(varna.getDividerLocation());
1530 rna.setSelectedRna(varna.getSelectedIndex());
1531 jseq.addRnaViewer(rna);
1534 * Store each Varna panel's state once in the project per sequence.
1535 * First time through only (storeDataset==false)
1537 // boolean storeSessions = false;
1538 // String sequenceViewId = viewId + seqsToIds.get(jds);
1539 // if (!storeDataset && !viewIds.contains(sequenceViewId))
1541 // viewIds.add(sequenceViewId);
1542 // storeSessions = true;
1544 for (RnaModel model : varna.getModels())
1546 if (model.seq == jds)
1549 * VARNA saves each view (sequence or alignment secondary
1550 * structure, gapped or trimmed) as a separate XML file
1552 String jarEntryName = rnaSessions.get(model);
1553 if (jarEntryName == null)
1556 String varnaStateFile = varna.getStateInfo(model.rna);
1557 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
1558 copyFileToJar(jout, varnaStateFile, jarEntryName);
1559 rnaSessions.put(model, jarEntryName);
1561 SecondaryStructure ss = new SecondaryStructure();
1562 String annotationId = varna.getAnnotation(jds).annotationId;
1563 ss.setAnnotationId(annotationId);
1564 ss.setViewerState(jarEntryName);
1565 ss.setGapped(model.gapped);
1566 ss.setTitle(model.title);
1567 rna.addSecondaryStructure(ss);
1576 * Copy the contents of a file to a new entry added to the output jar
1580 * @param jarEntryName
1582 protected void copyFileToJar(JarOutputStream jout, String infilePath,
1583 String jarEntryName)
1585 DataInputStream dis = null;
1588 File file = new File(infilePath);
1589 if (file.exists() && jout != null)
1591 dis = new DataInputStream(new FileInputStream(file));
1592 byte[] data = new byte[(int) file.length()];
1593 dis.readFully(data);
1594 writeJarEntry(jout, jarEntryName, data);
1596 } catch (Exception ex)
1598 ex.printStackTrace();
1606 } catch (IOException e)
1615 * Write the data to a new entry of given name in the output jar file
1618 * @param jarEntryName
1620 * @throws IOException
1622 protected void writeJarEntry(JarOutputStream jout, String jarEntryName,
1623 byte[] data) throws IOException
1627 System.out.println("Writing jar entry " + jarEntryName);
1628 jout.putNextEntry(new JarEntry(jarEntryName));
1629 DataOutputStream dout = new DataOutputStream(jout);
1630 dout.write(data, 0, data.length);
1637 * Save the state of a structure viewer
1642 * the archive XML element under which to save the state
1645 * @param matchedFile
1649 protected String saveStructureState(AlignmentPanel ap, SequenceI jds,
1650 Pdbids pdb, PDBEntry entry, List<String> viewIds,
1651 String matchedFile, StructureViewerBase viewFrame)
1653 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
1656 * Look for any bindings for this viewer to the PDB file of interest
1657 * (including part matches excluding chain id)
1659 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
1661 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
1662 final String pdbId = pdbentry.getId();
1663 if (!pdbId.equals(entry.getId())
1664 && !(entry.getId().length() > 4 && entry.getId()
1665 .toLowerCase().startsWith(pdbId.toLowerCase())))
1668 * not interested in a binding to a different PDB entry here
1672 if (matchedFile == null)
1674 matchedFile = pdbentry.getFile();
1676 else if (!matchedFile.equals(pdbentry.getFile()))
1679 .warn("Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
1680 + pdbentry.getFile());
1684 // can get at it if the ID
1685 // match is ambiguous (e.g.
1688 for (int smap = 0; smap < viewFrame.getBinding().getSequence()[peid].length; smap++)
1690 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
1691 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
1693 StructureState state = new StructureState();
1694 state.setVisible(true);
1695 state.setXpos(viewFrame.getX());
1696 state.setYpos(viewFrame.getY());
1697 state.setWidth(viewFrame.getWidth());
1698 state.setHeight(viewFrame.getHeight());
1699 final String viewId = viewFrame.getViewId();
1700 state.setViewId(viewId);
1701 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
1702 state.setColourwithAlignPanel(viewFrame.isUsedforcolourby(ap));
1703 state.setColourByJmol(viewFrame.isColouredByViewer());
1704 state.setType(viewFrame.getViewerType().toString());
1705 pdb.addStructureState(state);
1713 * Populates the AnnotationColours xml for save. This captures the settings of
1714 * the options in the 'Colour by Annotation' dialog.
1717 * @param userColours
1721 private AnnotationColours constructAnnotationColours(
1722 AnnotationColourGradient acg, List<UserColourScheme> userColours,
1723 JalviewModelSequence jms)
1725 AnnotationColours ac = new AnnotationColours();
1726 ac.setAboveThreshold(acg.getAboveThreshold());
1727 ac.setThreshold(acg.getAnnotationThreshold());
1728 // 2.10.2 save annotationId (unique) not annotation label
1729 ac.setAnnotation(acg.getAnnotation().annotationId);
1730 if (acg.getBaseColour() instanceof UserColourScheme)
1732 ac.setColourScheme(setUserColourScheme(acg.getBaseColour(),
1737 ac.setColourScheme(ColourSchemeProperty.getColourName(acg.getBaseColour()));
1740 ac.setMaxColour(acg.getMaxColour().getRGB());
1741 ac.setMinColour(acg.getMinColour().getRGB());
1742 ac.setPerSequence(acg.isSeqAssociated());
1743 ac.setPredefinedColours(acg.isPredefinedColours());
1747 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
1748 IdentityHashMap<SequenceGroup, String> groupRefs,
1749 AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
1750 SequenceSet vamsasSet)
1753 for (int i = 0; i < aa.length; i++)
1755 Annotation an = new Annotation();
1757 AlignmentAnnotation annotation = aa[i];
1758 if (annotation.annotationId != null)
1760 annotationIds.put(annotation.annotationId, annotation);
1763 an.setId(annotation.annotationId);
1765 an.setVisible(annotation.visible);
1767 an.setDescription(annotation.description);
1769 if (annotation.sequenceRef != null)
1771 // 2.9 JAL-1781 xref on sequence id rather than name
1772 an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
1774 if (annotation.groupRef != null)
1776 String groupIdr = groupRefs.get(annotation.groupRef);
1777 if (groupIdr == null)
1779 // make a locally unique String
1781 annotation.groupRef,
1782 groupIdr = ("" + System.currentTimeMillis()
1783 + annotation.groupRef.getName() + groupRefs
1786 an.setGroupRef(groupIdr.toString());
1789 // store all visualization attributes for annotation
1790 an.setGraphHeight(annotation.graphHeight);
1791 an.setCentreColLabels(annotation.centreColLabels);
1792 an.setScaleColLabels(annotation.scaleColLabel);
1793 an.setShowAllColLabels(annotation.showAllColLabels);
1794 an.setBelowAlignment(annotation.belowAlignment);
1796 if (annotation.graph > 0)
1799 an.setGraphType(annotation.graph);
1800 an.setGraphGroup(annotation.graphGroup);
1801 if (annotation.getThreshold() != null)
1803 ThresholdLine line = new ThresholdLine();
1804 line.setLabel(annotation.getThreshold().label);
1805 line.setValue(annotation.getThreshold().value);
1806 line.setColour(annotation.getThreshold().colour.getRGB());
1807 an.setThresholdLine(line);
1815 an.setLabel(annotation.label);
1817 if (annotation == av.getAlignmentQualityAnnot()
1818 || annotation == av.getAlignmentConservationAnnotation()
1819 || annotation == av.getAlignmentConsensusAnnotation()
1820 || annotation.autoCalculated)
1822 // new way of indicating autocalculated annotation -
1823 an.setAutoCalculated(annotation.autoCalculated);
1825 if (annotation.hasScore())
1827 an.setScore(annotation.getScore());
1830 if (annotation.getCalcId() != null)
1832 calcIdSet.add(annotation.getCalcId());
1833 an.setCalcId(annotation.getCalcId());
1835 if (annotation.hasProperties())
1837 for (String pr : annotation.getProperties())
1839 Property prop = new Property();
1841 prop.setValue(annotation.getProperty(pr));
1842 an.addProperty(prop);
1846 AnnotationElement ae;
1847 if (annotation.annotations != null)
1849 an.setScoreOnly(false);
1850 for (int a = 0; a < annotation.annotations.length; a++)
1852 if ((annotation == null) || (annotation.annotations[a] == null))
1857 ae = new AnnotationElement();
1858 if (annotation.annotations[a].description != null)
1860 ae.setDescription(annotation.annotations[a].description);
1862 if (annotation.annotations[a].displayCharacter != null)
1864 ae.setDisplayCharacter(annotation.annotations[a].displayCharacter);
1867 if (!Float.isNaN(annotation.annotations[a].value))
1869 ae.setValue(annotation.annotations[a].value);
1873 if (annotation.annotations[a].secondaryStructure > ' ')
1875 ae.setSecondaryStructure(annotation.annotations[a].secondaryStructure
1879 if (annotation.annotations[a].colour != null
1880 && annotation.annotations[a].colour != java.awt.Color.black)
1882 ae.setColour(annotation.annotations[a].colour.getRGB());
1885 an.addAnnotationElement(ae);
1886 if (annotation.autoCalculated)
1888 // only write one non-null entry into the annotation row -
1889 // sufficient to get the visualization attributes necessary to
1897 an.setScoreOnly(true);
1899 if (!storeDS || (storeDS && !annotation.autoCalculated))
1901 // skip autocalculated annotation - these are only provided for
1903 vamsasSet.addAnnotation(an);
1909 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
1911 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
1912 if (settings != null)
1914 CalcIdParam vCalcIdParam = new CalcIdParam();
1915 vCalcIdParam.setCalcId(calcId);
1916 vCalcIdParam.addServiceURL(settings.getServiceURI());
1917 // generic URI allowing a third party to resolve another instance of the
1918 // service used for this calculation
1919 for (String urls : settings.getServiceURLs())
1921 vCalcIdParam.addServiceURL(urls);
1923 vCalcIdParam.setVersion("1.0");
1924 if (settings.getPreset() != null)
1926 WsParamSetI setting = settings.getPreset();
1927 vCalcIdParam.setName(setting.getName());
1928 vCalcIdParam.setDescription(setting.getDescription());
1932 vCalcIdParam.setName("");
1933 vCalcIdParam.setDescription("Last used parameters");
1935 // need to be able to recover 1) settings 2) user-defined presets or
1936 // recreate settings from preset 3) predefined settings provided by
1937 // service - or settings that can be transferred (or discarded)
1938 vCalcIdParam.setParameters(settings.getWsParamFile().replace("\n",
1940 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
1941 // todo - decide if updateImmediately is needed for any projects.
1943 return vCalcIdParam;
1948 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
1951 if (calcIdParam.getVersion().equals("1.0"))
1953 Jws2Instance service = Jws2Discoverer.getDiscoverer()
1954 .getPreferredServiceFor(calcIdParam.getServiceURL());
1955 if (service != null)
1957 WsParamSetI parmSet = null;
1960 parmSet = service.getParamStore().parseServiceParameterFile(
1961 calcIdParam.getName(), calcIdParam.getDescription(),
1962 calcIdParam.getServiceURL(),
1963 calcIdParam.getParameters().replace("|\\n|", "\n"));
1964 } catch (IOException x)
1966 warn("Couldn't parse parameter data for "
1967 + calcIdParam.getCalcId(), x);
1970 List<ArgumentI> argList = null;
1971 if (calcIdParam.getName().length() > 0)
1973 parmSet = service.getParamStore()
1974 .getPreset(calcIdParam.getName());
1975 if (parmSet != null)
1977 // TODO : check we have a good match with settings in AACon -
1978 // otherwise we'll need to create a new preset
1983 argList = parmSet.getArguments();
1986 AAConSettings settings = new AAConSettings(
1987 calcIdParam.isAutoUpdate(), service, parmSet, argList);
1988 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
1989 calcIdParam.isNeedsUpdate());
1994 warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
1998 throw new Error(MessageManager.formatMessage(
1999 "error.unsupported_version_calcIdparam",
2000 new Object[] { calcIdParam.toString() }));
2004 * External mapping between jalview objects and objects yielding a valid and
2005 * unique object ID string. This is null for normal Jalview project IO, but
2006 * non-null when a jalview project is being read or written as part of a
2009 IdentityHashMap jv2vobj = null;
2012 * Construct a unique ID for jvobj using either existing bindings or if none
2013 * exist, the result of the hashcode call for the object.
2016 * jalview data object
2017 * @return unique ID for referring to jvobj
2019 private String makeHashCode(Object jvobj, String altCode)
2021 if (jv2vobj != null)
2023 Object id = jv2vobj.get(jvobj);
2026 return id.toString();
2028 // check string ID mappings
2029 if (jvids2vobj != null && jvobj instanceof String)
2031 id = jvids2vobj.get(jvobj);
2035 return id.toString();
2037 // give up and warn that something has gone wrong
2038 warn("Cannot find ID for object in external mapping : " + jvobj);
2044 * return local jalview object mapped to ID, if it exists
2048 * @return null or object bound to idcode
2050 private Object retrieveExistingObj(String idcode)
2052 if (idcode != null && vobj2jv != null)
2054 return vobj2jv.get(idcode);
2060 * binding from ID strings from external mapping table to jalview data model
2063 private Hashtable vobj2jv;
2065 private Sequence createVamsasSequence(String id, SequenceI jds)
2067 return createVamsasSequence(true, id, jds, null);
2070 private Sequence createVamsasSequence(boolean recurse, String id,
2071 SequenceI jds, SequenceI parentseq)
2073 Sequence vamsasSeq = new Sequence();
2074 vamsasSeq.setId(id);
2075 vamsasSeq.setName(jds.getName());
2076 vamsasSeq.setSequence(jds.getSequenceAsString());
2077 vamsasSeq.setDescription(jds.getDescription());
2078 jalview.datamodel.DBRefEntry[] dbrefs = null;
2079 if (jds.getDatasetSequence() != null)
2081 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
2085 // seqId==dsseqid so we can tell which sequences really are
2086 // dataset sequences only
2087 vamsasSeq.setDsseqid(id);
2088 dbrefs = jds.getDBRefs();
2089 if (parentseq == null)
2096 for (int d = 0; d < dbrefs.length; d++)
2098 DBRef dbref = new DBRef();
2099 dbref.setSource(dbrefs[d].getSource());
2100 dbref.setVersion(dbrefs[d].getVersion());
2101 dbref.setAccessionId(dbrefs[d].getAccessionId());
2102 if (dbrefs[d].hasMap())
2104 Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
2106 dbref.setMapping(mp);
2108 vamsasSeq.addDBRef(dbref);
2114 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
2115 SequenceI parentseq, SequenceI jds, boolean recurse)
2118 if (jmp.getMap() != null)
2122 jalview.util.MapList mlst = jmp.getMap();
2123 List<int[]> r = mlst.getFromRanges();
2124 for (int[] range : r)
2126 MapListFrom mfrom = new MapListFrom();
2127 mfrom.setStart(range[0]);
2128 mfrom.setEnd(range[1]);
2129 mp.addMapListFrom(mfrom);
2131 r = mlst.getToRanges();
2132 for (int[] range : r)
2134 MapListTo mto = new MapListTo();
2135 mto.setStart(range[0]);
2136 mto.setEnd(range[1]);
2137 mp.addMapListTo(mto);
2139 mp.setMapFromUnit(mlst.getFromRatio());
2140 mp.setMapToUnit(mlst.getToRatio());
2141 if (jmp.getTo() != null)
2143 MappingChoice mpc = new MappingChoice();
2145 // check/create ID for the sequence referenced by getTo()
2148 SequenceI ps = null;
2149 if (parentseq != jmp.getTo()
2150 && parentseq.getDatasetSequence() != jmp.getTo())
2152 // chaining dbref rather than a handshaking one
2153 jmpid = seqHash(ps = jmp.getTo());
2157 jmpid = seqHash(ps = parentseq);
2159 mpc.setDseqFor(jmpid);
2160 if (!seqRefIds.containsKey(mpc.getDseqFor()))
2162 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
2163 seqRefIds.put(mpc.getDseqFor(), ps);
2167 jalview.bin.Cache.log.debug("reusing DseqFor ID");
2170 mp.setMappingChoice(mpc);
2176 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
2177 List<UserColourScheme> userColours, JalviewModelSequence jms)
2180 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
2181 boolean newucs = false;
2182 if (!userColours.contains(ucs))
2184 userColours.add(ucs);
2187 id = "ucs" + userColours.indexOf(ucs);
2190 // actually create the scheme's entry in the XML model
2191 java.awt.Color[] colours = ucs.getColours();
2192 jalview.schemabinding.version2.UserColours uc = new jalview.schemabinding.version2.UserColours();
2193 jalview.schemabinding.version2.UserColourScheme jbucs = new jalview.schemabinding.version2.UserColourScheme();
2195 for (int i = 0; i < colours.length; i++)
2197 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
2198 col.setName(ResidueProperties.aa[i]);
2199 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2200 jbucs.addColour(col);
2202 if (ucs.getLowerCaseColours() != null)
2204 colours = ucs.getLowerCaseColours();
2205 for (int i = 0; i < colours.length; i++)
2207 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
2208 col.setName(ResidueProperties.aa[i].toLowerCase());
2209 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2210 jbucs.addColour(col);
2215 uc.setUserColourScheme(jbucs);
2216 jms.addUserColours(uc);
2222 jalview.schemes.UserColourScheme getUserColourScheme(
2223 JalviewModelSequence jms, String id)
2225 UserColours[] uc = jms.getUserColours();
2226 UserColours colours = null;
2228 for (int i = 0; i < uc.length; i++)
2230 if (uc[i].getId().equals(id))
2238 java.awt.Color[] newColours = new java.awt.Color[24];
2240 for (int i = 0; i < 24; i++)
2242 newColours[i] = new java.awt.Color(Integer.parseInt(colours
2243 .getUserColourScheme().getColour(i).getRGB(), 16));
2246 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
2249 if (colours.getUserColourScheme().getColourCount() > 24)
2251 newColours = new java.awt.Color[23];
2252 for (int i = 0; i < 23; i++)
2254 newColours[i] = new java.awt.Color(Integer.parseInt(colours
2255 .getUserColourScheme().getColour(i + 24).getRGB(), 16));
2257 ucs.setLowerCaseColours(newColours);
2264 * contains last error message (if any) encountered by XML loader.
2266 String errorMessage = null;
2269 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
2270 * exceptions are raised during project XML parsing
2272 public boolean attemptversion1parse = true;
2275 * Load a jalview project archive from a jar file
2278 * - HTTP URL or filename
2280 public AlignFrame loadJalviewAlign(final String file)
2283 jalview.gui.AlignFrame af = null;
2287 // create list to store references for any new Jmol viewers created
2288 newStructureViewers = new Vector<>();
2289 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
2290 // Workaround is to make sure caller implements the JarInputStreamProvider
2292 // so we can re-open the jar input stream for each entry.
2294 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
2295 af = loadJalviewAlign(jprovider);
2297 } catch (MalformedURLException e)
2299 errorMessage = "Invalid URL format for '" + file + "'";
2305 SwingUtilities.invokeAndWait(new Runnable()
2310 setLoadingFinishedForNewStructureViewers();
2313 } catch (Exception x)
2315 System.err.println("Error loading alignment: " + x.getMessage());
2321 private jarInputStreamProvider createjarInputStreamProvider(
2322 final String file) throws MalformedURLException
2325 errorMessage = null;
2326 uniqueSetSuffix = null;
2328 viewportsAdded.clear();
2329 frefedSequence = null;
2331 if (file.startsWith("http://"))
2333 url = new URL(file);
2335 final URL _url = url;
2336 return new jarInputStreamProvider()
2340 public JarInputStream getJarInputStream() throws IOException
2344 return new JarInputStream(_url.openStream());
2348 return new JarInputStream(new FileInputStream(file));
2353 public String getFilename()
2361 * Recover jalview session from a jalview project archive. Caller may
2362 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
2363 * themselves. Any null fields will be initialised with default values,
2364 * non-null fields are left alone.
2369 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
2371 errorMessage = null;
2372 if (uniqueSetSuffix == null)
2374 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
2376 if (seqRefIds == null)
2380 AlignFrame af = null, _af = null;
2381 IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<>();
2382 Map<String, AlignFrame> gatherToThisFrame = new HashMap<>();
2383 final String file = jprovider.getFilename();
2386 JarInputStream jin = null;
2387 JarEntry jarentry = null;
2392 jin = jprovider.getJarInputStream();
2393 for (int i = 0; i < entryCount; i++)
2395 jarentry = jin.getNextJarEntry();
2398 if (jarentry != null && jarentry.getName().endsWith(".xml"))
2400 InputStreamReader in = new InputStreamReader(jin, UTF_8);
2401 JalviewModel object = new JalviewModel();
2403 Unmarshaller unmar = new Unmarshaller(object);
2404 unmar.setValidation(false);
2405 object = (JalviewModel) unmar.unmarshal(in);
2406 if (true) // !skipViewport(object))
2408 _af = loadFromObject(object, file, true, jprovider);
2410 && object.getJalviewModelSequence().getViewportCount() > 0)
2414 // store a reference to the first view
2417 if (_af.viewport.isGatherViewsHere())
2419 // if this is a gathered view, keep its reference since
2420 // after gathering views, only this frame will remain
2422 gatherToThisFrame.put(_af.viewport.getSequenceSetId(), _af);
2424 // Save dataset to register mappings once all resolved
2425 importedDatasets.put(af.viewport.getAlignment().getDataset(),
2426 af.viewport.getAlignment().getDataset());
2431 else if (jarentry != null)
2433 // Some other file here.
2436 } while (jarentry != null);
2437 resolveFrefedSequences();
2438 } catch (IOException ex)
2440 ex.printStackTrace();
2441 errorMessage = "Couldn't locate Jalview XML file : " + file;
2442 System.err.println("Exception whilst loading jalview XML file : "
2444 } catch (Exception ex)
2446 System.err.println("Parsing as Jalview Version 2 file failed.");
2447 ex.printStackTrace(System.err);
2448 if (attemptversion1parse)
2450 // Is Version 1 Jar file?
2453 af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
2454 } catch (Exception ex2)
2456 System.err.println("Exception whilst loading as jalviewXMLV1:");
2457 ex2.printStackTrace();
2461 if (Desktop.instance != null)
2463 Desktop.instance.stopLoading();
2467 System.out.println("Successfully loaded archive file");
2470 ex.printStackTrace();
2472 System.err.println("Exception whilst loading jalview XML file : "
2474 } catch (OutOfMemoryError e)
2476 // Don't use the OOM Window here
2477 errorMessage = "Out of memory loading jalview XML file";
2478 System.err.println("Out of memory whilst loading jalview XML file");
2479 e.printStackTrace();
2483 * Regather multiple views (with the same sequence set id) to the frame (if
2484 * any) that is flagged as the one to gather to, i.e. convert them to tabbed
2485 * views instead of separate frames. Note this doesn't restore a state where
2486 * some expanded views in turn have tabbed views - the last "first tab" read
2487 * in will play the role of gatherer for all.
2489 for (AlignFrame fr : gatherToThisFrame.values())
2491 Desktop.instance.gatherViews(fr);
2494 restoreSplitFrames();
2495 for (AlignmentI ds : importedDatasets.keySet())
2497 if (ds.getCodonFrames() != null)
2499 StructureSelectionManager.getStructureSelectionManager(
2500 Desktop.instance).registerMappings(ds.getCodonFrames());
2503 if (errorMessage != null)
2508 if (Desktop.instance != null)
2510 Desktop.instance.stopLoading();
2517 * Try to reconstruct and display SplitFrame windows, where each contains
2518 * complementary dna and protein alignments. Done by pairing up AlignFrame
2519 * objects (created earlier) which have complementary viewport ids associated.
2521 protected void restoreSplitFrames()
2523 List<SplitFrame> gatherTo = new ArrayList<>();
2524 List<AlignFrame> addedToSplitFrames = new ArrayList<>();
2525 Map<String, AlignFrame> dna = new HashMap<>();
2528 * Identify the DNA alignments
2530 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2533 AlignFrame af = candidate.getValue();
2534 if (af.getViewport().getAlignment().isNucleotide())
2536 dna.put(candidate.getKey().getId(), af);
2541 * Try to match up the protein complements
2543 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2546 AlignFrame af = candidate.getValue();
2547 if (!af.getViewport().getAlignment().isNucleotide())
2549 String complementId = candidate.getKey().getComplementId();
2550 // only non-null complements should be in the Map
2551 if (complementId != null && dna.containsKey(complementId))
2553 final AlignFrame dnaFrame = dna.get(complementId);
2554 SplitFrame sf = createSplitFrame(dnaFrame, af);
2555 addedToSplitFrames.add(dnaFrame);
2556 addedToSplitFrames.add(af);
2557 dnaFrame.setMenusForViewport();
2558 af.setMenusForViewport();
2559 if (af.viewport.isGatherViewsHere())
2568 * Open any that we failed to pair up (which shouldn't happen!) as
2569 * standalone AlignFrame's.
2571 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2574 AlignFrame af = candidate.getValue();
2575 if (!addedToSplitFrames.contains(af))
2577 Viewport view = candidate.getKey();
2578 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
2580 af.setMenusForViewport();
2581 System.err.println("Failed to restore view " + view.getTitle()
2582 + " to split frame");
2587 * Gather back into tabbed views as flagged.
2589 for (SplitFrame sf : gatherTo)
2591 Desktop.instance.gatherViews(sf);
2594 splitFrameCandidates.clear();
2598 * Construct and display one SplitFrame holding DNA and protein alignments.
2601 * @param proteinFrame
2604 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
2605 AlignFrame proteinFrame)
2607 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
2608 String title = MessageManager.getString("label.linked_view_title");
2609 int width = (int) dnaFrame.getBounds().getWidth();
2610 int height = (int) (dnaFrame.getBounds().getHeight()
2611 + proteinFrame.getBounds().getHeight() + 50);
2614 * SplitFrame location is saved to both enclosed frames
2616 splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
2617 Desktop.addInternalFrame(splitFrame, title, width, height);
2620 * And compute cDNA consensus (couldn't do earlier with consensus as
2621 * mappings were not yet present)
2623 proteinFrame.viewport.alignmentChanged(proteinFrame.alignPanel);
2629 * check errorMessage for a valid error message and raise an error box in the
2630 * GUI or write the current errorMessage to stderr and then clear the error
2633 protected void reportErrors()
2635 reportErrors(false);
2638 protected void reportErrors(final boolean saving)
2640 if (errorMessage != null)
2642 final String finalErrorMessage = errorMessage;
2645 javax.swing.SwingUtilities.invokeLater(new Runnable()
2651 .showInternalMessageDialog(Desktop.desktop,
2652 finalErrorMessage, "Error "
2653 + (saving ? "saving" : "loading")
2655 JvOptionPane.WARNING_MESSAGE);
2661 System.err.println("Problem loading Jalview file: " + errorMessage);
2664 errorMessage = null;
2667 Map<String, String> alreadyLoadedPDB = new HashMap<>();
2670 * when set, local views will be updated from view stored in JalviewXML
2671 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
2672 * sync if this is set to true.
2674 private final boolean updateLocalViews = false;
2677 * Returns the path to a temporary file holding the PDB file for the given PDB
2678 * id. The first time of asking, searches for a file of that name in the
2679 * Jalview project jar, and copies it to a new temporary file. Any repeat
2680 * requests just return the path to the file previously created.
2686 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
2689 if (alreadyLoadedPDB.containsKey(pdbId))
2691 return alreadyLoadedPDB.get(pdbId).toString();
2694 String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
2696 if (tempFile != null)
2698 alreadyLoadedPDB.put(pdbId, tempFile);
2704 * Copies the jar entry of given name to a new temporary file and returns the
2705 * path to the file, or null if the entry is not found.
2708 * @param jarEntryName
2710 * a prefix for the temporary file name, must be at least three
2713 * null or original file - so new file can be given the same suffix
2717 protected String copyJarEntry(jarInputStreamProvider jprovider,
2718 String jarEntryName, String prefix, String origFile)
2720 BufferedReader in = null;
2721 PrintWriter out = null;
2722 String suffix = ".tmp";
2723 if (origFile == null)
2725 origFile = jarEntryName;
2727 int sfpos = origFile.lastIndexOf(".");
2728 if (sfpos > -1 && sfpos < (origFile.length() - 3))
2730 suffix = "." + origFile.substring(sfpos + 1);
2734 JarInputStream jin = jprovider.getJarInputStream();
2736 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
2737 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
2738 * FileInputStream(jprovider)); }
2741 JarEntry entry = null;
2744 entry = jin.getNextJarEntry();
2745 } while (entry != null && !entry.getName().equals(jarEntryName));
2748 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
2749 File outFile = File.createTempFile(prefix, suffix);
2750 outFile.deleteOnExit();
2751 out = new PrintWriter(new FileOutputStream(outFile));
2754 while ((data = in.readLine()) != null)
2759 String t = outFile.getAbsolutePath();
2764 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
2766 } catch (Exception ex)
2768 ex.printStackTrace();
2776 } catch (IOException e)
2790 private class JvAnnotRow
2792 public JvAnnotRow(int i, AlignmentAnnotation jaa)
2799 * persisted version of annotation row from which to take vis properties
2801 public jalview.datamodel.AlignmentAnnotation template;
2804 * original position of the annotation row in the alignment
2810 * Load alignment frame from jalview XML DOM object
2815 * filename source string
2816 * @param loadTreesAndStructures
2817 * when false only create Viewport
2819 * data source provider
2820 * @return alignment frame created from view stored in DOM
2822 AlignFrame loadFromObject(JalviewModel object, String file,
2823 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
2825 SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
2826 Sequence[] vamsasSeq = vamsasSet.getSequence();
2828 JalviewModelSequence jms = object.getJalviewModelSequence();
2830 Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
2833 // ////////////////////////////////
2836 List<SequenceI> hiddenSeqs = null;
2838 List<SequenceI> tmpseqs = new ArrayList<>();
2840 boolean multipleView = false;
2841 SequenceI referenceseqForView = null;
2842 JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
2843 int vi = 0; // counter in vamsasSeq array
2844 for (int i = 0; i < jseqs.length; i++)
2846 String seqId = jseqs[i].getId();
2848 SequenceI tmpSeq = seqRefIds.get(seqId);
2851 if (!incompleteSeqs.containsKey(seqId))
2853 // may not need this check, but keep it for at least 2.9,1 release
2854 if (tmpSeq.getStart() != jseqs[i].getStart()
2855 || tmpSeq.getEnd() != jseqs[i].getEnd())
2858 .println("Warning JAL-2154 regression: updating start/end for sequence "
2859 + tmpSeq.toString() + " to " + jseqs[i]);
2864 incompleteSeqs.remove(seqId);
2866 if (vamsasSeq.length > vi && vamsasSeq[vi].getId().equals(seqId))
2868 // most likely we are reading a dataset XML document so
2869 // update from vamsasSeq section of XML for this sequence
2870 tmpSeq.setName(vamsasSeq[vi].getName());
2871 tmpSeq.setDescription(vamsasSeq[vi].getDescription());
2872 tmpSeq.setSequence(vamsasSeq[vi].getSequence());
2877 // reading multiple views, so vamsasSeq set is a subset of JSeq
2878 multipleView = true;
2880 tmpSeq.setStart(jseqs[i].getStart());
2881 tmpSeq.setEnd(jseqs[i].getEnd());
2882 tmpseqs.add(tmpSeq);
2886 tmpSeq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
2887 vamsasSeq[vi].getSequence());
2888 tmpSeq.setDescription(vamsasSeq[vi].getDescription());
2889 tmpSeq.setStart(jseqs[i].getStart());
2890 tmpSeq.setEnd(jseqs[i].getEnd());
2891 tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
2892 seqRefIds.put(vamsasSeq[vi].getId(), tmpSeq);
2893 tmpseqs.add(tmpSeq);
2897 if (jseqs[i].hasViewreference() && jseqs[i].getViewreference())
2899 referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
2902 if (jseqs[i].getHidden())
2904 if (hiddenSeqs == null)
2906 hiddenSeqs = new ArrayList<>();
2909 hiddenSeqs.add(tmpSeq);
2914 // Create the alignment object from the sequence set
2915 // ///////////////////////////////
2916 SequenceI[] orderedSeqs = tmpseqs
2917 .toArray(new SequenceI[tmpseqs.size()]);
2919 AlignmentI al = null;
2920 // so we must create or recover the dataset alignment before going further
2921 // ///////////////////////////////
2922 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
2924 // older jalview projects do not have a dataset - so creat alignment and
2926 al = new Alignment(orderedSeqs);
2927 al.setDataset(null);
2931 boolean isdsal = object.getJalviewModelSequence().getViewportCount() == 0;
2934 // we are importing a dataset record, so
2935 // recover reference to an alignment already materialsed as dataset
2936 al = getDatasetFor(vamsasSet.getDatasetId());
2940 // materialse the alignment
2941 al = new Alignment(orderedSeqs);
2945 addDatasetRef(vamsasSet.getDatasetId(), al);
2948 // finally, verify all data in vamsasSet is actually present in al
2949 // passing on flag indicating if it is actually a stored dataset
2950 recoverDatasetFor(vamsasSet, al, isdsal);
2953 if (referenceseqForView != null)
2955 al.setSeqrep(referenceseqForView);
2957 // / Add the alignment properties
2958 for (int i = 0; i < vamsasSet.getSequenceSetPropertiesCount(); i++)
2960 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties(i);
2961 al.setProperty(ssp.getKey(), ssp.getValue());
2964 // ///////////////////////////////
2966 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
2969 // load sequence features, database references and any associated PDB
2970 // structures for the alignment
2972 // prior to 2.10, this part would only be executed the first time a
2973 // sequence was encountered, but not afterwards.
2974 // now, for 2.10 projects, this is also done if the xml doc includes
2975 // dataset sequences not actually present in any particular view.
2977 for (int i = 0; i < vamsasSeq.length; i++)
2979 if (jseqs[i].getFeaturesCount() > 0)
2981 Features[] features = jseqs[i].getFeatures();
2982 for (int f = 0; f < features.length; f++)
2984 SequenceFeature sf = new SequenceFeature(features[f].getType(),
2985 features[f].getDescription(), features[f].getBegin(),
2986 features[f].getEnd(), features[f].getScore(),
2987 features[f].getFeatureGroup());
2988 sf.setStatus(features[f].getStatus());
2989 for (int od = 0; od < features[f].getOtherDataCount(); od++)
2991 OtherData keyValue = features[f].getOtherData(od);
2992 if (keyValue.getKey().startsWith("LINK"))
2994 sf.addLink(keyValue.getValue());
2998 sf.setValue(keyValue.getKey(), keyValue.getValue());
3002 // adds feature to datasequence's feature set (since Jalview 2.10)
3003 al.getSequenceAt(i).addSequenceFeature(sf);
3006 if (vamsasSeq[i].getDBRefCount() > 0)
3008 // adds dbrefs to datasequence's set (since Jalview 2.10)
3010 al.getSequenceAt(i).getDatasetSequence() == null ? al.getSequenceAt(i)
3011 : al.getSequenceAt(i).getDatasetSequence(),
3014 if (jseqs[i].getPdbidsCount() > 0)
3016 Pdbids[] ids = jseqs[i].getPdbids();
3017 for (int p = 0; p < ids.length; p++)
3019 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
3020 entry.setId(ids[p].getId());
3021 if (ids[p].getType() != null)
3023 if (PDBEntry.Type.getType(ids[p].getType()) != null)
3025 entry.setType(PDBEntry.Type.getType(ids[p].getType()));
3029 entry.setType(PDBEntry.Type.FILE);
3032 // jprovider is null when executing 'New View'
3033 if (ids[p].getFile() != null && jprovider != null)
3035 if (!pdbloaded.containsKey(ids[p].getFile()))
3037 entry.setFile(loadPDBFile(jprovider, ids[p].getId(),
3042 entry.setFile(pdbloaded.get(ids[p].getId()).toString());
3045 if (ids[p].getPdbentryItem() != null)
3047 for (PdbentryItem item : ids[p].getPdbentryItem())
3049 for (Property pr : item.getProperty())
3051 entry.setProperty(pr.getName(), pr.getValue());
3055 StructureSelectionManager.getStructureSelectionManager(
3056 Desktop.instance).registerPDBEntry(entry);
3057 // adds PDBEntry to datasequence's set (since Jalview 2.10)
3058 if (al.getSequenceAt(i).getDatasetSequence() != null)
3060 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
3064 al.getSequenceAt(i).addPDBId(entry);
3069 } // end !multipleview
3071 // ///////////////////////////////
3072 // LOAD SEQUENCE MAPPINGS
3074 if (vamsasSet.getAlcodonFrameCount() > 0)
3076 // TODO Potentially this should only be done once for all views of an
3078 AlcodonFrame[] alc = vamsasSet.getAlcodonFrame();
3079 for (int i = 0; i < alc.length; i++)
3081 AlignedCodonFrame cf = new AlignedCodonFrame();
3082 if (alc[i].getAlcodMapCount() > 0)
3084 AlcodMap[] maps = alc[i].getAlcodMap();
3085 for (int m = 0; m < maps.length; m++)
3087 SequenceI dnaseq = seqRefIds.get(maps[m].getDnasq());
3089 jalview.datamodel.Mapping mapping = null;
3090 // attach to dna sequence reference.
3091 if (maps[m].getMapping() != null)
3093 mapping = addMapping(maps[m].getMapping());
3094 if (dnaseq != null && mapping.getTo() != null)
3096 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
3101 frefedSequence.add(newAlcodMapRef(maps[m].getDnasq(), cf,
3106 al.addCodonFrame(cf);
3111 // ////////////////////////////////
3113 List<JvAnnotRow> autoAlan = new ArrayList<>();
3116 * store any annotations which forward reference a group's ID
3118 Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<>();
3120 if (vamsasSet.getAnnotationCount() > 0)
3122 Annotation[] an = vamsasSet.getAnnotation();
3124 for (int i = 0; i < an.length; i++)
3126 Annotation annotation = an[i];
3129 * test if annotation is automatically calculated for this view only
3131 boolean autoForView = false;
3132 if (annotation.getLabel().equals("Quality")
3133 || annotation.getLabel().equals("Conservation")
3134 || annotation.getLabel().equals("Consensus"))
3136 // Kludge for pre 2.5 projects which lacked the autocalculated flag
3138 if (!annotation.hasAutoCalculated())
3140 annotation.setAutoCalculated(true);
3144 || (annotation.hasAutoCalculated() && annotation
3145 .isAutoCalculated()))
3147 // remove ID - we don't recover annotation from other views for
3148 // view-specific annotation
3149 annotation.setId(null);
3152 // set visiblity for other annotation in this view
3153 String annotationId = annotation.getId();
3154 if (annotationId != null && annotationIds.containsKey(annotationId))
3156 AlignmentAnnotation jda = annotationIds.get(annotationId);
3157 // in principle Visible should always be true for annotation displayed
3158 // in multiple views
3159 if (annotation.hasVisible())
3161 jda.visible = annotation.getVisible();
3164 al.addAnnotation(jda);
3168 // Construct new annotation from model.
3169 AnnotationElement[] ae = annotation.getAnnotationElement();
3170 jalview.datamodel.Annotation[] anot = null;
3171 java.awt.Color firstColour = null;
3173 if (!annotation.getScoreOnly())
3175 anot = new jalview.datamodel.Annotation[al.getWidth()];
3176 for (int aa = 0; aa < ae.length && aa < anot.length; aa++)
3178 anpos = ae[aa].getPosition();
3180 if (anpos >= anot.length)
3185 anot[anpos] = new jalview.datamodel.Annotation(
3187 ae[aa].getDisplayCharacter(), ae[aa].getDescription(),
3188 (ae[aa].getSecondaryStructure() == null || ae[aa]
3189 .getSecondaryStructure().length() == 0) ? ' '
3190 : ae[aa].getSecondaryStructure().charAt(0),
3194 // JBPNote: Consider verifying dataflow for IO of secondary
3195 // structure annotation read from Stockholm files
3196 // this was added to try to ensure that
3197 // if (anot[ae[aa].getPosition()].secondaryStructure>' ')
3199 // anot[ae[aa].getPosition()].displayCharacter = "";
3201 anot[anpos].colour = new java.awt.Color(ae[aa].getColour());
3202 if (firstColour == null)
3204 firstColour = anot[anpos].colour;
3208 jalview.datamodel.AlignmentAnnotation jaa = null;
3210 if (annotation.getGraph())
3212 float llim = 0, hlim = 0;
3213 // if (autoForView || an[i].isAutoCalculated()) {
3216 jaa = new jalview.datamodel.AlignmentAnnotation(
3217 annotation.getLabel(), annotation.getDescription(), anot,
3218 llim, hlim, annotation.getGraphType());
3220 jaa.graphGroup = annotation.getGraphGroup();
3221 jaa._linecolour = firstColour;
3222 if (annotation.getThresholdLine() != null)
3224 jaa.setThreshold(new jalview.datamodel.GraphLine(annotation
3225 .getThresholdLine().getValue(), annotation
3226 .getThresholdLine().getLabel(), new java.awt.Color(
3227 annotation.getThresholdLine().getColour())));
3230 if (autoForView || annotation.isAutoCalculated())
3232 // Hardwire the symbol display line to ensure that labels for
3233 // histograms are displayed
3239 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
3240 an[i].getDescription(), anot);
3241 jaa._linecolour = firstColour;
3243 // register new annotation
3244 if (an[i].getId() != null)
3246 annotationIds.put(an[i].getId(), jaa);
3247 jaa.annotationId = an[i].getId();
3249 // recover sequence association
3250 String sequenceRef = an[i].getSequenceRef();
3251 if (sequenceRef != null)
3253 // from 2.9 sequenceRef is to sequence id (JAL-1781)
3254 SequenceI sequence = seqRefIds.get(sequenceRef);
3255 if (sequence == null)
3257 // in pre-2.9 projects sequence ref is to sequence name
3258 sequence = al.findName(sequenceRef);
3260 if (sequence != null)
3262 jaa.createSequenceMapping(sequence, 1, true);
3263 sequence.addAlignmentAnnotation(jaa);
3266 // and make a note of any group association
3267 if (an[i].getGroupRef() != null && an[i].getGroupRef().length() > 0)
3269 List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
3270 .get(an[i].getGroupRef());
3273 aal = new ArrayList<>();
3274 groupAnnotRefs.put(an[i].getGroupRef(), aal);
3279 if (an[i].hasScore())
3281 jaa.setScore(an[i].getScore());
3283 if (an[i].hasVisible())
3285 jaa.visible = an[i].getVisible();
3288 if (an[i].hasCentreColLabels())
3290 jaa.centreColLabels = an[i].getCentreColLabels();
3293 if (an[i].hasScaleColLabels())
3295 jaa.scaleColLabel = an[i].getScaleColLabels();
3297 if (an[i].hasAutoCalculated() && an[i].isAutoCalculated())
3299 // newer files have an 'autoCalculated' flag and store calculation
3300 // state in viewport properties
3301 jaa.autoCalculated = true; // means annotation will be marked for
3302 // update at end of load.
3304 if (an[i].hasGraphHeight())
3306 jaa.graphHeight = an[i].getGraphHeight();
3308 if (an[i].hasBelowAlignment())
3310 jaa.belowAlignment = an[i].isBelowAlignment();
3312 jaa.setCalcId(an[i].getCalcId());
3313 if (an[i].getPropertyCount() > 0)
3315 for (jalview.schemabinding.version2.Property prop : an[i]
3318 jaa.setProperty(prop.getName(), prop.getValue());
3321 if (jaa.autoCalculated)
3323 autoAlan.add(new JvAnnotRow(i, jaa));
3326 // if (!autoForView)
3328 // add autocalculated group annotation and any user created annotation
3330 al.addAnnotation(jaa);
3334 // ///////////////////////
3336 // Create alignment markup and styles for this view
3337 if (jms.getJGroupCount() > 0)
3339 JGroup[] groups = jms.getJGroup();
3340 boolean addAnnotSchemeGroup = false;
3341 for (int i = 0; i < groups.length; i++)
3343 JGroup jGroup = groups[i];
3344 ColourSchemeI cs = null;
3345 if (jGroup.getColour() != null)
3347 if (jGroup.getColour().startsWith("ucs"))
3349 cs = getUserColourScheme(jms, jGroup.getColour());
3351 else if (jGroup.getColour().equals("AnnotationColourGradient")
3352 && jGroup.getAnnotationColours() != null)
3354 addAnnotSchemeGroup = true;
3358 cs = ColourSchemeProperty.getColourScheme(al, jGroup.getColour());
3361 int pidThreshold = jGroup.getPidThreshold();
3363 Vector<SequenceI> seqs = new Vector<>();
3365 for (int s = 0; s < jGroup.getSeqCount(); s++)
3367 String seqId = jGroup.getSeq(s) + "";
3368 SequenceI ts = seqRefIds.get(seqId);
3372 seqs.addElement(ts);
3376 if (seqs.size() < 1)
3381 SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
3382 jGroup.getDisplayBoxes(), jGroup.getDisplayText(),
3383 jGroup.getColourText(), jGroup.getStart(), jGroup.getEnd());
3384 sg.getGroupColourScheme().setThreshold(pidThreshold, true);
3385 sg.getGroupColourScheme().setConservationInc(jGroup.getConsThreshold());
3386 sg.setOutlineColour(new java.awt.Color(jGroup.getOutlineColour()));
3388 sg.textColour = new java.awt.Color(jGroup.getTextCol1());
3389 sg.textColour2 = new java.awt.Color(jGroup.getTextCol2());
3390 sg.setShowNonconserved(jGroup.hasShowUnconserved() ? jGroup
3391 .isShowUnconserved() : false);
3392 sg.thresholdTextColour = jGroup.getTextColThreshold();
3393 if (jGroup.hasShowConsensusHistogram())
3395 sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
3398 if (jGroup.hasShowSequenceLogo())
3400 sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
3402 if (jGroup.hasNormaliseSequenceLogo())
3404 sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
3406 if (jGroup.hasIgnoreGapsinConsensus())
3408 sg.setIgnoreGapsConsensus(jGroup.getIgnoreGapsinConsensus());
3410 if (jGroup.getConsThreshold() != 0)
3412 Conservation c = new Conservation("All", sg.getSequences(null),
3413 0, sg.getWidth() - 1);
3415 c.verdict(false, 25);
3416 sg.cs.setConservation(c);
3419 if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
3421 // re-instate unique group/annotation row reference
3422 List<AlignmentAnnotation> jaal = groupAnnotRefs.get(jGroup
3426 for (AlignmentAnnotation jaa : jaal)
3429 if (jaa.autoCalculated)
3431 // match up and try to set group autocalc alignment row for this
3433 if (jaa.label.startsWith("Consensus for "))
3435 sg.setConsensus(jaa);
3437 // match up and try to set group autocalc alignment row for this
3439 if (jaa.label.startsWith("Conservation for "))
3441 sg.setConservationRow(jaa);
3448 if (addAnnotSchemeGroup)
3450 // reconstruct the annotation colourscheme
3451 sg.setColourScheme(constructAnnotationColour(
3452 jGroup.getAnnotationColours(), null, al, jms, false));
3458 // only dataset in this model, so just return.
3461 // ///////////////////////////////
3464 // If we just load in the same jar file again, the sequenceSetId
3465 // will be the same, and we end up with multiple references
3466 // to the same sequenceSet. We must modify this id on load
3467 // so that each load of the file gives a unique id
3468 String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
3469 String viewId = (view.getId() == null ? null : view.getId()
3471 AlignFrame af = null;
3472 AlignViewport av = null;
3473 // now check to see if we really need to create a new viewport.
3474 if (multipleView && viewportsAdded.size() == 0)
3476 // We recovered an alignment for which a viewport already exists.
3477 // TODO: fix up any settings necessary for overlaying stored state onto
3478 // state recovered from another document. (may not be necessary).
3479 // we may need a binding from a viewport in memory to one recovered from
3481 // and then recover its containing af to allow the settings to be applied.
3482 // TODO: fix for vamsas demo
3484 .println("About to recover a viewport for existing alignment: Sequence set ID is "
3486 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
3487 if (seqsetobj != null)
3489 if (seqsetobj instanceof String)
3491 uniqueSeqSetId = (String) seqsetobj;
3493 .println("Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
3499 .println("Warning : Collision between sequence set ID string and existing jalview object mapping.");
3505 * indicate that annotation colours are applied across all groups (pre
3506 * Jalview 2.8.1 behaviour)
3508 boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan(
3509 "2.8.1", object.getVersion());
3511 AlignmentPanel ap = null;
3512 boolean isnewview = true;
3515 // Check to see if this alignment already has a view id == viewId
3516 jalview.gui.AlignmentPanel views[] = Desktop
3517 .getAlignmentPanels(uniqueSeqSetId);
3518 if (views != null && views.length > 0)
3520 for (int v = 0; v < views.length; v++)
3522 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
3524 // recover the existing alignpanel, alignframe, viewport
3525 af = views[v].alignFrame;
3528 // TODO: could even skip resetting view settings if we don't want to
3529 // change the local settings from other jalview processes
3538 af = loadViewport(file, jseqs, hiddenSeqs, al, jms, view,
3539 uniqueSeqSetId, viewId, autoAlan);
3545 * Load any trees, PDB structures and viewers
3547 * Not done if flag is false (when this method is used for New View)
3549 if (loadTreesAndStructures)
3551 loadTrees(jms, view, af, av, ap);
3552 loadPDBStructures(jprovider, jseqs, af, ap);
3553 loadRnaViewers(jprovider, jseqs, ap);
3555 // and finally return.
3560 * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
3561 * panel is restored from separate jar entries, two (gapped and trimmed) per
3562 * sequence and secondary structure.
3564 * Currently each viewer shows just one sequence and structure (gapped and
3565 * trimmed), however this method is designed to support multiple sequences or
3566 * structures in viewers if wanted in future.
3572 private void loadRnaViewers(jarInputStreamProvider jprovider,
3573 JSeq[] jseqs, AlignmentPanel ap)
3576 * scan the sequences for references to viewers; create each one the first
3577 * time it is referenced, add Rna models to existing viewers
3579 for (JSeq jseq : jseqs)
3581 for (int i = 0; i < jseq.getRnaViewerCount(); i++)
3583 RnaViewer viewer = jseq.getRnaViewer(i);
3584 AppVarna appVarna = findOrCreateVarnaViewer(viewer,
3585 uniqueSetSuffix, ap);
3587 for (int j = 0; j < viewer.getSecondaryStructureCount(); j++)
3589 SecondaryStructure ss = viewer.getSecondaryStructure(j);
3590 SequenceI seq = seqRefIds.get(jseq.getId());
3591 AlignmentAnnotation ann = this.annotationIds.get(ss
3592 .getAnnotationId());
3595 * add the structure to the Varna display (with session state copied
3596 * from the jar to a temporary file)
3598 boolean gapped = ss.isGapped();
3599 String rnaTitle = ss.getTitle();
3600 String sessionState = ss.getViewerState();
3601 String tempStateFile = copyJarEntry(jprovider, sessionState,
3603 RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
3604 appVarna.addModelSession(rna, rnaTitle, tempStateFile);
3606 appVarna.setInitialSelection(viewer.getSelectedRna());
3612 * Locate and return an already instantiated matching AppVarna, or create one
3616 * @param viewIdSuffix
3620 protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
3621 String viewIdSuffix, AlignmentPanel ap)
3624 * on each load a suffix is appended to the saved viewId, to avoid conflicts
3625 * if load is repeated
3627 String postLoadId = viewer.getViewId() + viewIdSuffix;
3628 for (JInternalFrame frame : getAllFrames())
3630 if (frame instanceof AppVarna)
3632 AppVarna varna = (AppVarna) frame;
3633 if (postLoadId.equals(varna.getViewId()))
3635 // this viewer is already instantiated
3636 // could in future here add ap as another 'parent' of the
3637 // AppVarna window; currently just 1-to-many
3644 * viewer not found - make it
3646 RnaViewerModel model = new RnaViewerModel(postLoadId,
3647 viewer.getTitle(), viewer.getXpos(), viewer.getYpos(),
3648 viewer.getWidth(), viewer.getHeight(),
3649 viewer.getDividerLocation());
3650 AppVarna varna = new AppVarna(model, ap);
3656 * Load any saved trees
3664 protected void loadTrees(JalviewModelSequence jms, Viewport view,
3665 AlignFrame af, AlignViewport av, AlignmentPanel ap)
3667 // TODO result of automated refactoring - are all these parameters needed?
3670 for (int t = 0; t < jms.getTreeCount(); t++)
3673 Tree tree = jms.getTree(t);
3675 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
3678 tp = af.showNewickTree(
3679 new jalview.io.NewickFile(tree.getNewick()),
3680 tree.getTitle(), tree.getWidth(), tree.getHeight(),
3681 tree.getXpos(), tree.getYpos());
3682 if (tree.getId() != null)
3684 // perhaps bind the tree id to something ?
3689 // update local tree attributes ?
3690 // TODO: should check if tp has been manipulated by user - if so its
3691 // settings shouldn't be modified
3692 tp.setTitle(tree.getTitle());
3693 tp.setBounds(new Rectangle(tree.getXpos(), tree.getYpos(), tree
3694 .getWidth(), tree.getHeight()));
3695 tp.av = av; // af.viewport; // TODO: verify 'associate with all
3698 tp.treeCanvas.av = av; // af.viewport;
3699 tp.treeCanvas.ap = ap; // af.alignPanel;
3704 warn("There was a problem recovering stored Newick tree: \n"
3705 + tree.getNewick());
3709 tp.fitToWindow.setState(tree.getFitToWindow());
3710 tp.fitToWindow_actionPerformed(null);
3712 if (tree.getFontName() != null)
3714 tp.setTreeFont(new java.awt.Font(tree.getFontName(), tree
3715 .getFontStyle(), tree.getFontSize()));
3719 tp.setTreeFont(new java.awt.Font(view.getFontName(), view
3720 .getFontStyle(), tree.getFontSize()));
3723 tp.showPlaceholders(tree.getMarkUnlinked());
3724 tp.showBootstrap(tree.getShowBootstrap());
3725 tp.showDistances(tree.getShowDistances());
3727 tp.treeCanvas.threshold = tree.getThreshold();
3729 if (tree.getCurrentTree())
3731 af.viewport.setCurrentTree(tp.getTree());
3735 } catch (Exception ex)
3737 ex.printStackTrace();
3742 * Load and link any saved structure viewers.
3749 protected void loadPDBStructures(jarInputStreamProvider jprovider,
3750 JSeq[] jseqs, AlignFrame af, AlignmentPanel ap)
3753 * Run through all PDB ids on the alignment, and collect mappings between
3754 * distinct view ids and all sequences referring to that view.
3756 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<>();
3758 for (int i = 0; i < jseqs.length; i++)
3760 if (jseqs[i].getPdbidsCount() > 0)
3762 Pdbids[] ids = jseqs[i].getPdbids();
3763 for (int p = 0; p < ids.length; p++)
3765 final int structureStateCount = ids[p].getStructureStateCount();
3766 for (int s = 0; s < structureStateCount; s++)
3768 // check to see if we haven't already created this structure view
3769 final StructureState structureState = ids[p]
3770 .getStructureState(s);
3771 String sviewid = (structureState.getViewId() == null) ? null
3772 : structureState.getViewId() + uniqueSetSuffix;
3773 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
3774 // Originally : ids[p].getFile()
3775 // : TODO: verify external PDB file recovery still works in normal
3776 // jalview project load
3777 jpdb.setFile(loadPDBFile(jprovider, ids[p].getId(),
3779 jpdb.setId(ids[p].getId());
3781 int x = structureState.getXpos();
3782 int y = structureState.getYpos();
3783 int width = structureState.getWidth();
3784 int height = structureState.getHeight();
3786 // Probably don't need to do this anymore...
3787 // Desktop.desktop.getComponentAt(x, y);
3788 // TODO: NOW: check that this recovers the PDB file correctly.
3789 String pdbFile = loadPDBFile(jprovider, ids[p].getId(),
3791 jalview.datamodel.SequenceI seq = seqRefIds.get(jseqs[i]
3793 if (sviewid == null)
3795 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width
3798 if (!structureViewers.containsKey(sviewid))
3800 structureViewers.put(sviewid,
3801 new StructureViewerModel(x, y, width, height, false,
3802 false, true, structureState.getViewId(),
3803 structureState.getType()));
3804 // Legacy pre-2.7 conversion JAL-823 :
3805 // do not assume any view has to be linked for colour by
3809 // assemble String[] { pdb files }, String[] { id for each
3810 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
3811 // seqs_file 2}, boolean[] {
3812 // linkAlignPanel,superposeWithAlignpanel}} from hash
3813 StructureViewerModel jmoldat = structureViewers.get(sviewid);
3814 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
3815 | (structureState.hasAlignwithAlignPanel() ? structureState
3816 .getAlignwithAlignPanel() : false));
3819 * Default colour by linked panel to false if not specified (e.g.
3820 * for pre-2.7 projects)
3822 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
3823 colourWithAlignPanel |= (structureState
3824 .hasColourwithAlignPanel() ? structureState
3825 .getColourwithAlignPanel() : false);
3826 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
3829 * Default colour by viewer to true if not specified (e.g. for
3832 boolean colourByViewer = jmoldat.isColourByViewer();
3833 colourByViewer &= structureState.hasColourByJmol() ? structureState
3834 .getColourByJmol() : true;
3835 jmoldat.setColourByViewer(colourByViewer);
3837 if (jmoldat.getStateData().length() < structureState
3838 .getContent().length())
3841 jmoldat.setStateData(structureState.getContent());
3844 if (ids[p].getFile() != null)
3846 File mapkey = new File(ids[p].getFile());
3847 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
3848 if (seqstrmaps == null)
3850 jmoldat.getFileData().put(
3852 seqstrmaps = jmoldat.new StructureData(pdbFile,
3855 if (!seqstrmaps.getSeqList().contains(seq))
3857 seqstrmaps.getSeqList().add(seq);
3863 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");
3870 // Instantiate the associated structure views
3871 for (Entry<String, StructureViewerModel> entry : structureViewers
3876 createOrLinkStructureViewer(entry, af, ap, jprovider);
3877 } catch (Exception e)
3879 System.err.println("Error loading structure viewer: "
3881 // failed - try the next one
3893 protected void createOrLinkStructureViewer(
3894 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
3895 AlignmentPanel ap, jarInputStreamProvider jprovider)
3897 final StructureViewerModel stateData = viewerData.getValue();
3900 * Search for any viewer windows already open from other alignment views
3901 * that exactly match the stored structure state
3903 StructureViewerBase comp = findMatchingViewer(viewerData);
3907 linkStructureViewer(ap, comp, stateData);
3912 * From 2.9: stateData.type contains JMOL or CHIMERA, data is in jar entry
3913 * "viewer_"+stateData.viewId
3915 if (ViewerType.CHIMERA.toString().equals(stateData.getType()))
3917 createChimeraViewer(viewerData, af, jprovider);
3922 * else Jmol (if pre-2.9, stateData contains JMOL state string)
3924 createJmolViewer(viewerData, af, jprovider);
3929 * Create a new Chimera viewer.
3935 protected void createChimeraViewer(
3936 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
3937 jarInputStreamProvider jprovider)
3939 StructureViewerModel data = viewerData.getValue();
3940 String chimeraSessionFile = data.getStateData();
3943 * Copy Chimera session from jar entry "viewer_"+viewId to a temporary file
3945 * NB this is the 'saved' viewId as in the project file XML, _not_ the
3946 * 'uniquified' sviewid used to reconstruct the viewer here
3948 String viewerJarEntryName = getViewerJarEntryName(data.getViewId());
3949 chimeraSessionFile = copyJarEntry(jprovider, viewerJarEntryName,
3952 Set<Entry<File, StructureData>> fileData = data.getFileData()
3954 List<PDBEntry> pdbs = new ArrayList<>();
3955 List<SequenceI[]> allseqs = new ArrayList<>();
3956 for (Entry<File, StructureData> pdb : fileData)
3958 String filePath = pdb.getValue().getFilePath();
3959 String pdbId = pdb.getValue().getPdbId();
3960 // pdbs.add(new PDBEntry(filePath, pdbId));
3961 pdbs.add(new PDBEntry(pdbId, null, PDBEntry.Type.PDB, filePath));
3962 final List<SequenceI> seqList = pdb.getValue().getSeqList();
3963 SequenceI[] seqs = seqList.toArray(new SequenceI[seqList.size()]);
3967 boolean colourByChimera = data.isColourByViewer();
3968 boolean colourBySequence = data.isColourWithAlignPanel();
3970 // TODO use StructureViewer as a factory here, see JAL-1761
3971 final PDBEntry[] pdbArray = pdbs.toArray(new PDBEntry[pdbs.size()]);
3972 final SequenceI[][] seqsArray = allseqs.toArray(new SequenceI[allseqs
3974 String newViewId = viewerData.getKey();
3976 ChimeraViewFrame cvf = new ChimeraViewFrame(chimeraSessionFile,
3977 af.alignPanel, pdbArray, seqsArray, colourByChimera,
3978 colourBySequence, newViewId);
3979 cvf.setSize(data.getWidth(), data.getHeight());
3980 cvf.setLocation(data.getX(), data.getY());
3984 * Create a new Jmol window. First parse the Jmol state to translate filenames
3985 * loaded into the view, and record the order in which files are shown in the
3986 * Jmol view, so we can add the sequence mappings in same order.
3992 protected void createJmolViewer(
3993 final Entry<String, StructureViewerModel> viewerData,
3994 AlignFrame af, jarInputStreamProvider jprovider)
3996 final StructureViewerModel svattrib = viewerData.getValue();
3997 String state = svattrib.getStateData();
4000 * Pre-2.9: state element value is the Jmol state string
4002 * 2.9+: @type is "JMOL", state data is in a Jar file member named "viewer_"
4005 if (ViewerType.JMOL.toString().equals(svattrib.getType()))
4007 state = readJarEntry(jprovider,
4008 getViewerJarEntryName(svattrib.getViewId()));
4011 List<String> pdbfilenames = new ArrayList<>();
4012 List<SequenceI[]> seqmaps = new ArrayList<>();
4013 List<String> pdbids = new ArrayList<>();
4014 StringBuilder newFileLoc = new StringBuilder(64);
4015 int cp = 0, ncp, ecp;
4016 Map<File, StructureData> oldFiles = svattrib.getFileData();
4017 while ((ncp = state.indexOf("load ", cp)) > -1)
4021 // look for next filename in load statement
4022 newFileLoc.append(state.substring(cp,
4023 ncp = (state.indexOf("\"", ncp + 1) + 1)));
4024 String oldfilenam = state.substring(ncp,
4025 ecp = state.indexOf("\"", ncp));
4026 // recover the new mapping data for this old filename
4027 // have to normalize filename - since Jmol and jalview do
4029 // translation differently.
4030 StructureData filedat = oldFiles.get(new File(oldfilenam));
4031 if (filedat == null)
4033 String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
4034 filedat = oldFiles.get(new File(reformatedOldFilename));
4036 newFileLoc.append(Platform.escapeString(filedat.getFilePath()));
4037 pdbfilenames.add(filedat.getFilePath());
4038 pdbids.add(filedat.getPdbId());
4039 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4040 newFileLoc.append("\"");
4041 cp = ecp + 1; // advance beyond last \" and set cursor so we can
4042 // look for next file statement.
4043 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
4047 // just append rest of state
4048 newFileLoc.append(state.substring(cp));
4052 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
4053 newFileLoc = new StringBuilder(state);
4054 newFileLoc.append("; load append ");
4055 for (File id : oldFiles.keySet())
4057 // add this and any other pdb files that should be present in
4059 StructureData filedat = oldFiles.get(id);
4060 newFileLoc.append(filedat.getFilePath());
4061 pdbfilenames.add(filedat.getFilePath());
4062 pdbids.add(filedat.getPdbId());
4063 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4064 newFileLoc.append(" \"");
4065 newFileLoc.append(filedat.getFilePath());
4066 newFileLoc.append("\"");
4069 newFileLoc.append(";");
4072 if (newFileLoc.length() == 0)
4076 int histbug = newFileLoc.indexOf("history = ");
4080 * change "history = [true|false];" to "history = [1|0];"
4083 int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";", histbug);
4084 String val = (diff == -1) ? null : newFileLoc
4085 .substring(histbug, diff);
4086 if (val != null && val.length() >= 4)
4088 if (val.contains("e")) // eh? what can it be?
4090 if (val.trim().equals("true"))
4098 newFileLoc.replace(histbug, diff, val);
4103 final String[] pdbf = pdbfilenames.toArray(new String[pdbfilenames
4105 final String[] id = pdbids.toArray(new String[pdbids.size()]);
4106 final SequenceI[][] sq = seqmaps
4107 .toArray(new SequenceI[seqmaps.size()][]);
4108 final String fileloc = newFileLoc.toString();
4109 final String sviewid = viewerData.getKey();
4110 final AlignFrame alf = af;
4111 final Rectangle rect = new Rectangle(svattrib.getX(), svattrib.getY(),
4112 svattrib.getWidth(), svattrib.getHeight());
4115 javax.swing.SwingUtilities.invokeAndWait(new Runnable()
4120 JalviewStructureDisplayI sview = null;
4123 sview = new StructureViewer(alf.alignPanel
4124 .getStructureSelectionManager()).createView(
4125 StructureViewer.ViewerType.JMOL, pdbf, id, sq,
4126 alf.alignPanel, svattrib, fileloc, rect, sviewid);
4127 addNewStructureViewer(sview);
4128 } catch (OutOfMemoryError ex)
4130 new OOMWarning("restoring structure view for PDB id " + id,
4131 (OutOfMemoryError) ex.getCause());
4132 if (sview != null && sview.isVisible())
4134 sview.closeViewer(false);
4135 sview.setVisible(false);
4141 } catch (InvocationTargetException ex)
4143 warn("Unexpected error when opening Jmol view.", ex);
4145 } catch (InterruptedException e)
4147 // e.printStackTrace();
4153 * Generates a name for the entry in the project jar file to hold state
4154 * information for a structure viewer
4159 protected String getViewerJarEntryName(String viewId)
4161 return VIEWER_PREFIX + viewId;
4165 * Returns any open frame that matches given structure viewer data. The match
4166 * is based on the unique viewId, or (for older project versions) the frame's
4172 protected StructureViewerBase findMatchingViewer(
4173 Entry<String, StructureViewerModel> viewerData)
4175 final String sviewid = viewerData.getKey();
4176 final StructureViewerModel svattrib = viewerData.getValue();
4177 StructureViewerBase comp = null;
4178 JInternalFrame[] frames = getAllFrames();
4179 for (JInternalFrame frame : frames)
4181 if (frame instanceof StructureViewerBase)
4184 * Post jalview 2.4 schema includes structure view id
4187 && ((StructureViewerBase) frame).getViewId()
4190 comp = (StructureViewerBase) frame;
4191 break; // break added in 2.9
4194 * Otherwise test for matching position and size of viewer frame
4196 else if (frame.getX() == svattrib.getX()
4197 && frame.getY() == svattrib.getY()
4198 && frame.getHeight() == svattrib.getHeight()
4199 && frame.getWidth() == svattrib.getWidth())
4201 comp = (StructureViewerBase) frame;
4202 // no break in faint hope of an exact match on viewId
4210 * Link an AlignmentPanel to an existing structure viewer.
4215 * @param useinViewerSuperpos
4216 * @param usetoColourbyseq
4217 * @param viewerColouring
4219 protected void linkStructureViewer(AlignmentPanel ap,
4220 StructureViewerBase viewer, StructureViewerModel stateData)
4222 // NOTE: if the jalview project is part of a shared session then
4223 // view synchronization should/could be done here.
4225 final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
4226 final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
4227 final boolean viewerColouring = stateData.isColourByViewer();
4228 Map<File, StructureData> oldFiles = stateData.getFileData();
4231 * Add mapping for sequences in this view to an already open viewer
4233 final AAStructureBindingModel binding = viewer.getBinding();
4234 for (File id : oldFiles.keySet())
4236 // add this and any other pdb files that should be present in the
4238 StructureData filedat = oldFiles.get(id);
4239 String pdbFile = filedat.getFilePath();
4240 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
4241 binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE);
4242 binding.addSequenceForStructFile(pdbFile, seq);
4244 // and add the AlignmentPanel's reference to the view panel
4245 viewer.addAlignmentPanel(ap);
4246 if (useinViewerSuperpos)
4248 viewer.useAlignmentPanelForSuperposition(ap);
4252 viewer.excludeAlignmentPanelForSuperposition(ap);
4254 if (usetoColourbyseq)
4256 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
4260 viewer.excludeAlignmentPanelForColourbyseq(ap);
4265 * Get all frames within the Desktop.
4269 protected JInternalFrame[] getAllFrames()
4271 JInternalFrame[] frames = null;
4272 // TODO is this necessary - is it safe - risk of hanging?
4277 frames = Desktop.desktop.getAllFrames();
4278 } catch (ArrayIndexOutOfBoundsException e)
4280 // occasional No such child exceptions are thrown here...
4284 } catch (InterruptedException f)
4288 } while (frames == null);
4293 * Answers true if 'version' is equal to or later than 'supported', where each
4294 * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
4295 * changes. Development and test values for 'version' are leniently treated
4299 * - minimum version we are comparing against
4301 * - version of data being processsed
4304 public static boolean isVersionStringLaterThan(String supported,
4307 if (supported == null || version == null
4308 || version.equalsIgnoreCase("DEVELOPMENT BUILD")
4309 || version.equalsIgnoreCase("Test")
4310 || version.equalsIgnoreCase("AUTOMATED BUILD"))
4312 System.err.println("Assuming project file with "
4313 + (version == null ? "null" : version)
4314 + " is compatible with Jalview version " + supported);
4319 return StringUtils.compareVersions(version, supported, "b") >= 0;
4323 Vector<JalviewStructureDisplayI> newStructureViewers = null;
4325 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
4327 if (newStructureViewers != null)
4329 sview.getBinding().setFinishedLoadingFromArchive(false);
4330 newStructureViewers.add(sview);
4334 protected void setLoadingFinishedForNewStructureViewers()
4336 if (newStructureViewers != null)
4338 for (JalviewStructureDisplayI sview : newStructureViewers)
4340 sview.getBinding().setFinishedLoadingFromArchive(true);
4342 newStructureViewers.clear();
4343 newStructureViewers = null;
4347 AlignFrame loadViewport(String file, JSeq[] JSEQ,
4348 List<SequenceI> hiddenSeqs, AlignmentI al,
4349 JalviewModelSequence jms, Viewport view, String uniqueSeqSetId,
4350 String viewId, List<JvAnnotRow> autoAlan)
4352 AlignFrame af = null;
4353 af = new AlignFrame(al, view.getWidth(), view.getHeight(),
4354 uniqueSeqSetId, viewId);
4356 af.setFileName(file, FileFormat.Jalview);
4358 for (int i = 0; i < JSEQ.length; i++)
4360 af.viewport.setSequenceColour(af.viewport.getAlignment()
4361 .getSequenceAt(i), new java.awt.Color(JSEQ[i].getColour()));
4366 af.getViewport().setColourByReferenceSeq(true);
4367 af.getViewport().setDisplayReferenceSeq(true);
4370 af.viewport.setGatherViewsHere(view.getGatheredViews());
4372 if (view.getSequenceSetId() != null)
4374 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
4376 af.viewport.setSequenceSetId(uniqueSeqSetId);
4379 // propagate shared settings to this new view
4380 af.viewport.setHistoryList(av.getHistoryList());
4381 af.viewport.setRedoList(av.getRedoList());
4385 viewportsAdded.put(uniqueSeqSetId, af.viewport);
4387 // TODO: check if this method can be called repeatedly without
4388 // side-effects if alignpanel already registered.
4389 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
4391 // apply Hidden regions to view.
4392 if (hiddenSeqs != null)
4394 for (int s = 0; s < JSEQ.length; s++)
4396 SequenceGroup hidden = new SequenceGroup();
4397 boolean isRepresentative = false;
4398 for (int r = 0; r < JSEQ[s].getHiddenSequencesCount(); r++)
4400 isRepresentative = true;
4401 SequenceI sequenceToHide = al.getSequenceAt(JSEQ[s]
4402 .getHiddenSequences(r));
4403 hidden.addSequence(sequenceToHide, false);
4404 // remove from hiddenSeqs list so we don't try to hide it twice
4405 hiddenSeqs.remove(sequenceToHide);
4407 if (isRepresentative)
4409 SequenceI representativeSequence = al.getSequenceAt(s);
4410 hidden.addSequence(representativeSequence, false);
4411 af.viewport.hideRepSequences(representativeSequence, hidden);
4415 SequenceI[] hseqs = hiddenSeqs.toArray(new SequenceI[hiddenSeqs
4417 af.viewport.hideSequence(hseqs);
4420 // recover view properties and display parameters
4421 if (view.getViewName() != null)
4423 af.viewport.viewName = view.getViewName();
4424 af.setInitialTabVisible();
4426 af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(),
4429 af.viewport.setShowAnnotation(view.getShowAnnotation());
4430 af.viewport.setAbovePIDThreshold(view.getPidSelected());
4431 af.viewport.setThreshold(view.getPidThreshold());
4433 af.viewport.setColourText(view.getShowColourText());
4435 af.viewport.setConservationSelected(view.getConservationSelected());
4436 af.viewport.setIncrement(view.getConsThreshold());
4437 af.viewport.setShowJVSuffix(view.getShowFullId());
4438 af.viewport.setRightAlignIds(view.getRightAlignIds());
4439 af.viewport.setFont(
4440 new java.awt.Font(view.getFontName(), view.getFontStyle(), view
4441 .getFontSize()), true);
4442 ViewStyleI vs = af.viewport.getViewStyle();
4443 vs.setScaleProteinAsCdna(view.isScaleProteinAsCdna());
4444 af.viewport.setViewStyle(vs);
4445 // TODO: allow custom charWidth/Heights to be restored by updating them
4446 // after setting font - which means set above to false
4447 af.viewport.setRenderGaps(view.getRenderGaps());
4448 af.viewport.setWrapAlignment(view.getWrapAlignment());
4449 af.viewport.setShowAnnotation(view.getShowAnnotation());
4451 af.viewport.setShowBoxes(view.getShowBoxes());
4453 af.viewport.setShowText(view.getShowText());
4455 af.viewport.setTextColour(new java.awt.Color(view.getTextCol1()));
4456 af.viewport.setTextColour2(new java.awt.Color(view.getTextCol2()));
4457 af.viewport.setThresholdTextColour(view.getTextColThreshold());
4458 af.viewport.setShowUnconserved(view.hasShowUnconserved() ? view
4459 .isShowUnconserved() : false);
4460 af.viewport.getRanges().setStartRes(view.getStartRes());
4461 // startSeq set in af.alignPanel.updateLayout below
4462 af.alignPanel.updateLayout();
4463 ColourSchemeI cs = null;
4464 // apply colourschemes
4465 if (view.getBgColour() != null)
4467 if (view.getBgColour().startsWith("ucs"))
4469 cs = getUserColourScheme(jms, view.getBgColour());
4471 else if (view.getBgColour().startsWith("Annotation"))
4473 AnnotationColours viewAnnColour = view.getAnnotationColours();
4474 cs = constructAnnotationColour(viewAnnColour, af, al, jms, true);
4481 cs = ColourSchemeProperty.getColourScheme(al, view.getBgColour());
4485 af.viewport.setGlobalColourScheme(cs);
4486 af.viewport.getResidueShading().setThreshold(
4487 view.getPidThreshold(), true);
4488 af.viewport.getResidueShading().setConsensus(
4489 af.viewport.getSequenceConsensusHash());
4490 af.viewport.setColourAppliesToAllGroups(false);
4492 if (view.getConservationSelected() && cs != null)
4494 af.viewport.getResidueShading().setConservationInc(
4495 view.getConsThreshold());
4498 af.changeColour(cs);
4500 af.viewport.setColourAppliesToAllGroups(true);
4502 af.viewport.setShowSequenceFeatures(view.getShowSequenceFeatures());
4504 if (view.hasCentreColumnLabels())
4506 af.viewport.setCentreColumnLabels(view.getCentreColumnLabels());
4508 if (view.hasIgnoreGapsinConsensus())
4510 af.viewport.setIgnoreGapsConsensus(view.getIgnoreGapsinConsensus(),
4513 if (view.hasFollowHighlight())
4515 af.viewport.setFollowHighlight(view.getFollowHighlight());
4517 if (view.hasFollowSelection())
4519 af.viewport.followSelection = view.getFollowSelection();
4521 if (view.hasShowConsensusHistogram())
4523 af.viewport.setShowConsensusHistogram(view
4524 .getShowConsensusHistogram());
4528 af.viewport.setShowConsensusHistogram(true);
4530 if (view.hasShowSequenceLogo())
4532 af.viewport.setShowSequenceLogo(view.getShowSequenceLogo());
4536 af.viewport.setShowSequenceLogo(false);
4538 if (view.hasNormaliseSequenceLogo())
4540 af.viewport.setNormaliseSequenceLogo(view.getNormaliseSequenceLogo());
4542 if (view.hasShowDbRefTooltip())
4544 af.viewport.setShowDBRefs(view.getShowDbRefTooltip());
4546 if (view.hasShowNPfeatureTooltip())
4548 af.viewport.setShowNPFeats(view.hasShowNPfeatureTooltip());
4550 if (view.hasShowGroupConsensus())
4552 af.viewport.setShowGroupConsensus(view.getShowGroupConsensus());
4556 af.viewport.setShowGroupConsensus(false);
4558 if (view.hasShowGroupConservation())
4560 af.viewport.setShowGroupConservation(view.getShowGroupConservation());
4564 af.viewport.setShowGroupConservation(false);
4567 // recover featre settings
4568 if (jms.getFeatureSettings() != null)
4570 FeaturesDisplayed fdi;
4571 af.viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
4572 String[] renderOrder = new String[jms.getFeatureSettings()
4573 .getSettingCount()];
4574 Map<String, FeatureColourI> featureColours = new Hashtable<>();
4575 Map<String, Float> featureOrder = new Hashtable<>();
4577 for (int fs = 0; fs < jms.getFeatureSettings().getSettingCount(); fs++)
4579 Setting setting = jms.getFeatureSettings().getSetting(fs);
4580 if (setting.hasMincolour())
4582 FeatureColourI gc = setting.hasMin() ? new FeatureColour(
4583 new Color(setting.getMincolour()), new Color(
4584 setting.getColour()), setting.getMin(),
4585 setting.getMax()) : new FeatureColour(new Color(
4586 setting.getMincolour()), new Color(setting.getColour()),
4588 if (setting.hasThreshold())
4590 gc.setThreshold(setting.getThreshold());
4591 int threshstate = setting.getThreshstate();
4592 // -1 = None, 0 = Below, 1 = Above threshold
4593 if (threshstate == 0)
4595 gc.setBelowThreshold(true);
4597 else if (threshstate == 1)
4599 gc.setAboveThreshold(true);
4602 gc.setAutoScaled(true); // default
4603 if (setting.hasAutoScale())
4605 gc.setAutoScaled(setting.getAutoScale());
4607 if (setting.hasColourByLabel())
4609 gc.setColourByLabel(setting.getColourByLabel());
4611 // and put in the feature colour table.
4612 featureColours.put(setting.getType(), gc);
4616 featureColours.put(setting.getType(), new FeatureColour(
4617 new Color(setting.getColour())));
4619 renderOrder[fs] = setting.getType();
4620 if (setting.hasOrder())
4622 featureOrder.put(setting.getType(), setting.getOrder());
4626 featureOrder.put(setting.getType(), new Float(fs
4627 / jms.getFeatureSettings().getSettingCount()));
4629 if (setting.getDisplay())
4631 fdi.setVisible(setting.getType());
4634 Map<String, Boolean> fgtable = new Hashtable<>();
4635 for (int gs = 0; gs < jms.getFeatureSettings().getGroupCount(); gs++)
4637 Group grp = jms.getFeatureSettings().getGroup(gs);
4638 fgtable.put(grp.getName(), new Boolean(grp.getDisplay()));
4640 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
4641 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
4642 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
4643 FeatureRendererSettings frs = new FeatureRendererSettings(
4644 renderOrder, fgtable, featureColours, 1.0f, featureOrder);
4645 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
4646 .transferSettings(frs);
4650 if (view.getHiddenColumnsCount() > 0)
4652 for (int c = 0; c < view.getHiddenColumnsCount(); c++)
4654 af.viewport.hideColumns(view.getHiddenColumns(c).getStart(), view
4655 .getHiddenColumns(c).getEnd() // +1
4659 if (view.getCalcIdParam() != null)
4661 for (CalcIdParam calcIdParam : view.getCalcIdParam())
4663 if (calcIdParam != null)
4665 if (recoverCalcIdParam(calcIdParam, af.viewport))
4670 warn("Couldn't recover parameters for "
4671 + calcIdParam.getCalcId());
4676 af.setMenusFromViewport(af.viewport);
4677 af.setTitle(view.getTitle());
4678 // TODO: we don't need to do this if the viewport is aready visible.
4680 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
4681 * has a 'cdna/protein complement' view, in which case save it in order to
4682 * populate a SplitFrame once all views have been read in.
4684 String complementaryViewId = view.getComplementId();
4685 if (complementaryViewId == null)
4687 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
4689 // recompute any autoannotation
4690 af.alignPanel.updateAnnotation(false, true);
4691 reorderAutoannotation(af, al, autoAlan);
4692 af.alignPanel.alignmentChanged();
4696 splitFrameCandidates.put(view, af);
4702 * Reads saved data to restore Colour by Annotation settings
4704 * @param viewAnnColour
4708 * @param checkGroupAnnColour
4711 private ColourSchemeI constructAnnotationColour(
4712 AnnotationColours viewAnnColour, AlignFrame af, AlignmentI al,
4713 JalviewModelSequence jms, boolean checkGroupAnnColour)
4715 boolean propagateAnnColour = false;
4716 AlignmentI annAlignment = af != null ? af.viewport.getAlignment() : al;
4717 if (checkGroupAnnColour && al.getGroups() != null
4718 && al.getGroups().size() > 0)
4720 // pre 2.8.1 behaviour
4721 // check to see if we should transfer annotation colours
4722 propagateAnnColour = true;
4723 for (SequenceGroup sg : al.getGroups())
4725 if (sg.getColourScheme() instanceof AnnotationColourGradient)
4727 propagateAnnColour = false;
4733 * 2.10.2- : saved annotationId is AlignmentAnnotation.annotationId
4735 String annotationId = viewAnnColour.getAnnotation();
4736 AlignmentAnnotation matchedAnnotation = annotationIds.get(annotationId);
4739 * pre 2.10.2: saved annotationId is AlignmentAnnotation.label
4741 if (matchedAnnotation == null && annAlignment.getAlignmentAnnotation() != null)
4743 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
4746 .equals(annAlignment.getAlignmentAnnotation()[i].label))
4748 matchedAnnotation = annAlignment.getAlignmentAnnotation()[i];
4753 if (matchedAnnotation == null)
4755 System.err.println("Failed to match annotation colour scheme for "
4759 if (matchedAnnotation.getThreshold() == null)
4761 matchedAnnotation.setThreshold(new GraphLine(viewAnnColour.getThreshold(),
4762 "Threshold", Color.black));
4765 AnnotationColourGradient cs = null;
4766 if (viewAnnColour.getColourScheme().equals("None"))
4768 cs = new AnnotationColourGradient(matchedAnnotation, new Color(
4769 viewAnnColour.getMinColour()), new Color(
4770 viewAnnColour.getMaxColour()),
4771 viewAnnColour.getAboveThreshold());
4773 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
4775 cs = new AnnotationColourGradient(matchedAnnotation, getUserColourScheme(
4776 jms, viewAnnColour.getColourScheme()),
4777 viewAnnColour.getAboveThreshold());
4781 cs = new AnnotationColourGradient(matchedAnnotation,
4782 ColourSchemeProperty.getColourScheme(al,
4783 viewAnnColour.getColourScheme()),
4784 viewAnnColour.getAboveThreshold());
4787 boolean perSequenceOnly = viewAnnColour.isPerSequence();
4788 boolean useOriginalColours = viewAnnColour.isPredefinedColours();
4789 cs.setSeqAssociated(perSequenceOnly);
4790 cs.setPredefinedColours(useOriginalColours);
4792 if (propagateAnnColour && al.getGroups() != null)
4794 // Also use these settings for all the groups
4795 for (int g = 0; g < al.getGroups().size(); g++)
4797 SequenceGroup sg = al.getGroups().get(g);
4798 if (sg.getGroupColourScheme() == null)
4803 AnnotationColourGradient groupScheme = new AnnotationColourGradient(
4804 matchedAnnotation, sg.getColourScheme(),
4805 viewAnnColour.getAboveThreshold());
4806 sg.setColourScheme(groupScheme);
4807 groupScheme.setSeqAssociated(perSequenceOnly);
4808 groupScheme.setPredefinedColours(useOriginalColours);
4814 private void reorderAutoannotation(AlignFrame af, AlignmentI al,
4815 List<JvAnnotRow> autoAlan)
4817 // copy over visualization settings for autocalculated annotation in the
4819 if (al.getAlignmentAnnotation() != null)
4822 * Kludge for magic autoannotation names (see JAL-811)
4824 String[] magicNames = new String[] { "Consensus", "Quality",
4826 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
4827 Hashtable<String, JvAnnotRow> visan = new Hashtable<>();
4828 for (String nm : magicNames)
4830 visan.put(nm, nullAnnot);
4832 for (JvAnnotRow auan : autoAlan)
4834 visan.put(auan.template.label
4835 + (auan.template.getCalcId() == null ? "" : "\t"
4836 + auan.template.getCalcId()), auan);
4838 int hSize = al.getAlignmentAnnotation().length;
4839 List<JvAnnotRow> reorder = new ArrayList<>();
4840 // work through any autoCalculated annotation already on the view
4841 // removing it if it should be placed in a different location on the
4842 // annotation panel.
4843 List<String> remains = new ArrayList<>(visan.keySet());
4844 for (int h = 0; h < hSize; h++)
4846 jalview.datamodel.AlignmentAnnotation jalan = al
4847 .getAlignmentAnnotation()[h];
4848 if (jalan.autoCalculated)
4851 JvAnnotRow valan = visan.get(k = jalan.label);
4852 if (jalan.getCalcId() != null)
4854 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
4859 // delete the auto calculated row from the alignment
4860 al.deleteAnnotation(jalan, false);
4864 if (valan != nullAnnot)
4866 if (jalan != valan.template)
4868 // newly created autoannotation row instance
4869 // so keep a reference to the visible annotation row
4870 // and copy over all relevant attributes
4871 if (valan.template.graphHeight >= 0)
4874 jalan.graphHeight = valan.template.graphHeight;
4876 jalan.visible = valan.template.visible;
4878 reorder.add(new JvAnnotRow(valan.order, jalan));
4883 // Add any (possibly stale) autocalculated rows that were not appended to
4884 // the view during construction
4885 for (String other : remains)
4887 JvAnnotRow othera = visan.get(other);
4888 if (othera != nullAnnot && othera.template.getCalcId() != null
4889 && othera.template.getCalcId().length() > 0)
4891 reorder.add(othera);
4894 // now put the automatic annotation in its correct place
4895 int s = 0, srt[] = new int[reorder.size()];
4896 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
4897 for (JvAnnotRow jvar : reorder)
4900 srt[s++] = jvar.order;
4903 jalview.util.QuickSort.sort(srt, rws);
4904 // and re-insert the annotation at its correct position
4905 for (JvAnnotRow jvar : rws)
4907 al.addAnnotation(jvar.template, jvar.order);
4909 af.alignPanel.adjustAnnotationHeight();
4913 Hashtable skipList = null;
4916 * TODO remove this method
4919 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
4920 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
4921 * throw new Error("Implementation Error. No skipList defined for this
4922 * Jalview2XML instance."); } return (AlignFrame)
4923 * skipList.get(view.getSequenceSetId()); }
4927 * Check if the Jalview view contained in object should be skipped or not.
4930 * @return true if view's sequenceSetId is a key in skipList
4932 private boolean skipViewport(JalviewModel object)
4934 if (skipList == null)
4939 if (skipList.containsKey(id = object.getJalviewModelSequence()
4940 .getViewport()[0].getSequenceSetId()))
4942 if (Cache.log != null && Cache.log.isDebugEnabled())
4944 Cache.log.debug("Skipping seuqence set id " + id);
4951 public void addToSkipList(AlignFrame af)
4953 if (skipList == null)
4955 skipList = new Hashtable();
4957 skipList.put(af.getViewport().getSequenceSetId(), af);
4960 public void clearSkipList()
4962 if (skipList != null)
4969 private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
4970 boolean ignoreUnrefed)
4972 jalview.datamodel.AlignmentI ds = getDatasetFor(vamsasSet
4974 Vector dseqs = null;
4977 // create a list of new dataset sequences
4978 dseqs = new Vector();
4980 for (int i = 0, iSize = vamsasSet.getSequenceCount(); i < iSize; i++)
4982 Sequence vamsasSeq = vamsasSet.getSequence(i);
4983 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed, i);
4985 // create a new dataset
4988 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
4989 dseqs.copyInto(dsseqs);
4990 ds = new jalview.datamodel.Alignment(dsseqs);
4991 debug("Created new dataset " + vamsasSet.getDatasetId()
4992 + " for alignment " + System.identityHashCode(al));
4993 addDatasetRef(vamsasSet.getDatasetId(), ds);
4995 // set the dataset for the newly imported alignment.
4996 if (al.getDataset() == null && !ignoreUnrefed)
5005 * sequence definition to create/merge dataset sequence for
5009 * vector to add new dataset sequence to
5010 * @param ignoreUnrefed
5011 * - when true, don't create new sequences from vamsasSeq if it's id
5012 * doesn't already have an asssociated Jalview sequence.
5014 * - used to reorder the sequence in the alignment according to the
5015 * vamsasSeq array ordering, to preserve ordering of dataset
5017 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
5018 AlignmentI ds, Vector dseqs, boolean ignoreUnrefed, int vseqpos)
5020 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
5022 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
5023 boolean reorder = false;
5024 SequenceI dsq = null;
5025 if (sq != null && sq.getDatasetSequence() != null)
5027 dsq = sq.getDatasetSequence();
5033 if (sq == null && ignoreUnrefed)
5037 String sqid = vamsasSeq.getDsseqid();
5040 // need to create or add a new dataset sequence reference to this sequence
5043 dsq = seqRefIds.get(sqid);
5048 // make a new dataset sequence
5049 dsq = sq.createDatasetSequence();
5052 // make up a new dataset reference for this sequence
5053 sqid = seqHash(dsq);
5055 dsq.setVamsasId(uniqueSetSuffix + sqid);
5056 seqRefIds.put(sqid, dsq);
5061 dseqs.addElement(dsq);
5066 ds.addSequence(dsq);
5072 { // make this dataset sequence sq's dataset sequence
5073 sq.setDatasetSequence(dsq);
5074 // and update the current dataset alignment
5079 if (!dseqs.contains(dsq))
5086 if (ds.findIndex(dsq) < 0)
5088 ds.addSequence(dsq);
5095 // TODO: refactor this as a merge dataset sequence function
5096 // now check that sq (the dataset sequence) sequence really is the union of
5097 // all references to it
5098 // boolean pre = sq.getStart() < dsq.getStart();
5099 // boolean post = sq.getEnd() > dsq.getEnd();
5103 // StringBuffer sb = new StringBuffer();
5104 String newres = jalview.analysis.AlignSeq.extractGaps(
5105 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
5106 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
5107 && newres.length() > dsq.getLength())
5109 // Update with the longer sequence.
5113 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
5114 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
5115 * sb.append(newres.substring(newres.length() - sq.getEnd() -
5116 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
5118 dsq.setSequence(newres);
5120 // TODO: merges will never happen if we 'know' we have the real dataset
5121 // sequence - this should be detected when id==dssid
5123 .println("DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
5124 // + (pre ? "prepended" : "") + " "
5125 // + (post ? "appended" : ""));
5130 // sequence refs are identical. We may need to update the existing dataset
5131 // alignment with this one, though.
5132 if (ds != null && dseqs == null)
5134 int opos = ds.findIndex(dsq);
5135 SequenceI tseq = null;
5136 if (opos != -1 && vseqpos != opos)
5138 // remove from old position
5139 ds.deleteSequence(dsq);
5141 if (vseqpos < ds.getHeight())
5143 if (vseqpos != opos)
5145 // save sequence at destination position
5146 tseq = ds.getSequenceAt(vseqpos);
5147 ds.replaceSequenceAt(vseqpos, dsq);
5148 ds.addSequence(tseq);
5153 ds.addSequence(dsq);
5160 * TODO use AlignmentI here and in related methods - needs
5161 * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
5163 Hashtable<String, AlignmentI> datasetIds = null;
5165 IdentityHashMap<AlignmentI, String> dataset2Ids = null;
5167 private AlignmentI getDatasetFor(String datasetId)
5169 if (datasetIds == null)
5171 datasetIds = new Hashtable<>();
5174 if (datasetIds.containsKey(datasetId))
5176 return datasetIds.get(datasetId);
5181 private void addDatasetRef(String datasetId, AlignmentI dataset)
5183 if (datasetIds == null)
5185 datasetIds = new Hashtable<>();
5187 datasetIds.put(datasetId, dataset);
5191 * make a new dataset ID for this jalview dataset alignment
5196 private String getDatasetIdRef(AlignmentI dataset)
5198 if (dataset.getDataset() != null)
5200 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
5202 String datasetId = makeHashCode(dataset, null);
5203 if (datasetId == null)
5205 // make a new datasetId and record it
5206 if (dataset2Ids == null)
5208 dataset2Ids = new IdentityHashMap<>();
5212 datasetId = dataset2Ids.get(dataset);
5214 if (datasetId == null)
5216 datasetId = "ds" + dataset2Ids.size() + 1;
5217 dataset2Ids.put(dataset, datasetId);
5223 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
5225 for (int d = 0; d < sequence.getDBRefCount(); d++)
5227 DBRef dr = sequence.getDBRef(d);
5228 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
5229 sequence.getDBRef(d).getSource(), sequence.getDBRef(d)
5230 .getVersion(), sequence.getDBRef(d).getAccessionId());
5231 if (dr.getMapping() != null)
5233 entry.setMap(addMapping(dr.getMapping()));
5235 datasetSequence.addDBRef(entry);
5239 private jalview.datamodel.Mapping addMapping(Mapping m)
5241 SequenceI dsto = null;
5242 // Mapping m = dr.getMapping();
5243 int fr[] = new int[m.getMapListFromCount() * 2];
5244 Enumeration f = m.enumerateMapListFrom();
5245 for (int _i = 0; f.hasMoreElements(); _i += 2)
5247 MapListFrom mf = (MapListFrom) f.nextElement();
5248 fr[_i] = mf.getStart();
5249 fr[_i + 1] = mf.getEnd();
5251 int fto[] = new int[m.getMapListToCount() * 2];
5252 f = m.enumerateMapListTo();
5253 for (int _i = 0; f.hasMoreElements(); _i += 2)
5255 MapListTo mf = (MapListTo) f.nextElement();
5256 fto[_i] = mf.getStart();
5257 fto[_i + 1] = mf.getEnd();
5259 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto,
5260 fr, fto, (int) m.getMapFromUnit(), (int) m.getMapToUnit());
5261 if (m.getMappingChoice() != null)
5263 MappingChoice mc = m.getMappingChoice();
5264 if (mc.getDseqFor() != null)
5266 String dsfor = "" + mc.getDseqFor();
5267 if (seqRefIds.containsKey(dsfor))
5272 jmap.setTo(seqRefIds.get(dsfor));
5276 frefedSequence.add(newMappingRef(dsfor, jmap));
5282 * local sequence definition
5284 Sequence ms = mc.getSequence();
5285 SequenceI djs = null;
5286 String sqid = ms.getDsseqid();
5287 if (sqid != null && sqid.length() > 0)
5290 * recover dataset sequence
5292 djs = seqRefIds.get(sqid);
5297 .println("Warning - making up dataset sequence id for DbRef sequence map reference");
5298 sqid = ((Object) ms).toString(); // make up a new hascode for
5299 // undefined dataset sequence hash
5300 // (unlikely to happen)
5306 * make a new dataset sequence and add it to refIds hash
5308 djs = new jalview.datamodel.Sequence(ms.getName(),
5310 djs.setStart(jmap.getMap().getToLowest());
5311 djs.setEnd(jmap.getMap().getToHighest());
5312 djs.setVamsasId(uniqueSetSuffix + sqid);
5314 incompleteSeqs.put(sqid, djs);
5315 seqRefIds.put(sqid, djs);
5318 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
5327 public jalview.gui.AlignmentPanel copyAlignPanel(AlignmentPanel ap,
5328 boolean keepSeqRefs)
5331 JalviewModel jm = saveState(ap, null, null, null);
5336 jm.getJalviewModelSequence().getViewport(0).setSequenceSetId(null);
5340 uniqueSetSuffix = "";
5341 jm.getJalviewModelSequence().getViewport(0).setId(null); // we don't
5346 if (this.frefedSequence == null)
5348 frefedSequence = new Vector();
5351 viewportsAdded.clear();
5353 AlignFrame af = loadFromObject(jm, null, false, null);
5354 af.alignPanels.clear();
5355 af.closeMenuItem_actionPerformed(true);
5358 * if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
5359 * i<ap.av.getAlignment().getAlignmentAnnotation().length; i++) {
5360 * if(!ap.av.getAlignment().getAlignmentAnnotation()[i].autoCalculated) {
5361 * af.alignPanel.av.getAlignment().getAlignmentAnnotation()[i] =
5362 * ap.av.getAlignment().getAlignmentAnnotation()[i]; } } }
5365 return af.alignPanel;
5369 * flag indicating if hashtables should be cleared on finalization TODO this
5370 * flag may not be necessary
5372 private final boolean _cleartables = true;
5374 private Hashtable jvids2vobj;
5379 * @see java.lang.Object#finalize()
5382 protected void finalize() throws Throwable
5384 // really make sure we have no buried refs left.
5389 this.seqRefIds = null;
5390 this.seqsToIds = null;
5394 private void warn(String msg)
5399 private void warn(String msg, Exception e)
5401 if (Cache.log != null)
5405 Cache.log.warn(msg, e);
5409 Cache.log.warn(msg);
5414 System.err.println("Warning: " + msg);
5417 e.printStackTrace();
5422 private void debug(String string)
5424 debug(string, null);
5427 private void debug(String msg, Exception e)
5429 if (Cache.log != null)
5433 Cache.log.debug(msg, e);
5437 Cache.log.debug(msg);
5442 System.err.println("Warning: " + msg);
5445 e.printStackTrace();
5451 * set the object to ID mapping tables used to write/recover objects and XML
5452 * ID strings for the jalview project. If external tables are provided then
5453 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
5454 * object goes out of scope. - also populates the datasetIds hashtable with
5455 * alignment objects containing dataset sequences
5458 * Map from ID strings to jalview datamodel
5460 * Map from jalview datamodel to ID strings
5464 public void setObjectMappingTables(Hashtable vobj2jv,
5465 IdentityHashMap jv2vobj)
5467 this.jv2vobj = jv2vobj;
5468 this.vobj2jv = vobj2jv;
5469 Iterator ds = jv2vobj.keySet().iterator();
5471 while (ds.hasNext())
5473 Object jvobj = ds.next();
5474 id = jv2vobj.get(jvobj).toString();
5475 if (jvobj instanceof jalview.datamodel.Alignment)
5477 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
5479 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
5482 else if (jvobj instanceof jalview.datamodel.Sequence)
5484 // register sequence object so the XML parser can recover it.
5485 if (seqRefIds == null)
5487 seqRefIds = new HashMap<>();
5489 if (seqsToIds == null)
5491 seqsToIds = new IdentityHashMap<>();
5493 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
5494 seqsToIds.put((SequenceI) jvobj, id);
5496 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
5499 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
5500 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
5501 if (jvann.annotationId == null)
5503 jvann.annotationId = anid;
5505 if (!jvann.annotationId.equals(anid))
5507 // TODO verify that this is the correct behaviour
5508 this.warn("Overriding Annotation ID for " + anid
5509 + " from different id : " + jvann.annotationId);
5510 jvann.annotationId = anid;
5513 else if (jvobj instanceof String)
5515 if (jvids2vobj == null)
5517 jvids2vobj = new Hashtable();
5518 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
5523 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
5529 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
5530 * objects created from the project archive. If string is null (default for
5531 * construction) then suffix will be set automatically.
5535 public void setUniqueSetSuffix(String string)
5537 uniqueSetSuffix = string;
5542 * uses skipList2 as the skipList for skipping views on sequence sets
5543 * associated with keys in the skipList
5547 public void setSkipList(Hashtable skipList2)
5549 skipList = skipList2;
5553 * Reads the jar entry of given name and returns its contents, or null if the
5554 * entry is not found.
5557 * @param jarEntryName
5560 protected String readJarEntry(jarInputStreamProvider jprovider,
5561 String jarEntryName)
5563 String result = null;
5564 BufferedReader in = null;
5569 * Reopen the jar input stream and traverse its entries to find a matching
5572 JarInputStream jin = jprovider.getJarInputStream();
5573 JarEntry entry = null;
5576 entry = jin.getNextJarEntry();
5577 } while (entry != null && !entry.getName().equals(jarEntryName));
5581 StringBuilder out = new StringBuilder(256);
5582 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
5585 while ((data = in.readLine()) != null)
5589 result = out.toString();
5593 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
5595 } catch (Exception ex)
5597 ex.printStackTrace();
5605 } catch (IOException e)
5616 * Returns an incrementing counter (0, 1, 2...)
5620 private synchronized int nextCounter()