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