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