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