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