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