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