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