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