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