JAL-1681 create mappings before AlignFrame to ensure cDNA consensus
[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, true));
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 any cDNA/protein mappings can be made between the alignments, offer to
802      * open a linked alignment with split frame option.
803      */
804     if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, false))
805     {
806       if (AlignmentUtils.isMappable(al, getAlignment()))
807       {
808         if (openLinkedAlignment(al, title))
809         {
810           return;
811         }
812       }
813     }
814
815     /*
816      * No mappings, or offer declined - add sequences to this alignment
817      */
818     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
819     // provenance) should share the same dataset sequence
820
821     for (int i = 0; i < al.getHeight(); i++)
822     {
823       getAlignment().addSequence(al.getSequenceAt(i));
824     }
825
826     setEndSeq(getAlignment().getHeight());
827     firePropertyChange("alignment", null, getAlignment().getSequences());
828   }
829
830   /**
831    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
832    * alignment, either as a standalone alignment or in a split frame. Returns
833    * true if the new alignment was opened, false if not, because the user
834    * declined the offer.
835    * 
836    * @param al
837    * @param title
838    */
839   protected boolean openLinkedAlignment(AlignmentI al, String title)
840   {
841     String[] options = new String[]
842     { MessageManager.getString("action.no"),
843         MessageManager.getString("label.split_window"),
844         MessageManager.getString("label.new_window"), };
845     final String question = JvSwingUtils.wrapTooltip(true,
846             MessageManager.getString("label.open_split_window?"));
847     int response = JOptionPane.showOptionDialog(Desktop.desktop, question,
848             MessageManager.getString("label.open_split_window"),
849             JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
850             options, options[0]);
851
852     if (response != 1 && response != 2)
853     {
854       return false;
855     }
856     final boolean openSplitPane = (response == 1);
857     final boolean openInNewWindow = (response == 2);
858
859     /*
860      * Identify protein and dna alignments. Make a copy of this one if opening
861      * in a new split pane.
862      */
863     AlignmentI thisAlignment = openSplitPane ? new Alignment(getAlignment())
864             : getAlignment();
865     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
866     final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
867
868     /*
869      * Map sequences. At least one should get mapped as we have already passed
870      * the test for 'mappability'. Any mappings made will be added to the
871      * protein alignment. Note creating dataset sequences on the new alignment
872      * is a pre-requisite for building mappings.
873      */
874     al.setDataset(null);
875     AlignmentUtils.mapProteinToCdna(protein, cdna);
876
877     /*
878      * Create the AlignFrame for the added alignment. Note this will include the
879      * cDNA consensus annotation if it is protein (because the alignment holds
880      * mappings to nucleotide)
881      */
882     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
883             AlignFrame.DEFAULT_HEIGHT);
884     newAlignFrame.setTitle(title);
885     newAlignFrame.statusBar.setText(MessageManager.formatMessage(
886             "label.successfully_loaded_file", new Object[]
887             { title }));
888
889     // TODO if we want this (e.g. to enable reload of the alignment from file),
890     // we will need to add parameters to the stack.
891     // if (!protocol.equals(AppletFormatAdapter.PASTE))
892     // {
893     // alignFrame.setFileName(file, format);
894     // }
895
896     if (openInNewWindow)
897     {
898       Desktop.addInternalFrame(newAlignFrame, title,
899               AlignFrame.DEFAULT_WIDTH,
900               AlignFrame.DEFAULT_HEIGHT);
901     }
902
903     try
904     {
905       newAlignFrame.setMaximum(jalview.bin.Cache.getDefault(
906               "SHOW_FULLSCREEN",
907               false));
908     } catch (java.beans.PropertyVetoException ex)
909     {
910     }
911
912     if (openSplitPane)
913     {
914       protein = openSplitFrame(newAlignFrame, thisAlignment,
915               protein.getCodonFrames());
916     }
917
918     /*
919      * Register the mappings (held on the protein alignment) with the
920      * StructureSelectionManager (for mouseover linking).
921      */
922     final StructureSelectionManager ssm = StructureSelectionManager
923             .getStructureSelectionManager(Desktop.instance);
924     ssm.addMappings(protein.getCodonFrames());
925
926     return true;
927   }
928
929   /**
930    * Helper method to open a new SplitFrame holding linked dna and protein
931    * alignments.
932    * 
933    * @param newAlignFrame
934    *          containing a new alignment to be shown
935    * @param complement
936    *          cdna/protein complement alignment to show in the other split half
937    * @param mappings
938    * @return the protein alignment in the split frame
939    */
940   protected AlignmentI openSplitFrame(AlignFrame newAlignFrame,
941           AlignmentI complement, Set<AlignedCodonFrame> mappings)
942   {
943     /*
944      * Make a new frame with a copy of the alignment we are adding to. If this
945      * is protein, the new frame will have a cDNA consensus annotation row
946      * added.
947      */
948     AlignFrame copyMe = new AlignFrame(complement,
949             AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
950     copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
951
952     AlignmentI al = newAlignFrame.viewport.getAlignment();
953     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
954             : newAlignFrame;
955     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame
956             : copyMe;
957     AlignmentI protein = proteinFrame.viewport.getAlignment();
958     protein.setCodonFrames(mappings);
959
960     cdnaFrame.setVisible(true);
961     proteinFrame.setVisible(true);
962     String linkedTitle = MessageManager
963             .getString("label.linked_view_title");
964
965     /*
966      * Open in split pane. DNA sequence above, protein below.
967      */
968     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
969     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
970
971     return protein;
972   }
973
974   public AnnotationColumnChooser getAnnotationColumnSelectionState()
975   {
976     return annotationColumnSelectionState;
977   }
978
979   public void setAnnotationColumnSelectionState(
980           AnnotationColumnChooser currentAnnotationColumnSelectionState)
981   {
982     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
983   }
984
985   @Override
986   public void setIdWidth(int i)
987   {
988     super.setIdWidth(i);
989     AlignmentPanel ap = getAlignPanel();
990     if (ap != null)
991     {
992       // modify GUI elements to reflect geometry change
993       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
994               .getPreferredSize();
995       idw.width = i;
996       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
997     }
998   }
999
1000   public Rectangle getExplodedGeometry()
1001   {
1002     return explodedGeometry;
1003   }
1004
1005   public void setExplodedGeometry(Rectangle explodedPosition)
1006   {
1007     this.explodedGeometry = explodedPosition;
1008   }
1009
1010   public boolean isGatherViewsHere()
1011   {
1012     return gatherViewsHere;
1013   }
1014
1015   public void setGatherViewsHere(boolean gatherViewsHere)
1016   {
1017     this.gatherViewsHere = gatherViewsHere;
1018   }
1019
1020   /**
1021    * If this viewport has a (Protein/cDNA) complement, then scroll the
1022    * complementary alignment to match this one.
1023    */
1024   public void scrollComplementaryAlignment()
1025   {
1026     /*
1027      * Populate a SearchResults object with the mapped location to scroll to. If
1028      * there is no complement, or it is not following highlights, or no mapping
1029      * is found, the result will be empty.
1030      */
1031     SearchResults sr = new SearchResults();
1032     int seqOffset = findComplementScrollTarget(sr);
1033     if (!sr.isEmpty())
1034     {
1035       // TODO would like next line without cast but needs more refactoring...
1036       final AlignmentPanel complementPanel = ((AlignViewport) getCodingComplement()).getAlignPanel();
1037       complementPanel.setFollowingComplementScroll(true);
1038       complementPanel.scrollToCentre(sr, seqOffset);
1039     }
1040   }
1041 }