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