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.PDBEntry;
33 import jalview.datamodel.RnaViewerModel;
34 import jalview.datamodel.SequenceGroup;
35 import jalview.datamodel.SequenceI;
36 import jalview.datamodel.StructureViewerModel;
37 import jalview.datamodel.StructureViewerModel.StructureData;
38 import jalview.ext.varna.RnaModel;
39 import jalview.gui.StructureViewer.ViewerType;
40 import jalview.io.DataSourceType;
41 import jalview.io.FileFormat;
42 import jalview.schemabinding.version2.AlcodMap;
43 import jalview.schemabinding.version2.AlcodonFrame;
44 import jalview.schemabinding.version2.Annotation;
45 import jalview.schemabinding.version2.AnnotationColours;
46 import jalview.schemabinding.version2.AnnotationElement;
47 import jalview.schemabinding.version2.CalcIdParam;
48 import jalview.schemabinding.version2.DBRef;
49 import jalview.schemabinding.version2.Features;
50 import jalview.schemabinding.version2.Group;
51 import jalview.schemabinding.version2.HiddenColumns;
52 import jalview.schemabinding.version2.JGroup;
53 import jalview.schemabinding.version2.JSeq;
54 import jalview.schemabinding.version2.JalviewModel;
55 import jalview.schemabinding.version2.JalviewModelSequence;
56 import jalview.schemabinding.version2.MapListFrom;
57 import jalview.schemabinding.version2.MapListTo;
58 import jalview.schemabinding.version2.Mapping;
59 import jalview.schemabinding.version2.MappingChoice;
60 import jalview.schemabinding.version2.OtherData;
61 import jalview.schemabinding.version2.PdbentryItem;
62 import jalview.schemabinding.version2.Pdbids;
63 import jalview.schemabinding.version2.Property;
64 import jalview.schemabinding.version2.RnaViewer;
65 import jalview.schemabinding.version2.SecondaryStructure;
66 import jalview.schemabinding.version2.Sequence;
67 import jalview.schemabinding.version2.SequenceSet;
68 import jalview.schemabinding.version2.SequenceSetProperties;
69 import jalview.schemabinding.version2.Setting;
70 import jalview.schemabinding.version2.StructureState;
71 import jalview.schemabinding.version2.ThresholdLine;
72 import jalview.schemabinding.version2.Tree;
73 import jalview.schemabinding.version2.UserColours;
74 import jalview.schemabinding.version2.Viewport;
75 import jalview.schemes.AnnotationColourGradient;
76 import jalview.schemes.ColourSchemeI;
77 import jalview.schemes.ColourSchemeProperty;
78 import jalview.schemes.FeatureColour;
79 import jalview.schemes.ResidueColourScheme;
80 import jalview.schemes.ResidueProperties;
81 import jalview.schemes.UserColourScheme;
82 import jalview.structure.StructureSelectionManager;
83 import jalview.structures.models.AAStructureBindingModel;
84 import jalview.util.MessageManager;
85 import jalview.util.Platform;
86 import jalview.util.StringUtils;
87 import jalview.util.jarInputStreamProvider;
88 import jalview.viewmodel.AlignmentViewport;
89 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
90 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
91 import jalview.ws.jws2.Jws2Discoverer;
92 import jalview.ws.jws2.dm.AAConSettings;
93 import jalview.ws.jws2.jabaws2.Jws2Instance;
94 import jalview.ws.params.ArgumentI;
95 import jalview.ws.params.AutoCalcSetting;
96 import jalview.ws.params.WsParamSetI;
98 import java.awt.Color;
99 import java.awt.Rectangle;
100 import java.io.BufferedReader;
101 import java.io.DataInputStream;
102 import java.io.DataOutputStream;
104 import java.io.FileInputStream;
105 import java.io.FileOutputStream;
106 import java.io.IOException;
107 import java.io.InputStreamReader;
108 import java.io.OutputStreamWriter;
109 import java.io.PrintWriter;
110 import java.lang.reflect.InvocationTargetException;
111 import java.net.MalformedURLException;
113 import java.util.ArrayList;
114 import java.util.Arrays;
115 import java.util.Enumeration;
116 import java.util.HashMap;
117 import java.util.HashSet;
118 import java.util.Hashtable;
119 import java.util.IdentityHashMap;
120 import java.util.Iterator;
121 import java.util.LinkedHashMap;
122 import java.util.List;
123 import java.util.Map;
124 import java.util.Map.Entry;
125 import java.util.Set;
126 import java.util.Vector;
127 import java.util.jar.JarEntry;
128 import java.util.jar.JarInputStream;
129 import java.util.jar.JarOutputStream;
131 import javax.swing.JInternalFrame;
132 import javax.swing.SwingUtilities;
134 import org.exolab.castor.xml.Marshaller;
135 import org.exolab.castor.xml.Unmarshaller;
138 * Write out the current jalview desktop state as a Jalview XML stream.
140 * Note: the vamsas objects referred to here are primitive versions of the
141 * VAMSAS project schema elements - they are not the same and most likely never
145 * @version $Revision: 1.134 $
147 public class Jalview2XML
149 private static final String VIEWER_PREFIX = "viewer_";
151 private static final String RNA_PREFIX = "rna_";
153 private static final String UTF_8 = "UTF-8";
155 // use this with nextCounter() to make unique names for entities
156 private int counter = 0;
159 * SequenceI reference -> XML ID string in jalview XML. Populated as XML reps
160 * of sequence objects are created.
162 IdentityHashMap<SequenceI, String> seqsToIds = null;
165 * jalview XML Sequence ID to jalview sequence object reference (both dataset
166 * and alignment sequences. Populated as XML reps of sequence objects are
169 Map<String, SequenceI> seqRefIds = null;
171 Map<String, SequenceI> incompleteSeqs = null;
173 List<SeqFref> frefedSequence = null;
175 boolean raiseGUI = true; // whether errors are raised in dialog boxes or not
178 * Map of reconstructed AlignFrame objects that appear to have come from
179 * SplitFrame objects (have a dna/protein complement view).
181 private Map<Viewport, AlignFrame> splitFrameCandidates = new HashMap<Viewport, AlignFrame>();
184 * Map from displayed rna structure models to their saved session state jar
187 private Map<RnaModel, String> rnaSessions = new HashMap<RnaModel, String>();
190 * create/return unique hash string for sq
193 * @return new or existing unique string for sq
195 String seqHash(SequenceI sq)
197 if (seqsToIds == null)
201 if (seqsToIds.containsKey(sq))
203 return seqsToIds.get(sq);
207 // create sequential key
208 String key = "sq" + (seqsToIds.size() + 1);
209 key = makeHashCode(sq, key); // check we don't have an external reference
211 seqsToIds.put(sq, key);
220 if (seqRefIds != null)
224 if (seqsToIds != null)
228 if (incompleteSeqs != null)
230 incompleteSeqs.clear();
238 warn("clearSeqRefs called when _cleartables was not set. Doing nothing.");
239 // seqRefIds = new Hashtable();
240 // seqsToIds = new IdentityHashMap();
246 if (seqsToIds == null)
248 seqsToIds = new IdentityHashMap<SequenceI, String>();
250 if (seqRefIds == null)
252 seqRefIds = new HashMap<String, SequenceI>();
254 if (incompleteSeqs == null)
256 incompleteSeqs = new HashMap<String, SequenceI>();
258 if (frefedSequence == null)
260 frefedSequence = new ArrayList<SeqFref>();
268 public Jalview2XML(boolean raiseGUI)
270 this.raiseGUI = raiseGUI;
274 * base class for resolving forward references to sequences by their ID
279 abstract class SeqFref
285 public SeqFref(String _sref, String type)
291 public String getSref()
296 public SequenceI getSrefSeq()
298 return seqRefIds.get(sref);
301 public boolean isResolvable()
303 return seqRefIds.get(sref) != null;
306 public SequenceI getSrefDatasetSeq()
308 SequenceI sq = seqRefIds.get(sref);
311 while (sq.getDatasetSequence() != null)
313 sq = sq.getDatasetSequence();
320 * @return true if the forward reference was fully resolved
322 abstract boolean resolve();
325 public String toString()
327 return type + " reference to " + sref;
332 * create forward reference for a mapping
338 public SeqFref newMappingRef(final String sref,
339 final jalview.datamodel.Mapping _jmap)
341 SeqFref fref = new SeqFref(sref, "Mapping")
343 public jalview.datamodel.Mapping jmap = _jmap;
348 SequenceI seq = getSrefDatasetSeq();
360 public SeqFref newAlcodMapRef(final String sref,
361 final AlignedCodonFrame _cf, final jalview.datamodel.Mapping _jmap)
364 SeqFref fref = new SeqFref(sref, "Codon Frame")
366 AlignedCodonFrame cf = _cf;
368 public jalview.datamodel.Mapping mp = _jmap;
371 public boolean isResolvable()
373 return super.isResolvable() && mp.getTo() != null;
379 SequenceI seq = getSrefDatasetSeq();
384 cf.addMap(seq, mp.getTo(), mp.getMap());
391 public void resolveFrefedSequences()
393 Iterator<SeqFref> nextFref = frefedSequence.iterator();
394 int toresolve = frefedSequence.size();
395 int unresolved = 0, failedtoresolve = 0;
396 while (nextFref.hasNext())
398 SeqFref ref = nextFref.next();
399 if (ref.isResolvable())
411 } catch (Exception x)
414 .println("IMPLEMENTATION ERROR: Failed to resolve forward reference for sequence "
427 System.err.println("Jalview Project Import: There were " + unresolved
428 + " forward references left unresolved on the stack.");
430 if (failedtoresolve > 0)
432 System.err.println("SERIOUS! " + failedtoresolve
433 + " resolvable forward references failed to resolve.");
435 if (incompleteSeqs != null && incompleteSeqs.size() > 0)
437 System.err.println("Jalview Project Import: There are "
438 + incompleteSeqs.size()
439 + " sequences which may have incomplete metadata.");
440 if (incompleteSeqs.size() < 10)
442 for (SequenceI s : incompleteSeqs.values())
444 System.err.println(s.toString());
450 .println("Too many to report. Skipping output of incomplete sequences.");
456 * This maintains a map of viewports, the key being the seqSetId. Important to
457 * set historyItem and redoList for multiple views
459 Map<String, AlignViewport> viewportsAdded = new HashMap<String, AlignViewport>();
461 Map<String, AlignmentAnnotation> annotationIds = new HashMap<String, AlignmentAnnotation>();
463 String uniqueSetSuffix = "";
466 * List of pdbfiles added to Jar
468 List<String> pdbfiles = null;
470 // SAVES SEVERAL ALIGNMENT WINDOWS TO SAME JARFILE
471 public void saveState(File statefile)
473 FileOutputStream fos = null;
476 fos = new FileOutputStream(statefile);
477 JarOutputStream jout = new JarOutputStream(fos);
480 } catch (Exception e)
482 // TODO: inform user of the problem - they need to know if their data was
484 if (errorMessage == null)
486 errorMessage = "Couldn't write Jalview Archive to output file '"
487 + statefile + "' - See console error log for details";
491 errorMessage += "(output file was '" + statefile + "')";
501 } catch (IOException e)
511 * Writes a jalview project archive to the given Jar output stream.
515 public void saveState(JarOutputStream jout)
517 AlignFrame[] frames = Desktop.getAlignFrames();
523 saveAllFrames(Arrays.asList(frames), jout);
527 * core method for storing state for a set of AlignFrames.
530 * - frames involving all data to be exported (including containing
533 * - project output stream
535 private void saveAllFrames(List<AlignFrame> frames, JarOutputStream jout)
537 Hashtable<String, AlignFrame> dsses = new Hashtable<String, AlignFrame>();
540 * ensure cached data is clear before starting
542 // todo tidy up seqRefIds, seqsToIds initialisation / reset
544 splitFrameCandidates.clear();
549 // NOTE UTF-8 MUST BE USED FOR WRITING UNICODE CHARS
550 // //////////////////////////////////////////////////
552 List<String> shortNames = new ArrayList<String>();
553 List<String> viewIds = new ArrayList<String>();
556 for (int i = frames.size() - 1; i > -1; i--)
558 AlignFrame af = frames.get(i);
562 .containsKey(af.getViewport().getSequenceSetId()))
567 String shortName = makeFilename(af, shortNames);
569 int ap, apSize = af.alignPanels.size();
571 for (ap = 0; ap < apSize; ap++)
573 AlignmentPanel apanel = af.alignPanels.get(ap);
574 String fileName = apSize == 1 ? shortName : ap + shortName;
575 if (!fileName.endsWith(".xml"))
577 fileName = fileName + ".xml";
580 saveState(apanel, fileName, jout, viewIds);
582 String dssid = getDatasetIdRef(af.getViewport().getAlignment()
584 if (!dsses.containsKey(dssid))
586 dsses.put(dssid, af);
591 writeDatasetFor(dsses, "" + jout.hashCode() + " " + uniqueSetSuffix,
597 } catch (Exception foo)
602 } catch (Exception ex)
604 // TODO: inform user of the problem - they need to know if their data was
606 if (errorMessage == null)
608 errorMessage = "Couldn't write Jalview Archive - see error output for details";
610 ex.printStackTrace();
615 * Generates a distinct file name, based on the title of the AlignFrame, by
616 * appending _n for increasing n until an unused name is generated. The new
617 * name (without its extension) is added to the list.
621 * @return the generated name, with .xml extension
623 protected String makeFilename(AlignFrame af, List<String> namesUsed)
625 String shortName = af.getTitle();
627 if (shortName.indexOf(File.separatorChar) > -1)
629 shortName = shortName.substring(shortName
630 .lastIndexOf(File.separatorChar) + 1);
635 while (namesUsed.contains(shortName))
637 if (shortName.endsWith("_" + (count - 1)))
639 shortName = shortName.substring(0, shortName.lastIndexOf("_"));
642 shortName = shortName.concat("_" + count);
646 namesUsed.add(shortName);
648 if (!shortName.endsWith(".xml"))
650 shortName = shortName + ".xml";
655 // USE THIS METHOD TO SAVE A SINGLE ALIGNMENT WINDOW
656 public boolean saveAlignment(AlignFrame af, String jarFile,
661 FileOutputStream fos = new FileOutputStream(jarFile);
662 JarOutputStream jout = new JarOutputStream(fos);
663 List<AlignFrame> frames = new ArrayList<AlignFrame>();
665 // resolve splitframes
666 if (af.getViewport().getCodingComplement() != null)
668 frames = ((SplitFrame) af.getSplitViewContainer()).getAlignFrames();
674 saveAllFrames(frames, jout);
678 } catch (Exception foo)
684 } catch (Exception ex)
686 errorMessage = "Couldn't Write alignment view to Jalview Archive - see error output for details";
687 ex.printStackTrace();
692 private void writeDatasetFor(Hashtable<String, AlignFrame> dsses,
693 String fileName, JarOutputStream jout)
696 for (String dssids : dsses.keySet())
698 AlignFrame _af = dsses.get(dssids);
699 String jfileName = fileName + " Dataset for " + _af.getTitle();
700 if (!jfileName.endsWith(".xml"))
702 jfileName = jfileName + ".xml";
704 saveState(_af.alignPanel, jfileName, true, jout, null);
709 * create a JalviewModel from an alignment view and marshall it to a
713 * panel to create jalview model for
715 * name of alignment panel written to output stream
722 public JalviewModel saveState(AlignmentPanel ap, String fileName,
723 JarOutputStream jout, List<String> viewIds)
725 return saveState(ap, fileName, false, jout, viewIds);
729 * create a JalviewModel from an alignment view and marshall it to a
733 * panel to create jalview model for
735 * name of alignment panel written to output stream
737 * when true, only write the dataset for the alignment, not the data
738 * associated with the view.
744 public JalviewModel saveState(AlignmentPanel ap, String fileName,
745 boolean storeDS, JarOutputStream jout, List<String> viewIds)
749 viewIds = new ArrayList<String>();
754 List<UserColourScheme> userColours = new ArrayList<UserColourScheme>();
756 AlignViewport av = ap.av;
758 JalviewModel object = new JalviewModel();
759 object.setVamsasModel(new jalview.schemabinding.version2.VamsasModel());
761 object.setCreationDate(new java.util.Date(System.currentTimeMillis()));
762 object.setVersion(jalview.bin.Cache.getDefault("VERSION",
763 "Development Build"));
766 * rjal is full height alignment, jal is actual alignment with full metadata
767 * but excludes hidden sequences.
769 jalview.datamodel.AlignmentI rjal = av.getAlignment(), jal = rjal;
771 if (av.hasHiddenRows())
773 rjal = jal.getHiddenSequences().getFullAlignment();
776 SequenceSet vamsasSet = new SequenceSet();
778 JalviewModelSequence jms = new JalviewModelSequence();
780 vamsasSet.setGapChar(jal.getGapCharacter() + "");
782 if (jal.getDataset() != null)
784 // dataset id is the dataset's hashcode
785 vamsasSet.setDatasetId(getDatasetIdRef(jal.getDataset()));
788 // switch jal and the dataset
789 jal = jal.getDataset();
793 if (jal.getProperties() != null)
795 Enumeration en = jal.getProperties().keys();
796 while (en.hasMoreElements())
798 String key = en.nextElement().toString();
799 SequenceSetProperties ssp = new SequenceSetProperties();
801 ssp.setValue(jal.getProperties().get(key).toString());
802 vamsasSet.addSequenceSetProperties(ssp);
807 Set<String> calcIdSet = new HashSet<String>();
808 // record the set of vamsas sequence XML POJO we create.
809 HashMap<String, Sequence> vamsasSetIds = new HashMap<String, Sequence>();
811 for (final SequenceI jds : rjal.getSequences())
813 final SequenceI jdatasq = jds.getDatasetSequence() == null ? jds
814 : jds.getDatasetSequence();
815 String id = seqHash(jds);
816 if (vamsasSetIds.get(id) == null)
818 if (seqRefIds.get(id) != null && !storeDS)
820 // This happens for two reasons: 1. multiple views are being
822 // 2. the hashCode has collided with another sequence's code. This
824 // HAPPEN! (PF00072.15.stk does this)
825 // JBPNote: Uncomment to debug writing out of files that do not read
826 // back in due to ArrayOutOfBoundExceptions.
827 // System.err.println("vamsasSeq backref: "+id+"");
828 // System.err.println(jds.getName()+"
829 // "+jds.getStart()+"-"+jds.getEnd()+" "+jds.getSequenceAsString());
830 // System.err.println("Hashcode: "+seqHash(jds));
831 // SequenceI rsq = (SequenceI) seqRefIds.get(id + "");
832 // System.err.println(rsq.getName()+"
833 // "+rsq.getStart()+"-"+rsq.getEnd()+" "+rsq.getSequenceAsString());
834 // System.err.println("Hashcode: "+seqHash(rsq));
838 vamsasSeq = createVamsasSequence(id, jds);
839 vamsasSet.addSequence(vamsasSeq);
840 vamsasSetIds.put(id, vamsasSeq);
841 seqRefIds.put(id, jds);
845 jseq.setStart(jds.getStart());
846 jseq.setEnd(jds.getEnd());
847 jseq.setColour(av.getSequenceColour(jds).getRGB());
849 jseq.setId(id); // jseq id should be a string not a number
852 // Store any sequences this sequence represents
853 if (av.hasHiddenRows())
855 // use rjal, contains the full height alignment
856 jseq.setHidden(av.getAlignment().getHiddenSequences()
859 if (av.isHiddenRepSequence(jds))
861 jalview.datamodel.SequenceI[] reps = av
862 .getRepresentedSequences(jds).getSequencesInOrder(rjal);
864 for (int h = 0; h < reps.length; h++)
868 jseq.addHiddenSequences(rjal.findIndex(reps[h]));
873 // mark sequence as reference - if it is the reference for this view
876 jseq.setViewreference(jds == jal.getSeqrep());
880 // TODO: omit sequence features from each alignment view's XML dump if we
881 // are storing dataset
882 if (jds.getSequenceFeatures() != null)
884 jalview.datamodel.SequenceFeature[] sf = jds.getSequenceFeatures();
886 while (index < sf.length)
888 Features features = new Features();
890 features.setBegin(sf[index].getBegin());
891 features.setEnd(sf[index].getEnd());
892 features.setDescription(sf[index].getDescription());
893 features.setType(sf[index].getType());
894 features.setFeatureGroup(sf[index].getFeatureGroup());
895 features.setScore(sf[index].getScore());
896 if (sf[index].links != null)
898 for (int l = 0; l < sf[index].links.size(); l++)
900 OtherData keyValue = new OtherData();
901 keyValue.setKey("LINK_" + l);
902 keyValue.setValue(sf[index].links.elementAt(l).toString());
903 features.addOtherData(keyValue);
906 if (sf[index].otherDetails != null)
909 Iterator<String> keys = sf[index].otherDetails.keySet()
911 while (keys.hasNext())
914 OtherData keyValue = new OtherData();
915 keyValue.setKey(key);
916 keyValue.setValue(sf[index].otherDetails.get(key).toString());
917 features.addOtherData(keyValue);
921 jseq.addFeatures(features);
926 if (jdatasq.getAllPDBEntries() != null)
928 Enumeration en = jdatasq.getAllPDBEntries().elements();
929 while (en.hasMoreElements())
931 Pdbids pdb = new Pdbids();
932 jalview.datamodel.PDBEntry entry = (jalview.datamodel.PDBEntry) en
935 String pdbId = entry.getId();
937 pdb.setType(entry.getType());
940 * Store any structure views associated with this sequence. This
941 * section copes with duplicate entries in the project, so a dataset
942 * only view *should* be coped with sensibly.
944 // This must have been loaded, is it still visible?
945 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
946 String matchedFile = null;
947 for (int f = frames.length - 1; f > -1; f--)
949 if (frames[f] instanceof StructureViewerBase)
951 StructureViewerBase viewFrame = (StructureViewerBase) frames[f];
952 matchedFile = saveStructureState(ap, jds, pdb, entry,
953 viewIds, matchedFile, viewFrame);
955 * Only store each structure viewer's state once in the project
956 * jar. First time through only (storeDS==false)
958 String viewId = viewFrame.getViewId();
959 if (!storeDS && !viewIds.contains(viewId))
964 String viewerState = viewFrame.getStateInfo();
965 writeJarEntry(jout, getViewerJarEntryName(viewId),
966 viewerState.getBytes());
967 } catch (IOException e)
969 System.err.println("Error saving viewer state: "
976 if (matchedFile != null || entry.getFile() != null)
978 if (entry.getFile() != null)
981 matchedFile = entry.getFile();
983 pdb.setFile(matchedFile); // entry.getFile());
984 if (pdbfiles == null)
986 pdbfiles = new ArrayList<String>();
989 if (!pdbfiles.contains(pdbId))
992 copyFileToJar(jout, matchedFile, pdbId);
996 Enumeration<String> props = entry.getProperties();
997 if (props.hasMoreElements())
999 PdbentryItem item = new PdbentryItem();
1000 while (props.hasMoreElements())
1002 Property prop = new Property();
1003 String key = props.nextElement();
1005 prop.setValue(entry.getProperty(key).toString());
1006 item.addProperty(prop);
1008 pdb.addPdbentryItem(item);
1011 jseq.addPdbids(pdb);
1015 saveRnaViewers(jout, jseq, jds, viewIds, ap, storeDS);
1020 if (!storeDS && av.hasHiddenRows())
1022 jal = av.getAlignment();
1026 if (storeDS && jal.getCodonFrames() != null)
1028 List<AlignedCodonFrame> jac = jal.getCodonFrames();
1029 for (AlignedCodonFrame acf : jac)
1031 AlcodonFrame alc = new AlcodonFrame();
1032 if (acf.getProtMappings() != null
1033 && acf.getProtMappings().length > 0)
1035 boolean hasMap = false;
1036 SequenceI[] dnas = acf.getdnaSeqs();
1037 jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1038 for (int m = 0; m < pmaps.length; m++)
1040 AlcodMap alcmap = new AlcodMap();
1041 alcmap.setDnasq(seqHash(dnas[m]));
1042 alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1044 alc.addAlcodMap(alcmap);
1049 vamsasSet.addAlcodonFrame(alc);
1052 // TODO: delete this ? dead code from 2.8.3->2.9 ?
1054 // AlcodonFrame alc = new AlcodonFrame();
1055 // vamsasSet.addAlcodonFrame(alc);
1056 // for (int p = 0; p < acf.aaWidth; p++)
1058 // Alcodon cmap = new Alcodon();
1059 // if (acf.codons[p] != null)
1061 // // Null codons indicate a gapped column in the translated peptide
1063 // cmap.setPos1(acf.codons[p][0]);
1064 // cmap.setPos2(acf.codons[p][1]);
1065 // cmap.setPos3(acf.codons[p][2]);
1067 // alc.addAlcodon(cmap);
1069 // if (acf.getProtMappings() != null
1070 // && acf.getProtMappings().length > 0)
1072 // SequenceI[] dnas = acf.getdnaSeqs();
1073 // jalview.datamodel.Mapping[] pmaps = acf.getProtMappings();
1074 // for (int m = 0; m < pmaps.length; m++)
1076 // AlcodMap alcmap = new AlcodMap();
1077 // alcmap.setDnasq(seqHash(dnas[m]));
1078 // alcmap.setMapping(createVamsasMapping(pmaps[m], dnas[m], null,
1080 // alc.addAlcodMap(alcmap);
1087 // /////////////////////////////////
1088 if (!storeDS && av.currentTree != null)
1090 // FIND ANY ASSOCIATED TREES
1091 // NOT IMPLEMENTED FOR HEADLESS STATE AT PRESENT
1092 if (Desktop.desktop != null)
1094 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1096 for (int t = 0; t < frames.length; t++)
1098 if (frames[t] instanceof TreePanel)
1100 TreePanel tp = (TreePanel) frames[t];
1102 if (tp.treeCanvas.av.getAlignment() == jal)
1104 Tree tree = new Tree();
1105 tree.setTitle(tp.getTitle());
1106 tree.setCurrentTree((av.currentTree == tp.getTree()));
1107 tree.setNewick(tp.getTree().toString());
1108 tree.setThreshold(tp.treeCanvas.threshold);
1110 tree.setFitToWindow(tp.fitToWindow.getState());
1111 tree.setFontName(tp.getTreeFont().getName());
1112 tree.setFontSize(tp.getTreeFont().getSize());
1113 tree.setFontStyle(tp.getTreeFont().getStyle());
1114 tree.setMarkUnlinked(tp.placeholdersMenu.getState());
1116 tree.setShowBootstrap(tp.bootstrapMenu.getState());
1117 tree.setShowDistances(tp.distanceMenu.getState());
1119 tree.setHeight(tp.getHeight());
1120 tree.setWidth(tp.getWidth());
1121 tree.setXpos(tp.getX());
1122 tree.setYpos(tp.getY());
1123 tree.setId(makeHashCode(tp, null));
1133 * store forward refs from an annotationRow to any groups
1135 IdentityHashMap<SequenceGroup, String> groupRefs = new IdentityHashMap<SequenceGroup, String>();
1138 for (SequenceI sq : jal.getSequences())
1140 // Store annotation on dataset sequences only
1141 AlignmentAnnotation[] aa = sq.getAnnotation();
1142 if (aa != null && aa.length > 0)
1144 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1151 if (jal.getAlignmentAnnotation() != null)
1153 // Store the annotation shown on the alignment.
1154 AlignmentAnnotation[] aa = jal.getAlignmentAnnotation();
1155 storeAlignmentAnnotation(aa, groupRefs, av, calcIdSet, storeDS,
1160 if (jal.getGroups() != null)
1162 JGroup[] groups = new JGroup[jal.getGroups().size()];
1164 for (jalview.datamodel.SequenceGroup sg : jal.getGroups())
1166 JGroup jGroup = new JGroup();
1167 groups[++i] = jGroup;
1169 jGroup.setStart(sg.getStartRes());
1170 jGroup.setEnd(sg.getEndRes());
1171 jGroup.setName(sg.getName());
1172 if (groupRefs.containsKey(sg))
1174 // group has references so set its ID field
1175 jGroup.setId(groupRefs.get(sg));
1179 if (sg.cs.conservationApplied())
1181 jGroup.setConsThreshold(sg.cs.getConservationInc());
1183 if (sg.cs instanceof jalview.schemes.UserColourScheme)
1185 jGroup.setColour(setUserColourScheme(sg.cs, userColours, jms));
1189 jGroup.setColour(sg.cs.getSchemeName());
1192 else if (sg.cs instanceof jalview.schemes.AnnotationColourGradient)
1194 jGroup.setColour("AnnotationColourGradient");
1195 jGroup.setAnnotationColours(constructAnnotationColours(
1196 (jalview.schemes.AnnotationColourGradient) sg.cs,
1199 else if (sg.cs instanceof jalview.schemes.UserColourScheme)
1201 jGroup.setColour(setUserColourScheme(sg.cs, userColours, jms));
1205 jGroup.setColour(sg.cs.getSchemeName());
1208 jGroup.setPidThreshold(sg.cs.getThreshold());
1211 jGroup.setOutlineColour(sg.getOutlineColour().getRGB());
1212 jGroup.setDisplayBoxes(sg.getDisplayBoxes());
1213 jGroup.setDisplayText(sg.getDisplayText());
1214 jGroup.setColourText(sg.getColourText());
1215 jGroup.setTextCol1(sg.textColour.getRGB());
1216 jGroup.setTextCol2(sg.textColour2.getRGB());
1217 jGroup.setTextColThreshold(sg.thresholdTextColour);
1218 jGroup.setShowUnconserved(sg.getShowNonconserved());
1219 jGroup.setIgnoreGapsinConsensus(sg.getIgnoreGapsConsensus());
1220 jGroup.setShowConsensusHistogram(sg.isShowConsensusHistogram());
1221 jGroup.setShowSequenceLogo(sg.isShowSequenceLogo());
1222 jGroup.setNormaliseSequenceLogo(sg.isNormaliseSequenceLogo());
1223 for (SequenceI seq : sg.getSequences())
1225 jGroup.addSeq(seqHash(seq));
1229 jms.setJGroup(groups);
1233 // /////////SAVE VIEWPORT
1234 Viewport view = new Viewport();
1235 view.setTitle(ap.alignFrame.getTitle());
1236 view.setSequenceSetId(makeHashCode(av.getSequenceSetId(),
1237 av.getSequenceSetId()));
1238 view.setId(av.getViewId());
1239 if (av.getCodingComplement() != null)
1241 view.setComplementId(av.getCodingComplement().getViewId());
1243 view.setViewName(av.viewName);
1244 view.setGatheredViews(av.isGatherViewsHere());
1246 Rectangle size = ap.av.getExplodedGeometry();
1247 Rectangle position = size;
1250 size = ap.alignFrame.getBounds();
1251 if (av.getCodingComplement() != null)
1253 position = ((SplitFrame) ap.alignFrame.getSplitViewContainer())
1261 view.setXpos(position.x);
1262 view.setYpos(position.y);
1264 view.setWidth(size.width);
1265 view.setHeight(size.height);
1267 view.setStartRes(av.startRes);
1268 view.setStartSeq(av.startSeq);
1270 if (av.getGlobalColourScheme() instanceof jalview.schemes.UserColourScheme)
1272 view.setBgColour(setUserColourScheme(av.getGlobalColourScheme(),
1275 else if (av.getGlobalColourScheme() instanceof jalview.schemes.AnnotationColourGradient)
1277 AnnotationColours ac = constructAnnotationColours(
1278 (jalview.schemes.AnnotationColourGradient) av
1279 .getGlobalColourScheme(),
1282 view.setAnnotationColours(ac);
1283 view.setBgColour("AnnotationColourGradient");
1287 view.setBgColour(ColourSchemeProperty.getColourName(av
1288 .getGlobalColourScheme()));
1291 ColourSchemeI cs = av.getGlobalColourScheme();
1295 if (cs.conservationApplied())
1297 view.setConsThreshold(cs.getConservationInc());
1298 if (cs instanceof jalview.schemes.UserColourScheme)
1300 view.setBgColour(setUserColourScheme(cs, userColours, jms));
1304 if (cs instanceof ResidueColourScheme)
1306 view.setPidThreshold(cs.getThreshold());
1310 view.setConservationSelected(av.getConservationSelected());
1311 view.setPidSelected(av.getAbovePIDThreshold());
1312 view.setFontName(av.font.getName());
1313 view.setFontSize(av.font.getSize());
1314 view.setFontStyle(av.font.getStyle());
1315 view.setScaleProteinAsCdna(av.getViewStyle().isScaleProteinAsCdna());
1316 view.setRenderGaps(av.isRenderGaps());
1317 view.setShowAnnotation(av.isShowAnnotation());
1318 view.setShowBoxes(av.getShowBoxes());
1319 view.setShowColourText(av.getColourText());
1320 view.setShowFullId(av.getShowJVSuffix());
1321 view.setRightAlignIds(av.isRightAlignIds());
1322 view.setShowSequenceFeatures(av.isShowSequenceFeatures());
1323 view.setShowText(av.getShowText());
1324 view.setShowUnconserved(av.getShowUnconserved());
1325 view.setWrapAlignment(av.getWrapAlignment());
1326 view.setTextCol1(av.getTextColour().getRGB());
1327 view.setTextCol2(av.getTextColour2().getRGB());
1328 view.setTextColThreshold(av.getThresholdTextColour());
1329 view.setShowConsensusHistogram(av.isShowConsensusHistogram());
1330 view.setShowSequenceLogo(av.isShowSequenceLogo());
1331 view.setNormaliseSequenceLogo(av.isNormaliseSequenceLogo());
1332 view.setShowGroupConsensus(av.isShowGroupConsensus());
1333 view.setShowGroupConservation(av.isShowGroupConservation());
1334 view.setShowNPfeatureTooltip(av.isShowNPFeats());
1335 view.setShowDbRefTooltip(av.isShowDBRefs());
1336 view.setFollowHighlight(av.isFollowHighlight());
1337 view.setFollowSelection(av.followSelection);
1338 view.setIgnoreGapsinConsensus(av.isIgnoreGapsConsensus());
1339 if (av.getFeaturesDisplayed() != null)
1341 jalview.schemabinding.version2.FeatureSettings fs = new jalview.schemabinding.version2.FeatureSettings();
1343 String[] renderOrder = ap.getSeqPanel().seqCanvas
1344 .getFeatureRenderer().getRenderOrder()
1345 .toArray(new String[0]);
1347 Vector<String> settingsAdded = new Vector<String>();
1348 if (renderOrder != null)
1350 for (String featureType : renderOrder)
1352 FeatureColourI fcol = ap.getSeqPanel().seqCanvas
1353 .getFeatureRenderer().getFeatureStyle(featureType);
1354 Setting setting = new Setting();
1355 setting.setType(featureType);
1356 if (!fcol.isSimpleColour())
1358 setting.setColour(fcol.getMaxColour().getRGB());
1359 setting.setMincolour(fcol.getMinColour().getRGB());
1360 setting.setMin(fcol.getMin());
1361 setting.setMax(fcol.getMax());
1362 setting.setColourByLabel(fcol.isColourByLabel());
1363 setting.setAutoScale(fcol.isAutoScaled());
1364 setting.setThreshold(fcol.getThreshold());
1365 // -1 = No threshold, 0 = Below, 1 = Above
1366 setting.setThreshstate(fcol.isAboveThreshold() ? 1 : (fcol
1367 .isBelowThreshold() ? 0 : -1));
1371 setting.setColour(fcol.getColour().getRGB());
1374 setting.setDisplay(av.getFeaturesDisplayed().isVisible(
1376 float rorder = ap.getSeqPanel().seqCanvas.getFeatureRenderer()
1377 .getOrder(featureType);
1380 setting.setOrder(rorder);
1382 fs.addSetting(setting);
1383 settingsAdded.addElement(featureType);
1387 // is groups actually supposed to be a map here ?
1388 Iterator<String> en = ap.getSeqPanel().seqCanvas
1389 .getFeatureRenderer().getFeatureGroups().iterator();
1390 Vector<String> groupsAdded = new Vector<String>();
1391 while (en.hasNext())
1393 String grp = en.next();
1394 if (groupsAdded.contains(grp))
1398 Group g = new Group();
1400 g.setDisplay(((Boolean) ap.getSeqPanel().seqCanvas
1401 .getFeatureRenderer().checkGroupVisibility(grp, false))
1404 groupsAdded.addElement(grp);
1406 jms.setFeatureSettings(fs);
1409 if (av.hasHiddenColumns())
1411 if (av.getColumnSelection() == null
1412 || av.getColumnSelection().getHiddenColumns() == null)
1414 warn("REPORT BUG: avoided null columnselection bug (DMAM reported). Please contact Jim about this.");
1418 for (int c = 0; c < av.getColumnSelection().getHiddenColumns()
1421 int[] region = av.getColumnSelection().getHiddenColumns()
1423 HiddenColumns hc = new HiddenColumns();
1424 hc.setStart(region[0]);
1425 hc.setEnd(region[1]);
1426 view.addHiddenColumns(hc);
1430 if (calcIdSet.size() > 0)
1432 for (String calcId : calcIdSet)
1434 if (calcId.trim().length() > 0)
1436 CalcIdParam cidp = createCalcIdParam(calcId, av);
1437 // Some calcIds have no parameters.
1440 view.addCalcIdParam(cidp);
1446 jms.addViewport(view);
1448 object.setJalviewModelSequence(jms);
1449 object.getVamsasModel().addSequenceSet(vamsasSet);
1451 if (jout != null && fileName != null)
1453 // We may not want to write the object to disk,
1454 // eg we can copy the alignViewport to a new view object
1455 // using save and then load
1458 System.out.println("Writing jar entry " + fileName);
1459 JarEntry entry = new JarEntry(fileName);
1460 jout.putNextEntry(entry);
1461 PrintWriter pout = new PrintWriter(new OutputStreamWriter(jout,
1463 Marshaller marshaller = new Marshaller(pout);
1464 marshaller.marshal(object);
1467 } catch (Exception ex)
1469 // TODO: raise error in GUI if marshalling failed.
1470 ex.printStackTrace();
1477 * Save any Varna viewers linked to this sequence. Writes an rnaViewer element
1478 * for each viewer, with
1480 * <li>viewer geometry (position, size, split pane divider location)</li>
1481 * <li>index of the selected structure in the viewer (currently shows gapped
1483 * <li>the id of the annotation holding RNA secondary structure</li>
1484 * <li>(currently only one SS is shown per viewer, may be more in future)</li>
1486 * Varna viewer state is also written out (in native Varna XML) to separate
1487 * project jar entries. A separate entry is written for each RNA structure
1488 * displayed, with the naming convention
1490 * <li>rna_viewId_sequenceId_annotationId_[gapped|trimmed]</li>
1498 * @param storeDataset
1500 protected void saveRnaViewers(JarOutputStream jout, JSeq jseq,
1501 final SequenceI jds, List<String> viewIds, AlignmentPanel ap,
1502 boolean storeDataset)
1504 if (Desktop.desktop == null)
1508 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1509 for (int f = frames.length - 1; f > -1; f--)
1511 if (frames[f] instanceof AppVarna)
1513 AppVarna varna = (AppVarna) frames[f];
1515 * link the sequence to every viewer that is showing it and is linked to
1516 * its alignment panel
1518 if (varna.isListeningFor(jds) && ap == varna.getAlignmentPanel())
1520 String viewId = varna.getViewId();
1521 RnaViewer rna = new RnaViewer();
1522 rna.setViewId(viewId);
1523 rna.setTitle(varna.getTitle());
1524 rna.setXpos(varna.getX());
1525 rna.setYpos(varna.getY());
1526 rna.setWidth(varna.getWidth());
1527 rna.setHeight(varna.getHeight());
1528 rna.setDividerLocation(varna.getDividerLocation());
1529 rna.setSelectedRna(varna.getSelectedIndex());
1530 jseq.addRnaViewer(rna);
1533 * Store each Varna panel's state once in the project per sequence.
1534 * First time through only (storeDataset==false)
1536 // boolean storeSessions = false;
1537 // String sequenceViewId = viewId + seqsToIds.get(jds);
1538 // if (!storeDataset && !viewIds.contains(sequenceViewId))
1540 // viewIds.add(sequenceViewId);
1541 // storeSessions = true;
1543 for (RnaModel model : varna.getModels())
1545 if (model.seq == jds)
1548 * VARNA saves each view (sequence or alignment secondary
1549 * structure, gapped or trimmed) as a separate XML file
1551 String jarEntryName = rnaSessions.get(model);
1552 if (jarEntryName == null)
1555 String varnaStateFile = varna.getStateInfo(model.rna);
1556 jarEntryName = RNA_PREFIX + viewId + "_" + nextCounter();
1557 copyFileToJar(jout, varnaStateFile, jarEntryName);
1558 rnaSessions.put(model, jarEntryName);
1560 SecondaryStructure ss = new SecondaryStructure();
1561 String annotationId = varna.getAnnotation(jds).annotationId;
1562 ss.setAnnotationId(annotationId);
1563 ss.setViewerState(jarEntryName);
1564 ss.setGapped(model.gapped);
1565 ss.setTitle(model.title);
1566 rna.addSecondaryStructure(ss);
1575 * Copy the contents of a file to a new entry added to the output jar
1579 * @param jarEntryName
1581 protected void copyFileToJar(JarOutputStream jout, String infilePath,
1582 String jarEntryName)
1584 DataInputStream dis = null;
1587 File file = new File(infilePath);
1588 if (file.exists() && jout != null)
1590 dis = new DataInputStream(new FileInputStream(file));
1591 byte[] data = new byte[(int) file.length()];
1592 dis.readFully(data);
1593 writeJarEntry(jout, jarEntryName, data);
1595 } catch (Exception ex)
1597 ex.printStackTrace();
1605 } catch (IOException e)
1614 * Write the data to a new entry of given name in the output jar file
1617 * @param jarEntryName
1619 * @throws IOException
1621 protected void writeJarEntry(JarOutputStream jout, String jarEntryName,
1622 byte[] data) throws IOException
1626 System.out.println("Writing jar entry " + jarEntryName);
1627 jout.putNextEntry(new JarEntry(jarEntryName));
1628 DataOutputStream dout = new DataOutputStream(jout);
1629 dout.write(data, 0, data.length);
1636 * Save the state of a structure viewer
1641 * the archive XML element under which to save the state
1644 * @param matchedFile
1648 protected String saveStructureState(AlignmentPanel ap, SequenceI jds,
1649 Pdbids pdb, PDBEntry entry, List<String> viewIds,
1650 String matchedFile, StructureViewerBase viewFrame)
1652 final AAStructureBindingModel bindingModel = viewFrame.getBinding();
1655 * Look for any bindings for this viewer to the PDB file of interest
1656 * (including part matches excluding chain id)
1658 for (int peid = 0; peid < bindingModel.getPdbCount(); peid++)
1660 final PDBEntry pdbentry = bindingModel.getPdbEntry(peid);
1661 final String pdbId = pdbentry.getId();
1662 if (!pdbId.equals(entry.getId())
1663 && !(entry.getId().length() > 4 && entry.getId()
1664 .toLowerCase().startsWith(pdbId.toLowerCase())))
1667 * not interested in a binding to a different PDB entry here
1671 if (matchedFile == null)
1673 matchedFile = pdbentry.getFile();
1675 else if (!matchedFile.equals(pdbentry.getFile()))
1678 .warn("Probably lost some PDB-Sequence mappings for this structure file (which apparently has same PDB Entry code): "
1679 + pdbentry.getFile());
1683 // can get at it if the ID
1684 // match is ambiguous (e.g.
1687 for (int smap = 0; smap < viewFrame.getBinding().getSequence()[peid].length; smap++)
1689 // if (jal.findIndex(jmol.jmb.sequence[peid][smap]) > -1)
1690 if (jds == viewFrame.getBinding().getSequence()[peid][smap])
1692 StructureState state = new StructureState();
1693 state.setVisible(true);
1694 state.setXpos(viewFrame.getX());
1695 state.setYpos(viewFrame.getY());
1696 state.setWidth(viewFrame.getWidth());
1697 state.setHeight(viewFrame.getHeight());
1698 final String viewId = viewFrame.getViewId();
1699 state.setViewId(viewId);
1700 state.setAlignwithAlignPanel(viewFrame.isUsedforaligment(ap));
1701 state.setColourwithAlignPanel(viewFrame.isUsedforcolourby(ap));
1702 state.setColourByJmol(viewFrame.isColouredByViewer());
1703 state.setType(viewFrame.getViewerType().toString());
1704 pdb.addStructureState(state);
1711 private AnnotationColours constructAnnotationColours(
1712 AnnotationColourGradient acg, List<UserColourScheme> userColours,
1713 JalviewModelSequence jms)
1715 AnnotationColours ac = new AnnotationColours();
1716 ac.setAboveThreshold(acg.getAboveThreshold());
1717 ac.setThreshold(acg.getAnnotationThreshold());
1718 ac.setAnnotation(acg.getAnnotation());
1719 if (acg.getBaseColour() instanceof jalview.schemes.UserColourScheme)
1721 ac.setColourScheme(setUserColourScheme(acg.getBaseColour(),
1726 ac.setColourScheme(ColourSchemeProperty.getColourName(acg.getBaseColour()));
1729 ac.setMaxColour(acg.getMaxColour().getRGB());
1730 ac.setMinColour(acg.getMinColour().getRGB());
1731 ac.setPerSequence(acg.isSeqAssociated());
1732 ac.setPredefinedColours(acg.isPredefinedColours());
1736 private void storeAlignmentAnnotation(AlignmentAnnotation[] aa,
1737 IdentityHashMap<SequenceGroup, String> groupRefs,
1738 AlignmentViewport av, Set<String> calcIdSet, boolean storeDS,
1739 SequenceSet vamsasSet)
1742 for (int i = 0; i < aa.length; i++)
1744 Annotation an = new Annotation();
1746 AlignmentAnnotation annotation = aa[i];
1747 if (annotation.annotationId != null)
1749 annotationIds.put(annotation.annotationId, annotation);
1752 an.setId(annotation.annotationId);
1754 an.setVisible(annotation.visible);
1756 an.setDescription(annotation.description);
1758 if (annotation.sequenceRef != null)
1760 // 2.9 JAL-1781 xref on sequence id rather than name
1761 an.setSequenceRef(seqsToIds.get(annotation.sequenceRef));
1763 if (annotation.groupRef != null)
1765 String groupIdr = groupRefs.get(annotation.groupRef);
1766 if (groupIdr == null)
1768 // make a locally unique String
1770 annotation.groupRef,
1771 groupIdr = ("" + System.currentTimeMillis()
1772 + annotation.groupRef.getName() + groupRefs
1775 an.setGroupRef(groupIdr.toString());
1778 // store all visualization attributes for annotation
1779 an.setGraphHeight(annotation.graphHeight);
1780 an.setCentreColLabels(annotation.centreColLabels);
1781 an.setScaleColLabels(annotation.scaleColLabel);
1782 an.setShowAllColLabels(annotation.showAllColLabels);
1783 an.setBelowAlignment(annotation.belowAlignment);
1785 if (annotation.graph > 0)
1788 an.setGraphType(annotation.graph);
1789 an.setGraphGroup(annotation.graphGroup);
1790 if (annotation.getThreshold() != null)
1792 ThresholdLine line = new ThresholdLine();
1793 line.setLabel(annotation.getThreshold().label);
1794 line.setValue(annotation.getThreshold().value);
1795 line.setColour(annotation.getThreshold().colour.getRGB());
1796 an.setThresholdLine(line);
1804 an.setLabel(annotation.label);
1806 if (annotation == av.getAlignmentQualityAnnot()
1807 || annotation == av.getAlignmentConservationAnnotation()
1808 || annotation == av.getAlignmentConsensusAnnotation()
1809 || annotation.autoCalculated)
1811 // new way of indicating autocalculated annotation -
1812 an.setAutoCalculated(annotation.autoCalculated);
1814 if (annotation.hasScore())
1816 an.setScore(annotation.getScore());
1819 if (annotation.getCalcId() != null)
1821 calcIdSet.add(annotation.getCalcId());
1822 an.setCalcId(annotation.getCalcId());
1824 if (annotation.hasProperties())
1826 for (String pr : annotation.getProperties())
1828 Property prop = new Property();
1830 prop.setValue(annotation.getProperty(pr));
1831 an.addProperty(prop);
1835 AnnotationElement ae;
1836 if (annotation.annotations != null)
1838 an.setScoreOnly(false);
1839 for (int a = 0; a < annotation.annotations.length; a++)
1841 if ((annotation == null) || (annotation.annotations[a] == null))
1846 ae = new AnnotationElement();
1847 if (annotation.annotations[a].description != null)
1849 ae.setDescription(annotation.annotations[a].description);
1851 if (annotation.annotations[a].displayCharacter != null)
1853 ae.setDisplayCharacter(annotation.annotations[a].displayCharacter);
1856 if (!Float.isNaN(annotation.annotations[a].value))
1858 ae.setValue(annotation.annotations[a].value);
1862 if (annotation.annotations[a].secondaryStructure > ' ')
1864 ae.setSecondaryStructure(annotation.annotations[a].secondaryStructure
1868 if (annotation.annotations[a].colour != null
1869 && annotation.annotations[a].colour != java.awt.Color.black)
1871 ae.setColour(annotation.annotations[a].colour.getRGB());
1874 an.addAnnotationElement(ae);
1875 if (annotation.autoCalculated)
1877 // only write one non-null entry into the annotation row -
1878 // sufficient to get the visualization attributes necessary to
1886 an.setScoreOnly(true);
1888 if (!storeDS || (storeDS && !annotation.autoCalculated))
1890 // skip autocalculated annotation - these are only provided for
1892 vamsasSet.addAnnotation(an);
1898 private CalcIdParam createCalcIdParam(String calcId, AlignViewport av)
1900 AutoCalcSetting settings = av.getCalcIdSettingsFor(calcId);
1901 if (settings != null)
1903 CalcIdParam vCalcIdParam = new CalcIdParam();
1904 vCalcIdParam.setCalcId(calcId);
1905 vCalcIdParam.addServiceURL(settings.getServiceURI());
1906 // generic URI allowing a third party to resolve another instance of the
1907 // service used for this calculation
1908 for (String urls : settings.getServiceURLs())
1910 vCalcIdParam.addServiceURL(urls);
1912 vCalcIdParam.setVersion("1.0");
1913 if (settings.getPreset() != null)
1915 WsParamSetI setting = settings.getPreset();
1916 vCalcIdParam.setName(setting.getName());
1917 vCalcIdParam.setDescription(setting.getDescription());
1921 vCalcIdParam.setName("");
1922 vCalcIdParam.setDescription("Last used parameters");
1924 // need to be able to recover 1) settings 2) user-defined presets or
1925 // recreate settings from preset 3) predefined settings provided by
1926 // service - or settings that can be transferred (or discarded)
1927 vCalcIdParam.setParameters(settings.getWsParamFile().replace("\n",
1929 vCalcIdParam.setAutoUpdate(settings.isAutoUpdate());
1930 // todo - decide if updateImmediately is needed for any projects.
1932 return vCalcIdParam;
1937 private boolean recoverCalcIdParam(CalcIdParam calcIdParam,
1940 if (calcIdParam.getVersion().equals("1.0"))
1942 Jws2Instance service = Jws2Discoverer.getDiscoverer()
1943 .getPreferredServiceFor(calcIdParam.getServiceURL());
1944 if (service != null)
1946 WsParamSetI parmSet = null;
1949 parmSet = service.getParamStore().parseServiceParameterFile(
1950 calcIdParam.getName(), calcIdParam.getDescription(),
1951 calcIdParam.getServiceURL(),
1952 calcIdParam.getParameters().replace("|\\n|", "\n"));
1953 } catch (IOException x)
1955 warn("Couldn't parse parameter data for "
1956 + calcIdParam.getCalcId(), x);
1959 List<ArgumentI> argList = null;
1960 if (calcIdParam.getName().length() > 0)
1962 parmSet = service.getParamStore()
1963 .getPreset(calcIdParam.getName());
1964 if (parmSet != null)
1966 // TODO : check we have a good match with settings in AACon -
1967 // otherwise we'll need to create a new preset
1972 argList = parmSet.getArguments();
1975 AAConSettings settings = new AAConSettings(
1976 calcIdParam.isAutoUpdate(), service, parmSet, argList);
1977 av.setCalcIdSettingsFor(calcIdParam.getCalcId(), settings,
1978 calcIdParam.isNeedsUpdate());
1983 warn("Cannot resolve a service for the parameters used in this project. Try configuring a JABAWS server.");
1987 throw new Error(MessageManager.formatMessage(
1988 "error.unsupported_version_calcIdparam",
1989 new Object[] { calcIdParam.toString() }));
1993 * External mapping between jalview objects and objects yielding a valid and
1994 * unique object ID string. This is null for normal Jalview project IO, but
1995 * non-null when a jalview project is being read or written as part of a
1998 IdentityHashMap jv2vobj = null;
2001 * Construct a unique ID for jvobj using either existing bindings or if none
2002 * exist, the result of the hashcode call for the object.
2005 * jalview data object
2006 * @return unique ID for referring to jvobj
2008 private String makeHashCode(Object jvobj, String altCode)
2010 if (jv2vobj != null)
2012 Object id = jv2vobj.get(jvobj);
2015 return id.toString();
2017 // check string ID mappings
2018 if (jvids2vobj != null && jvobj instanceof String)
2020 id = jvids2vobj.get(jvobj);
2024 return id.toString();
2026 // give up and warn that something has gone wrong
2027 warn("Cannot find ID for object in external mapping : " + jvobj);
2033 * return local jalview object mapped to ID, if it exists
2037 * @return null or object bound to idcode
2039 private Object retrieveExistingObj(String idcode)
2041 if (idcode != null && vobj2jv != null)
2043 return vobj2jv.get(idcode);
2049 * binding from ID strings from external mapping table to jalview data model
2052 private Hashtable vobj2jv;
2054 private Sequence createVamsasSequence(String id, SequenceI jds)
2056 return createVamsasSequence(true, id, jds, null);
2059 private Sequence createVamsasSequence(boolean recurse, String id,
2060 SequenceI jds, SequenceI parentseq)
2062 Sequence vamsasSeq = new Sequence();
2063 vamsasSeq.setId(id);
2064 vamsasSeq.setName(jds.getName());
2065 vamsasSeq.setSequence(jds.getSequenceAsString());
2066 vamsasSeq.setDescription(jds.getDescription());
2067 jalview.datamodel.DBRefEntry[] dbrefs = null;
2068 if (jds.getDatasetSequence() != null)
2070 vamsasSeq.setDsseqid(seqHash(jds.getDatasetSequence()));
2074 // seqId==dsseqid so we can tell which sequences really are
2075 // dataset sequences only
2076 vamsasSeq.setDsseqid(id);
2077 dbrefs = jds.getDBRefs();
2078 if (parentseq == null)
2085 for (int d = 0; d < dbrefs.length; d++)
2087 DBRef dbref = new DBRef();
2088 dbref.setSource(dbrefs[d].getSource());
2089 dbref.setVersion(dbrefs[d].getVersion());
2090 dbref.setAccessionId(dbrefs[d].getAccessionId());
2091 if (dbrefs[d].hasMap())
2093 Mapping mp = createVamsasMapping(dbrefs[d].getMap(), parentseq,
2095 dbref.setMapping(mp);
2097 vamsasSeq.addDBRef(dbref);
2103 private Mapping createVamsasMapping(jalview.datamodel.Mapping jmp,
2104 SequenceI parentseq, SequenceI jds, boolean recurse)
2107 if (jmp.getMap() != null)
2111 jalview.util.MapList mlst = jmp.getMap();
2112 List<int[]> r = mlst.getFromRanges();
2113 for (int[] range : r)
2115 MapListFrom mfrom = new MapListFrom();
2116 mfrom.setStart(range[0]);
2117 mfrom.setEnd(range[1]);
2118 mp.addMapListFrom(mfrom);
2120 r = mlst.getToRanges();
2121 for (int[] range : r)
2123 MapListTo mto = new MapListTo();
2124 mto.setStart(range[0]);
2125 mto.setEnd(range[1]);
2126 mp.addMapListTo(mto);
2128 mp.setMapFromUnit(mlst.getFromRatio());
2129 mp.setMapToUnit(mlst.getToRatio());
2130 if (jmp.getTo() != null)
2132 MappingChoice mpc = new MappingChoice();
2134 // check/create ID for the sequence referenced by getTo()
2137 SequenceI ps = null;
2138 if (parentseq != jmp.getTo()
2139 && parentseq.getDatasetSequence() != jmp.getTo())
2141 // chaining dbref rather than a handshaking one
2142 jmpid = seqHash(ps = jmp.getTo());
2146 jmpid = seqHash(ps = parentseq);
2148 mpc.setDseqFor(jmpid);
2149 if (!seqRefIds.containsKey(mpc.getDseqFor()))
2151 jalview.bin.Cache.log.debug("creatign new DseqFor ID");
2152 seqRefIds.put(mpc.getDseqFor(), ps);
2156 jalview.bin.Cache.log.debug("reusing DseqFor ID");
2159 mp.setMappingChoice(mpc);
2165 String setUserColourScheme(jalview.schemes.ColourSchemeI cs,
2166 List<UserColourScheme> userColours, JalviewModelSequence jms)
2169 jalview.schemes.UserColourScheme ucs = (jalview.schemes.UserColourScheme) cs;
2170 boolean newucs = false;
2171 if (!userColours.contains(ucs))
2173 userColours.add(ucs);
2176 id = "ucs" + userColours.indexOf(ucs);
2179 // actually create the scheme's entry in the XML model
2180 java.awt.Color[] colours = ucs.getColours();
2181 jalview.schemabinding.version2.UserColours uc = new jalview.schemabinding.version2.UserColours();
2182 jalview.schemabinding.version2.UserColourScheme jbucs = new jalview.schemabinding.version2.UserColourScheme();
2184 for (int i = 0; i < colours.length; i++)
2186 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
2187 col.setName(ResidueProperties.aa[i]);
2188 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2189 jbucs.addColour(col);
2191 if (ucs.getLowerCaseColours() != null)
2193 colours = ucs.getLowerCaseColours();
2194 for (int i = 0; i < colours.length; i++)
2196 jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
2197 col.setName(ResidueProperties.aa[i].toLowerCase());
2198 col.setRGB(jalview.util.Format.getHexString(colours[i]));
2199 jbucs.addColour(col);
2204 uc.setUserColourScheme(jbucs);
2205 jms.addUserColours(uc);
2211 jalview.schemes.UserColourScheme getUserColourScheme(
2212 JalviewModelSequence jms, String id)
2214 UserColours[] uc = jms.getUserColours();
2215 UserColours colours = null;
2217 for (int i = 0; i < uc.length; i++)
2219 if (uc[i].getId().equals(id))
2227 java.awt.Color[] newColours = new java.awt.Color[24];
2229 for (int i = 0; i < 24; i++)
2231 newColours[i] = new java.awt.Color(Integer.parseInt(colours
2232 .getUserColourScheme().getColour(i).getRGB(), 16));
2235 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
2238 if (colours.getUserColourScheme().getColourCount() > 24)
2240 newColours = new java.awt.Color[23];
2241 for (int i = 0; i < 23; i++)
2243 newColours[i] = new java.awt.Color(Integer.parseInt(colours
2244 .getUserColourScheme().getColour(i + 24).getRGB(), 16));
2246 ucs.setLowerCaseColours(newColours);
2253 * contains last error message (if any) encountered by XML loader.
2255 String errorMessage = null;
2258 * flag to control whether the Jalview2XML_V1 parser should be deferred to if
2259 * exceptions are raised during project XML parsing
2261 public boolean attemptversion1parse = true;
2264 * Load a jalview project archive from a jar file
2267 * - HTTP URL or filename
2269 public AlignFrame loadJalviewAlign(final String file)
2272 jalview.gui.AlignFrame af = null;
2276 // create list to store references for any new Jmol viewers created
2277 newStructureViewers = new Vector<JalviewStructureDisplayI>();
2278 // UNMARSHALLER SEEMS TO CLOSE JARINPUTSTREAM, MOST ANNOYING
2279 // Workaround is to make sure caller implements the JarInputStreamProvider
2281 // so we can re-open the jar input stream for each entry.
2283 jarInputStreamProvider jprovider = createjarInputStreamProvider(file);
2284 af = loadJalviewAlign(jprovider);
2286 } catch (MalformedURLException e)
2288 errorMessage = "Invalid URL format for '" + file + "'";
2294 SwingUtilities.invokeAndWait(new Runnable()
2299 setLoadingFinishedForNewStructureViewers();
2302 } catch (Exception x)
2304 System.err.println("Error loading alignment: " + x.getMessage());
2310 private jarInputStreamProvider createjarInputStreamProvider(
2311 final String file) throws MalformedURLException
2314 errorMessage = null;
2315 uniqueSetSuffix = null;
2317 viewportsAdded.clear();
2318 frefedSequence = null;
2320 if (file.startsWith("http://"))
2322 url = new URL(file);
2324 final URL _url = url;
2325 return new jarInputStreamProvider()
2329 public JarInputStream getJarInputStream() throws IOException
2333 return new JarInputStream(_url.openStream());
2337 return new JarInputStream(new FileInputStream(file));
2342 public String getFilename()
2350 * Recover jalview session from a jalview project archive. Caller may
2351 * initialise uniqueSetSuffix, seqRefIds, viewportsAdded and frefedSequence
2352 * themselves. Any null fields will be initialised with default values,
2353 * non-null fields are left alone.
2358 public AlignFrame loadJalviewAlign(final jarInputStreamProvider jprovider)
2360 errorMessage = null;
2361 if (uniqueSetSuffix == null)
2363 uniqueSetSuffix = System.currentTimeMillis() % 100000 + "";
2365 if (seqRefIds == null)
2369 AlignFrame af = null, _af = null;
2370 IdentityHashMap<AlignmentI, AlignmentI> importedDatasets = new IdentityHashMap<AlignmentI, AlignmentI>();
2371 Map<String, AlignFrame> gatherToThisFrame = new HashMap<String, AlignFrame>();
2372 final String file = jprovider.getFilename();
2375 JarInputStream jin = null;
2376 JarEntry jarentry = null;
2381 jin = jprovider.getJarInputStream();
2382 for (int i = 0; i < entryCount; i++)
2384 jarentry = jin.getNextJarEntry();
2387 if (jarentry != null && jarentry.getName().endsWith(".xml"))
2389 InputStreamReader in = new InputStreamReader(jin, UTF_8);
2390 JalviewModel object = new JalviewModel();
2392 Unmarshaller unmar = new Unmarshaller(object);
2393 unmar.setValidation(false);
2394 object = (JalviewModel) unmar.unmarshal(in);
2395 if (true) // !skipViewport(object))
2397 _af = loadFromObject(object, file, true, jprovider);
2399 && object.getJalviewModelSequence().getViewportCount() > 0)
2403 // store a reference to the first view
2406 if (_af.viewport.isGatherViewsHere())
2408 // if this is a gathered view, keep its reference since
2409 // after gathering views, only this frame will remain
2411 gatherToThisFrame.put(_af.viewport.getSequenceSetId(), _af);
2413 // Save dataset to register mappings once all resolved
2414 importedDatasets.put(af.viewport.getAlignment().getDataset(),
2415 af.viewport.getAlignment().getDataset());
2420 else if (jarentry != null)
2422 // Some other file here.
2425 } while (jarentry != null);
2426 resolveFrefedSequences();
2427 } catch (IOException ex)
2429 ex.printStackTrace();
2430 errorMessage = "Couldn't locate Jalview XML file : " + file;
2431 System.err.println("Exception whilst loading jalview XML file : "
2433 } catch (Exception ex)
2435 System.err.println("Parsing as Jalview Version 2 file failed.");
2436 ex.printStackTrace(System.err);
2437 if (attemptversion1parse)
2439 // Is Version 1 Jar file?
2442 af = new Jalview2XML_V1(raiseGUI).LoadJalviewAlign(jprovider);
2443 } catch (Exception ex2)
2445 System.err.println("Exception whilst loading as jalviewXMLV1:");
2446 ex2.printStackTrace();
2450 if (Desktop.instance != null)
2452 Desktop.instance.stopLoading();
2456 System.out.println("Successfully loaded archive file");
2459 ex.printStackTrace();
2461 System.err.println("Exception whilst loading jalview XML file : "
2463 } catch (OutOfMemoryError e)
2465 // Don't use the OOM Window here
2466 errorMessage = "Out of memory loading jalview XML file";
2467 System.err.println("Out of memory whilst loading jalview XML file");
2468 e.printStackTrace();
2472 * Regather multiple views (with the same sequence set id) to the frame (if
2473 * any) that is flagged as the one to gather to, i.e. convert them to tabbed
2474 * views instead of separate frames. Note this doesn't restore a state where
2475 * some expanded views in turn have tabbed views - the last "first tab" read
2476 * in will play the role of gatherer for all.
2478 for (AlignFrame fr : gatherToThisFrame.values())
2480 Desktop.instance.gatherViews(fr);
2483 restoreSplitFrames();
2484 for (AlignmentI ds : importedDatasets.keySet())
2486 if (ds.getCodonFrames() != null)
2488 StructureSelectionManager.getStructureSelectionManager(
2489 Desktop.instance).registerMappings(ds.getCodonFrames());
2492 if (errorMessage != null)
2497 if (Desktop.instance != null)
2499 Desktop.instance.stopLoading();
2506 * Try to reconstruct and display SplitFrame windows, where each contains
2507 * complementary dna and protein alignments. Done by pairing up AlignFrame
2508 * objects (created earlier) which have complementary viewport ids associated.
2510 protected void restoreSplitFrames()
2512 List<SplitFrame> gatherTo = new ArrayList<SplitFrame>();
2513 List<AlignFrame> addedToSplitFrames = new ArrayList<AlignFrame>();
2514 Map<String, AlignFrame> dna = new HashMap<String, AlignFrame>();
2517 * Identify the DNA alignments
2519 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2522 AlignFrame af = candidate.getValue();
2523 if (af.getViewport().getAlignment().isNucleotide())
2525 dna.put(candidate.getKey().getId(), af);
2530 * Try to match up the protein complements
2532 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2535 AlignFrame af = candidate.getValue();
2536 if (!af.getViewport().getAlignment().isNucleotide())
2538 String complementId = candidate.getKey().getComplementId();
2539 // only non-null complements should be in the Map
2540 if (complementId != null && dna.containsKey(complementId))
2542 final AlignFrame dnaFrame = dna.get(complementId);
2543 SplitFrame sf = createSplitFrame(dnaFrame, af);
2544 addedToSplitFrames.add(dnaFrame);
2545 addedToSplitFrames.add(af);
2546 dnaFrame.setMenusForViewport();
2547 af.setMenusForViewport();
2548 if (af.viewport.isGatherViewsHere())
2557 * Open any that we failed to pair up (which shouldn't happen!) as
2558 * standalone AlignFrame's.
2560 for (Entry<Viewport, AlignFrame> candidate : splitFrameCandidates
2563 AlignFrame af = candidate.getValue();
2564 if (!addedToSplitFrames.contains(af))
2566 Viewport view = candidate.getKey();
2567 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
2569 af.setMenusForViewport();
2570 System.err.println("Failed to restore view " + view.getTitle()
2571 + " to split frame");
2576 * Gather back into tabbed views as flagged.
2578 for (SplitFrame sf : gatherTo)
2580 Desktop.instance.gatherViews(sf);
2583 splitFrameCandidates.clear();
2587 * Construct and display one SplitFrame holding DNA and protein alignments.
2590 * @param proteinFrame
2593 protected SplitFrame createSplitFrame(AlignFrame dnaFrame,
2594 AlignFrame proteinFrame)
2596 SplitFrame splitFrame = new SplitFrame(dnaFrame, proteinFrame);
2597 String title = MessageManager.getString("label.linked_view_title");
2598 int width = (int) dnaFrame.getBounds().getWidth();
2599 int height = (int) (dnaFrame.getBounds().getHeight()
2600 + proteinFrame.getBounds().getHeight() + 50);
2603 * SplitFrame location is saved to both enclosed frames
2605 splitFrame.setLocation(dnaFrame.getX(), dnaFrame.getY());
2606 Desktop.addInternalFrame(splitFrame, title, width, height);
2609 * And compute cDNA consensus (couldn't do earlier with consensus as
2610 * mappings were not yet present)
2612 proteinFrame.viewport.alignmentChanged(proteinFrame.alignPanel);
2618 * check errorMessage for a valid error message and raise an error box in the
2619 * GUI or write the current errorMessage to stderr and then clear the error
2622 protected void reportErrors()
2624 reportErrors(false);
2627 protected void reportErrors(final boolean saving)
2629 if (errorMessage != null)
2631 final String finalErrorMessage = errorMessage;
2634 javax.swing.SwingUtilities.invokeLater(new Runnable()
2639 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2640 finalErrorMessage, "Error "
2641 + (saving ? "saving" : "loading")
2642 + " Jalview file", JvOptionPane.WARNING_MESSAGE);
2648 System.err.println("Problem loading Jalview file: " + errorMessage);
2651 errorMessage = null;
2654 Map<String, String> alreadyLoadedPDB = new HashMap<String, String>();
2657 * when set, local views will be updated from view stored in JalviewXML
2658 * Currently (28th Sep 2008) things will go horribly wrong in vamsas document
2659 * sync if this is set to true.
2661 private final boolean updateLocalViews = false;
2664 * Returns the path to a temporary file holding the PDB file for the given PDB
2665 * id. The first time of asking, searches for a file of that name in the
2666 * Jalview project jar, and copies it to a new temporary file. Any repeat
2667 * requests just return the path to the file previously created.
2673 String loadPDBFile(jarInputStreamProvider jprovider, String pdbId,
2676 if (alreadyLoadedPDB.containsKey(pdbId))
2678 return alreadyLoadedPDB.get(pdbId).toString();
2681 String tempFile = copyJarEntry(jprovider, pdbId, "jalview_pdb",
2683 if (tempFile != null)
2685 alreadyLoadedPDB.put(pdbId, tempFile);
2691 * Copies the jar entry of given name to a new temporary file and returns the
2692 * path to the file, or null if the entry is not found.
2695 * @param jarEntryName
2697 * a prefix for the temporary file name, must be at least three
2700 * null or original file - so new file can be given the same suffix
2704 protected String copyJarEntry(jarInputStreamProvider jprovider,
2705 String jarEntryName, String prefix, String origFile)
2707 BufferedReader in = null;
2708 PrintWriter out = null;
2709 String suffix = ".tmp";
2710 if (origFile == null)
2712 origFile = jarEntryName;
2714 int sfpos = origFile.lastIndexOf(".");
2715 if (sfpos > -1 && sfpos < (origFile.length() - 3))
2717 suffix = "." + origFile.substring(sfpos + 1);
2721 JarInputStream jin = jprovider.getJarInputStream();
2723 * if (jprovider.startsWith("http://")) { jin = new JarInputStream(new
2724 * URL(jprovider).openStream()); } else { jin = new JarInputStream(new
2725 * FileInputStream(jprovider)); }
2728 JarEntry entry = null;
2731 entry = jin.getNextJarEntry();
2732 } while (entry != null && !entry.getName().equals(jarEntryName));
2735 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
2736 File outFile = File.createTempFile(prefix, suffix);
2737 outFile.deleteOnExit();
2738 out = new PrintWriter(new FileOutputStream(outFile));
2741 while ((data = in.readLine()) != null)
2746 String t = outFile.getAbsolutePath();
2751 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
2753 } catch (Exception ex)
2755 ex.printStackTrace();
2763 } catch (IOException e)
2777 private class JvAnnotRow
2779 public JvAnnotRow(int i, AlignmentAnnotation jaa)
2786 * persisted version of annotation row from which to take vis properties
2788 public jalview.datamodel.AlignmentAnnotation template;
2791 * original position of the annotation row in the alignment
2797 * Load alignment frame from jalview XML DOM object
2802 * filename source string
2803 * @param loadTreesAndStructures
2804 * when false only create Viewport
2806 * data source provider
2807 * @return alignment frame created from view stored in DOM
2809 AlignFrame loadFromObject(JalviewModel object, String file,
2810 boolean loadTreesAndStructures, jarInputStreamProvider jprovider)
2812 SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
2813 Sequence[] vamsasSeq = vamsasSet.getSequence();
2815 JalviewModelSequence jms = object.getJalviewModelSequence();
2817 Viewport view = (jms.getViewportCount() > 0) ? jms.getViewport(0)
2820 // ////////////////////////////////
2823 List<SequenceI> hiddenSeqs = null;
2825 List<SequenceI> tmpseqs = new ArrayList<SequenceI>();
2827 boolean multipleView = false;
2828 SequenceI referenceseqForView = null;
2829 JSeq[] jseqs = object.getJalviewModelSequence().getJSeq();
2830 int vi = 0; // counter in vamsasSeq array
2831 for (int i = 0; i < jseqs.length; i++)
2833 String seqId = jseqs[i].getId();
2835 SequenceI tmpSeq = seqRefIds.get(seqId);
2838 if (!incompleteSeqs.containsKey(seqId))
2840 // may not need this check, but keep it for at least 2.9,1 release
2841 if (tmpSeq.getStart() != jseqs[i].getStart()
2842 || tmpSeq.getEnd() != jseqs[i].getEnd())
2845 .println("Warning JAL-2154 regression: updating start/end for sequence "
2846 + tmpSeq.toString() + " to " + jseqs[i]);
2851 incompleteSeqs.remove(seqId);
2853 if (vamsasSeq.length > vi && vamsasSeq[vi].getId().equals(seqId))
2855 // most likely we are reading a dataset XML document so
2856 // update from vamsasSeq section of XML for this sequence
2857 tmpSeq.setName(vamsasSeq[vi].getName());
2858 tmpSeq.setDescription(vamsasSeq[vi].getDescription());
2859 tmpSeq.setSequence(vamsasSeq[vi].getSequence());
2864 // reading multiple views, so vamsasSeq set is a subset of JSeq
2865 multipleView = true;
2867 tmpSeq.setStart(jseqs[i].getStart());
2868 tmpSeq.setEnd(jseqs[i].getEnd());
2869 tmpseqs.add(tmpSeq);
2873 tmpSeq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
2874 vamsasSeq[vi].getSequence());
2875 tmpSeq.setDescription(vamsasSeq[vi].getDescription());
2876 tmpSeq.setStart(jseqs[i].getStart());
2877 tmpSeq.setEnd(jseqs[i].getEnd());
2878 tmpSeq.setVamsasId(uniqueSetSuffix + seqId);
2879 seqRefIds.put(vamsasSeq[vi].getId(), tmpSeq);
2880 tmpseqs.add(tmpSeq);
2884 if (jseqs[i].hasViewreference() && jseqs[i].getViewreference())
2886 referenceseqForView = tmpseqs.get(tmpseqs.size() - 1);
2889 if (jseqs[i].getHidden())
2891 if (hiddenSeqs == null)
2893 hiddenSeqs = new ArrayList<SequenceI>();
2896 hiddenSeqs.add(tmpSeq);
2901 // Create the alignment object from the sequence set
2902 // ///////////////////////////////
2903 SequenceI[] orderedSeqs = tmpseqs
2904 .toArray(new SequenceI[tmpseqs.size()]);
2906 AlignmentI al = null;
2907 // so we must create or recover the dataset alignment before going further
2908 // ///////////////////////////////
2909 if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
2911 // older jalview projects do not have a dataset - so creat alignment and
2913 al = new Alignment(orderedSeqs);
2914 al.setDataset(null);
2918 boolean isdsal = object.getJalviewModelSequence().getViewportCount() == 0;
2921 // we are importing a dataset record, so
2922 // recover reference to an alignment already materialsed as dataset
2923 al = getDatasetFor(vamsasSet.getDatasetId());
2927 // materialse the alignment
2928 al = new Alignment(orderedSeqs);
2932 addDatasetRef(vamsasSet.getDatasetId(), al);
2935 // finally, verify all data in vamsasSet is actually present in al
2936 // passing on flag indicating if it is actually a stored dataset
2937 recoverDatasetFor(vamsasSet, al, isdsal);
2940 if (referenceseqForView != null)
2942 al.setSeqrep(referenceseqForView);
2944 // / Add the alignment properties
2945 for (int i = 0; i < vamsasSet.getSequenceSetPropertiesCount(); i++)
2947 SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties(i);
2948 al.setProperty(ssp.getKey(), ssp.getValue());
2951 // ///////////////////////////////
2953 Hashtable pdbloaded = new Hashtable(); // TODO nothing writes to this??
2956 // load sequence features, database references and any associated PDB
2957 // structures for the alignment
2959 // prior to 2.10, this part would only be executed the first time a
2960 // sequence was encountered, but not afterwards.
2961 // now, for 2.10 projects, this is also done if the xml doc includes
2962 // dataset sequences not actually present in any particular view.
2964 for (int i = 0; i < vamsasSeq.length; i++)
2966 if (jseqs[i].getFeaturesCount() > 0)
2968 Features[] features = jseqs[i].getFeatures();
2969 for (int f = 0; f < features.length; f++)
2971 jalview.datamodel.SequenceFeature sf = new jalview.datamodel.SequenceFeature(
2972 features[f].getType(), features[f].getDescription(),
2973 features[f].getStatus(), features[f].getBegin(),
2974 features[f].getEnd(), features[f].getFeatureGroup());
2976 sf.setScore(features[f].getScore());
2977 for (int od = 0; od < features[f].getOtherDataCount(); od++)
2979 OtherData keyValue = features[f].getOtherData(od);
2980 if (keyValue.getKey().startsWith("LINK"))
2982 sf.addLink(keyValue.getValue());
2986 sf.setValue(keyValue.getKey(), keyValue.getValue());
2990 // adds feature to datasequence's feature set (since Jalview 2.10)
2991 al.getSequenceAt(i).addSequenceFeature(sf);
2994 if (vamsasSeq[i].getDBRefCount() > 0)
2996 // adds dbrefs to datasequence's set (since Jalview 2.10)
2998 al.getSequenceAt(i).getDatasetSequence() == null ? al.getSequenceAt(i)
2999 : al.getSequenceAt(i).getDatasetSequence(),
3002 if (jseqs[i].getPdbidsCount() > 0)
3004 Pdbids[] ids = jseqs[i].getPdbids();
3005 for (int p = 0; p < ids.length; p++)
3007 jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
3008 entry.setId(ids[p].getId());
3009 if (ids[p].getType() != null)
3011 if (PDBEntry.Type.getType(ids[p].getType()) != null)
3013 entry.setType(PDBEntry.Type.getType(ids[p].getType()));
3017 entry.setType(PDBEntry.Type.FILE);
3020 // jprovider is null when executing 'New View'
3021 if (ids[p].getFile() != null && jprovider != null)
3023 if (!pdbloaded.containsKey(ids[p].getFile()))
3025 entry.setFile(loadPDBFile(jprovider, ids[p].getId(),
3030 entry.setFile(pdbloaded.get(ids[p].getId()).toString());
3033 if (ids[p].getPdbentryItem() != null)
3035 for (PdbentryItem item : ids[p].getPdbentryItem())
3037 for (Property pr : item.getProperty())
3039 entry.setProperty(pr.getName(), pr.getValue());
3043 StructureSelectionManager.getStructureSelectionManager(
3044 Desktop.instance).registerPDBEntry(entry);
3045 // adds PDBEntry to datasequence's set (since Jalview 2.10)
3046 if (al.getSequenceAt(i).getDatasetSequence() != null)
3048 al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
3052 al.getSequenceAt(i).addPDBId(entry);
3057 } // end !multipleview
3059 // ///////////////////////////////
3060 // LOAD SEQUENCE MAPPINGS
3062 if (vamsasSet.getAlcodonFrameCount() > 0)
3064 // TODO Potentially this should only be done once for all views of an
3066 AlcodonFrame[] alc = vamsasSet.getAlcodonFrame();
3067 for (int i = 0; i < alc.length; i++)
3069 AlignedCodonFrame cf = new AlignedCodonFrame();
3070 if (alc[i].getAlcodMapCount() > 0)
3072 AlcodMap[] maps = alc[i].getAlcodMap();
3073 for (int m = 0; m < maps.length; m++)
3075 SequenceI dnaseq = seqRefIds.get(maps[m].getDnasq());
3077 jalview.datamodel.Mapping mapping = null;
3078 // attach to dna sequence reference.
3079 if (maps[m].getMapping() != null)
3081 mapping = addMapping(maps[m].getMapping());
3082 if (dnaseq != null && mapping.getTo() != null)
3084 cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
3089 frefedSequence.add(newAlcodMapRef(maps[m].getDnasq(), cf,
3094 al.addCodonFrame(cf);
3099 // ////////////////////////////////
3101 List<JvAnnotRow> autoAlan = new ArrayList<JvAnnotRow>();
3104 * store any annotations which forward reference a group's ID
3106 Map<String, List<AlignmentAnnotation>> groupAnnotRefs = new Hashtable<String, List<AlignmentAnnotation>>();
3108 if (vamsasSet.getAnnotationCount() > 0)
3110 Annotation[] an = vamsasSet.getAnnotation();
3112 for (int i = 0; i < an.length; i++)
3114 Annotation annotation = an[i];
3117 * test if annotation is automatically calculated for this view only
3119 boolean autoForView = false;
3120 if (annotation.getLabel().equals("Quality")
3121 || annotation.getLabel().equals("Conservation")
3122 || annotation.getLabel().equals("Consensus"))
3124 // Kludge for pre 2.5 projects which lacked the autocalculated flag
3126 if (!annotation.hasAutoCalculated())
3128 annotation.setAutoCalculated(true);
3132 || (annotation.hasAutoCalculated() && annotation
3133 .isAutoCalculated()))
3135 // remove ID - we don't recover annotation from other views for
3136 // view-specific annotation
3137 annotation.setId(null);
3140 // set visiblity for other annotation in this view
3141 String annotationId = annotation.getId();
3142 if (annotationId != null && annotationIds.containsKey(annotationId))
3144 AlignmentAnnotation jda = annotationIds.get(annotationId);
3145 // in principle Visible should always be true for annotation displayed
3146 // in multiple views
3147 if (annotation.hasVisible())
3149 jda.visible = annotation.getVisible();
3152 al.addAnnotation(jda);
3156 // Construct new annotation from model.
3157 AnnotationElement[] ae = annotation.getAnnotationElement();
3158 jalview.datamodel.Annotation[] anot = null;
3159 java.awt.Color firstColour = null;
3161 if (!annotation.getScoreOnly())
3163 anot = new jalview.datamodel.Annotation[al.getWidth()];
3164 for (int aa = 0; aa < ae.length && aa < anot.length; aa++)
3166 anpos = ae[aa].getPosition();
3168 if (anpos >= anot.length)
3173 anot[anpos] = new jalview.datamodel.Annotation(
3175 ae[aa].getDisplayCharacter(), ae[aa].getDescription(),
3176 (ae[aa].getSecondaryStructure() == null || ae[aa]
3177 .getSecondaryStructure().length() == 0) ? ' '
3178 : ae[aa].getSecondaryStructure().charAt(0),
3182 // JBPNote: Consider verifying dataflow for IO of secondary
3183 // structure annotation read from Stockholm files
3184 // this was added to try to ensure that
3185 // if (anot[ae[aa].getPosition()].secondaryStructure>' ')
3187 // anot[ae[aa].getPosition()].displayCharacter = "";
3189 anot[anpos].colour = new java.awt.Color(ae[aa].getColour());
3190 if (firstColour == null)
3192 firstColour = anot[anpos].colour;
3196 jalview.datamodel.AlignmentAnnotation jaa = null;
3198 if (annotation.getGraph())
3200 float llim = 0, hlim = 0;
3201 // if (autoForView || an[i].isAutoCalculated()) {
3204 jaa = new jalview.datamodel.AlignmentAnnotation(
3205 annotation.getLabel(), annotation.getDescription(), anot,
3206 llim, hlim, annotation.getGraphType());
3208 jaa.graphGroup = annotation.getGraphGroup();
3209 jaa._linecolour = firstColour;
3210 if (annotation.getThresholdLine() != null)
3212 jaa.setThreshold(new jalview.datamodel.GraphLine(annotation
3213 .getThresholdLine().getValue(), annotation
3214 .getThresholdLine().getLabel(), new java.awt.Color(
3215 annotation.getThresholdLine().getColour())));
3218 if (autoForView || annotation.isAutoCalculated())
3220 // Hardwire the symbol display line to ensure that labels for
3221 // histograms are displayed
3227 jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
3228 an[i].getDescription(), anot);
3229 jaa._linecolour = firstColour;
3231 // register new annotation
3232 if (an[i].getId() != null)
3234 annotationIds.put(an[i].getId(), jaa);
3235 jaa.annotationId = an[i].getId();
3237 // recover sequence association
3238 String sequenceRef = an[i].getSequenceRef();
3239 if (sequenceRef != null)
3241 // from 2.9 sequenceRef is to sequence id (JAL-1781)
3242 SequenceI sequence = seqRefIds.get(sequenceRef);
3243 if (sequence == null)
3245 // in pre-2.9 projects sequence ref is to sequence name
3246 sequence = al.findName(sequenceRef);
3248 if (sequence != null)
3250 jaa.createSequenceMapping(sequence, 1, true);
3251 sequence.addAlignmentAnnotation(jaa);
3254 // and make a note of any group association
3255 if (an[i].getGroupRef() != null && an[i].getGroupRef().length() > 0)
3257 List<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
3258 .get(an[i].getGroupRef());
3261 aal = new ArrayList<jalview.datamodel.AlignmentAnnotation>();
3262 groupAnnotRefs.put(an[i].getGroupRef(), aal);
3267 if (an[i].hasScore())
3269 jaa.setScore(an[i].getScore());
3271 if (an[i].hasVisible())
3273 jaa.visible = an[i].getVisible();
3276 if (an[i].hasCentreColLabels())
3278 jaa.centreColLabels = an[i].getCentreColLabels();
3281 if (an[i].hasScaleColLabels())
3283 jaa.scaleColLabel = an[i].getScaleColLabels();
3285 if (an[i].hasAutoCalculated() && an[i].isAutoCalculated())
3287 // newer files have an 'autoCalculated' flag and store calculation
3288 // state in viewport properties
3289 jaa.autoCalculated = true; // means annotation will be marked for
3290 // update at end of load.
3292 if (an[i].hasGraphHeight())
3294 jaa.graphHeight = an[i].getGraphHeight();
3296 if (an[i].hasBelowAlignment())
3298 jaa.belowAlignment = an[i].isBelowAlignment();
3300 jaa.setCalcId(an[i].getCalcId());
3301 if (an[i].getPropertyCount() > 0)
3303 for (jalview.schemabinding.version2.Property prop : an[i]
3306 jaa.setProperty(prop.getName(), prop.getValue());
3309 if (jaa.autoCalculated)
3311 autoAlan.add(new JvAnnotRow(i, jaa));
3314 // if (!autoForView)
3316 // add autocalculated group annotation and any user created annotation
3318 al.addAnnotation(jaa);
3322 // ///////////////////////
3324 // Create alignment markup and styles for this view
3325 if (jms.getJGroupCount() > 0)
3327 JGroup[] groups = jms.getJGroup();
3328 boolean addAnnotSchemeGroup = false;
3329 for (int i = 0; i < groups.length; i++)
3331 JGroup jGroup = groups[i];
3332 ColourSchemeI cs = null;
3333 if (jGroup.getColour() != null)
3335 if (jGroup.getColour().startsWith("ucs"))
3337 cs = getUserColourScheme(jms, jGroup.getColour());
3339 else if (jGroup.getColour().equals("AnnotationColourGradient")
3340 && jGroup.getAnnotationColours() != null)
3342 addAnnotSchemeGroup = true;
3347 cs = ColourSchemeProperty.getColourScheme(al, jGroup.getColour());
3352 cs.setThreshold(jGroup.getPidThreshold(), true);
3356 Vector<SequenceI> seqs = new Vector<SequenceI>();
3358 for (int s = 0; s < jGroup.getSeqCount(); s++)
3360 String seqId = jGroup.getSeq(s) + "";
3361 SequenceI ts = seqRefIds.get(seqId);
3365 seqs.addElement(ts);
3369 if (seqs.size() < 1)
3374 SequenceGroup sg = new SequenceGroup(seqs, jGroup.getName(), cs,
3375 jGroup.getDisplayBoxes(), jGroup.getDisplayText(),
3376 jGroup.getColourText(), jGroup.getStart(), jGroup.getEnd());
3378 sg.setOutlineColour(new java.awt.Color(jGroup.getOutlineColour()));
3380 sg.textColour = new java.awt.Color(jGroup.getTextCol1());
3381 sg.textColour2 = new java.awt.Color(jGroup.getTextCol2());
3382 sg.setShowNonconserved(jGroup.hasShowUnconserved() ? jGroup
3383 .isShowUnconserved() : false);
3384 sg.thresholdTextColour = jGroup.getTextColThreshold();
3385 if (jGroup.hasShowConsensusHistogram())
3387 sg.setShowConsensusHistogram(jGroup.isShowConsensusHistogram());
3390 if (jGroup.hasShowSequenceLogo())
3392 sg.setshowSequenceLogo(jGroup.isShowSequenceLogo());
3394 if (jGroup.hasNormaliseSequenceLogo())
3396 sg.setNormaliseSequenceLogo(jGroup.isNormaliseSequenceLogo());
3398 if (jGroup.hasIgnoreGapsinConsensus())
3400 sg.setIgnoreGapsConsensus(jGroup.getIgnoreGapsinConsensus());
3402 if (jGroup.getConsThreshold() != 0)
3404 Conservation c = new Conservation("All", sg.getSequences(null),
3405 0, sg.getWidth() - 1);
3407 c.verdict(false, 25);
3408 sg.cs.setConservation(c);
3411 if (jGroup.getId() != null && groupAnnotRefs.size() > 0)
3413 // re-instate unique group/annotation row reference
3414 List<AlignmentAnnotation> jaal = groupAnnotRefs.get(jGroup
3418 for (AlignmentAnnotation jaa : jaal)
3421 if (jaa.autoCalculated)
3423 // match up and try to set group autocalc alignment row for this
3425 if (jaa.label.startsWith("Consensus for "))
3427 sg.setConsensus(jaa);
3429 // match up and try to set group autocalc alignment row for this
3431 if (jaa.label.startsWith("Conservation for "))
3433 sg.setConservationRow(jaa);
3440 if (addAnnotSchemeGroup)
3442 // reconstruct the annotation colourscheme
3443 sg.cs = constructAnnotationColour(jGroup.getAnnotationColours(),
3444 null, al, jms, false);
3450 // only dataset in this model, so just return.
3453 // ///////////////////////////////
3456 // If we just load in the same jar file again, the sequenceSetId
3457 // will be the same, and we end up with multiple references
3458 // to the same sequenceSet. We must modify this id on load
3459 // so that each load of the file gives a unique id
3460 String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
3461 String viewId = (view.getId() == null ? null : view.getId()
3463 AlignFrame af = null;
3464 AlignViewport av = null;
3465 // now check to see if we really need to create a new viewport.
3466 if (multipleView && viewportsAdded.size() == 0)
3468 // We recovered an alignment for which a viewport already exists.
3469 // TODO: fix up any settings necessary for overlaying stored state onto
3470 // state recovered from another document. (may not be necessary).
3471 // we may need a binding from a viewport in memory to one recovered from
3473 // and then recover its containing af to allow the settings to be applied.
3474 // TODO: fix for vamsas demo
3476 .println("About to recover a viewport for existing alignment: Sequence set ID is "
3478 Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
3479 if (seqsetobj != null)
3481 if (seqsetobj instanceof String)
3483 uniqueSeqSetId = (String) seqsetobj;
3485 .println("Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
3491 .println("Warning : Collision between sequence set ID string and existing jalview object mapping.");
3497 * indicate that annotation colours are applied across all groups (pre
3498 * Jalview 2.8.1 behaviour)
3500 boolean doGroupAnnColour = Jalview2XML.isVersionStringLaterThan(
3501 "2.8.1", object.getVersion());
3503 AlignmentPanel ap = null;
3504 boolean isnewview = true;
3507 // Check to see if this alignment already has a view id == viewId
3508 jalview.gui.AlignmentPanel views[] = Desktop
3509 .getAlignmentPanels(uniqueSeqSetId);
3510 if (views != null && views.length > 0)
3512 for (int v = 0; v < views.length; v++)
3514 if (views[v].av.getViewId().equalsIgnoreCase(viewId))
3516 // recover the existing alignpanel, alignframe, viewport
3517 af = views[v].alignFrame;
3520 // TODO: could even skip resetting view settings if we don't want to
3521 // change the local settings from other jalview processes
3530 af = loadViewport(file, jseqs, hiddenSeqs, al, jms, view,
3531 uniqueSeqSetId, viewId, autoAlan);
3537 * Load any trees, PDB structures and viewers
3539 * Not done if flag is false (when this method is used for New View)
3541 if (loadTreesAndStructures)
3543 loadTrees(jms, view, af, av, ap);
3544 loadPDBStructures(jprovider, jseqs, af, ap);
3545 loadRnaViewers(jprovider, jseqs, ap);
3547 // and finally return.
3552 * Instantiate and link any saved RNA (Varna) viewers. The state of the Varna
3553 * panel is restored from separate jar entries, two (gapped and trimmed) per
3554 * sequence and secondary structure.
3556 * Currently each viewer shows just one sequence and structure (gapped and
3557 * trimmed), however this method is designed to support multiple sequences or
3558 * structures in viewers if wanted in future.
3564 private void loadRnaViewers(jarInputStreamProvider jprovider,
3565 JSeq[] jseqs, AlignmentPanel ap)
3568 * scan the sequences for references to viewers; create each one the first
3569 * time it is referenced, add Rna models to existing viewers
3571 for (JSeq jseq : jseqs)
3573 for (int i = 0; i < jseq.getRnaViewerCount(); i++)
3575 RnaViewer viewer = jseq.getRnaViewer(i);
3576 AppVarna appVarna = findOrCreateVarnaViewer(viewer,
3577 uniqueSetSuffix, ap);
3579 for (int j = 0; j < viewer.getSecondaryStructureCount(); j++)
3581 SecondaryStructure ss = viewer.getSecondaryStructure(j);
3582 SequenceI seq = seqRefIds.get(jseq.getId());
3583 AlignmentAnnotation ann = this.annotationIds.get(ss
3584 .getAnnotationId());
3587 * add the structure to the Varna display (with session state copied
3588 * from the jar to a temporary file)
3590 boolean gapped = ss.isGapped();
3591 String rnaTitle = ss.getTitle();
3592 String sessionState = ss.getViewerState();
3593 String tempStateFile = copyJarEntry(jprovider, sessionState,
3595 RnaModel rna = new RnaModel(rnaTitle, ann, seq, null, gapped);
3596 appVarna.addModelSession(rna, rnaTitle, tempStateFile);
3598 appVarna.setInitialSelection(viewer.getSelectedRna());
3604 * Locate and return an already instantiated matching AppVarna, or create one
3608 * @param viewIdSuffix
3612 protected AppVarna findOrCreateVarnaViewer(RnaViewer viewer,
3613 String viewIdSuffix, AlignmentPanel ap)
3616 * on each load a suffix is appended to the saved viewId, to avoid conflicts
3617 * if load is repeated
3619 String postLoadId = viewer.getViewId() + viewIdSuffix;
3620 for (JInternalFrame frame : getAllFrames())
3622 if (frame instanceof AppVarna)
3624 AppVarna varna = (AppVarna) frame;
3625 if (postLoadId.equals(varna.getViewId()))
3627 // this viewer is already instantiated
3628 // could in future here add ap as another 'parent' of the
3629 // AppVarna window; currently just 1-to-many
3636 * viewer not found - make it
3638 RnaViewerModel model = new RnaViewerModel(postLoadId,
3639 viewer.getTitle(), viewer.getXpos(), viewer.getYpos(),
3640 viewer.getWidth(), viewer.getHeight(),
3641 viewer.getDividerLocation());
3642 AppVarna varna = new AppVarna(model, ap);
3648 * Load any saved trees
3656 protected void loadTrees(JalviewModelSequence jms, Viewport view,
3657 AlignFrame af, AlignViewport av, AlignmentPanel ap)
3659 // TODO result of automated refactoring - are all these parameters needed?
3662 for (int t = 0; t < jms.getTreeCount(); t++)
3665 Tree tree = jms.getTree(t);
3667 TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
3670 tp = af.ShowNewickTree(
3671 new jalview.io.NewickFile(tree.getNewick()),
3672 tree.getTitle(), tree.getWidth(), tree.getHeight(),
3673 tree.getXpos(), tree.getYpos());
3674 if (tree.getId() != null)
3676 // perhaps bind the tree id to something ?
3681 // update local tree attributes ?
3682 // TODO: should check if tp has been manipulated by user - if so its
3683 // settings shouldn't be modified
3684 tp.setTitle(tree.getTitle());
3685 tp.setBounds(new Rectangle(tree.getXpos(), tree.getYpos(), tree
3686 .getWidth(), tree.getHeight()));
3687 tp.av = av; // af.viewport; // TODO: verify 'associate with all
3690 tp.treeCanvas.av = av; // af.viewport;
3691 tp.treeCanvas.ap = ap; // af.alignPanel;
3696 warn("There was a problem recovering stored Newick tree: \n"
3697 + tree.getNewick());
3701 tp.fitToWindow.setState(tree.getFitToWindow());
3702 tp.fitToWindow_actionPerformed(null);
3704 if (tree.getFontName() != null)
3706 tp.setTreeFont(new java.awt.Font(tree.getFontName(), tree
3707 .getFontStyle(), tree.getFontSize()));
3711 tp.setTreeFont(new java.awt.Font(view.getFontName(), view
3712 .getFontStyle(), tree.getFontSize()));
3715 tp.showPlaceholders(tree.getMarkUnlinked());
3716 tp.showBootstrap(tree.getShowBootstrap());
3717 tp.showDistances(tree.getShowDistances());
3719 tp.treeCanvas.threshold = tree.getThreshold();
3721 if (tree.getCurrentTree())
3723 af.viewport.setCurrentTree(tp.getTree());
3727 } catch (Exception ex)
3729 ex.printStackTrace();
3734 * Load and link any saved structure viewers.
3741 protected void loadPDBStructures(jarInputStreamProvider jprovider,
3742 JSeq[] jseqs, AlignFrame af, AlignmentPanel ap)
3745 * Run through all PDB ids on the alignment, and collect mappings between
3746 * distinct view ids and all sequences referring to that view.
3748 Map<String, StructureViewerModel> structureViewers = new LinkedHashMap<String, StructureViewerModel>();
3750 for (int i = 0; i < jseqs.length; i++)
3752 if (jseqs[i].getPdbidsCount() > 0)
3754 Pdbids[] ids = jseqs[i].getPdbids();
3755 for (int p = 0; p < ids.length; p++)
3757 final int structureStateCount = ids[p].getStructureStateCount();
3758 for (int s = 0; s < structureStateCount; s++)
3760 // check to see if we haven't already created this structure view
3761 final StructureState structureState = ids[p]
3762 .getStructureState(s);
3763 String sviewid = (structureState.getViewId() == null) ? null
3764 : structureState.getViewId() + uniqueSetSuffix;
3765 jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
3766 // Originally : ids[p].getFile()
3767 // : TODO: verify external PDB file recovery still works in normal
3768 // jalview project load
3769 jpdb.setFile(loadPDBFile(jprovider, ids[p].getId(),
3771 jpdb.setId(ids[p].getId());
3773 int x = structureState.getXpos();
3774 int y = structureState.getYpos();
3775 int width = structureState.getWidth();
3776 int height = structureState.getHeight();
3778 // Probably don't need to do this anymore...
3779 // Desktop.desktop.getComponentAt(x, y);
3780 // TODO: NOW: check that this recovers the PDB file correctly.
3781 String pdbFile = loadPDBFile(jprovider, ids[p].getId(),
3783 jalview.datamodel.SequenceI seq = seqRefIds.get(jseqs[i]
3785 if (sviewid == null)
3787 sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width
3790 if (!structureViewers.containsKey(sviewid))
3792 structureViewers.put(sviewid,
3793 new StructureViewerModel(x, y, width, height, false,
3794 false, true, structureState.getViewId(),
3795 structureState.getType()));
3796 // Legacy pre-2.7 conversion JAL-823 :
3797 // do not assume any view has to be linked for colour by
3801 // assemble String[] { pdb files }, String[] { id for each
3802 // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
3803 // seqs_file 2}, boolean[] {
3804 // linkAlignPanel,superposeWithAlignpanel}} from hash
3805 StructureViewerModel jmoldat = structureViewers.get(sviewid);
3806 jmoldat.setAlignWithPanel(jmoldat.isAlignWithPanel()
3807 | (structureState.hasAlignwithAlignPanel() ? structureState
3808 .getAlignwithAlignPanel() : false));
3811 * Default colour by linked panel to false if not specified (e.g.
3812 * for pre-2.7 projects)
3814 boolean colourWithAlignPanel = jmoldat.isColourWithAlignPanel();
3815 colourWithAlignPanel |= (structureState
3816 .hasColourwithAlignPanel() ? structureState
3817 .getColourwithAlignPanel() : false);
3818 jmoldat.setColourWithAlignPanel(colourWithAlignPanel);
3821 * Default colour by viewer to true if not specified (e.g. for
3824 boolean colourByViewer = jmoldat.isColourByViewer();
3825 colourByViewer &= structureState.hasColourByJmol() ? structureState
3826 .getColourByJmol() : true;
3827 jmoldat.setColourByViewer(colourByViewer);
3829 if (jmoldat.getStateData().length() < structureState
3830 .getContent().length())
3833 jmoldat.setStateData(structureState.getContent());
3836 if (ids[p].getFile() != null)
3838 File mapkey = new File(ids[p].getFile());
3839 StructureData seqstrmaps = jmoldat.getFileData().get(mapkey);
3840 if (seqstrmaps == null)
3842 jmoldat.getFileData().put(
3844 seqstrmaps = jmoldat.new StructureData(pdbFile,
3847 if (!seqstrmaps.getSeqList().contains(seq))
3849 seqstrmaps.getSeqList().add(seq);
3855 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");
3862 // Instantiate the associated structure views
3863 for (Entry<String, StructureViewerModel> entry : structureViewers
3868 createOrLinkStructureViewer(entry, af, ap, jprovider);
3869 } catch (Exception e)
3871 System.err.println("Error loading structure viewer: "
3873 // failed - try the next one
3885 protected void createOrLinkStructureViewer(
3886 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
3887 AlignmentPanel ap, jarInputStreamProvider jprovider)
3889 final StructureViewerModel stateData = viewerData.getValue();
3892 * Search for any viewer windows already open from other alignment views
3893 * that exactly match the stored structure state
3895 StructureViewerBase comp = findMatchingViewer(viewerData);
3899 linkStructureViewer(ap, comp, stateData);
3904 * From 2.9: stateData.type contains JMOL or CHIMERA, data is in jar entry
3905 * "viewer_"+stateData.viewId
3907 if (ViewerType.CHIMERA.toString().equals(stateData.getType()))
3909 createChimeraViewer(viewerData, af, jprovider);
3914 * else Jmol (if pre-2.9, stateData contains JMOL state string)
3916 createJmolViewer(viewerData, af, jprovider);
3921 * Create a new Chimera viewer.
3927 protected void createChimeraViewer(
3928 Entry<String, StructureViewerModel> viewerData, AlignFrame af,
3929 jarInputStreamProvider jprovider)
3931 StructureViewerModel data = viewerData.getValue();
3932 String chimeraSessionFile = data.getStateData();
3935 * Copy Chimera session from jar entry "viewer_"+viewId to a temporary file
3937 * NB this is the 'saved' viewId as in the project file XML, _not_ the
3938 * 'uniquified' sviewid used to reconstruct the viewer here
3940 String viewerJarEntryName = getViewerJarEntryName(data.getViewId());
3941 chimeraSessionFile = copyJarEntry(jprovider, viewerJarEntryName,
3944 Set<Entry<File, StructureData>> fileData = data.getFileData()
3946 List<PDBEntry> pdbs = new ArrayList<PDBEntry>();
3947 List<SequenceI[]> allseqs = new ArrayList<SequenceI[]>();
3948 for (Entry<File, StructureData> pdb : fileData)
3950 String filePath = pdb.getValue().getFilePath();
3951 String pdbId = pdb.getValue().getPdbId();
3952 // pdbs.add(new PDBEntry(filePath, pdbId));
3953 pdbs.add(new PDBEntry(pdbId, null, PDBEntry.Type.PDB, filePath));
3954 final List<SequenceI> seqList = pdb.getValue().getSeqList();
3955 SequenceI[] seqs = seqList.toArray(new SequenceI[seqList.size()]);
3959 boolean colourByChimera = data.isColourByViewer();
3960 boolean colourBySequence = data.isColourWithAlignPanel();
3962 // TODO use StructureViewer as a factory here, see JAL-1761
3963 final PDBEntry[] pdbArray = pdbs.toArray(new PDBEntry[pdbs.size()]);
3964 final SequenceI[][] seqsArray = allseqs.toArray(new SequenceI[allseqs
3966 String newViewId = viewerData.getKey();
3968 ChimeraViewFrame cvf = new ChimeraViewFrame(chimeraSessionFile,
3969 af.alignPanel, pdbArray, seqsArray, colourByChimera,
3970 colourBySequence, newViewId);
3971 cvf.setSize(data.getWidth(), data.getHeight());
3972 cvf.setLocation(data.getX(), data.getY());
3976 * Create a new Jmol window. First parse the Jmol state to translate filenames
3977 * loaded into the view, and record the order in which files are shown in the
3978 * Jmol view, so we can add the sequence mappings in same order.
3984 protected void createJmolViewer(
3985 final Entry<String, StructureViewerModel> viewerData,
3986 AlignFrame af, jarInputStreamProvider jprovider)
3988 final StructureViewerModel svattrib = viewerData.getValue();
3989 String state = svattrib.getStateData();
3992 * Pre-2.9: state element value is the Jmol state string
3994 * 2.9+: @type is "JMOL", state data is in a Jar file member named "viewer_"
3997 if (ViewerType.JMOL.toString().equals(svattrib.getType()))
3999 state = readJarEntry(jprovider,
4000 getViewerJarEntryName(svattrib.getViewId()));
4003 List<String> pdbfilenames = new ArrayList<String>();
4004 List<SequenceI[]> seqmaps = new ArrayList<SequenceI[]>();
4005 List<String> pdbids = new ArrayList<String>();
4006 StringBuilder newFileLoc = new StringBuilder(64);
4007 int cp = 0, ncp, ecp;
4008 Map<File, StructureData> oldFiles = svattrib.getFileData();
4009 while ((ncp = state.indexOf("load ", cp)) > -1)
4013 // look for next filename in load statement
4014 newFileLoc.append(state.substring(cp,
4015 ncp = (state.indexOf("\"", ncp + 1) + 1)));
4016 String oldfilenam = state.substring(ncp,
4017 ecp = state.indexOf("\"", ncp));
4018 // recover the new mapping data for this old filename
4019 // have to normalize filename - since Jmol and jalview do
4021 // translation differently.
4022 StructureData filedat = oldFiles.get(new File(oldfilenam));
4023 if (filedat == null)
4025 String reformatedOldFilename = oldfilenam.replaceAll("/", "\\\\");
4026 filedat = oldFiles.get(new File(reformatedOldFilename));
4028 newFileLoc.append(Platform.escapeString(filedat.getFilePath()));
4029 pdbfilenames.add(filedat.getFilePath());
4030 pdbids.add(filedat.getPdbId());
4031 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4032 newFileLoc.append("\"");
4033 cp = ecp + 1; // advance beyond last \" and set cursor so we can
4034 // look for next file statement.
4035 } while ((ncp = state.indexOf("/*file*/", cp)) > -1);
4039 // just append rest of state
4040 newFileLoc.append(state.substring(cp));
4044 System.err.print("Ignoring incomplete Jmol state for PDB ids: ");
4045 newFileLoc = new StringBuilder(state);
4046 newFileLoc.append("; load append ");
4047 for (File id : oldFiles.keySet())
4049 // add this and any other pdb files that should be present in
4051 StructureData filedat = oldFiles.get(id);
4052 newFileLoc.append(filedat.getFilePath());
4053 pdbfilenames.add(filedat.getFilePath());
4054 pdbids.add(filedat.getPdbId());
4055 seqmaps.add(filedat.getSeqList().toArray(new SequenceI[0]));
4056 newFileLoc.append(" \"");
4057 newFileLoc.append(filedat.getFilePath());
4058 newFileLoc.append("\"");
4061 newFileLoc.append(";");
4064 if (newFileLoc.length() == 0)
4068 int histbug = newFileLoc.indexOf("history = ");
4072 * change "history = [true|false];" to "history = [1|0];"
4075 int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";", histbug);
4076 String val = (diff == -1) ? null : newFileLoc
4077 .substring(histbug, diff);
4078 if (val != null && val.length() >= 4)
4080 if (val.contains("e")) // eh? what can it be?
4082 if (val.trim().equals("true"))
4090 newFileLoc.replace(histbug, diff, val);
4095 final String[] pdbf = pdbfilenames.toArray(new String[pdbfilenames
4097 final String[] id = pdbids.toArray(new String[pdbids.size()]);
4098 final SequenceI[][] sq = seqmaps
4099 .toArray(new SequenceI[seqmaps.size()][]);
4100 final String fileloc = newFileLoc.toString();
4101 final String sviewid = viewerData.getKey();
4102 final AlignFrame alf = af;
4103 final Rectangle rect = new Rectangle(svattrib.getX(), svattrib.getY(),
4104 svattrib.getWidth(), svattrib.getHeight());
4107 javax.swing.SwingUtilities.invokeAndWait(new Runnable()
4112 JalviewStructureDisplayI sview = null;
4115 sview = new StructureViewer(alf.alignPanel
4116 .getStructureSelectionManager()).createView(
4117 StructureViewer.ViewerType.JMOL, pdbf, id, sq,
4118 alf.alignPanel, svattrib, fileloc, rect, sviewid);
4119 addNewStructureViewer(sview);
4120 } catch (OutOfMemoryError ex)
4122 new OOMWarning("restoring structure view for PDB id " + id,
4123 (OutOfMemoryError) ex.getCause());
4124 if (sview != null && sview.isVisible())
4126 sview.closeViewer(false);
4127 sview.setVisible(false);
4133 } catch (InvocationTargetException ex)
4135 warn("Unexpected error when opening Jmol view.", ex);
4137 } catch (InterruptedException e)
4139 // e.printStackTrace();
4145 * Generates a name for the entry in the project jar file to hold state
4146 * information for a structure viewer
4151 protected String getViewerJarEntryName(String viewId)
4153 return VIEWER_PREFIX + viewId;
4157 * Returns any open frame that matches given structure viewer data. The match
4158 * is based on the unique viewId, or (for older project versions) the frame's
4164 protected StructureViewerBase findMatchingViewer(
4165 Entry<String, StructureViewerModel> viewerData)
4167 final String sviewid = viewerData.getKey();
4168 final StructureViewerModel svattrib = viewerData.getValue();
4169 StructureViewerBase comp = null;
4170 JInternalFrame[] frames = getAllFrames();
4171 for (JInternalFrame frame : frames)
4173 if (frame instanceof StructureViewerBase)
4176 * Post jalview 2.4 schema includes structure view id
4179 && ((StructureViewerBase) frame).getViewId()
4182 comp = (StructureViewerBase) frame;
4183 break; // break added in 2.9
4186 * Otherwise test for matching position and size of viewer frame
4188 else if (frame.getX() == svattrib.getX()
4189 && frame.getY() == svattrib.getY()
4190 && frame.getHeight() == svattrib.getHeight()
4191 && frame.getWidth() == svattrib.getWidth())
4193 comp = (StructureViewerBase) frame;
4194 // no break in faint hope of an exact match on viewId
4202 * Link an AlignmentPanel to an existing structure viewer.
4207 * @param useinViewerSuperpos
4208 * @param usetoColourbyseq
4209 * @param viewerColouring
4211 protected void linkStructureViewer(AlignmentPanel ap,
4212 StructureViewerBase viewer, StructureViewerModel stateData)
4214 // NOTE: if the jalview project is part of a shared session then
4215 // view synchronization should/could be done here.
4217 final boolean useinViewerSuperpos = stateData.isAlignWithPanel();
4218 final boolean usetoColourbyseq = stateData.isColourWithAlignPanel();
4219 final boolean viewerColouring = stateData.isColourByViewer();
4220 Map<File, StructureData> oldFiles = stateData.getFileData();
4223 * Add mapping for sequences in this view to an already open viewer
4225 final AAStructureBindingModel binding = viewer.getBinding();
4226 for (File id : oldFiles.keySet())
4228 // add this and any other pdb files that should be present in the
4230 StructureData filedat = oldFiles.get(id);
4231 String pdbFile = filedat.getFilePath();
4232 SequenceI[] seq = filedat.getSeqList().toArray(new SequenceI[0]);
4233 binding.getSsm().setMapping(seq, null, pdbFile, DataSourceType.FILE);
4234 binding.addSequenceForStructFile(pdbFile, seq);
4236 // and add the AlignmentPanel's reference to the view panel
4237 viewer.addAlignmentPanel(ap);
4238 if (useinViewerSuperpos)
4240 viewer.useAlignmentPanelForSuperposition(ap);
4244 viewer.excludeAlignmentPanelForSuperposition(ap);
4246 if (usetoColourbyseq)
4248 viewer.useAlignmentPanelForColourbyseq(ap, !viewerColouring);
4252 viewer.excludeAlignmentPanelForColourbyseq(ap);
4257 * Get all frames within the Desktop.
4261 protected JInternalFrame[] getAllFrames()
4263 JInternalFrame[] frames = null;
4264 // TODO is this necessary - is it safe - risk of hanging?
4269 frames = Desktop.desktop.getAllFrames();
4270 } catch (ArrayIndexOutOfBoundsException e)
4272 // occasional No such child exceptions are thrown here...
4276 } catch (InterruptedException f)
4280 } while (frames == null);
4285 * Answers true if 'version' is equal to or later than 'supported', where each
4286 * is formatted as major/minor versions like "2.8.3" or "2.3.4b1" for bugfix
4287 * changes. Development and test values for 'version' are leniently treated
4291 * - minimum version we are comparing against
4293 * - version of data being processsed
4296 public static boolean isVersionStringLaterThan(String supported,
4299 if (supported == null || version == null
4300 || version.equalsIgnoreCase("DEVELOPMENT BUILD")
4301 || version.equalsIgnoreCase("Test")
4302 || version.equalsIgnoreCase("AUTOMATED BUILD"))
4304 System.err.println("Assuming project file with "
4305 + (version == null ? "null" : version)
4306 + " is compatible with Jalview version " + supported);
4311 return StringUtils.compareVersions(version, supported, "b") >= 0;
4315 Vector<JalviewStructureDisplayI> newStructureViewers = null;
4317 protected void addNewStructureViewer(JalviewStructureDisplayI sview)
4319 if (newStructureViewers != null)
4321 sview.getBinding().setFinishedLoadingFromArchive(false);
4322 newStructureViewers.add(sview);
4326 protected void setLoadingFinishedForNewStructureViewers()
4328 if (newStructureViewers != null)
4330 for (JalviewStructureDisplayI sview : newStructureViewers)
4332 sview.getBinding().setFinishedLoadingFromArchive(true);
4334 newStructureViewers.clear();
4335 newStructureViewers = null;
4339 AlignFrame loadViewport(String file, JSeq[] JSEQ,
4340 List<SequenceI> hiddenSeqs, AlignmentI al,
4341 JalviewModelSequence jms, Viewport view, String uniqueSeqSetId,
4342 String viewId, List<JvAnnotRow> autoAlan)
4344 AlignFrame af = null;
4345 af = new AlignFrame(al, view.getWidth(), view.getHeight(),
4346 uniqueSeqSetId, viewId);
4348 af.setFileName(file, FileFormat.Jalview);
4350 for (int i = 0; i < JSEQ.length; i++)
4352 af.viewport.setSequenceColour(af.viewport.getAlignment()
4353 .getSequenceAt(i), new java.awt.Color(JSEQ[i].getColour()));
4358 af.getViewport().setColourByReferenceSeq(true);
4359 af.getViewport().setDisplayReferenceSeq(true);
4362 af.viewport.setGatherViewsHere(view.getGatheredViews());
4364 if (view.getSequenceSetId() != null)
4366 AlignmentViewport av = viewportsAdded.get(uniqueSeqSetId);
4368 af.viewport.setSequenceSetId(uniqueSeqSetId);
4371 // propagate shared settings to this new view
4372 af.viewport.setHistoryList(av.getHistoryList());
4373 af.viewport.setRedoList(av.getRedoList());
4377 viewportsAdded.put(uniqueSeqSetId, af.viewport);
4379 // TODO: check if this method can be called repeatedly without
4380 // side-effects if alignpanel already registered.
4381 PaintRefresher.Register(af.alignPanel, uniqueSeqSetId);
4383 // apply Hidden regions to view.
4384 if (hiddenSeqs != null)
4386 for (int s = 0; s < JSEQ.length; s++)
4388 SequenceGroup hidden = new SequenceGroup();
4389 boolean isRepresentative = false;
4390 for (int r = 0; r < JSEQ[s].getHiddenSequencesCount(); r++)
4392 isRepresentative = true;
4393 SequenceI sequenceToHide = al.getSequenceAt(JSEQ[s]
4394 .getHiddenSequences(r));
4395 hidden.addSequence(sequenceToHide, false);
4396 // remove from hiddenSeqs list so we don't try to hide it twice
4397 hiddenSeqs.remove(sequenceToHide);
4399 if (isRepresentative)
4401 SequenceI representativeSequence = al.getSequenceAt(s);
4402 hidden.addSequence(representativeSequence, false);
4403 af.viewport.hideRepSequences(representativeSequence, hidden);
4407 SequenceI[] hseqs = hiddenSeqs.toArray(new SequenceI[hiddenSeqs
4409 af.viewport.hideSequence(hseqs);
4412 // recover view properties and display parameters
4413 if (view.getViewName() != null)
4415 af.viewport.viewName = view.getViewName();
4416 af.setInitialTabVisible();
4418 af.setBounds(view.getXpos(), view.getYpos(), view.getWidth(),
4421 af.viewport.setShowAnnotation(view.getShowAnnotation());
4422 af.viewport.setAbovePIDThreshold(view.getPidSelected());
4424 af.viewport.setColourText(view.getShowColourText());
4426 af.viewport.setConservationSelected(view.getConservationSelected());
4427 af.viewport.setShowJVSuffix(view.getShowFullId());
4428 af.viewport.setRightAlignIds(view.getRightAlignIds());
4429 af.viewport.setFont(
4430 new java.awt.Font(view.getFontName(), view.getFontStyle(), view
4431 .getFontSize()), true);
4432 ViewStyleI vs = af.viewport.getViewStyle();
4433 vs.setScaleProteinAsCdna(view.isScaleProteinAsCdna());
4434 af.viewport.setViewStyle(vs);
4435 // TODO: allow custom charWidth/Heights to be restored by updating them
4436 // after setting font - which means set above to false
4437 af.viewport.setRenderGaps(view.getRenderGaps());
4438 af.viewport.setWrapAlignment(view.getWrapAlignment());
4439 af.viewport.setShowAnnotation(view.getShowAnnotation());
4441 af.viewport.setShowBoxes(view.getShowBoxes());
4443 af.viewport.setShowText(view.getShowText());
4445 af.viewport.setTextColour(new java.awt.Color(view.getTextCol1()));
4446 af.viewport.setTextColour2(new java.awt.Color(view.getTextCol2()));
4447 af.viewport.setThresholdTextColour(view.getTextColThreshold());
4448 af.viewport.setShowUnconserved(view.hasShowUnconserved() ? view
4449 .isShowUnconserved() : false);
4450 af.viewport.setStartRes(view.getStartRes());
4451 af.viewport.setStartSeq(view.getStartSeq());
4452 af.alignPanel.updateLayout();
4453 ColourSchemeI cs = null;
4454 // apply colourschemes
4455 if (view.getBgColour() != null)
4457 if (view.getBgColour().startsWith("ucs"))
4459 cs = getUserColourScheme(jms, view.getBgColour());
4461 else if (view.getBgColour().startsWith("Annotation"))
4463 AnnotationColours viewAnnColour = view.getAnnotationColours();
4464 cs = constructAnnotationColour(viewAnnColour, af, al, jms, true);
4471 cs = ColourSchemeProperty.getColourScheme(al, view.getBgColour());
4476 cs.setThreshold(view.getPidThreshold(), true);
4477 cs.setConsensus(af.viewport.getSequenceConsensusHash());
4481 af.viewport.setGlobalColourScheme(cs);
4482 af.viewport.setColourAppliesToAllGroups(false);
4484 if (view.getConservationSelected() && cs != null)
4486 cs.setConservationInc(view.getConsThreshold());
4489 af.changeColour(cs);
4491 af.viewport.setColourAppliesToAllGroups(true);
4493 af.viewport.setShowSequenceFeatures(view.getShowSequenceFeatures());
4495 if (view.hasCentreColumnLabels())
4497 af.viewport.setCentreColumnLabels(view.getCentreColumnLabels());
4499 if (view.hasIgnoreGapsinConsensus())
4501 af.viewport.setIgnoreGapsConsensus(view.getIgnoreGapsinConsensus(),
4504 if (view.hasFollowHighlight())
4506 af.viewport.setFollowHighlight(view.getFollowHighlight());
4508 if (view.hasFollowSelection())
4510 af.viewport.followSelection = view.getFollowSelection();
4512 if (view.hasShowConsensusHistogram())
4514 af.viewport.setShowConsensusHistogram(view
4515 .getShowConsensusHistogram());
4519 af.viewport.setShowConsensusHistogram(true);
4521 if (view.hasShowSequenceLogo())
4523 af.viewport.setShowSequenceLogo(view.getShowSequenceLogo());
4527 af.viewport.setShowSequenceLogo(false);
4529 if (view.hasNormaliseSequenceLogo())
4531 af.viewport.setNormaliseSequenceLogo(view.getNormaliseSequenceLogo());
4533 if (view.hasShowDbRefTooltip())
4535 af.viewport.setShowDBRefs(view.getShowDbRefTooltip());
4537 if (view.hasShowNPfeatureTooltip())
4539 af.viewport.setShowNPFeats(view.hasShowNPfeatureTooltip());
4541 if (view.hasShowGroupConsensus())
4543 af.viewport.setShowGroupConsensus(view.getShowGroupConsensus());
4547 af.viewport.setShowGroupConsensus(false);
4549 if (view.hasShowGroupConservation())
4551 af.viewport.setShowGroupConservation(view.getShowGroupConservation());
4555 af.viewport.setShowGroupConservation(false);
4558 // recover featre settings
4559 if (jms.getFeatureSettings() != null)
4561 FeaturesDisplayed fdi;
4562 af.viewport.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
4563 String[] renderOrder = new String[jms.getFeatureSettings()
4564 .getSettingCount()];
4565 Map<String, FeatureColourI> featureColours = new Hashtable<String, FeatureColourI>();
4566 Map<String, Float> featureOrder = new Hashtable<String, Float>();
4568 for (int fs = 0; fs < jms.getFeatureSettings().getSettingCount(); fs++)
4570 Setting setting = jms.getFeatureSettings().getSetting(fs);
4571 if (setting.hasMincolour())
4573 FeatureColourI gc = setting.hasMin() ? new FeatureColour(
4574 new Color(setting.getMincolour()), new Color(
4575 setting.getColour()), setting.getMin(),
4576 setting.getMax()) : new FeatureColour(new Color(
4577 setting.getMincolour()), new Color(setting.getColour()),
4579 if (setting.hasThreshold())
4581 gc.setThreshold(setting.getThreshold());
4582 int threshstate = setting.getThreshstate();
4583 // -1 = None, 0 = Below, 1 = Above threshold
4584 if (threshstate == 0)
4586 gc.setBelowThreshold(true);
4588 else if (threshstate == 1)
4590 gc.setAboveThreshold(true);
4593 gc.setAutoScaled(true); // default
4594 if (setting.hasAutoScale())
4596 gc.setAutoScaled(setting.getAutoScale());
4598 if (setting.hasColourByLabel())
4600 gc.setColourByLabel(setting.getColourByLabel());
4602 // and put in the feature colour table.
4603 featureColours.put(setting.getType(), gc);
4607 featureColours.put(setting.getType(), new FeatureColour(
4608 new Color(setting.getColour())));
4610 renderOrder[fs] = setting.getType();
4611 if (setting.hasOrder())
4613 featureOrder.put(setting.getType(), setting.getOrder());
4617 featureOrder.put(setting.getType(), new Float(fs
4618 / jms.getFeatureSettings().getSettingCount()));
4620 if (setting.getDisplay())
4622 fdi.setVisible(setting.getType());
4625 Map<String, Boolean> fgtable = new Hashtable<String, Boolean>();
4626 for (int gs = 0; gs < jms.getFeatureSettings().getGroupCount(); gs++)
4628 Group grp = jms.getFeatureSettings().getGroup(gs);
4629 fgtable.put(grp.getName(), new Boolean(grp.getDisplay()));
4631 // FeatureRendererSettings frs = new FeatureRendererSettings(renderOrder,
4632 // fgtable, featureColours, jms.getFeatureSettings().hasTransparency() ?
4633 // jms.getFeatureSettings().getTransparency() : 0.0, featureOrder);
4634 FeatureRendererSettings frs = new FeatureRendererSettings(
4635 renderOrder, fgtable, featureColours, 1.0f, featureOrder);
4636 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
4637 .transferSettings(frs);
4641 if (view.getHiddenColumnsCount() > 0)
4643 for (int c = 0; c < view.getHiddenColumnsCount(); c++)
4645 af.viewport.hideColumns(view.getHiddenColumns(c).getStart(), view
4646 .getHiddenColumns(c).getEnd() // +1
4650 if (view.getCalcIdParam() != null)
4652 for (CalcIdParam calcIdParam : view.getCalcIdParam())
4654 if (calcIdParam != null)
4656 if (recoverCalcIdParam(calcIdParam, af.viewport))
4661 warn("Couldn't recover parameters for "
4662 + calcIdParam.getCalcId());
4667 af.setMenusFromViewport(af.viewport);
4668 af.setTitle(view.getTitle());
4669 // TODO: we don't need to do this if the viewport is aready visible.
4671 * Add the AlignFrame to the desktop (it may be 'gathered' later), unless it
4672 * has a 'cdna/protein complement' view, in which case save it in order to
4673 * populate a SplitFrame once all views have been read in.
4675 String complementaryViewId = view.getComplementId();
4676 if (complementaryViewId == null)
4678 Desktop.addInternalFrame(af, view.getTitle(), view.getWidth(),
4680 // recompute any autoannotation
4681 af.alignPanel.updateAnnotation(false, true);
4682 reorderAutoannotation(af, al, autoAlan);
4683 af.alignPanel.alignmentChanged();
4687 splitFrameCandidates.put(view, af);
4692 private ColourSchemeI constructAnnotationColour(
4693 AnnotationColours viewAnnColour, AlignFrame af, AlignmentI al,
4694 JalviewModelSequence jms, boolean checkGroupAnnColour)
4696 boolean propagateAnnColour = false;
4697 ColourSchemeI cs = null;
4698 AlignmentI annAlignment = af != null ? af.viewport.getAlignment() : al;
4699 if (checkGroupAnnColour && al.getGroups() != null
4700 && al.getGroups().size() > 0)
4702 // pre 2.8.1 behaviour
4703 // check to see if we should transfer annotation colours
4704 propagateAnnColour = true;
4705 for (jalview.datamodel.SequenceGroup sg : al.getGroups())
4707 if (sg.cs instanceof AnnotationColourGradient)
4709 propagateAnnColour = false;
4713 // int find annotation
4714 if (annAlignment.getAlignmentAnnotation() != null)
4716 for (int i = 0; i < annAlignment.getAlignmentAnnotation().length; i++)
4718 if (annAlignment.getAlignmentAnnotation()[i].label
4719 .equals(viewAnnColour.getAnnotation()))
4721 if (annAlignment.getAlignmentAnnotation()[i].getThreshold() == null)
4723 annAlignment.getAlignmentAnnotation()[i]
4724 .setThreshold(new jalview.datamodel.GraphLine(
4725 viewAnnColour.getThreshold(), "Threshold",
4726 java.awt.Color.black)
4731 if (viewAnnColour.getColourScheme().equals(
4732 ResidueColourScheme.NONE))
4734 cs = new AnnotationColourGradient(
4735 annAlignment.getAlignmentAnnotation()[i],
4736 new java.awt.Color(viewAnnColour.getMinColour()),
4737 new java.awt.Color(viewAnnColour.getMaxColour()),
4738 viewAnnColour.getAboveThreshold());
4740 else if (viewAnnColour.getColourScheme().startsWith("ucs"))
4742 cs = new AnnotationColourGradient(
4743 annAlignment.getAlignmentAnnotation()[i],
4744 getUserColourScheme(jms,
4745 viewAnnColour.getColourScheme()),
4746 viewAnnColour.getAboveThreshold());
4750 cs = new AnnotationColourGradient(
4751 annAlignment.getAlignmentAnnotation()[i],
4752 ColourSchemeProperty.getColourScheme(al,
4753 viewAnnColour.getColourScheme()),
4754 viewAnnColour.getAboveThreshold());
4756 if (viewAnnColour.hasPerSequence())
4758 ((AnnotationColourGradient) cs).setSeqAssociated(viewAnnColour
4761 if (viewAnnColour.hasPredefinedColours())
4763 ((AnnotationColourGradient) cs)
4764 .setPredefinedColours(viewAnnColour
4765 .isPredefinedColours());
4767 if (propagateAnnColour && al.getGroups() != null)
4769 // Also use these settings for all the groups
4770 for (int g = 0; g < al.getGroups().size(); g++)
4772 jalview.datamodel.SequenceGroup sg = al.getGroups().get(g);
4780 * if (viewAnnColour.getColourScheme().equals(ResidueColourScheme.NONE)) { sg.cs =
4781 * new AnnotationColourGradient(
4782 * annAlignment.getAlignmentAnnotation()[i], new
4783 * java.awt.Color(viewAnnColour. getMinColour()), new
4784 * java.awt.Color(viewAnnColour. getMaxColour()),
4785 * viewAnnColour.getAboveThreshold()); } else
4788 sg.cs = new AnnotationColourGradient(
4789 annAlignment.getAlignmentAnnotation()[i], sg.cs,
4790 viewAnnColour.getAboveThreshold());
4791 if (cs instanceof AnnotationColourGradient)
4793 if (viewAnnColour.hasPerSequence())
4795 ((AnnotationColourGradient) cs)
4796 .setSeqAssociated(viewAnnColour.isPerSequence());
4798 if (viewAnnColour.hasPredefinedColours())
4800 ((AnnotationColourGradient) cs)
4801 .setPredefinedColours(viewAnnColour
4802 .isPredefinedColours());
4818 private void reorderAutoannotation(AlignFrame af, AlignmentI al,
4819 List<JvAnnotRow> autoAlan)
4821 // copy over visualization settings for autocalculated annotation in the
4823 if (al.getAlignmentAnnotation() != null)
4826 * Kludge for magic autoannotation names (see JAL-811)
4828 String[] magicNames = new String[] { "Consensus", "Quality",
4830 JvAnnotRow nullAnnot = new JvAnnotRow(-1, null);
4831 Hashtable<String, JvAnnotRow> visan = new Hashtable<String, JvAnnotRow>();
4832 for (String nm : magicNames)
4834 visan.put(nm, nullAnnot);
4836 for (JvAnnotRow auan : autoAlan)
4838 visan.put(auan.template.label
4839 + (auan.template.getCalcId() == null ? "" : "\t"
4840 + auan.template.getCalcId()), auan);
4842 int hSize = al.getAlignmentAnnotation().length;
4843 List<JvAnnotRow> reorder = new ArrayList<JvAnnotRow>();
4844 // work through any autoCalculated annotation already on the view
4845 // removing it if it should be placed in a different location on the
4846 // annotation panel.
4847 List<String> remains = new ArrayList<String>(visan.keySet());
4848 for (int h = 0; h < hSize; h++)
4850 jalview.datamodel.AlignmentAnnotation jalan = al
4851 .getAlignmentAnnotation()[h];
4852 if (jalan.autoCalculated)
4855 JvAnnotRow valan = visan.get(k = jalan.label);
4856 if (jalan.getCalcId() != null)
4858 valan = visan.get(k = jalan.label + "\t" + jalan.getCalcId());
4863 // delete the auto calculated row from the alignment
4864 al.deleteAnnotation(jalan, false);
4868 if (valan != nullAnnot)
4870 if (jalan != valan.template)
4872 // newly created autoannotation row instance
4873 // so keep a reference to the visible annotation row
4874 // and copy over all relevant attributes
4875 if (valan.template.graphHeight >= 0)
4878 jalan.graphHeight = valan.template.graphHeight;
4880 jalan.visible = valan.template.visible;
4882 reorder.add(new JvAnnotRow(valan.order, jalan));
4887 // Add any (possibly stale) autocalculated rows that were not appended to
4888 // the view during construction
4889 for (String other : remains)
4891 JvAnnotRow othera = visan.get(other);
4892 if (othera != nullAnnot && othera.template.getCalcId() != null
4893 && othera.template.getCalcId().length() > 0)
4895 reorder.add(othera);
4898 // now put the automatic annotation in its correct place
4899 int s = 0, srt[] = new int[reorder.size()];
4900 JvAnnotRow[] rws = new JvAnnotRow[reorder.size()];
4901 for (JvAnnotRow jvar : reorder)
4904 srt[s++] = jvar.order;
4907 jalview.util.QuickSort.sort(srt, rws);
4908 // and re-insert the annotation at its correct position
4909 for (JvAnnotRow jvar : rws)
4911 al.addAnnotation(jvar.template, jvar.order);
4913 af.alignPanel.adjustAnnotationHeight();
4917 Hashtable skipList = null;
4920 * TODO remove this method
4923 * @return AlignFrame bound to sequenceSetId from view, if one exists. private
4924 * AlignFrame getSkippedFrame(Viewport view) { if (skipList==null) {
4925 * throw new Error("Implementation Error. No skipList defined for this
4926 * Jalview2XML instance."); } return (AlignFrame)
4927 * skipList.get(view.getSequenceSetId()); }
4931 * Check if the Jalview view contained in object should be skipped or not.
4934 * @return true if view's sequenceSetId is a key in skipList
4936 private boolean skipViewport(JalviewModel object)
4938 if (skipList == null)
4943 if (skipList.containsKey(id = object.getJalviewModelSequence()
4944 .getViewport()[0].getSequenceSetId()))
4946 if (Cache.log != null && Cache.log.isDebugEnabled())
4948 Cache.log.debug("Skipping seuqence set id " + id);
4955 public void addToSkipList(AlignFrame af)
4957 if (skipList == null)
4959 skipList = new Hashtable();
4961 skipList.put(af.getViewport().getSequenceSetId(), af);
4964 public void clearSkipList()
4966 if (skipList != null)
4973 private void recoverDatasetFor(SequenceSet vamsasSet, AlignmentI al,
4974 boolean ignoreUnrefed)
4976 jalview.datamodel.AlignmentI ds = getDatasetFor(vamsasSet
4978 Vector dseqs = null;
4981 // create a list of new dataset sequences
4982 dseqs = new Vector();
4984 for (int i = 0, iSize = vamsasSet.getSequenceCount(); i < iSize; i++)
4986 Sequence vamsasSeq = vamsasSet.getSequence(i);
4987 ensureJalviewDatasetSequence(vamsasSeq, ds, dseqs, ignoreUnrefed, i);
4989 // create a new dataset
4992 SequenceI[] dsseqs = new SequenceI[dseqs.size()];
4993 dseqs.copyInto(dsseqs);
4994 ds = new jalview.datamodel.Alignment(dsseqs);
4995 debug("Created new dataset " + vamsasSet.getDatasetId()
4996 + " for alignment " + System.identityHashCode(al));
4997 addDatasetRef(vamsasSet.getDatasetId(), ds);
4999 // set the dataset for the newly imported alignment.
5000 if (al.getDataset() == null && !ignoreUnrefed)
5009 * sequence definition to create/merge dataset sequence for
5013 * vector to add new dataset sequence to
5014 * @param ignoreUnrefed
5015 * - when true, don't create new sequences from vamsasSeq if it's id
5016 * doesn't already have an asssociated Jalview sequence.
5018 * - used to reorder the sequence in the alignment according to the
5019 * vamsasSeq array ordering, to preserve ordering of dataset
5021 private void ensureJalviewDatasetSequence(Sequence vamsasSeq,
5022 AlignmentI ds, Vector dseqs, boolean ignoreUnrefed, int vseqpos)
5024 // JBP TODO: Check this is called for AlCodonFrames to support recovery of
5026 SequenceI sq = seqRefIds.get(vamsasSeq.getId());
5027 boolean reorder = false;
5028 SequenceI dsq = null;
5029 if (sq != null && sq.getDatasetSequence() != null)
5031 dsq = sq.getDatasetSequence();
5037 if (sq == null && ignoreUnrefed)
5041 String sqid = vamsasSeq.getDsseqid();
5044 // need to create or add a new dataset sequence reference to this sequence
5047 dsq = seqRefIds.get(sqid);
5052 // make a new dataset sequence
5053 dsq = sq.createDatasetSequence();
5056 // make up a new dataset reference for this sequence
5057 sqid = seqHash(dsq);
5059 dsq.setVamsasId(uniqueSetSuffix + sqid);
5060 seqRefIds.put(sqid, dsq);
5065 dseqs.addElement(dsq);
5070 ds.addSequence(dsq);
5076 { // make this dataset sequence sq's dataset sequence
5077 sq.setDatasetSequence(dsq);
5078 // and update the current dataset alignment
5083 if (!dseqs.contains(dsq))
5090 if (ds.findIndex(dsq) < 0)
5092 ds.addSequence(dsq);
5099 // TODO: refactor this as a merge dataset sequence function
5100 // now check that sq (the dataset sequence) sequence really is the union of
5101 // all references to it
5102 // boolean pre = sq.getStart() < dsq.getStart();
5103 // boolean post = sq.getEnd() > dsq.getEnd();
5107 // StringBuffer sb = new StringBuffer();
5108 String newres = jalview.analysis.AlignSeq.extractGaps(
5109 jalview.util.Comparison.GapChars, sq.getSequenceAsString());
5110 if (!newres.equalsIgnoreCase(dsq.getSequenceAsString())
5111 && newres.length() > dsq.getLength())
5113 // Update with the longer sequence.
5117 * if (pre) { sb.insert(0, newres .substring(0, dsq.getStart() -
5118 * sq.getStart())); dsq.setStart(sq.getStart()); } if (post) {
5119 * sb.append(newres.substring(newres.length() - sq.getEnd() -
5120 * dsq.getEnd())); dsq.setEnd(sq.getEnd()); }
5122 dsq.setSequence(newres);
5124 // TODO: merges will never happen if we 'know' we have the real dataset
5125 // sequence - this should be detected when id==dssid
5127 .println("DEBUG Notice: Merged dataset sequence (if you see this often, post at http://issues.jalview.org/browse/JAL-1474)"); // ("
5128 // + (pre ? "prepended" : "") + " "
5129 // + (post ? "appended" : ""));
5134 // sequence refs are identical. We may need to update the existing dataset
5135 // alignment with this one, though.
5136 if (ds != null && dseqs == null)
5138 int opos = ds.findIndex(dsq);
5139 SequenceI tseq = null;
5140 if (opos != -1 && vseqpos != opos)
5142 // remove from old position
5143 ds.deleteSequence(dsq);
5145 if (vseqpos < ds.getHeight())
5147 if (vseqpos != opos)
5149 // save sequence at destination position
5150 tseq = ds.getSequenceAt(vseqpos);
5151 ds.replaceSequenceAt(vseqpos, dsq);
5152 ds.addSequence(tseq);
5157 ds.addSequence(dsq);
5164 * TODO use AlignmentI here and in related methods - needs
5165 * AlignmentI.getDataset() changed to return AlignmentI instead of Alignment
5167 Hashtable<String, AlignmentI> datasetIds = null;
5169 IdentityHashMap<AlignmentI, String> dataset2Ids = null;
5171 private AlignmentI getDatasetFor(String datasetId)
5173 if (datasetIds == null)
5175 datasetIds = new Hashtable<String, AlignmentI>();
5178 if (datasetIds.containsKey(datasetId))
5180 return datasetIds.get(datasetId);
5185 private void addDatasetRef(String datasetId, AlignmentI dataset)
5187 if (datasetIds == null)
5189 datasetIds = new Hashtable<String, AlignmentI>();
5191 datasetIds.put(datasetId, dataset);
5195 * make a new dataset ID for this jalview dataset alignment
5200 private String getDatasetIdRef(AlignmentI dataset)
5202 if (dataset.getDataset() != null)
5204 warn("Serious issue! Dataset Object passed to getDatasetIdRef is not a Jalview DATASET alignment...");
5206 String datasetId = makeHashCode(dataset, null);
5207 if (datasetId == null)
5209 // make a new datasetId and record it
5210 if (dataset2Ids == null)
5212 dataset2Ids = new IdentityHashMap<AlignmentI, String>();
5216 datasetId = dataset2Ids.get(dataset);
5218 if (datasetId == null)
5220 datasetId = "ds" + dataset2Ids.size() + 1;
5221 dataset2Ids.put(dataset, datasetId);
5227 private void addDBRefs(SequenceI datasetSequence, Sequence sequence)
5229 for (int d = 0; d < sequence.getDBRefCount(); d++)
5231 DBRef dr = sequence.getDBRef(d);
5232 jalview.datamodel.DBRefEntry entry = new jalview.datamodel.DBRefEntry(
5233 sequence.getDBRef(d).getSource(), sequence.getDBRef(d)
5234 .getVersion(), sequence.getDBRef(d).getAccessionId());
5235 if (dr.getMapping() != null)
5237 entry.setMap(addMapping(dr.getMapping()));
5239 datasetSequence.addDBRef(entry);
5243 private jalview.datamodel.Mapping addMapping(Mapping m)
5245 SequenceI dsto = null;
5246 // Mapping m = dr.getMapping();
5247 int fr[] = new int[m.getMapListFromCount() * 2];
5248 Enumeration f = m.enumerateMapListFrom();
5249 for (int _i = 0; f.hasMoreElements(); _i += 2)
5251 MapListFrom mf = (MapListFrom) f.nextElement();
5252 fr[_i] = mf.getStart();
5253 fr[_i + 1] = mf.getEnd();
5255 int fto[] = new int[m.getMapListToCount() * 2];
5256 f = m.enumerateMapListTo();
5257 for (int _i = 0; f.hasMoreElements(); _i += 2)
5259 MapListTo mf = (MapListTo) f.nextElement();
5260 fto[_i] = mf.getStart();
5261 fto[_i + 1] = mf.getEnd();
5263 jalview.datamodel.Mapping jmap = new jalview.datamodel.Mapping(dsto,
5264 fr, fto, (int) m.getMapFromUnit(), (int) m.getMapToUnit());
5265 if (m.getMappingChoice() != null)
5267 MappingChoice mc = m.getMappingChoice();
5268 if (mc.getDseqFor() != null)
5270 String dsfor = "" + mc.getDseqFor();
5271 if (seqRefIds.containsKey(dsfor))
5276 jmap.setTo(seqRefIds.get(dsfor));
5280 frefedSequence.add(newMappingRef(dsfor, jmap));
5286 * local sequence definition
5288 Sequence ms = mc.getSequence();
5289 SequenceI djs = null;
5290 String sqid = ms.getDsseqid();
5291 if (sqid != null && sqid.length() > 0)
5294 * recover dataset sequence
5296 djs = seqRefIds.get(sqid);
5301 .println("Warning - making up dataset sequence id for DbRef sequence map reference");
5302 sqid = ((Object) ms).toString(); // make up a new hascode for
5303 // undefined dataset sequence hash
5304 // (unlikely to happen)
5310 * make a new dataset sequence and add it to refIds hash
5312 djs = new jalview.datamodel.Sequence(ms.getName(),
5314 djs.setStart(jmap.getMap().getToLowest());
5315 djs.setEnd(jmap.getMap().getToHighest());
5316 djs.setVamsasId(uniqueSetSuffix + sqid);
5318 incompleteSeqs.put(sqid, djs);
5319 seqRefIds.put(sqid, djs);
5322 jalview.bin.Cache.log.debug("about to recurse on addDBRefs.");
5331 public jalview.gui.AlignmentPanel copyAlignPanel(AlignmentPanel ap,
5332 boolean keepSeqRefs)
5335 JalviewModel jm = saveState(ap, null, null, null);
5340 jm.getJalviewModelSequence().getViewport(0).setSequenceSetId(null);
5344 uniqueSetSuffix = "";
5345 jm.getJalviewModelSequence().getViewport(0).setId(null); // we don't
5350 if (this.frefedSequence == null)
5352 frefedSequence = new Vector();
5355 viewportsAdded.clear();
5357 AlignFrame af = loadFromObject(jm, null, false, null);
5358 af.alignPanels.clear();
5359 af.closeMenuItem_actionPerformed(true);
5362 * if(ap.av.getAlignment().getAlignmentAnnotation()!=null) { for(int i=0;
5363 * i<ap.av.getAlignment().getAlignmentAnnotation().length; i++) {
5364 * if(!ap.av.getAlignment().getAlignmentAnnotation()[i].autoCalculated) {
5365 * af.alignPanel.av.getAlignment().getAlignmentAnnotation()[i] =
5366 * ap.av.getAlignment().getAlignmentAnnotation()[i]; } } }
5369 return af.alignPanel;
5373 * flag indicating if hashtables should be cleared on finalization TODO this
5374 * flag may not be necessary
5376 private final boolean _cleartables = true;
5378 private Hashtable jvids2vobj;
5383 * @see java.lang.Object#finalize()
5386 protected void finalize() throws Throwable
5388 // really make sure we have no buried refs left.
5393 this.seqRefIds = null;
5394 this.seqsToIds = null;
5398 private void warn(String msg)
5403 private void warn(String msg, Exception e)
5405 if (Cache.log != null)
5409 Cache.log.warn(msg, e);
5413 Cache.log.warn(msg);
5418 System.err.println("Warning: " + msg);
5421 e.printStackTrace();
5426 private void debug(String string)
5428 debug(string, null);
5431 private void debug(String msg, Exception e)
5433 if (Cache.log != null)
5437 Cache.log.debug(msg, e);
5441 Cache.log.debug(msg);
5446 System.err.println("Warning: " + msg);
5449 e.printStackTrace();
5455 * set the object to ID mapping tables used to write/recover objects and XML
5456 * ID strings for the jalview project. If external tables are provided then
5457 * finalize and clearSeqRefs will not clear the tables when the Jalview2XML
5458 * object goes out of scope. - also populates the datasetIds hashtable with
5459 * alignment objects containing dataset sequences
5462 * Map from ID strings to jalview datamodel
5464 * Map from jalview datamodel to ID strings
5468 public void setObjectMappingTables(Hashtable vobj2jv,
5469 IdentityHashMap jv2vobj)
5471 this.jv2vobj = jv2vobj;
5472 this.vobj2jv = vobj2jv;
5473 Iterator ds = jv2vobj.keySet().iterator();
5475 while (ds.hasNext())
5477 Object jvobj = ds.next();
5478 id = jv2vobj.get(jvobj).toString();
5479 if (jvobj instanceof jalview.datamodel.Alignment)
5481 if (((jalview.datamodel.Alignment) jvobj).getDataset() == null)
5483 addDatasetRef(id, (jalview.datamodel.Alignment) jvobj);
5486 else if (jvobj instanceof jalview.datamodel.Sequence)
5488 // register sequence object so the XML parser can recover it.
5489 if (seqRefIds == null)
5491 seqRefIds = new HashMap<String, SequenceI>();
5493 if (seqsToIds == null)
5495 seqsToIds = new IdentityHashMap<SequenceI, String>();
5497 seqRefIds.put(jv2vobj.get(jvobj).toString(), (SequenceI) jvobj);
5498 seqsToIds.put((SequenceI) jvobj, id);
5500 else if (jvobj instanceof jalview.datamodel.AlignmentAnnotation)
5503 AlignmentAnnotation jvann = (AlignmentAnnotation) jvobj;
5504 annotationIds.put(anid = jv2vobj.get(jvobj).toString(), jvann);
5505 if (jvann.annotationId == null)
5507 jvann.annotationId = anid;
5509 if (!jvann.annotationId.equals(anid))
5511 // TODO verify that this is the correct behaviour
5512 this.warn("Overriding Annotation ID for " + anid
5513 + " from different id : " + jvann.annotationId);
5514 jvann.annotationId = anid;
5517 else if (jvobj instanceof String)
5519 if (jvids2vobj == null)
5521 jvids2vobj = new Hashtable();
5522 jvids2vobj.put(jvobj, jv2vobj.get(jvobj).toString());
5527 Cache.log.debug("Ignoring " + jvobj.getClass() + " (ID = " + id);
5533 * set the uniqueSetSuffix used to prefix/suffix object IDs for jalview
5534 * objects created from the project archive. If string is null (default for
5535 * construction) then suffix will be set automatically.
5539 public void setUniqueSetSuffix(String string)
5541 uniqueSetSuffix = string;
5546 * uses skipList2 as the skipList for skipping views on sequence sets
5547 * associated with keys in the skipList
5551 public void setSkipList(Hashtable skipList2)
5553 skipList = skipList2;
5557 * Reads the jar entry of given name and returns its contents, or null if the
5558 * entry is not found.
5561 * @param jarEntryName
5564 protected String readJarEntry(jarInputStreamProvider jprovider,
5565 String jarEntryName)
5567 String result = null;
5568 BufferedReader in = null;
5573 * Reopen the jar input stream and traverse its entries to find a matching
5576 JarInputStream jin = jprovider.getJarInputStream();
5577 JarEntry entry = null;
5580 entry = jin.getNextJarEntry();
5581 } while (entry != null && !entry.getName().equals(jarEntryName));
5585 StringBuilder out = new StringBuilder(256);
5586 in = new BufferedReader(new InputStreamReader(jin, UTF_8));
5589 while ((data = in.readLine()) != null)
5593 result = out.toString();
5597 warn("Couldn't find entry in Jalview Jar for " + jarEntryName);
5599 } catch (Exception ex)
5601 ex.printStackTrace();
5609 } catch (IOException e)
5620 * Returns an incrementing counter (0, 1, 2...)
5624 private synchronized int nextCounter()