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