JAL-1705 first pass at applying preset feature colouring for EnsemblGene
[jalview.git] / src / jalview / gui / AlignViewport.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 /*
22  * Jalview - A Sequence Alignment Editor and Viewer
23  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
24  *
25  * This program is free software; you can redistribute it and/or
26  * modify it under the terms of the GNU General Public License
27  * as published by the Free Software Foundation; either version 2
28  * of the License, or (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program; if not, write to the Free Software
37  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
38  */
39 package jalview.gui;
40
41 import jalview.analysis.AlignmentUtils;
42 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
43 import jalview.analysis.NJTree;
44 import jalview.api.AlignViewportI;
45 import jalview.api.AlignmentViewPanel;
46 import jalview.api.FeatureColourI;
47 import jalview.api.FeatureSettingsI;
48 import jalview.api.FeaturesDisplayedI;
49 import jalview.api.ViewStyleI;
50 import jalview.bin.Cache;
51 import jalview.commands.CommandI;
52 import jalview.datamodel.AlignedCodonFrame;
53 import jalview.datamodel.Alignment;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.PDBEntry;
57 import jalview.datamodel.SearchResults;
58 import jalview.datamodel.Sequence;
59 import jalview.datamodel.SequenceGroup;
60 import jalview.datamodel.SequenceI;
61 import jalview.schemes.ColourSchemeProperty;
62 import jalview.schemes.UserColourScheme;
63 import jalview.structure.CommandListener;
64 import jalview.structure.SelectionSource;
65 import jalview.structure.StructureSelectionManager;
66 import jalview.structure.VamsasSource;
67 import jalview.util.MessageManager;
68 import jalview.viewmodel.AlignmentViewport;
69 import jalview.ws.params.AutoCalcSetting;
70
71 import java.awt.Container;
72 import java.awt.Dimension;
73 import java.awt.Font;
74 import java.awt.Rectangle;
75 import java.util.ArrayList;
76 import java.util.Hashtable;
77 import java.util.List;
78 import java.util.Map;
79 import java.util.Vector;
80
81 import javax.swing.JInternalFrame;
82 import javax.swing.JOptionPane;
83
84 /**
85  * DOCUMENT ME!
86  * 
87  * @author $author$
88  * @version $Revision: 1.141 $
89  */
90 public class AlignViewport extends AlignmentViewport implements
91         SelectionSource, CommandListener
92 {
93   Font font;
94
95   NJTree currentTree = null;
96
97   boolean cursorMode = false;
98
99   boolean antiAlias = false;
100
101   private Rectangle explodedGeometry;
102
103   String viewName;
104
105   /*
106    * Flag set true on the view that should 'gather' multiple views of the same
107    * sequence set id when a project is reloaded. Set false on all views when
108    * they are 'exploded' into separate windows. Set true on the current view
109    * when 'Gather' is performed, and also on the first tab when the first new
110    * view is created.
111    */
112   private boolean gatherViewsHere = false;
113
114   private AnnotationColumnChooser annotationColumnSelectionState;
115
116   /**
117    * Creates a new AlignViewport object.
118    * 
119    * @param al
120    *          alignment to view
121    */
122   public AlignViewport(AlignmentI al)
123   {
124     setAlignment(al);
125     init();
126   }
127
128   /**
129    * Create a new AlignViewport object with a specific sequence set ID
130    * 
131    * @param al
132    * @param seqsetid
133    *          (may be null - but potential for ambiguous constructor exception)
134    */
135   public AlignViewport(AlignmentI al, String seqsetid)
136   {
137     this(al, seqsetid, null);
138   }
139
140   public AlignViewport(AlignmentI al, String seqsetid, String viewid)
141   {
142     sequenceSetID = seqsetid;
143     viewId = viewid;
144     // TODO remove these once 2.4.VAMSAS release finished
145     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
146     {
147       Cache.log.debug("Setting viewport's sequence set id : "
148               + sequenceSetID);
149     }
150     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
151     {
152       Cache.log.debug("Setting viewport's view id : " + viewId);
153     }
154     setAlignment(al);
155     init();
156   }
157
158   /**
159    * Create a new AlignViewport with hidden regions
160    * 
161    * @param al
162    *          AlignmentI
163    * @param hiddenColumns
164    *          ColumnSelection
165    */
166   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns)
167   {
168     setAlignment(al);
169     if (hiddenColumns != null)
170     {
171       colSel = hiddenColumns;
172     }
173     init();
174   }
175
176   /**
177    * New viewport with hidden columns and an existing sequence set id
178    * 
179    * @param al
180    * @param hiddenColumns
181    * @param seqsetid
182    *          (may be null)
183    */
184   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns,
185           String seqsetid)
186   {
187     this(al, hiddenColumns, seqsetid, null);
188   }
189
190   /**
191    * New viewport with hidden columns and an existing sequence set id and viewid
192    * 
193    * @param al
194    * @param hiddenColumns
195    * @param seqsetid
196    *          (may be null)
197    * @param viewid
198    *          (may be null)
199    */
200   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns,
201           String seqsetid, String viewid)
202   {
203     sequenceSetID = seqsetid;
204     viewId = viewid;
205     // TODO remove these once 2.4.VAMSAS release finished
206     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
207     {
208       Cache.log.debug("Setting viewport's sequence set id : "
209               + sequenceSetID);
210     }
211     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
212     {
213       Cache.log.debug("Setting viewport's view id : " + viewId);
214     }
215     setAlignment(al);
216     if (hiddenColumns != null)
217     {
218       colSel = hiddenColumns;
219     }
220     init();
221   }
222
223   /**
224    * Apply any settings saved in user preferences
225    */
226   private void applyViewProperties()
227   {
228     antiAlias = Cache.getDefault("ANTI_ALIAS", false);
229
230     viewStyle.setShowJVSuffix(Cache.getDefault("SHOW_JVSUFFIX", true));
231     setShowAnnotation(Cache.getDefault("SHOW_ANNOTATIONS", true));
232
233     setRightAlignIds(Cache.getDefault("RIGHT_ALIGN_IDS", false));
234     setCentreColumnLabels(Cache.getDefault("CENTRE_COLUMN_LABELS", false));
235     autoCalculateConsensus = Cache.getDefault("AUTO_CALC_CONSENSUS", true);
236
237     setPadGaps(Cache.getDefault("PAD_GAPS", true));
238     setShowNPFeats(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
239     setShowDBRefs(Cache.getDefault("SHOW_DBREFS_TOOLTIP", true));
240     viewStyle.setSeqNameItalics(Cache.getDefault("ID_ITALICS", true));
241     viewStyle.setWrapAlignment(Cache.getDefault("WRAP_ALIGNMENT", false));
242     viewStyle.setShowUnconserved(Cache
243             .getDefault("SHOW_UNCONSERVED", false));
244     sortByTree = Cache.getDefault("SORT_BY_TREE", false);
245     followSelection = Cache.getDefault("FOLLOW_SELECTIONS", true);
246     sortAnnotationsBy = SequenceAnnotationOrder.valueOf(Cache.getDefault(
247             Preferences.SORT_ANNOTATIONS,
248             SequenceAnnotationOrder.NONE.name()));
249     showAutocalculatedAbove = Cache.getDefault(
250             Preferences.SHOW_AUTOCALC_ABOVE, false);
251     viewStyle.setScaleProteinAsCdna(Cache.getDefault(
252             Preferences.SCALE_PROTEIN_TO_CDNA, true));
253   }
254
255   void init()
256   {
257     this.startRes = 0;
258     this.endRes = alignment.getWidth() - 1;
259     this.startSeq = 0;
260     this.endSeq = alignment.getHeight() - 1;
261     applyViewProperties();
262
263     String fontName = Cache.getDefault("FONT_NAME", "SansSerif");
264     String fontStyle = Cache.getDefault("FONT_STYLE", Font.PLAIN + "");
265     String fontSize = Cache.getDefault("FONT_SIZE", "10");
266
267     int style = 0;
268
269     if (fontStyle.equals("bold"))
270     {
271       style = 1;
272     }
273     else if (fontStyle.equals("italic"))
274     {
275       style = 2;
276     }
277
278     setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
279
280     alignment
281             .setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(0));
282
283     // We must set conservation and consensus before setting colour,
284     // as Blosum and Clustal require this to be done
285     if (hconsensus == null && !isDataset)
286     {
287       if (!alignment.isNucleotide())
288       {
289         showConservation = Cache.getDefault("SHOW_CONSERVATION", true);
290         showQuality = Cache.getDefault("SHOW_QUALITY", true);
291         showGroupConservation = Cache.getDefault("SHOW_GROUP_CONSERVATION",
292                 false);
293       }
294       showConsensusHistogram = Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM",
295               true);
296       showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", false);
297       normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO",
298               false);
299       showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false);
300       showConsensus = Cache.getDefault("SHOW_IDENTITY", true);
301     }
302     initAutoAnnotation();
303     String colourProperty = alignment.isNucleotide() ? Preferences.DEFAULT_COLOUR_NUC
304             : Preferences.DEFAULT_COLOUR_PROT;
305     String propertyValue = Cache.getProperty(colourProperty);
306     if (propertyValue == null)
307     {
308       // fall back on this property for backwards compatibility
309       propertyValue = Cache.getProperty(Preferences.DEFAULT_COLOUR);
310     }
311     if (propertyValue != null)
312     {
313       globalColourScheme = ColourSchemeProperty.getColour(alignment,
314               propertyValue);
315
316       if (globalColourScheme instanceof UserColourScheme)
317       {
318         globalColourScheme = UserDefinedColours.loadDefaultColours();
319         ((UserColourScheme) globalColourScheme).setThreshold(0,
320                 isIgnoreGapsConsensus());
321       }
322
323       if (globalColourScheme != null)
324       {
325         globalColourScheme.setConsensus(hconsensus);
326       }
327     }
328   }
329
330   /**
331    * get the consensus sequence as displayed under the PID consensus annotation
332    * row.
333    * 
334    * @return consensus sequence as a new sequence object
335    */
336   public SequenceI getConsensusSeq()
337   {
338     if (consensus == null)
339     {
340       updateConsensus(null);
341     }
342     if (consensus == null)
343     {
344       return null;
345     }
346     StringBuffer seqs = new StringBuffer();
347     for (int i = 0; i < consensus.annotations.length; i++)
348     {
349       if (consensus.annotations[i] != null)
350       {
351         if (consensus.annotations[i].description.charAt(0) == '[')
352         {
353           seqs.append(consensus.annotations[i].description.charAt(1));
354         }
355         else
356         {
357           seqs.append(consensus.annotations[i].displayCharacter);
358         }
359       }
360     }
361
362     SequenceI sq = new Sequence("Consensus", seqs.toString());
363     sq.setDescription("Percentage Identity Consensus "
364             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
365     return sq;
366   }
367
368   boolean validCharWidth;
369
370   /**
371    * update view settings with the given font. You may need to call
372    * alignPanel.fontChanged to update the layout geometry
373    * 
374    * @param setGrid
375    *          when true, charWidth/height is set according to font mentrics
376    */
377   public void setFont(Font f, boolean setGrid)
378   {
379     font = f;
380
381     Container c = new Container();
382
383     java.awt.FontMetrics fm = c.getFontMetrics(font);
384     int w = viewStyle.getCharWidth(), ww = fm.charWidth('M'), h = viewStyle
385             .getCharHeight();
386     if (setGrid)
387     {
388       setCharHeight(fm.getHeight());
389       setCharWidth(ww);
390     }
391     viewStyle.setFontName(font.getName());
392     viewStyle.setFontStyle(font.getStyle());
393     viewStyle.setFontSize(font.getSize());
394
395     validCharWidth = true;
396   }
397
398   @Override
399   public void setViewStyle(ViewStyleI settingsForView)
400   {
401     super.setViewStyle(settingsForView);
402     setFont(new Font(viewStyle.getFontName(), viewStyle.getFontStyle(),
403             viewStyle.getFontSize()), false);
404
405   }
406
407   /**
408    * DOCUMENT ME!
409    * 
410    * @return DOCUMENT ME!
411    */
412   public Font getFont()
413   {
414     return font;
415   }
416
417   /**
418    * DOCUMENT ME!
419    * 
420    * @param align
421    *          DOCUMENT ME!
422    */
423   public void setAlignment(AlignmentI align)
424   {
425     replaceMappings(align);
426     this.alignment = align;
427   }
428
429   /**
430    * Replace any codon mappings for this viewport with those for the given
431    * viewport
432    * 
433    * @param align
434    */
435   public void replaceMappings(AlignmentI align)
436   {
437
438     /*
439      * Deregister current mappings (if any)
440      */
441     deregisterMappings();
442
443     /*
444      * Register new mappings (if any)
445      */
446     if (align != null)
447     {
448       StructureSelectionManager ssm = StructureSelectionManager
449               .getStructureSelectionManager(Desktop.instance);
450       ssm.registerMappings(align.getCodonFrames());
451     }
452
453     /*
454      * replace mappings on our alignment
455      */
456     if (alignment != null && align != null)
457     {
458       alignment.setCodonFrames(align.getCodonFrames());
459     }
460   }
461
462   protected void deregisterMappings()
463   {
464     AlignmentI al = getAlignment();
465     if (al != null)
466     {
467       List<AlignedCodonFrame> mappings = al.getCodonFrames();
468       if (mappings != null)
469       {
470         StructureSelectionManager ssm = StructureSelectionManager
471                 .getStructureSelectionManager(Desktop.instance);
472         for (AlignedCodonFrame acf : mappings)
473         {
474           if (noReferencesTo(acf))
475           {
476             ssm.deregisterMapping(acf);
477           }
478         }
479       }
480     }
481   }
482
483   /**
484    * DOCUMENT ME!
485    * 
486    * @return DOCUMENT ME!
487    */
488   @Override
489   public char getGapCharacter()
490   {
491     return getAlignment().getGapCharacter();
492   }
493
494   /**
495    * DOCUMENT ME!
496    * 
497    * @param gap
498    *          DOCUMENT ME!
499    */
500   public void setGapCharacter(char gap)
501   {
502     if (getAlignment() != null)
503     {
504       getAlignment().setGapCharacter(gap);
505     }
506   }
507
508   /**
509    * DOCUMENT ME!
510    * 
511    * @return DOCUMENT ME!
512    */
513   @Override
514   public ColumnSelection getColumnSelection()
515   {
516     return colSel;
517   }
518
519   /**
520    * DOCUMENT ME!
521    * 
522    * @param tree
523    *          DOCUMENT ME!
524    */
525   public void setCurrentTree(NJTree tree)
526   {
527     currentTree = tree;
528   }
529
530   /**
531    * DOCUMENT ME!
532    * 
533    * @return DOCUMENT ME!
534    */
535   public NJTree getCurrentTree()
536   {
537     return currentTree;
538   }
539
540   /**
541    * returns the visible column regions of the alignment
542    * 
543    * @param selectedRegionOnly
544    *          true to just return the contigs intersecting with the selected
545    *          area
546    * @return
547    */
548   public int[] getViewAsVisibleContigs(boolean selectedRegionOnly)
549   {
550     int[] viscontigs = null;
551     int start = 0, end = 0;
552     if (selectedRegionOnly && selectionGroup != null)
553     {
554       start = selectionGroup.getStartRes();
555       end = selectionGroup.getEndRes() + 1;
556     }
557     else
558     {
559       end = alignment.getWidth();
560     }
561     viscontigs = colSel.getVisibleContigs(start, end);
562     return viscontigs;
563   }
564
565   /**
566    * get hash of undo and redo list for the alignment
567    * 
568    * @return long[] { historyList.hashCode, redoList.hashCode };
569    */
570   public long[] getUndoRedoHash()
571   {
572     // TODO: JAL-1126
573     if (historyList == null || redoList == null)
574     {
575       return new long[] { -1, -1 };
576     }
577     return new long[] { historyList.hashCode(), this.redoList.hashCode() };
578   }
579
580   /**
581    * test if a particular set of hashcodes are different to the hashcodes for
582    * the undo and redo list.
583    * 
584    * @param undoredo
585    *          the stored set of hashcodes as returned by getUndoRedoHash
586    * @return true if the hashcodes differ (ie the alignment has been edited) or
587    *         the stored hashcode array differs in size
588    */
589   public boolean isUndoRedoHashModified(long[] undoredo)
590   {
591     if (undoredo == null)
592     {
593       return true;
594     }
595     long[] cstate = getUndoRedoHash();
596     if (cstate.length != undoredo.length)
597     {
598       return true;
599     }
600
601     for (int i = 0; i < cstate.length; i++)
602     {
603       if (cstate[i] != undoredo[i])
604       {
605         return true;
606       }
607     }
608     return false;
609   }
610
611   public boolean followSelection = true;
612
613   /**
614    * @return true if view selection should always follow the selections
615    *         broadcast by other selection sources
616    */
617   public boolean getFollowSelection()
618   {
619     return followSelection;
620   }
621
622   /**
623    * Send the current selection to be broadcast to any selection listeners.
624    */
625   @Override
626   public void sendSelection()
627   {
628     jalview.structure.StructureSelectionManager
629             .getStructureSelectionManager(Desktop.instance).sendSelection(
630                     new SequenceGroup(getSelectionGroup()),
631                     new ColumnSelection(getColumnSelection()), this);
632   }
633
634   /**
635    * return the alignPanel containing the given viewport. Use this to get the
636    * components currently handling the given viewport.
637    * 
638    * @param av
639    * @return null or an alignPanel guaranteed to have non-null alignFrame
640    *         reference
641    */
642   public AlignmentPanel getAlignPanel()
643   {
644     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(this
645             .getSequenceSetId());
646     for (int p = 0; aps != null && p < aps.length; p++)
647     {
648       if (aps[p].av == this)
649       {
650         return aps[p];
651       }
652     }
653     return null;
654   }
655
656   public boolean getSortByTree()
657   {
658     return sortByTree;
659   }
660
661   public void setSortByTree(boolean sort)
662   {
663     sortByTree = sort;
664   }
665
666   /**
667    * synthesize a column selection if none exists so it covers the given
668    * selection group. if wholewidth is false, no column selection is made if the
669    * selection group covers the whole alignment width.
670    * 
671    * @param sg
672    * @param wholewidth
673    */
674   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
675   {
676     int sgs, sge;
677     if (sg != null
678             && (sgs = sg.getStartRes()) >= 0
679             && sg.getStartRes() <= (sge = sg.getEndRes())
680             && (colSel == null || colSel.getSelected() == null || colSel
681                     .getSelected().size() == 0))
682     {
683       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
684       {
685         // do nothing
686         return;
687       }
688       if (colSel == null)
689       {
690         colSel = new ColumnSelection();
691       }
692       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
693       {
694         colSel.addElement(cspos);
695       }
696     }
697   }
698
699   /**
700    * Returns the (Desktop) instance of the StructureSelectionManager
701    */
702   @Override
703   public StructureSelectionManager getStructureSelectionManager()
704   {
705     return StructureSelectionManager
706             .getStructureSelectionManager(Desktop.instance);
707   }
708
709   /**
710    * 
711    * @param pdbEntries
712    * @return an array of SequenceI arrays, one for each PDBEntry, listing which
713    *         sequences in the alignment hold a reference to it
714    */
715   public SequenceI[][] collateForPDB(PDBEntry[] pdbEntries)
716   {
717     List<SequenceI[]> seqvectors = new ArrayList<SequenceI[]>();
718     for (PDBEntry pdb : pdbEntries)
719     {
720       List<SequenceI> seqs = new ArrayList<SequenceI>();
721       for (SequenceI sq : alignment.getSequences())
722       {
723         Vector<PDBEntry> pdbs = sq.getDatasetSequence().getAllPDBEntries();
724         if (pdbs == null)
725         {
726           continue;
727         }
728         for (PDBEntry p1 : pdbs)
729         {
730           if (p1.getId().equals(pdb.getId()))
731           {
732             if (!seqs.contains(sq))
733             {
734               seqs.add(sq);
735               continue;
736             }
737           }
738         }
739       }
740       seqvectors.add(seqs.toArray(new SequenceI[seqs.size()]));
741     }
742     return seqvectors.toArray(new SequenceI[seqvectors.size()][]);
743   }
744
745   @Override
746   public boolean isNormaliseSequenceLogo()
747   {
748     return normaliseSequenceLogo;
749   }
750
751   public void setNormaliseSequenceLogo(boolean state)
752   {
753     normaliseSequenceLogo = state;
754   }
755
756   /**
757    * 
758    * @return true if alignment characters should be displayed
759    */
760   @Override
761   public boolean isValidCharWidth()
762   {
763     return validCharWidth;
764   }
765
766   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<String, AutoCalcSetting>();
767
768   public AutoCalcSetting getCalcIdSettingsFor(String calcId)
769   {
770     return calcIdParams.get(calcId);
771   }
772
773   public void setCalcIdSettingsFor(String calcId, AutoCalcSetting settings,
774           boolean needsUpdate)
775   {
776     calcIdParams.put(calcId, settings);
777     // TODO: create a restart list to trigger any calculations that need to be
778     // restarted after load
779     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
780     if (needsUpdate)
781     {
782       Cache.log.debug("trigger update for " + calcId);
783     }
784   }
785
786   /**
787    * Method called when another alignment's edit (or possibly other) command is
788    * broadcast to here.
789    *
790    * To allow for sequence mappings (e.g. protein to cDNA), we have to first
791    * 'unwind' the command on the source sequences (in simulation, not in fact),
792    * and then for each edit in turn:
793    * <ul>
794    * <li>compute the equivalent edit on the mapped sequences</li>
795    * <li>apply the mapped edit</li>
796    * <li>'apply' the source edit to the working copy of the source sequences</li>
797    * </ul>
798    * 
799    * @param command
800    * @param undo
801    * @param ssm
802    */
803   @Override
804   public void mirrorCommand(CommandI command, boolean undo,
805           StructureSelectionManager ssm, VamsasSource source)
806   {
807     /*
808      * Do nothing unless we are a 'complement' of the source. May replace this
809      * with direct calls not via SSM.
810      */
811     if (source instanceof AlignViewportI
812             && ((AlignViewportI) source).getCodingComplement() == this)
813     {
814       // ok to continue;
815     }
816     else
817     {
818       return;
819     }
820
821     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
822             getGapCharacter());
823     if (mappedCommand != null)
824     {
825       AlignmentI[] views = getAlignPanel().alignFrame.getViewAlignments();
826       mappedCommand.doCommand(views);
827       getAlignPanel().alignmentChanged();
828     }
829   }
830
831   /**
832    * Add the sequences from the given alignment to this viewport. Optionally,
833    * may give the user the option to open a new frame, or split panel, with cDNA
834    * and protein linked.
835    * 
836    * @param toAdd
837    * @param title
838    */
839   public void addAlignment(AlignmentI toAdd, String title)
840   {
841     // TODO: promote to AlignViewportI? applet CutAndPasteTransfer is different
842
843     // JBPComment: title is a largely redundant parameter at the moment
844     // JBPComment: this really should be an 'insert/pre/append' controller
845     // JBPComment: but the DNA/Protein check makes it a bit more complex
846
847     // refactored from FileLoader / CutAndPasteTransfer / SequenceFetcher with
848     // this comment:
849     // TODO: create undo object for this JAL-1101
850
851     /*
852      * Ensure datasets are created for the new alignment as
853      * mappings operate on dataset sequences
854      */
855     toAdd.setDataset(null);
856
857     /*
858      * Check if any added sequence could be the object of a mapping or
859      * cross-reference; if so, make the mapping explicit 
860      */
861     getAlignment().realiseMappings(toAdd.getSequences());
862
863     /*
864      * If any cDNA/protein mappings exist or can be made between the alignments, 
865      * offer to open a split frame with linked alignments
866      */
867     if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
868     {
869       if (AlignmentUtils.isMappable(toAdd, getAlignment()))
870       {
871         if (openLinkedAlignment(toAdd, title))
872         {
873           return;
874         }
875       }
876     }
877
878     /*
879      * No mappings, or offer declined - add sequences to this alignment
880      */
881     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
882     // provenance) should share the same dataset sequence
883
884     AlignmentI al = getAlignment();
885     String gap = String.valueOf(al.getGapCharacter());
886     for (int i = 0; i < toAdd.getHeight(); i++)
887     {
888       SequenceI seq = toAdd.getSequenceAt(i);
889       /*
890        * experimental!
891        * - 'align' any mapped sequences as per existing 
892        *    e.g. cdna to genome, domain hit to protein sequence
893        * very experimental! (need a separate menu option for this)
894        * - only add mapped sequences ('select targets from a dataset')
895        */
896       if (true /*AlignmentUtils.alignSequenceAs(seq, al, gap, true, true)*/)
897       {
898         al.addSequence(seq);
899       }
900     }
901
902     setEndSeq(getAlignment().getHeight());
903     firePropertyChange("alignment", null, getAlignment().getSequences());
904   }
905
906   /**
907    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
908    * alignment, either as a standalone alignment or in a split frame. Returns
909    * true if the new alignment was opened, false if not, because the user
910    * declined the offer.
911    * 
912    * @param al
913    * @param title
914    */
915   protected boolean openLinkedAlignment(AlignmentI al, String title)
916   {
917     String[] options = new String[] {
918         MessageManager.getString("action.no"),
919         MessageManager.getString("label.split_window"),
920         MessageManager.getString("label.new_window"), };
921     final String question = JvSwingUtils.wrapTooltip(true,
922             MessageManager.getString("label.open_split_window?"));
923     int response = JOptionPane.showOptionDialog(Desktop.desktop, question,
924             MessageManager.getString("label.open_split_window"),
925             JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
926             options, options[0]);
927
928     if (response != 1 && response != 2)
929     {
930       return false;
931     }
932     final boolean openSplitPane = (response == 1);
933     final boolean openInNewWindow = (response == 2);
934
935     /*
936      * Identify protein and dna alignments. Make a copy of this one if opening
937      * in a new split pane.
938      */
939     AlignmentI thisAlignment = openSplitPane ? new Alignment(getAlignment())
940             : getAlignment();
941     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
942     final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
943
944     /*
945      * Map sequences. At least one should get mapped as we have already passed
946      * the test for 'mappability'. Any mappings made will be added to the
947      * protein alignment. Note creating dataset sequences on the new alignment
948      * is a pre-requisite for building mappings.
949      */
950     al.setDataset(null);
951     AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna);
952
953     /*
954      * Create the AlignFrame for the added alignment. If it is protein, mappings
955      * are registered with StructureSelectionManager as a side-effect.
956      */
957     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
958             AlignFrame.DEFAULT_HEIGHT);
959     newAlignFrame.setTitle(title);
960     newAlignFrame.statusBar.setText(MessageManager.formatMessage(
961             "label.successfully_loaded_file", new Object[] { title }));
962
963     // TODO if we want this (e.g. to enable reload of the alignment from file),
964     // we will need to add parameters to the stack.
965     // if (!protocol.equals(AppletFormatAdapter.PASTE))
966     // {
967     // alignFrame.setFileName(file, format);
968     // }
969
970     if (openInNewWindow)
971     {
972       Desktop.addInternalFrame(newAlignFrame, title,
973               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
974     }
975
976     try
977     {
978       newAlignFrame.setMaximum(jalview.bin.Cache.getDefault(
979               "SHOW_FULLSCREEN", false));
980     } catch (java.beans.PropertyVetoException ex)
981     {
982     }
983
984     if (openSplitPane)
985     {
986       al.alignAs(thisAlignment);
987       protein = openSplitFrame(newAlignFrame, thisAlignment);
988     }
989
990     return true;
991   }
992
993   /**
994    * Helper method to open a new SplitFrame holding linked dna and protein
995    * alignments.
996    * 
997    * @param newAlignFrame
998    *          containing a new alignment to be shown
999    * @param complement
1000    *          cdna/protein complement alignment to show in the other split half
1001    * @return the protein alignment in the split frame
1002    */
1003   protected AlignmentI openSplitFrame(AlignFrame newAlignFrame,
1004           AlignmentI complement)
1005   {
1006     /*
1007      * Make a new frame with a copy of the alignment we are adding to. If this
1008      * is protein, the mappings to cDNA will be registered with
1009      * StructureSelectionManager as a side-effect.
1010      */
1011     AlignFrame copyMe = new AlignFrame(complement,
1012             AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
1013     copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
1014
1015     AlignmentI al = newAlignFrame.viewport.getAlignment();
1016     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
1017             : newAlignFrame;
1018     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame : copyMe;
1019     cdnaFrame.setVisible(true);
1020     proteinFrame.setVisible(true);
1021     String linkedTitle = MessageManager
1022             .getString("label.linked_view_title");
1023
1024     /*
1025      * Open in split pane. DNA sequence above, protein below.
1026      */
1027     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
1028     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
1029
1030     return proteinFrame.viewport.getAlignment();
1031   }
1032
1033   public AnnotationColumnChooser getAnnotationColumnSelectionState()
1034   {
1035     return annotationColumnSelectionState;
1036   }
1037
1038   public void setAnnotationColumnSelectionState(
1039           AnnotationColumnChooser currentAnnotationColumnSelectionState)
1040   {
1041     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
1042   }
1043
1044   @Override
1045   public void setIdWidth(int i)
1046   {
1047     super.setIdWidth(i);
1048     AlignmentPanel ap = getAlignPanel();
1049     if (ap != null)
1050     {
1051       // modify GUI elements to reflect geometry change
1052       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
1053               .getPreferredSize();
1054       idw.width = i;
1055       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
1056     }
1057   }
1058
1059   public Rectangle getExplodedGeometry()
1060   {
1061     return explodedGeometry;
1062   }
1063
1064   public void setExplodedGeometry(Rectangle explodedPosition)
1065   {
1066     this.explodedGeometry = explodedPosition;
1067   }
1068
1069   public boolean isGatherViewsHere()
1070   {
1071     return gatherViewsHere;
1072   }
1073
1074   public void setGatherViewsHere(boolean gatherViewsHere)
1075   {
1076     this.gatherViewsHere = gatherViewsHere;
1077   }
1078
1079   /**
1080    * If this viewport has a (Protein/cDNA) complement, then scroll the
1081    * complementary alignment to match this one.
1082    */
1083   public void scrollComplementaryAlignment()
1084   {
1085     /*
1086      * Populate a SearchResults object with the mapped location to scroll to. If
1087      * there is no complement, or it is not following highlights, or no mapping
1088      * is found, the result will be empty.
1089      */
1090     SearchResults sr = new SearchResults();
1091     int verticalOffset = findComplementScrollTarget(sr);
1092     if (!sr.isEmpty())
1093     {
1094       // TODO would like next line without cast but needs more refactoring...
1095       final AlignmentPanel complementPanel = ((AlignViewport) getCodingComplement())
1096               .getAlignPanel();
1097       complementPanel.setDontScrollComplement(true);
1098       complementPanel.scrollToCentre(sr, verticalOffset);
1099     }
1100   }
1101
1102   /**
1103    * Answers true if no alignment holds a reference to the given mapping
1104    * 
1105    * @param acf
1106    * @return
1107    */
1108   protected boolean noReferencesTo(AlignedCodonFrame acf)
1109   {
1110     AlignFrame[] frames = Desktop.getAlignFrames();
1111     if (frames == null)
1112     {
1113       return true;
1114     }
1115     for (AlignFrame af : frames)
1116     {
1117       if (!af.isClosed())
1118       {
1119         for (AlignmentViewPanel ap : af.getAlignPanels())
1120         {
1121           AlignmentI al = ap.getAlignment();
1122           if (al != null && al.getCodonFrames().contains(acf))
1123           {
1124             return false;
1125           }
1126         }
1127       }
1128     }
1129     return true;
1130   }
1131
1132   /**
1133    * Applies the supplied feature settings descriptor to currently known
1134    * features. This supports an 'initial configuration' of feature colouring
1135    * based on a preset or user favourite. This may then be modified in the usual
1136    * way using the Feature Settings dialogue.
1137    * 
1138    * @param featureSettings
1139    */
1140   public void applyFeaturesStyle(FeatureSettingsI featureSettings)
1141   {
1142     if (featureSettings == null)
1143     {
1144       return;
1145     }
1146
1147     FeatureRenderer fr = getAlignPanel().getSeqPanel().seqCanvas
1148             .getFeatureRenderer();
1149     Map<String, Object> featureColours = fr.getFeatureColours();
1150     fr.findAllFeatures(true);
1151     List<String> renderOrder = fr.getRenderOrder();
1152     FeaturesDisplayedI displayed = fr.getFeaturesDisplayed();
1153     displayed.clear();
1154     // TODO this clears displayed.featuresRegistered - do we care?
1155
1156     /*
1157      * set feature colour if specified by feature settings
1158      * set visibility of all features
1159      */
1160     for (String type : renderOrder)
1161     {
1162       FeatureColourI preferredColour = featureSettings
1163               .getFeatureColour(type);
1164       if (preferredColour != null)
1165       {
1166         fr.setColour(type, preferredColour);
1167       }
1168       if (featureSettings.isFeatureDisplayed(type))
1169       {
1170         displayed.setVisible(type);
1171       }
1172     }
1173
1174     /*
1175      * set visibility of feature groups
1176      */
1177     for (String group : fr.getFeatureGroups())
1178     {
1179       fr.setGroupVisibility(group, featureSettings.isGroupDisplayed(group));
1180     }
1181
1182     /*
1183      * order the features
1184      */
1185     if (featureSettings.optimiseOrder())
1186     {
1187       // TODO not supported (yet?)
1188     }
1189     else
1190     {
1191       fr.orderFeatures(featureSettings);
1192     }
1193     fr.setTransparency(featureSettings.getTransparency());
1194   }
1195
1196 }