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