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