JAL-2629 storage and lifecycle of alignment/group HMM annotations revised
[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   boolean validCharWidth;
98
99   public boolean followSelection = true;
100
101   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<>();
102
103   /**
104    * Creates a new AlignViewport object.
105    * 
106    * @param al
107    *          alignment to view
108    */
109   public AlignViewport(AlignmentI al)
110   {
111     super(al);
112     init();
113   }
114
115   /**
116    * Create a new AlignViewport object with a specific sequence set ID
117    * 
118    * @param al
119    * @param seqsetid
120    *          (may be null - but potential for ambiguous constructor exception)
121    */
122   public AlignViewport(AlignmentI al, String seqsetid)
123   {
124     this(al, seqsetid, null);
125   }
126
127   public AlignViewport(AlignmentI al, String seqsetid, String viewid)
128   {
129     super(al);
130     sequenceSetID = seqsetid;
131     viewId = viewid;
132     // TODO remove these once 2.4.VAMSAS release finished
133     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
134     {
135       Cache.log.debug(
136               "Setting viewport's sequence set id : " + sequenceSetID);
137     }
138     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
139     {
140       Cache.log.debug("Setting viewport's view id : " + viewId);
141     }
142     init();
143
144   }
145
146   /**
147    * Create a new AlignViewport with hidden regions
148    * 
149    * @param al
150    *          AlignmentI
151    * @param hiddenColumns
152    *          ColumnSelection
153    */
154   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns)
155   {
156     super(al);
157     if (hiddenColumns != null)
158     {
159       al.setHiddenColumns(hiddenColumns);
160     }
161     init();
162   }
163
164   /**
165    * New viewport with hidden columns and an existing sequence set id
166    * 
167    * @param al
168    * @param hiddenColumns
169    * @param seqsetid
170    *          (may be null)
171    */
172   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
173           String seqsetid)
174   {
175     this(al, hiddenColumns, seqsetid, null);
176   }
177
178   /**
179    * New viewport with hidden columns and an existing sequence set id and viewid
180    * 
181    * @param al
182    * @param hiddenColumns
183    * @param seqsetid
184    *          (may be null)
185    * @param viewid
186    *          (may be null)
187    */
188   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
189           String seqsetid, String viewid)
190   {
191     super(al);
192     sequenceSetID = seqsetid;
193     viewId = viewid;
194     // TODO remove these once 2.4.VAMSAS release finished
195     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
196     {
197       Cache.log.debug(
198               "Setting viewport's sequence set id : " + sequenceSetID);
199     }
200     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
201     {
202       Cache.log.debug("Setting viewport's view id : " + viewId);
203     }
204
205     if (hiddenColumns != null)
206     {
207       al.setHiddenColumns(hiddenColumns);
208     }
209     init();
210   }
211
212   /**
213    * Apply any settings saved in user preferences
214    */
215   private void applyViewProperties()
216   {
217     antiAlias = Cache.getDefault("ANTI_ALIAS", false);
218
219     viewStyle.setShowJVSuffix(Cache.getDefault("SHOW_JVSUFFIX", true));
220     setShowAnnotation(Cache.getDefault("SHOW_ANNOTATIONS", true));
221
222     setRightAlignIds(Cache.getDefault("RIGHT_ALIGN_IDS", false));
223     setCentreColumnLabels(Cache.getDefault("CENTRE_COLUMN_LABELS", false));
224     autoCalculateConsensus = Cache.getDefault("AUTO_CALC_CONSENSUS", true);
225
226     setPadGaps(Cache.getDefault("PAD_GAPS", true));
227     setShowNPFeats(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
228     setShowDBRefs(Cache.getDefault("SHOW_DBREFS_TOOLTIP", true));
229     viewStyle.setSeqNameItalics(Cache.getDefault("ID_ITALICS", true));
230     viewStyle.setWrapAlignment(Cache.getDefault("WRAP_ALIGNMENT", false));
231     viewStyle.setShowUnconserved(
232             Cache.getDefault("SHOW_UNCONSERVED", false));
233     sortByTree = Cache.getDefault("SORT_BY_TREE", false);
234     followSelection = Cache.getDefault("FOLLOW_SELECTIONS", true);
235     sortAnnotationsBy = SequenceAnnotationOrder
236             .valueOf(Cache.getDefault(Preferences.SORT_ANNOTATIONS,
237                     SequenceAnnotationOrder.NONE.name()));
238     showAutocalculatedAbove = Cache
239             .getDefault(Preferences.SHOW_AUTOCALC_ABOVE, false);
240     viewStyle.setScaleProteinAsCdna(
241             Cache.getDefault(Preferences.SCALE_PROTEIN_TO_CDNA, true));
242   }
243
244   void init()
245   {
246     applyViewProperties();
247
248     String fontName = Cache.getDefault("FONT_NAME", "SansSerif");
249     String fontStyle = Cache.getDefault("FONT_STYLE", Font.PLAIN + "");
250     String fontSize = Cache.getDefault("FONT_SIZE", "10");
251
252     int style = 0;
253
254     if (fontStyle.equals("bold"))
255     {
256       style = 1;
257     }
258     else if (fontStyle.equals("italic"))
259     {
260       style = 2;
261     }
262
263     setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
264
265     AlignmentI al = getAlignment();
266     al.setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(0));
267
268     // We must set conservation and consensus before setting colour,
269     // as Blosum and Clustal require this to be done
270     if (consensusProfiles == null && !isDataset)
271     {
272       if (!al.isNucleotide())
273       {
274         showConservation = Cache.getDefault("SHOW_CONSERVATION", true);
275         showQuality = Cache.getDefault("SHOW_QUALITY", true);
276         showGroupConservation = Cache.getDefault("SHOW_GROUP_CONSERVATION",
277                 false);
278       }
279       showConsensusHistogram = Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM",
280               true);
281       showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", false);
282       normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO",
283               false);
284       showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false);
285       showConsensus = Cache.getDefault("SHOW_IDENTITY", true);
286
287       showOccupancy = Cache.getDefault(Preferences.SHOW_OCCUPANCY, true);
288     }
289     initAutoAnnotation();
290     // initInformation();
291
292     String colourProperty = al.isNucleotide()
293             ? Preferences.DEFAULT_COLOUR_NUC
294             : Preferences.DEFAULT_COLOUR_PROT;
295     String schemeName = Cache.getProperty(colourProperty);
296     if (schemeName == null)
297     {
298       // only DEFAULT_COLOUR available in Jalview before 2.9
299       schemeName = Cache.getDefault(Preferences.DEFAULT_COLOUR,
300               ResidueColourScheme.NONE);
301     }
302     ColourSchemeI colourScheme = ColourSchemeProperty
303             .getColourScheme(al, schemeName);
304     residueShading = new ResidueShader(colourScheme);
305
306     if (colourScheme instanceof UserColourScheme)
307     {
308       residueShading = new ResidueShader(
309               UserDefinedColours.loadDefaultColours());
310       residueShading.setThreshold(0, isIgnoreGapsConsensus());
311     }
312
313     if (residueShading != null)
314     {
315       residueShading.setConsensus(consensusProfiles);
316     }
317   }
318
319   /**
320    * {@inheritDoc}
321    */
322   @Override
323   public void setFont(Font f, boolean setGrid)
324   {
325     font = f;
326
327     Container c = new Container();
328
329     if (setGrid)
330     {
331       FontMetrics fm = c.getFontMetrics(font);
332       int ww = fm.charWidth('M');
333       setCharHeight(fm.getHeight());
334       setCharWidth(ww);
335     }
336     viewStyle.setFontName(font.getName());
337     viewStyle.setFontStyle(font.getStyle());
338     viewStyle.setFontSize(font.getSize());
339
340     validCharWidth = true;
341   }
342
343   @Override
344   public void setViewStyle(ViewStyleI settingsForView)
345   {
346     super.setViewStyle(settingsForView);
347     setFont(new Font(viewStyle.getFontName(), viewStyle.getFontStyle(),
348             viewStyle.getFontSize()), false);
349   }
350
351   /**
352    * DOCUMENT ME!
353    * 
354    * @return DOCUMENT ME!
355    */
356   public Font getFont()
357   {
358     return font;
359   }
360
361   /**
362    * DOCUMENT ME!
363    * 
364    * @param align
365    *          DOCUMENT ME!
366    */
367   @Override
368   public void setAlignment(AlignmentI align)
369   {
370     replaceMappings(align);
371     super.setAlignment(align);
372   }
373
374   /**
375    * Replace any codon mappings for this viewport with those for the given
376    * viewport
377    * 
378    * @param align
379    */
380   public void replaceMappings(AlignmentI align)
381   {
382
383     /*
384      * Deregister current mappings (if any)
385      */
386     deregisterMappings();
387
388     /*
389      * Register new mappings (if any)
390      */
391     if (align != null)
392     {
393       StructureSelectionManager ssm = StructureSelectionManager
394               .getStructureSelectionManager(Desktop.instance);
395       ssm.registerMappings(align.getCodonFrames());
396     }
397
398     /*
399      * replace mappings on our alignment
400      */
401     if (getAlignment() != null && align != null)
402     {
403       getAlignment().setCodonFrames(align.getCodonFrames());
404     }
405   }
406
407   protected void deregisterMappings()
408   {
409     AlignmentI al = getAlignment();
410     if (al != null)
411     {
412       List<AlignedCodonFrame> mappings = al.getCodonFrames();
413       if (mappings != null)
414       {
415         StructureSelectionManager ssm = StructureSelectionManager
416                 .getStructureSelectionManager(Desktop.instance);
417         for (AlignedCodonFrame acf : mappings)
418         {
419           if (noReferencesTo(acf))
420           {
421             ssm.deregisterMapping(acf);
422           }
423         }
424       }
425     }
426   }
427
428   /**
429    * DOCUMENT ME!
430    * 
431    * @return DOCUMENT ME!
432    */
433   @Override
434   public char getGapCharacter()
435   {
436     return getAlignment().getGapCharacter();
437   }
438
439   /**
440    * DOCUMENT ME!
441    * 
442    * @param gap
443    *          DOCUMENT ME!
444    */
445   public void setGapCharacter(char gap)
446   {
447     if (getAlignment() != null)
448     {
449       getAlignment().setGapCharacter(gap);
450     }
451   }
452
453   /**
454    * returns the visible column regions of the alignment
455    * 
456    * @param selectedRegionOnly
457    *          true to just return the contigs intersecting with the selected
458    *          area
459    * @return
460    */
461   public int[] getViewAsVisibleContigs(boolean selectedRegionOnly)
462   {
463     int[] viscontigs = null;
464     int start = 0, end = 0;
465     if (selectedRegionOnly && selectionGroup != null)
466     {
467       start = selectionGroup.getStartRes();
468       end = selectionGroup.getEndRes() + 1;
469     }
470     else
471     {
472       end = getAlignment().getWidth();
473     }
474     viscontigs = getAlignment().getHiddenColumns().getVisibleContigs(start,
475             end);
476     return viscontigs;
477   }
478
479   /**
480    * get hash of undo and redo list for the alignment
481    * 
482    * @return long[] { historyList.hashCode, redoList.hashCode };
483    */
484   public long[] getUndoRedoHash()
485   {
486     // TODO: JAL-1126
487     if (historyList == null || redoList == null)
488     {
489       return new long[] { -1, -1 };
490     }
491     return new long[] { historyList.hashCode(), this.redoList.hashCode() };
492   }
493
494   /**
495    * test if a particular set of hashcodes are different to the hashcodes for
496    * the undo and redo list.
497    * 
498    * @param undoredo
499    *          the stored set of hashcodes as returned by getUndoRedoHash
500    * @return true if the hashcodes differ (ie the alignment has been edited) or
501    *         the stored hashcode array differs in size
502    */
503   public boolean isUndoRedoHashModified(long[] undoredo)
504   {
505     if (undoredo == null)
506     {
507       return true;
508     }
509     long[] cstate = getUndoRedoHash();
510     if (cstate.length != undoredo.length)
511     {
512       return true;
513     }
514
515     for (int i = 0; i < cstate.length; i++)
516     {
517       if (cstate[i] != undoredo[i])
518       {
519         return true;
520       }
521     }
522     return false;
523   }
524
525   /**
526    * @return true if view selection should always follow the selections
527    *         broadcast by other selection sources
528    */
529   public boolean getFollowSelection()
530   {
531     return followSelection;
532   }
533
534   /**
535    * Send the current selection to be broadcast to any selection listeners.
536    */
537   @Override
538   public void sendSelection()
539   {
540     jalview.structure.StructureSelectionManager
541             .getStructureSelectionManager(Desktop.instance)
542             .sendSelection(new SequenceGroup(getSelectionGroup()),
543                     new ColumnSelection(getColumnSelection()),
544                     new HiddenColumns(getAlignment().getHiddenColumns()),
545                     this);
546   }
547
548   /**
549    * return the alignPanel containing the given viewport. Use this to get the
550    * components currently handling the given viewport.
551    * 
552    * @param av
553    * @return null or an alignPanel guaranteed to have non-null alignFrame
554    *         reference
555    */
556   public AlignmentPanel getAlignPanel()
557   {
558     AlignmentPanel[] aps = PaintRefresher
559             .getAssociatedPanels(this.getSequenceSetId());
560     for (int p = 0; aps != null && p < aps.length; p++)
561     {
562       if (aps[p].av == this)
563       {
564         return aps[p];
565       }
566     }
567     return null;
568   }
569
570   public boolean getSortByTree()
571   {
572     return sortByTree;
573   }
574
575   public void setSortByTree(boolean sort)
576   {
577     sortByTree = sort;
578   }
579
580   /**
581    * Returns the (Desktop) instance of the StructureSelectionManager
582    */
583   @Override
584   public StructureSelectionManager getStructureSelectionManager()
585   {
586     return StructureSelectionManager
587             .getStructureSelectionManager(Desktop.instance);
588   }
589
590   /**
591    * 
592    * @param pdbEntries
593    * @return an array of SequenceI arrays, one for each PDBEntry, listing which
594    *         sequences in the alignment hold a reference to it
595    */
596   public SequenceI[][] collateForPDB(PDBEntry[] pdbEntries)
597   {
598     List<SequenceI[]> seqvectors = new ArrayList<>();
599     for (PDBEntry pdb : pdbEntries)
600     {
601       List<SequenceI> choosenSeqs = new ArrayList<>();
602       for (SequenceI sq : getAlignment().getSequences())
603       {
604         Vector<PDBEntry> pdbRefEntries = sq.getDatasetSequence()
605                 .getAllPDBEntries();
606         if (pdbRefEntries == null)
607         {
608           continue;
609         }
610         for (PDBEntry pdbRefEntry : pdbRefEntries)
611         {
612           if (pdbRefEntry.getId().equals(pdb.getId()))
613           {
614             if (pdbRefEntry.getChainCode() != null
615                     && pdb.getChainCode() != null)
616             {
617               if (pdbRefEntry.getChainCode().equalsIgnoreCase(
618                       pdb.getChainCode()) && !choosenSeqs.contains(sq))
619               {
620                 choosenSeqs.add(sq);
621                 continue;
622               }
623             }
624             else
625             {
626               if (!choosenSeqs.contains(sq))
627               {
628                 choosenSeqs.add(sq);
629                 continue;
630               }
631             }
632
633           }
634         }
635       }
636       seqvectors
637               .add(choosenSeqs.toArray(new SequenceI[choosenSeqs.size()]));
638     }
639     return seqvectors.toArray(new SequenceI[seqvectors.size()][]);
640   }
641
642   @Override
643   public boolean isNormaliseSequenceLogo()
644   {
645     return normaliseSequenceLogo;
646   }
647
648
649   public void setNormaliseSequenceLogo(boolean state)
650   {
651     normaliseSequenceLogo = state;
652   }
653
654   public void setNormaliseHMMSequenceLogo(boolean state)
655   {
656     normaliseHMMSequenceLogo = state;
657   }
658
659   /**
660    * 
661    * @return true if alignment characters should be displayed
662    */
663   @Override
664   public boolean isValidCharWidth()
665   {
666     return validCharWidth;
667   }
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 }