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