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