2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.structure;
23 import jalview.analysis.AlignSeq;
24 import jalview.api.StructureSelectionManagerProvider;
25 import jalview.commands.CommandI;
26 import jalview.commands.EditCommand;
27 import jalview.commands.EditCommand.Action;
28 import jalview.commands.EditCommand.Edit;
29 import jalview.datamodel.AlignedCodonFrame;
30 import jalview.datamodel.AlignmentAnnotation;
31 import jalview.datamodel.Annotation;
32 import jalview.datamodel.PDBEntry;
33 import jalview.datamodel.SearchResults;
34 import jalview.datamodel.Sequence;
35 import jalview.datamodel.SequenceI;
36 import jalview.io.AppletFormatAdapter;
37 import jalview.util.MessageManager;
38 import jalview.util.StringUtils;
40 import java.io.PrintStream;
41 import java.util.ArrayList;
42 import java.util.Enumeration;
43 import java.util.HashMap;
44 import java.util.IdentityHashMap;
45 import java.util.Iterator;
46 import java.util.List;
48 import java.util.Vector;
51 import MCview.PDBChain;
53 public class StructureSelectionManager
55 static IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager> instances;
57 StructureMapping[] mappings;
59 private boolean processSecondaryStructure = false,
60 secStructServices = false, addTempFacAnnot = false;
62 List<AlignedCodonFrame> seqmappings = null;
64 private int[] seqmappingrefs = null; // refcount for seqmappings elements
66 private List<CommandListener> commandListeners = new ArrayList<CommandListener>();
69 * @return true if will try to use external services for processing secondary
72 public boolean isSecStructServices()
74 return secStructServices;
78 * control use of external services for processing secondary structure
80 * @param secStructServices
82 public void setSecStructServices(boolean secStructServices)
84 this.secStructServices = secStructServices;
88 * flag controlling addition of any kind of structural annotation
90 * @return true if temperature factor annotation will be added
92 public boolean isAddTempFacAnnot()
94 return addTempFacAnnot;
98 * set flag controlling addition of structural annotation
100 * @param addTempFacAnnot
102 public void setAddTempFacAnnot(boolean addTempFacAnnot)
104 this.addTempFacAnnot = addTempFacAnnot;
109 * @return if true, the structure manager will attempt to add secondary
110 * structure lines for unannotated sequences
113 public boolean isProcessSecondaryStructure()
115 return processSecondaryStructure;
119 * Control whether structure manager will try to annotate mapped sequences
120 * with secondary structure from PDB data.
124 public void setProcessSecondaryStructure(boolean enable)
126 processSecondaryStructure = enable;
130 * debug function - write all mappings to stdout
132 public void reportMapping()
134 if (mappings == null)
136 System.err.println("reportMapping: No PDB/Sequence mappings.");
140 System.err.println("reportMapping: There are " + mappings.length
142 for (int m = 0; m < mappings.length; m++)
144 System.err.println("mapping " + m + " : " + mappings[m].pdbfile);
150 * map between the PDB IDs (or structure identifiers) used by Jalview and the
151 * absolute filenames for PDB data that corresponds to it
153 HashMap<String, String> pdbIdFileName = new HashMap<String, String>(),
154 pdbFileNameId = new HashMap<String, String>();
156 public void registerPDBFile(String idForFile, String absoluteFile)
158 pdbIdFileName.put(idForFile, absoluteFile);
159 pdbFileNameId.put(absoluteFile, idForFile);
162 public String findIdForPDBFile(String idOrFile)
164 String id = pdbFileNameId.get(idOrFile);
168 public String findFileForPDBId(String idOrFile)
170 String id = pdbIdFileName.get(idOrFile);
174 public boolean isPDBFileRegistered(String idOrFile)
176 return pdbFileNameId.containsKey(idOrFile)
177 || pdbIdFileName.containsKey(idOrFile);
180 private static StructureSelectionManager nullProvider = null;
182 public static StructureSelectionManager getStructureSelectionManager(
183 StructureSelectionManagerProvider context)
187 if (nullProvider == null)
189 if (instances != null)
191 throw new Error(MessageManager.getString("error.implementation_error_structure_selection_manager_null"),
192 new NullPointerException(MessageManager.getString("exception.ssm_context_is_null")));
196 nullProvider = new StructureSelectionManager();
201 if (instances == null)
203 instances = new java.util.IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager>();
205 StructureSelectionManager instance = instances.get(context);
206 if (instance == null)
208 if (nullProvider != null)
210 instance = nullProvider;
214 instance = new StructureSelectionManager();
216 instances.put(context, instance);
222 * flag controlling whether SeqMappings are relayed from received sequence
223 * mouse over events to other sequences
225 boolean relaySeqMappings = true;
228 * Enable or disable relay of seqMapping events to other sequences. You might
229 * want to do this if there are many sequence mappings and the host computer
234 public void setRelaySeqMappings(boolean relay)
236 relaySeqMappings = relay;
240 * get the state of the relay seqMappings flag.
242 * @return true if sequence mouse overs are being relayed to other mapped
245 public boolean isRelaySeqMappingsEnabled()
247 return relaySeqMappings;
250 Vector listeners = new Vector();
253 * register a listener for alignment sequence mouseover events
257 public void addStructureViewerListener(Object svl)
259 if (!listeners.contains(svl))
261 listeners.addElement(svl);
265 public String alreadyMappedToFile(String pdbid)
267 if (mappings != null)
269 for (int i = 0; i < mappings.length; i++)
271 if (mappings[i].getPdbId().equals(pdbid))
273 return mappings[i].pdbfile;
281 * Import structure data and register a structure mapping for broadcasting
282 * colouring, mouseovers and selection events (convenience wrapper).
285 * - one or more sequences to be mapped to pdbFile
286 * @param targetChains
287 * - optional chain specification for mapping each sequence to pdb
288 * (may be nill, individual elements may be nill)
290 * - structure data resource
292 * - how to resolve data from resource
293 * @return null or the structure data parsed as a pdb file
295 synchronized public MCview.PDBfile setMapping(SequenceI[] sequence,
296 String[] targetChains, String pdbFile, String protocol)
298 return setMapping(true, sequence, targetChains, pdbFile, protocol);
302 * create sequence structure mappings between each sequence and the given
303 * pdbFile (retrieved via the given protocol).
305 * @param forStructureView
306 * when true, record the mapping for use in mouseOvers
309 * - one or more sequences to be mapped to pdbFile
310 * @param targetChains
311 * - optional chain specification for mapping each sequence to pdb
312 * (may be nill, individual elements may be nill)
314 * - structure data resource
316 * - how to resolve data from resource
317 * @return null or the structure data parsed as a pdb file
319 synchronized public MCview.PDBfile setMapping(boolean forStructureView,
320 SequenceI[] sequence,
321 String[] targetChains, String pdbFile, String protocol)
324 * There will be better ways of doing this in the future, for now we'll use
325 * the tried and tested MCview pdb mapping
327 MCview.PDBfile pdb = null;
328 boolean parseSecStr = processSecondaryStructure;
329 if (isPDBFileRegistered(pdbFile))
331 for (SequenceI sq : sequence)
334 while (ds.getDatasetSequence() != null)
336 ds = ds.getDatasetSequence();
339 if (ds.getAnnotation() != null)
341 for (AlignmentAnnotation ala : ds.getAnnotation())
343 // false if any annotation present from this structure
344 // JBPNote this fails for jmol/chimera view because the *file* is
345 // passed, not the structure data ID -
346 if (MCview.PDBfile.isCalcIdForFile(ala,
347 findIdForPDBFile(pdbFile)))
357 pdb = new MCview.PDBfile(addTempFacAnnot, parseSecStr,
358 secStructServices, pdbFile, protocol);
359 if (pdb.id != null && pdb.id.trim().length() > 0
360 && AppletFormatAdapter.FILE.equals(protocol))
362 registerPDBFile(pdb.id.trim(), pdbFile);
364 } catch (Exception ex)
366 ex.printStackTrace();
371 for (int s = 0; s < sequence.length; s++)
373 boolean infChain = true;
374 if (targetChains != null && targetChains[s] != null)
377 targetChain = targetChains[s];
379 else if (sequence[s].getName().indexOf("|") > -1)
381 targetChain = sequence[s].getName().substring(
382 sequence[s].getName().lastIndexOf("|") + 1);
383 if (targetChain.length() > 1)
385 if (targetChain.trim().length() == 0)
391 // not a valid chain identifier
402 AlignSeq maxAlignseq = null;
403 String maxChainId = " ";
404 PDBChain maxChain = null;
405 boolean first = true;
406 for (int i = 0; i < pdb.chains.size(); i++)
408 PDBChain chain = (pdb.chains.elementAt(i));
409 if (targetChain.length() > 0 && !targetChain.equals(chain.id)
412 continue; // don't try to map chains don't match.
414 // TODO: correctly determine sequence type for mixed na/peptide
416 AlignSeq as = new AlignSeq(sequence[s],
417 pdb.chains.elementAt(i).sequence,
418 pdb.chains.elementAt(i).isNa ? AlignSeq.DNA
420 as.calcScoreMatrix();
423 if (first || as.maxscore > max
424 || (as.maxscore == max && chain.id.equals(targetChain)))
430 maxChainId = chain.id;
433 if (maxChain == null)
437 final StringBuffer mappingDetails = new StringBuffer();
438 mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
439 + maxChain.sequence.getSequenceAsString());
440 mappingDetails.append("\nNo of residues = "
441 + maxChain.residues.size() + "\n\n");
442 PrintStream ps = new PrintStream(System.out)
445 public void print(String x)
447 mappingDetails.append(x);
451 public void println()
453 mappingDetails.append("\n");
457 maxAlignseq.printAlignment(ps);
459 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
460 + " " + maxAlignseq.seq2end);
461 mappingDetails.append("\nSEQ start/end "
462 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
463 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
465 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
466 jalview.datamodel.Mapping sqmpping = maxAlignseq
467 .getMappingFromS1(false);
468 jalview.datamodel.Mapping omap = new jalview.datamodel.Mapping(
469 sqmpping.getMap().getInverse());
470 maxChain.transferRESNUMFeatures(sequence[s], null);
472 // allocate enough slots to store the mapping from positions in
473 // sequence[s] to the associated chain
474 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
475 .getLength()) + 2][2];
481 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
482 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
484 resNum = tmp.resNumber;
485 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
486 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
490 } while (index < maxChain.atoms.size());
492 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
494 pdbFile = "INLINE" + pdb.id;
496 StructureMapping newMapping = new StructureMapping(sequence[s],
497 pdbFile, pdb.id, maxChainId, mapping,
498 mappingDetails.toString());
499 if (forStructureView)
502 if (mappings == null)
504 mappings = new StructureMapping[1];
508 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
509 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
513 mappings[mappings.length - 1] = newMapping;
515 maxChain.transferResidueAnnotation(newMapping, sqmpping);
522 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
524 listeners.removeElement(svl);
525 if (svl instanceof SequenceListener)
527 for (int i = 0; i < listeners.size(); i++)
529 if (listeners.elementAt(i) instanceof StructureListener)
531 ((StructureListener) listeners.elementAt(i))
532 .releaseReferences(svl);
537 if (pdbfiles == null)
542 Vector pdbs = new Vector();
543 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
547 StructureListener sl;
548 for (int i = 0; i < listeners.size(); i++)
550 if (listeners.elementAt(i) instanceof StructureListener)
552 sl = (StructureListener) listeners.elementAt(i);
553 handlepdbs = sl.getPdbFile();
554 for (int j = 0; j < handlepdbs.length; j++)
556 if (pdbs.contains(handlepdbs[j]))
558 pdbs.removeElement(handlepdbs[j]);
565 if (pdbs.size() > 0 && mappings != null)
567 Vector tmp = new Vector();
568 for (int i = 0; i < mappings.length; i++)
570 if (!pdbs.contains(mappings[i].pdbfile))
572 tmp.addElement(mappings[i]);
576 mappings = new StructureMapping[tmp.size()];
577 tmp.copyInto(mappings);
581 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
583 if (listeners == null)
585 // old or prematurely sent event
588 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
589 SearchResults results = null;
590 SequenceI lastseq = null;
591 int lastipos = -1, indexpos;
592 for (int i = 0; i < listeners.size(); i++)
594 if (listeners.elementAt(i) instanceof SequenceListener)
598 results = new SearchResults();
600 if (mappings != null)
602 for (int j = 0; j < mappings.length; j++)
604 if (mappings[j].pdbfile.equals(pdbfile)
605 && mappings[j].pdbchain.equals(chain))
607 indexpos = mappings[j].getSeqPos(pdbResNum);
608 if (lastipos != indexpos && lastseq != mappings[j].sequence)
610 results.addResult(mappings[j].sequence, indexpos, indexpos);
612 lastseq = mappings[j].sequence;
613 // construct highlighted sequence list
614 if (seqmappings != null)
616 for (AlignedCodonFrame acf : seqmappings)
618 acf.markMappedRegion(mappings[j].sequence, indexpos,
630 for (int i = 0; i < listeners.size(); i++)
632 Object li = listeners.elementAt(i);
633 if (li instanceof SequenceListener)
635 ((SequenceListener) li).highlightSequence(results);
642 * highlight regions associated with a position (indexpos) in seq
645 * the sequence that the mouse over occurred on
647 * the absolute position being mouseovered in seq (0 to seq.length())
649 * the sequence position (if -1, seq.findPosition is called to
650 * resolve the residue number)
652 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
655 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
656 SearchResults results = null;
659 index = seq.findPosition(indexpos);
661 for (int i = 0; i < listeners.size(); i++)
663 Object listener = listeners.elementAt(i);
664 if (listener == source)
666 // TODO listener (e.g. SeqPanel) is never == source (AlignViewport)
667 // Temporary fudge with SequenceListener.getVamsasSource()
670 if (listener instanceof StructureListener)
672 highlightStructure((StructureListener) listener, seq, index);
676 if (listener instanceof SequenceListener)
678 final SequenceListener seqListener = (SequenceListener) listener;
679 if (hasSequenceListeners
680 && seqListener.getVamsasSource() != source)
682 if (relaySeqMappings)
686 results = buildSearchResults(seq, index);
688 seqListener.highlightSequence(results);
692 else if (listener instanceof VamsasListener && !handlingVamsasMo)
694 ((VamsasListener) listener).mouseOverSequence(seq, indexpos,
697 else if (listener instanceof SecondaryStructureListener)
699 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
707 * Returns a SearchResults object describing the mapped region corresponding
708 * to the specified sequence position.
714 protected SearchResults buildSearchResults(SequenceI seq, int index)
716 SearchResults results;
717 results = new SearchResults();
718 if (index >= seq.getStart() && index <= seq.getEnd())
720 if (seqmappings != null)
722 for (AlignedCodonFrame acf : seqmappings)
724 acf.markMappedRegion(seq, index, results);
727 // hasSequenceListeners = results.getSize() > 0;
728 if (handlingVamsasMo)
730 // maybe have to resolve seq to a dataset sequence...
731 // add in additional direct sequence and/or dataset sequence
733 results.addResult(seq, index, index);
740 * Send suitable messages to a StructureListener to highlight atoms
741 * corresponding to the given sequence position.
747 protected void highlightStructure(StructureListener sl, SequenceI seq,
751 if (mappings != null)
753 List<AtomSpec> atoms = new ArrayList<AtomSpec>();
754 for (int j = 0; j < mappings.length; j++)
756 if (mappings[j].sequence == seq
757 || mappings[j].sequence == seq.getDatasetSequence())
759 atomNo = mappings[j].getAtomNum(index);
763 atoms.add(new AtomSpec(mappings[j].pdbfile,
764 mappings[j].pdbchain, mappings[j].getPDBResNum(index),
769 sl.highlightAtoms(atoms);
774 * true if a mouse over event from an external (ie Vamsas) source is being
777 boolean handlingVamsasMo = false;
782 * as mouseOverSequence but only route event to SequenceListeners
786 * in an alignment sequence
788 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
791 handlingVamsasMo = true;
792 long msg = sequenceI.hashCode() * (1 + position);
796 mouseOverSequence(sequenceI, position, -1, source);
798 handlingVamsasMo = false;
801 public Annotation[] colourSequenceFromStructure(SequenceI seq,
805 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
806 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
808 * Annotation [] annotations = new Annotation[seq.getLength()];
810 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
811 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
812 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
814 * for (int j = 0; j < mappings.length; j++) {
816 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
817 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
818 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
819 * "+mappings[j].pdbfile);
821 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
822 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
824 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
825 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
826 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
827 * mappings[j].pdbfile); }
829 * annotations[index] = new Annotation("X",null,' ',0,col); } return
830 * annotations; } } } }
832 * return annotations;
836 public void structureSelectionChanged()
840 public void sequenceSelectionChanged()
844 public void sequenceColoursChanged(Object source)
846 StructureListener sl;
847 for (int i = 0; i < listeners.size(); i++)
849 if (listeners.elementAt(i) instanceof StructureListener)
851 sl = (StructureListener) listeners.elementAt(i);
852 sl.updateColours(source);
857 public StructureMapping[] getMapping(String pdbfile)
859 Vector tmp = new Vector();
860 if (mappings != null)
862 for (int i = 0; i < mappings.length; i++)
864 if (mappings[i].pdbfile.equals(pdbfile))
866 tmp.addElement(mappings[i]);
870 StructureMapping[] ret = new StructureMapping[tmp.size()];
871 for (int i = 0; i < tmp.size(); i++)
873 ret[i] = (StructureMapping) tmp.elementAt(i);
879 public String printMapping(String pdbfile)
881 StringBuffer sb = new StringBuffer();
882 for (int i = 0; i < mappings.length; i++)
884 if (mappings[i].pdbfile.equals(pdbfile))
886 sb.append(mappings[i].mappingDetails);
890 return sb.toString();
893 private synchronized void modifySeqMappingList(boolean add,
894 AlignedCodonFrame[] codonFrames)
896 if (!add && (seqmappings == null || seqmappings.size() == 0))
900 if (seqmappings == null)
902 seqmappings = new ArrayList<AlignedCodonFrame>();
904 if (codonFrames != null && codonFrames.length > 0)
906 for (int cf = 0; cf < codonFrames.length; cf++)
908 if (seqmappings.contains(codonFrames[cf]))
912 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
916 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
918 int pos = seqmappings.indexOf(codonFrames[cf]);
919 int[] nr = new int[seqmappingrefs.length - 1];
922 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
924 if (pos < seqmappingrefs.length - 1)
926 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
927 seqmappingrefs.length - pos - 2);
936 seqmappings.add(codonFrames[cf]);
938 int[] nsr = new int[(seqmappingrefs == null) ? 1
939 : seqmappingrefs.length + 1];
940 if (seqmappingrefs != null && seqmappingrefs.length > 0)
942 System.arraycopy(seqmappingrefs, 0, nsr, 0,
943 seqmappingrefs.length);
945 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
946 seqmappingrefs = nsr;
953 public void removeMappings(AlignedCodonFrame[] codonFrames)
955 modifySeqMappingList(false, codonFrames);
958 public void addMappings(AlignedCodonFrame[] codonFrames)
960 modifySeqMappingList(true, codonFrames);
963 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
965 public void addSelectionListener(SelectionListener selecter)
967 if (!sel_listeners.contains(selecter))
969 sel_listeners.addElement(selecter);
973 public void removeSelectionListener(SelectionListener toremove)
975 if (sel_listeners.contains(toremove))
977 sel_listeners.removeElement(toremove);
981 public synchronized void sendSelection(
982 jalview.datamodel.SequenceGroup selection,
983 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
985 if (sel_listeners != null && sel_listeners.size() > 0)
987 Enumeration listeners = sel_listeners.elements();
988 while (listeners.hasMoreElements())
990 SelectionListener slis = ((SelectionListener) listeners
994 slis.selection(selection, colsel, source);
1001 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
1003 public synchronized void sendViewPosition(
1004 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
1005 int startSeq, int endSeq)
1008 if (view_listeners != null && view_listeners.size() > 0)
1010 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
1012 while (listeners.hasMoreElements())
1014 AlignmentViewPanelListener slis = listeners.nextElement();
1017 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
1024 public void finalize() throws Throwable
1026 if (listeners != null)
1031 if (pdbIdFileName != null)
1033 pdbIdFileName.clear();
1034 pdbIdFileName = null;
1036 if (sel_listeners != null)
1038 sel_listeners.clear();
1039 sel_listeners = null;
1041 if (view_listeners != null)
1043 view_listeners.clear();
1044 view_listeners = null;
1047 seqmappingrefs = null;
1051 * release all references associated with this manager provider
1053 * @param jalviewLite
1055 public static void release(StructureSelectionManagerProvider jalviewLite)
1057 // synchronized (instances)
1059 if (instances == null)
1063 StructureSelectionManager mnger = (instances.get(jalviewLite));
1066 instances.remove(jalviewLite);
1070 } catch (Throwable x)
1078 public void registerPDBEntry(PDBEntry pdbentry)
1080 if (pdbentry.getFile() != null
1081 && pdbentry.getFile().trim().length() > 0)
1083 registerPDBFile(pdbentry.getId(), pdbentry.getFile());
1087 public void addCommandListener(CommandListener cl)
1089 if (!commandListeners.contains(cl))
1091 commandListeners.add(cl);
1095 public boolean hasCommandListener(CommandListener cl)
1097 return this.commandListeners.contains(cl);
1100 public boolean removeEditListener(CommandListener l)
1102 return commandListeners.remove(l);
1106 * Forward a command to any command listeners (except for the command's
1110 * the command to be broadcast (in its form after being performed)
1112 * if true, the command was being 'undone'
1115 public void commandPerformed(CommandI command, boolean undo,
1116 VamsasSource source)
1118 for (CommandListener listener : commandListeners)
1120 if (listener.getVamsasSource() != source)
1122 listener.mirrorCommand(command, undo, this);
1128 * Returns a new EditCommand representing the given command as mapped to the
1129 * given sequences. If there is no mapping, returns an empty EditCommand.
1137 public EditCommand mapEditCommand(EditCommand command, boolean undo,
1138 final List<SequenceI> targetSeqs, char gapChar)
1141 * Cache a copy of the target sequences so we can mimic successive edits on
1142 * them. This lets us compute mappings for all edits in the set.
1144 Map<SequenceI, SequenceI> targetCopies = new HashMap<SequenceI, SequenceI>();
1145 for (SequenceI seq : targetSeqs)
1147 SequenceI ds = seq.getDatasetSequence();
1150 final Sequence copy = new Sequence("", new String(seq.getSequence()));
1151 copy.setDatasetSequence(ds);
1152 targetCopies.put(ds, copy);
1157 * Compute 'source' sequences as they were before applying edits:
1159 Map<SequenceI, SequenceI> originalSequences = command.priorState(undo);
1161 EditCommand result = new EditCommand();
1162 Iterator<Edit> edits = command.getEditIterator(!undo);
1163 while (edits.hasNext())
1165 Edit edit = edits.next();
1166 Action action = edit.getAction();
1169 * Invert sense of action if an Undo.
1173 action = action == Action.INSERT_GAP ? Action.DELETE_GAP
1174 : (action == Action.DELETE_GAP ? Action.INSERT_GAP : action);
1176 final int count = edit.getNumber();
1177 final int editPos = edit.getPosition();
1178 for (SequenceI seq : edit.getSequences())
1181 * Get residue position at (or to right of) edit location. Note we use
1182 * our 'copy' of the sequence before editing for this.
1184 SequenceI ds = seq.getDatasetSequence();
1189 final SequenceI actedOn = originalSequences.get(ds);
1190 final int seqpos = actedOn.findPosition(editPos);
1193 * Determine all mappings from this position to mapped sequences.
1195 SearchResults sr = buildSearchResults(seq, seqpos);
1199 for (SequenceI targetSeq : targetSeqs)
1201 ds = targetSeq.getDatasetSequence();
1206 SequenceI copyTarget = targetCopies.get(ds);
1207 final int[] match = sr.getResults(copyTarget, 0,
1208 copyTarget.getLength());
1211 final int ratio = 3; // TODO: compute this - how?
1212 final int mappedCount = count * ratio;
1215 * Shift Delete start position left, as it acts on positions to
1218 int mappedEditPos = action == Action.DELETE_GAP ? match[0]
1219 - mappedCount : match[0];
1220 Edit e = new EditCommand().new Edit(action, new SequenceI[]
1221 { targetSeq }, mappedEditPos, mappedCount, gapChar);
1225 * and 'apply' the edit to our copy of its target sequence
1227 if (action == Action.INSERT_GAP)
1229 copyTarget.setSequence(new String(StringUtils.insertCharAt(
1230 copyTarget.getSequence(), mappedEditPos,
1234 else if (action == Action.DELETE_GAP)
1236 copyTarget.setSequence(new String(StringUtils.deleteChars(
1237 copyTarget.getSequence(), mappedEditPos,
1238 mappedEditPos + mappedCount)));
1244 * and 'apply' the edit to our copy of its source sequence
1246 if (action == Action.INSERT_GAP) {
1247 actedOn.setSequence(new String(StringUtils.insertCharAt(
1248 actedOn.getSequence(), editPos, count, gapChar)));
1250 else if (action == Action.DELETE_GAP)
1252 actedOn.setSequence(new String(StringUtils.deleteChars(
1253 actedOn.getSequence(), editPos, editPos + count)));