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