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