JAL-1622 code tidy (+Junit) of collateForPdb()
[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   String viewName;
103
104   /*
105    * Flag set true on the view that should 'gather' multiple views of the same
106    * sequence set id when a project is reloaded. Set false on all views when
107    * they are 'exploded' into separate windows. Set true on the current view
108    * when 'Gather' is performed, and also on the first tab when the first new
109    * view is created.
110    */
111   private boolean gatherViewsHere = false;
112
113   private AnnotationColumnChooser annotationColumnSelectionState;
114   /**
115    * Creates a new AlignViewport object.
116    * 
117    * @param al
118    *          alignment to view
119    */
120   public AlignViewport(AlignmentI al)
121   {
122     setAlignment(al);
123     init();
124   }
125
126   /**
127    * Create a new AlignViewport object with a specific sequence set ID
128    * 
129    * @param al
130    * @param seqsetid
131    *          (may be null - but potential for ambiguous constructor exception)
132    */
133   public AlignViewport(AlignmentI al, String seqsetid)
134   {
135     this(al, seqsetid, null);
136   }
137
138   public AlignViewport(AlignmentI al, String seqsetid, String viewid)
139   {
140     sequenceSetID = seqsetid;
141     viewId = viewid;
142     // TODO remove these once 2.4.VAMSAS release finished
143     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
144     {
145       Cache.log.debug("Setting viewport's sequence set id : "
146               + sequenceSetID);
147     }
148     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
149     {
150       Cache.log.debug("Setting viewport's view id : " + viewId);
151     }
152     setAlignment(al);
153     init();
154   }
155
156   /**
157    * Create a new AlignViewport with hidden regions
158    * 
159    * @param al
160    *          AlignmentI
161    * @param hiddenColumns
162    *          ColumnSelection
163    */
164   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns)
165   {
166     setAlignment(al);
167     if (hiddenColumns != null)
168     {
169       colSel = hiddenColumns;
170     }
171     init();
172   }
173
174   /**
175    * New viewport with hidden columns and an existing sequence set id
176    * 
177    * @param al
178    * @param hiddenColumns
179    * @param seqsetid
180    *          (may be null)
181    */
182   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns,
183           String seqsetid)
184   {
185     this(al, hiddenColumns, seqsetid, null);
186   }
187
188   /**
189    * New viewport with hidden columns and an existing sequence set id and viewid
190    * 
191    * @param al
192    * @param hiddenColumns
193    * @param seqsetid
194    *          (may be null)
195    * @param viewid
196    *          (may be null)
197    */
198   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns,
199           String seqsetid, String viewid)
200   {
201     sequenceSetID = seqsetid;
202     viewId = viewid;
203     // TODO remove these once 2.4.VAMSAS release finished
204     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
205     {
206       Cache.log.debug("Setting viewport's sequence set id : "
207               + sequenceSetID);
208     }
209     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
210     {
211       Cache.log.debug("Setting viewport's view id : " + viewId);
212     }
213     setAlignment(al);
214     if (hiddenColumns != null)
215     {
216       colSel = hiddenColumns;
217     }
218     init();
219   }
220
221   /**
222    * Apply any settings saved in user preferences
223    */
224   private void applyViewProperties()
225   {
226     antiAlias = Cache.getDefault("ANTI_ALIAS", false);
227
228     viewStyle.setShowJVSuffix(Cache.getDefault("SHOW_JVSUFFIX", true));
229     setShowAnnotation(Cache.getDefault("SHOW_ANNOTATIONS", true));
230
231     setRightAlignIds(Cache.getDefault("RIGHT_ALIGN_IDS", false));
232     setCentreColumnLabels(Cache.getDefault("CENTRE_COLUMN_LABELS", false));
233     autoCalculateConsensus = Cache.getDefault("AUTO_CALC_CONSENSUS", true);
234
235     setPadGaps(Cache.getDefault("PAD_GAPS", true));
236     setShowNPFeats(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
237     setShowDBRefs(Cache.getDefault("SHOW_DBREFS_TOOLTIP", true));
238     viewStyle.setSeqNameItalics(Cache.getDefault("ID_ITALICS", true));
239     viewStyle.setWrapAlignment(Cache.getDefault("WRAP_ALIGNMENT", false));
240     viewStyle.setShowUnconserved(Cache
241             .getDefault("SHOW_UNCONSERVED", false));
242     sortByTree = Cache.getDefault("SORT_BY_TREE", false);
243     followSelection = Cache.getDefault("FOLLOW_SELECTIONS", true);
244     sortAnnotationsBy = SequenceAnnotationOrder.valueOf(Cache.getDefault(
245             Preferences.SORT_ANNOTATIONS,
246             SequenceAnnotationOrder.NONE.name()));
247     showAutocalculatedAbove = Cache.getDefault(
248             Preferences.SHOW_AUTOCALC_ABOVE, false);
249     viewStyle.setScaleProteinAsCdna(Cache.getDefault(
250             Preferences.SCALE_PROTEIN_TO_CDNA, true));
251   }
252
253   void init()
254   {
255     this.startRes = 0;
256     this.endRes = alignment.getWidth() - 1;
257     this.startSeq = 0;
258     this.endSeq = alignment.getHeight() - 1;
259     applyViewProperties();
260
261     String fontName = Cache.getDefault("FONT_NAME", "SansSerif");
262     String fontStyle = Cache.getDefault("FONT_STYLE", Font.PLAIN + "");
263     String fontSize = Cache.getDefault("FONT_SIZE", "10");
264
265     int style = 0;
266
267     if (fontStyle.equals("bold"))
268     {
269       style = 1;
270     }
271     else if (fontStyle.equals("italic"))
272     {
273       style = 2;
274     }
275
276     setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
277
278     alignment
279             .setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(0));
280
281     // We must set conservation and consensus before setting colour,
282     // as Blosum and Clustal require this to be done
283     if (hconsensus == null && !isDataset)
284     {
285       if (!alignment.isNucleotide())
286       {
287         showConservation = Cache.getDefault("SHOW_CONSERVATION", true);
288         showQuality = Cache.getDefault("SHOW_QUALITY", true);
289         showGroupConservation = Cache.getDefault("SHOW_GROUP_CONSERVATION",
290                 false);
291       }
292       showConsensusHistogram = Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM",
293               true);
294       showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", false);
295       normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO",
296               false);
297       showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false);
298       showConsensus = Cache.getDefault("SHOW_IDENTITY", true);
299     }
300     initAutoAnnotation();
301     String colourProperty = alignment.isNucleotide() ? Preferences.DEFAULT_COLOUR_NUC
302             : Preferences.DEFAULT_COLOUR_PROT;
303     String propertyValue = Cache.getProperty(colourProperty);
304     if (propertyValue == null)
305     {
306       // fall back on this property for backwards compatibility
307       propertyValue = Cache.getProperty(Preferences.DEFAULT_COLOUR);
308     }
309     if (propertyValue != null)
310     {
311       globalColourScheme = ColourSchemeProperty.getColour(alignment,
312               propertyValue);
313
314       if (globalColourScheme instanceof UserColourScheme)
315       {
316         globalColourScheme = UserDefinedColours.loadDefaultColours();
317         ((UserColourScheme) globalColourScheme).setThreshold(0,
318                 isIgnoreGapsConsensus());
319       }
320
321       if (globalColourScheme != null)
322       {
323         globalColourScheme.setConsensus(hconsensus);
324       }
325     }
326   }
327
328   /**
329    * get the consensus sequence as displayed under the PID consensus annotation
330    * row.
331    * 
332    * @return consensus sequence as a new sequence object
333    */
334   public SequenceI getConsensusSeq()
335   {
336     if (consensus == null)
337     {
338       updateConsensus(null);
339     }
340     if (consensus == null)
341     {
342       return null;
343     }
344     StringBuffer seqs = new StringBuffer();
345     for (int i = 0; i < consensus.annotations.length; i++)
346     {
347       if (consensus.annotations[i] != null)
348       {
349         if (consensus.annotations[i].description.charAt(0) == '[')
350         {
351           seqs.append(consensus.annotations[i].description.charAt(1));
352         }
353         else
354         {
355           seqs.append(consensus.annotations[i].displayCharacter);
356         }
357       }
358     }
359
360     SequenceI sq = new Sequence("Consensus", seqs.toString());
361     sq.setDescription("Percentage Identity Consensus "
362             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
363     return sq;
364   }
365
366   boolean validCharWidth;
367
368   /**
369    * update view settings with the given font. You may need to call
370    * alignPanel.fontChanged to update the layout geometry
371    * 
372    * @param setGrid
373    *          when true, charWidth/height is set according to font mentrics
374    */
375   public void setFont(Font f, boolean setGrid)
376   {
377     font = f;
378
379     Container c = new Container();
380
381     java.awt.FontMetrics fm = c.getFontMetrics(font);
382     int w = viewStyle.getCharWidth(), ww = fm.charWidth('M'), h = viewStyle
383             .getCharHeight();
384     if (setGrid)
385     {
386       setCharHeight(fm.getHeight());
387       setCharWidth(ww);
388     }
389     viewStyle.setFontName(font.getName());
390     viewStyle.setFontStyle(font.getStyle());
391     viewStyle.setFontSize(font.getSize());
392
393     validCharWidth = true;
394   }
395
396   @Override
397   public void setViewStyle(ViewStyleI settingsForView)
398   {
399     super.setViewStyle(settingsForView);
400     setFont(new Font(viewStyle.getFontName(), viewStyle.getFontStyle(),
401             viewStyle.getFontSize()), false);
402
403   }
404   /**
405    * DOCUMENT ME!
406    * 
407    * @return DOCUMENT ME!
408    */
409   public Font getFont()
410   {
411     return font;
412   }
413
414   /**
415    * DOCUMENT ME!
416    * 
417    * @param align
418    *          DOCUMENT ME!
419    */
420   public void setAlignment(AlignmentI align)
421   {
422     if (alignment != null && alignment.getCodonFrames() != null)
423     {
424       StructureSelectionManager.getStructureSelectionManager(
425               Desktop.instance).removeMappings(alignment.getCodonFrames());
426     }
427     this.alignment = align;
428     if (alignment != null && alignment.getCodonFrames() != null)
429     {
430       StructureSelectionManager.getStructureSelectionManager(
431               Desktop.instance).addMappings(alignment.getCodonFrames());
432     }
433   }
434
435   /**
436    * DOCUMENT ME!
437    * 
438    * @return DOCUMENT ME!
439    */
440   public char getGapCharacter()
441   {
442     return getAlignment().getGapCharacter();
443   }
444
445   /**
446    * DOCUMENT ME!
447    * 
448    * @param gap
449    *          DOCUMENT ME!
450    */
451   public void setGapCharacter(char gap)
452   {
453     if (getAlignment() != null)
454     {
455       getAlignment().setGapCharacter(gap);
456     }
457   }
458
459   /**
460    * DOCUMENT ME!
461    * 
462    * @return DOCUMENT ME!
463    */
464   public ColumnSelection getColumnSelection()
465   {
466     return colSel;
467   }
468
469   /**
470    * DOCUMENT ME!
471    * 
472    * @param tree
473    *          DOCUMENT ME!
474    */
475   public void setCurrentTree(NJTree tree)
476   {
477     currentTree = tree;
478   }
479
480   /**
481    * DOCUMENT ME!
482    * 
483    * @return DOCUMENT ME!
484    */
485   public NJTree getCurrentTree()
486   {
487     return currentTree;
488   }
489
490   /**
491    * returns the visible column regions of the alignment
492    * 
493    * @param selectedRegionOnly
494    *          true to just return the contigs intersecting with the selected
495    *          area
496    * @return
497    */
498   public int[] getViewAsVisibleContigs(boolean selectedRegionOnly)
499   {
500     int[] viscontigs = null;
501     int start = 0, end = 0;
502     if (selectedRegionOnly && selectionGroup != null)
503     {
504       start = selectionGroup.getStartRes();
505       end = selectionGroup.getEndRes() + 1;
506     }
507     else
508     {
509       end = alignment.getWidth();
510     }
511     viscontigs = colSel.getVisibleContigs(start, end);
512     return viscontigs;
513   }
514
515   /**
516    * get hash of undo and redo list for the alignment
517    * 
518    * @return long[] { historyList.hashCode, redoList.hashCode };
519    */
520   public long[] getUndoRedoHash()
521   {
522     // TODO: JAL-1126
523     if (historyList == null || redoList == null)
524     {
525       return new long[]
526       { -1, -1 };
527     }
528     return new long[]
529     { historyList.hashCode(), this.redoList.hashCode() };
530   }
531
532   /**
533    * test if a particular set of hashcodes are different to the hashcodes for
534    * the undo and redo list.
535    * 
536    * @param undoredo
537    *          the stored set of hashcodes as returned by getUndoRedoHash
538    * @return true if the hashcodes differ (ie the alignment has been edited) or
539    *         the stored hashcode array differs in size
540    */
541   public boolean isUndoRedoHashModified(long[] undoredo)
542   {
543     if (undoredo == null)
544     {
545       return true;
546     }
547     long[] cstate = getUndoRedoHash();
548     if (cstate.length != undoredo.length)
549     {
550       return true;
551     }
552
553     for (int i = 0; i < cstate.length; i++)
554     {
555       if (cstate[i] != undoredo[i])
556       {
557         return true;
558       }
559     }
560     return false;
561   }
562
563   public boolean followSelection = true;
564
565   /**
566    * @return true if view selection should always follow the selections
567    *         broadcast by other selection sources
568    */
569   public boolean getFollowSelection()
570   {
571     return followSelection;
572   }
573
574   /**
575    * Send the current selection to be broadcast to any selection listeners.
576    */
577   public void sendSelection()
578   {
579     jalview.structure.StructureSelectionManager
580             .getStructureSelectionManager(Desktop.instance).sendSelection(
581                     new SequenceGroup(getSelectionGroup()),
582                     new ColumnSelection(getColumnSelection()), this);
583   }
584
585   /**
586    * return the alignPanel containing the given viewport. Use this to get the
587    * components currently handling the given viewport.
588    * 
589    * @param av
590    * @return null or an alignPanel guaranteed to have non-null alignFrame
591    *         reference
592    */
593   public AlignmentPanel getAlignPanel()
594   {
595     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(this
596             .getSequenceSetId());
597     for (int p = 0; aps != null && p < aps.length; p++)
598     {
599       if (aps[p].av == this)
600       {
601         return aps[p];
602       }
603     }
604     return null;
605   }
606
607   public boolean getSortByTree()
608   {
609     return sortByTree;
610   }
611
612   public void setSortByTree(boolean sort)
613   {
614     sortByTree = sort;
615   }
616
617   /**
618    * synthesize a column selection if none exists so it covers the given
619    * selection group. if wholewidth is false, no column selection is made if the
620    * selection group covers the whole alignment width.
621    * 
622    * @param sg
623    * @param wholewidth
624    */
625   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
626   {
627     int sgs, sge;
628     if (sg != null
629             && (sgs = sg.getStartRes()) >= 0
630             && sg.getStartRes() <= (sge = sg.getEndRes())
631             && (colSel == null || colSel.getSelected() == null || colSel
632                     .getSelected().size() == 0))
633     {
634       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
635       {
636         // do nothing
637         return;
638       }
639       if (colSel == null)
640       {
641         colSel = new ColumnSelection();
642       }
643       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
644       {
645         colSel.addElement(cspos);
646       }
647     }
648   }
649
650   /**
651    * Returns the (Desktop) instance of the StructureSelectionManager
652    */
653   @Override
654   public StructureSelectionManager getStructureSelectionManager()
655   {
656     return StructureSelectionManager
657             .getStructureSelectionManager(Desktop.instance);
658   }
659
660   /**
661    * 
662    * @param pdbEntries
663    * @return an array of SequenceI arrays, one for each PDBEntry, listing which
664    *         sequences in the alignment hold a reference to it
665    */
666   public SequenceI[][] collateForPDB(PDBEntry[] pdbEntries)
667   {
668     List<SequenceI[]> seqvectors = new ArrayList<SequenceI[]>();
669     for (PDBEntry pdb : pdbEntries)
670     {
671       List<SequenceI> seqs = new ArrayList<SequenceI>();
672       for (SequenceI sq : alignment.getSequences())
673       {
674         Vector<PDBEntry> pdbs = sq
675                 .getDatasetSequence().getPDBId();
676         if (pdbs == null)
677         {
678           continue;
679         }
680         for (PDBEntry p1 : pdbs)
681         {
682           if (p1.getId().equals(pdb.getId()))
683           {
684             if (!seqs.contains(sq))
685             {
686               seqs.add(sq);
687               continue;
688             }
689           }
690         }
691       }
692       seqvectors.add(seqs.toArray(new SequenceI[seqs.size()]));
693     }
694     return seqvectors.toArray(new SequenceI[seqvectors.size()][]);
695   }
696
697   public boolean isNormaliseSequenceLogo()
698   {
699     return normaliseSequenceLogo;
700   }
701
702   public void setNormaliseSequenceLogo(boolean state)
703   {
704     normaliseSequenceLogo = state;
705   }
706
707   /**
708    * 
709    * @return true if alignment characters should be displayed
710    */
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 al
787    * @param title
788    */
789   public void addAlignment(AlignmentI al, 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      * If any cDNA/protein mappings can be made between the alignments, offer to
803      * open a linked alignment with split frame option.
804      */
805     if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, false))
806     {
807       if (AlignmentUtils.isMappable(al, getAlignment()))
808       {
809         if (openLinkedAlignment(al, title))
810         {
811           return;
812         }
813       }
814     }
815
816     /*
817      * No mappings, or offer declined - add sequences to this alignment
818      */
819     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
820     // provenance) should share the same dataset sequence
821
822     for (int i = 0; i < al.getHeight(); i++)
823     {
824       getAlignment().addSequence(al.getSequenceAt(i));
825     }
826
827     setEndSeq(getAlignment().getHeight());
828     firePropertyChange("alignment", null, getAlignment().getSequences());
829   }
830
831   /**
832    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
833    * alignment, either as a standalone alignment or in a split frame. Returns
834    * true if the new alignment was opened, false if not, because the user
835    * declined the offer.
836    * 
837    * @param al
838    * @param title
839    */
840   protected boolean openLinkedAlignment(AlignmentI al, String title)
841   {
842     String[] options = new String[]
843     { MessageManager.getString("action.no"),
844         MessageManager.getString("label.split_window"),
845         MessageManager.getString("label.new_window"), };
846     final String question = JvSwingUtils.wrapTooltip(true,
847             MessageManager.getString("label.open_split_window?"));
848     int response = JOptionPane.showOptionDialog(Desktop.desktop, question,
849             MessageManager.getString("label.open_split_window"),
850             JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
851             options, options[0]);
852
853     if (response != 1 && response != 2)
854     {
855       return false;
856     }
857     final boolean openSplitPane = (response == 1);
858     final boolean openInNewWindow = (response == 2);
859
860     /*
861      * Identify protein and dna alignments. Make a copy of this one if opening
862      * in a new split pane.
863      */
864     AlignmentI thisAlignment = openSplitPane ? new Alignment(getAlignment())
865             : getAlignment();
866     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
867     final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
868
869     /*
870      * Map sequences. At least one should get mapped as we have already passed
871      * the test for 'mappability'. Any mappings made will be added to the
872      * protein alignment. Note creating dataset sequences on the new alignment
873      * is a pre-requisite for building mappings.
874      */
875     al.setDataset(null);
876     AlignmentUtils.mapProteinToCdna(protein, cdna);
877
878     /*
879      * Create the AlignFrame for the added alignment. Note this will include the
880      * cDNA consensus annotation if it is protein (because the alignment holds
881      * mappings to nucleotide)
882      */
883     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
884             AlignFrame.DEFAULT_HEIGHT);
885     newAlignFrame.setTitle(title);
886     newAlignFrame.statusBar.setText(MessageManager.formatMessage(
887             "label.successfully_loaded_file", new Object[]
888             { title }));
889
890     // TODO if we want this (e.g. to enable reload of the alignment from file),
891     // we will need to add parameters to the stack.
892     // if (!protocol.equals(AppletFormatAdapter.PASTE))
893     // {
894     // alignFrame.setFileName(file, format);
895     // }
896
897     if (openInNewWindow)
898     {
899       Desktop.addInternalFrame(newAlignFrame, title,
900               AlignFrame.DEFAULT_WIDTH,
901               AlignFrame.DEFAULT_HEIGHT);
902     }
903
904     try
905     {
906       newAlignFrame.setMaximum(jalview.bin.Cache.getDefault(
907               "SHOW_FULLSCREEN",
908               false));
909     } catch (java.beans.PropertyVetoException ex)
910     {
911     }
912
913     if (openSplitPane)
914     {
915       protein = openSplitFrame(newAlignFrame, thisAlignment,
916               protein.getCodonFrames());
917     }
918
919     /*
920      * Register the mappings (held on the protein alignment) with the
921      * StructureSelectionManager (for mouseover linking).
922      */
923     final StructureSelectionManager ssm = StructureSelectionManager
924             .getStructureSelectionManager(Desktop.instance);
925     ssm.addMappings(protein.getCodonFrames());
926
927     return true;
928   }
929
930   /**
931    * Helper method to open a new SplitFrame holding linked dna and protein
932    * alignments.
933    * 
934    * @param newAlignFrame
935    *          containing a new alignment to be shown
936    * @param complement
937    *          cdna/protein complement alignment to show in the other split half
938    * @param mappings
939    * @return the protein alignment in the split frame
940    */
941   protected AlignmentI openSplitFrame(AlignFrame newAlignFrame,
942           AlignmentI complement, Set<AlignedCodonFrame> mappings)
943   {
944     /*
945      * Make a new frame with a copy of the alignment we are adding to. If this
946      * is protein, the new frame will have a cDNA consensus annotation row
947      * added.
948      */
949     AlignFrame copyMe = new AlignFrame(complement,
950             AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
951     copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
952
953     AlignmentI al = newAlignFrame.viewport.getAlignment();
954     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
955             : newAlignFrame;
956     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame
957             : copyMe;
958     AlignmentI protein = proteinFrame.viewport.getAlignment();
959     protein.setCodonFrames(mappings);
960
961     cdnaFrame.setVisible(true);
962     proteinFrame.setVisible(true);
963     String linkedTitle = MessageManager
964             .getString("label.linked_view_title");
965
966     /*
967      * Open in split pane. DNA sequence above, protein below.
968      */
969     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
970     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
971
972     return protein;
973   }
974
975   public AnnotationColumnChooser getAnnotationColumnSelectionState()
976   {
977     return annotationColumnSelectionState;
978   }
979
980   public void setAnnotationColumnSelectionState(
981           AnnotationColumnChooser currentAnnotationColumnSelectionState)
982   {
983     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
984   }
985
986   @Override
987   public void setIdWidth(int i)
988   {
989     super.setIdWidth(i);
990     AlignmentPanel ap = getAlignPanel();
991     if (ap != null)
992     {
993       // modify GUI elements to reflect geometry change
994       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
995               .getPreferredSize();
996       idw.width = i;
997       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
998     }
999   }
1000
1001   public Rectangle getExplodedGeometry()
1002   {
1003     return explodedGeometry;
1004   }
1005
1006   public void setExplodedGeometry(Rectangle explodedPosition)
1007   {
1008     this.explodedGeometry = explodedPosition;
1009   }
1010
1011   public boolean isGatherViewsHere()
1012   {
1013     return gatherViewsHere;
1014   }
1015
1016   public void setGatherViewsHere(boolean gatherViewsHere)
1017   {
1018     this.gatherViewsHere = gatherViewsHere;
1019   }
1020
1021   /**
1022    * If this viewport has a (Protein/cDNA) complement, then scroll the
1023    * complementary alignment to match this one.
1024    */
1025   public void scrollComplementaryAlignment()
1026   {
1027     /*
1028      * Populate a SearchResults object with the mapped location to scroll to. If
1029      * there is no complement, or it is not following highlights, or no mapping
1030      * is found, the result will be empty.
1031      */
1032     SearchResults sr = new SearchResults();
1033     int seqOffset = findComplementScrollTarget(sr);
1034     if (!sr.isEmpty())
1035     {
1036       // TODO would like next line without cast but needs more refactoring...
1037       final AlignmentPanel complementPanel = ((AlignViewport) getCodingComplement()).getAlignPanel();
1038       complementPanel.setFollowingComplementScroll(true);
1039       complementPanel.scrollToCentre(sr, seqOffset);
1040     }
1041   }
1042
1043   @Override
1044   public FeatureRenderer getFeatureRenderer()
1045   {
1046     return featureRenderer;
1047   }
1048
1049   @Override
1050   public void setFeatureRenderer(FeatureRenderer featureRenderer)
1051   {
1052     this.featureRenderer = featureRenderer;
1053   }
1054 }