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