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