JAL-4366 JAL-728 simple hack to use 3di matrix when gecos-3di is enabled
[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.FlowLayout;
26 import java.awt.Font;
27 import java.awt.FontMetrics;
28 import java.awt.Rectangle;
29 import java.io.File;
30 import java.util.ArrayList;
31 import java.util.Hashtable;
32 import java.util.List;
33
34 import javax.swing.JInternalFrame;
35
36 import jalview.analysis.AlignmentUtils;
37 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
38 import jalview.api.AlignViewportI;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.api.FeatureColourI;
41 import jalview.api.FeatureSettingsModelI;
42 import jalview.api.FeaturesDisplayedI;
43 import jalview.api.ViewStyleI;
44 import jalview.bin.Cache;
45 import jalview.bin.Console;
46 import jalview.commands.CommandI;
47 import jalview.datamodel.AlignedCodonFrame;
48 import jalview.datamodel.Alignment;
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                 + "(update new alignment)",
801         MessageManager.getString("label.new_window"),
802         MessageManager.getString(
803                 "label.split_window") + "(update this alignment)",
804         MessageManager.getString(
805                 "label.split_window") + "(leave both unchanged)" };
806     final String question = JvSwingUtils.wrapTooltip(true,
807             MessageManager.getString("label.open_split_window?"));
808     final AlignViewport us = this;
809
810     /*
811      * options No, Split Window, New Window correspond to
812      * dialog responses 0, 1, 2 (even though JOptionPane shows them
813      * in reverse order)
814      */
815     JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop)
816             .setResponseHandler(0, () -> {
817               addDataToAlignment(al);
818             }).setResponseHandler(1, () -> {
819               us.openLinkedAlignmentAs(al, title, true, 1);
820             }).setResponseHandler(2, () -> {
821               us.openLinkedAlignmentAs(al, title, false, 1);
822             }).setResponseHandler(3, () -> {
823               us.openLinkedAlignmentAs(al, title, true, 2);
824             }).setResponseHandler(4, () -> {
825               us.openLinkedAlignmentAs(al, title, true, 0);
826             });
827     dialog.setLayout(new FlowLayout(FlowLayout.CENTER));
828     dialog.setPreferredSize(new Dimension(350,300));
829     dialog.showDialog(question,
830             MessageManager.getString("label.open_split_window"),
831             JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
832             options, options[0]);
833   }
834
835   /**
836    * link given alignment to the alignment in this viewport and open
837    * @param al - alignment containing sequences to link to this alignment
838    * @param title
839    * @param newWindowOrSplitPane
840    * @param alignAs TODO
841    * @param alignAs - 0 - don't modify either alignment, 1 - align al according to us, 2- align us according to al
842    * @return alignFrame holding al
843    */
844   protected AlignFrame openLinkedAlignmentAs(AlignmentI al, String title,
845           boolean newWindowOrSplitPane, int alignAs)
846   {
847     /*
848      * Identify protein and dna alignments. Make a copy of this one if opening
849      * in a new split pane.
850      */
851     AlignmentI thisAlignment = newWindowOrSplitPane
852             ? new Alignment(getAlignment())
853             : getAlignment();
854     
855     
856     if (!al.isNucleotide() && !thisAlignment.isNucleotide())
857     {
858       // link AA to 3di or other kind of 'alternative' 1:1 mapping alignment
859       if (al.getDataset()==null)
860       {
861         al.setDataset(thisAlignment.getDataset());
862       }
863       AlignmentUtils.map3diPeptideToProteinAligment(thisAlignment,al);
864       if (thisAlignment.getCodonFrames().isEmpty()) {thisAlignment.getCodonFrames().addAll(al.getCodonFrames()); }
865       else {al.getCodonFrames().addAll(thisAlignment.getCodonFrames()); };
866
867
868     }
869     else
870     {
871       // shouldn't we be merging dataset here ?
872       // always create dataset for imported alignment before doing anything else..
873         al.setDataset(null);
874         // link CODON triplets to Protein
875       AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
876       final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
877
878       /*
879        * Map sequences. At least one should get mapped as we have already passed
880        * the test for 'mappability'. Any mappings made will be added to the
881        * protein alignment. Note creating dataset sequences on the new alignment
882        * is a pre-requisite for building mappings.
883        */
884       AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna);
885     }
886     
887     /*
888      * Create the AlignFrame for the added alignment. If it is protein, mappings
889      * are registered with StructureSelectionManager as a side-effect.
890      */
891     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
892             AlignFrame.DEFAULT_HEIGHT);
893     newAlignFrame.setTitle(title);
894     newAlignFrame.setStatus(MessageManager
895             .formatMessage("label.successfully_loaded_file", new Object[]
896             { title }));
897
898     // TODO if we want this (e.g. to enable reload of the alignment from file),
899     // we will need to add parameters to the stack.
900     // if (!protocol.equals(DataSourceType.PASTE))
901     // {
902     // alignFrame.setFileName(file, format);
903     // }
904
905     if (!newWindowOrSplitPane)
906     {
907       Desktop.addInternalFrame(newAlignFrame, title,
908               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
909     }
910
911     try
912     {
913       newAlignFrame.setMaximum(Cache.getDefault("SHOW_FULLSCREEN", false));
914     } catch (java.beans.PropertyVetoException ex)
915     {
916     }
917
918     if (newWindowOrSplitPane)
919     {
920       if (alignAs==1) {
921         al.alignAs(thisAlignment);
922       }
923       if (alignAs==2) {
924         thisAlignment.alignAs(al);
925       }
926       AlignmentI mapped = openSplitFrame(newAlignFrame, thisAlignment);
927     }
928     return newAlignFrame;
929   }
930
931   /**
932    * Helper method to open a new SplitFrame holding linked dna and protein
933    * alignments.
934    * 
935    * @param newAlignFrame
936    *          containing a new alignment to be shown
937    * @param complement
938    *          cdna/protein complement alignment to show in the other split half
939    * @return the protein alignment in the split frame
940    */
941   protected AlignmentI openSplitFrame(AlignFrame newAlignFrame,
942           AlignmentI complement)
943   {
944     /*
945      * Make a new frame with a copy of the alignment we are adding to. If this
946      * is protein, the mappings to cDNA will be registered with
947      * StructureSelectionManager as a side-effect.
948      */
949     AlignFrame copyMe = new AlignFrame(complement, AlignFrame.DEFAULT_WIDTH,
950             AlignFrame.DEFAULT_HEIGHT);
951     copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
952
953     AlignmentI al = newAlignFrame.viewport.getAlignment();
954     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
955             : newAlignFrame;
956     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame : copyMe;
957     cdnaFrame.setVisible(true);
958     proteinFrame.setVisible(true);
959     String linkedTitle = MessageManager
960             .getString("label.linked_view_title");
961
962     /*
963      * Open in split pane. DNA sequence above, protein below.
964      */
965     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
966     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
967
968     return proteinFrame.viewport.getAlignment();
969   }
970
971   public AnnotationColumnChooser getAnnotationColumnSelectionState()
972   {
973     return annotationColumnSelectionState;
974   }
975
976   public void setAnnotationColumnSelectionState(
977           AnnotationColumnChooser currentAnnotationColumnSelectionState)
978   {
979     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
980   }
981
982   @Override
983   public void setIdWidth(int i)
984   {
985     super.setIdWidth(i);
986     AlignmentPanel ap = getAlignPanel();
987     if (ap != null)
988     {
989       // modify GUI elements to reflect geometry change
990       Dimension idw = ap.getIdPanel().getIdCanvas().getPreferredSize();
991       idw.width = i;
992       ap.getIdPanel().getIdCanvas().setPreferredSize(idw);
993     }
994   }
995
996   public Rectangle getExplodedGeometry()
997   {
998     return explodedGeometry;
999   }
1000
1001   public void setExplodedGeometry(Rectangle explodedPosition)
1002   {
1003     this.explodedGeometry = explodedPosition;
1004   }
1005
1006   public boolean isGatherViewsHere()
1007   {
1008     return gatherViewsHere;
1009   }
1010
1011   public void setGatherViewsHere(boolean gatherViewsHere)
1012   {
1013     this.gatherViewsHere = gatherViewsHere;
1014   }
1015
1016   /**
1017    * If this viewport has a (Protein/cDNA) complement, then scroll the
1018    * complementary alignment to match this one.
1019    */
1020   public void scrollComplementaryAlignment()
1021   {
1022     /*
1023      * Populate a SearchResults object with the mapped location to scroll to. If
1024      * there is no complement, or it is not following highlights, or no mapping
1025      * is found, the result will be empty.
1026      */
1027     SearchResultsI sr = new SearchResults();
1028     int verticalOffset = findComplementScrollTarget(sr);
1029     if (!sr.isEmpty())
1030     {
1031       // TODO would like next line without cast but needs more refactoring...
1032       final AlignmentPanel complementPanel = ((AlignViewport) getCodingComplement())
1033               .getAlignPanel();
1034       complementPanel.setToScrollComplementPanel(false);
1035       complementPanel.scrollToCentre(sr, verticalOffset);
1036       complementPanel.setToScrollComplementPanel(true);
1037     }
1038   }
1039
1040   /**
1041    * Answers true if no alignment holds a reference to the given mapping
1042    * 
1043    * @param acf
1044    * @return
1045    */
1046   protected boolean noReferencesTo(AlignedCodonFrame acf)
1047   {
1048     AlignFrame[] frames = Desktop.getDesktopAlignFrames();
1049     if (frames == null)
1050     {
1051       return true;
1052     }
1053     for (AlignFrame af : frames)
1054     {
1055       if (!af.isClosed())
1056       {
1057         for (AlignmentViewPanel ap : af.getAlignPanels())
1058         {
1059           AlignmentI al = ap.getAlignment();
1060           if (al != null && al.getCodonFrames().contains(acf))
1061           {
1062             return false;
1063           }
1064         }
1065       }
1066     }
1067     return true;
1068   }
1069
1070   /**
1071    * Applies the supplied feature settings descriptor to currently known
1072    * features. This supports an 'initial configuration' of feature colouring
1073    * based on a preset or user favourite. This may then be modified in the usual
1074    * way using the Feature Settings dialogue.
1075    * 
1076    * @param featureSettings
1077    */
1078   @Override
1079   public void applyFeaturesStyle(FeatureSettingsModelI featureSettings)
1080   {
1081     transferFeaturesStyles(featureSettings, false);
1082   }
1083
1084   /**
1085    * Applies the supplied feature settings descriptor to currently known
1086    * features. This supports an 'initial configuration' of feature colouring
1087    * based on a preset or user favourite. This may then be modified in the usual
1088    * way using the Feature Settings dialogue.
1089    * 
1090    * @param featureSettings
1091    */
1092   @Override
1093   public void mergeFeaturesStyle(FeatureSettingsModelI featureSettings)
1094   {
1095     transferFeaturesStyles(featureSettings, true);
1096   }
1097
1098   /**
1099    * when mergeOnly is set, then group and feature visibility or feature colours
1100    * are not modified for features and groups already known to the feature
1101    * renderer. Feature ordering is always adjusted, and transparency is always
1102    * set regardless.
1103    * 
1104    * @param featureSettings
1105    * @param mergeOnly
1106    */
1107   private void transferFeaturesStyles(FeatureSettingsModelI featureSettings,
1108           boolean mergeOnly)
1109   {
1110     if (featureSettings == null)
1111     {
1112       return;
1113     }
1114
1115     FeatureRenderer fr = getAlignPanel().getSeqPanel().seqCanvas
1116             .getFeatureRenderer();
1117     List<String> origRenderOrder = new ArrayList<>();
1118     List<String> origGroups = new ArrayList<>();
1119     // preserve original render order - allows differentiation between user
1120     // configured colours and autogenerated ones
1121     origRenderOrder.addAll(fr.getRenderOrder());
1122     origGroups.addAll(fr.getFeatureGroups());
1123
1124     fr.findAllFeatures(true);
1125     List<String> renderOrder = fr.getRenderOrder();
1126     FeaturesDisplayedI displayed = fr.getFeaturesDisplayed();
1127     if (!mergeOnly)
1128     {
1129       // only clear displayed features if we are mergeing
1130       // displayed.clear();
1131     }
1132     // TODO this clears displayed.featuresRegistered - do we care?
1133     //
1134     // JAL-3330 - JBP - yes we do - calling applyFeatureStyle to a view where
1135     // feature visibility has already been configured is not very friendly
1136     /*
1137      * set feature colour if specified by feature settings
1138      * set visibility of all features
1139      */
1140     for (String type : renderOrder)
1141     {
1142       FeatureColourI preferredColour = featureSettings
1143               .getFeatureColour(type);
1144       FeatureColourI origColour = fr.getFeatureStyle(type);
1145       if (!mergeOnly || (!origRenderOrder.contains(type)
1146               || origColour == null
1147               || (!origColour.isGraduatedColour()
1148                       && origColour.getColour() != null
1149                       && origColour.getColour().equals(
1150                               ColorUtils.createColourFromName(type)))))
1151       {
1152         // if we are merging, only update if there wasn't already a colour
1153         // defined for
1154         // this type
1155         if (preferredColour != null)
1156         {
1157           fr.setColour(type, preferredColour);
1158         }
1159         if (featureSettings.isFeatureDisplayed(type))
1160         {
1161           displayed.setVisible(type);
1162         }
1163         else if (featureSettings.isFeatureHidden(type))
1164         {
1165           displayed.setHidden(type);
1166         }
1167       }
1168     }
1169
1170     /*
1171      * set visibility of feature groups
1172      */
1173     for (String group : fr.getFeatureGroups())
1174     {
1175       if (!mergeOnly || !origGroups.contains(group))
1176       {
1177         // when merging, display groups only if the aren't already marked as not
1178         // visible
1179         fr.setGroupVisibility(group,
1180                 featureSettings.isGroupDisplayed(group));
1181       }
1182     }
1183
1184     /*
1185      * order the features
1186      */
1187     if (featureSettings.optimiseOrder())
1188     {
1189       // TODO not supported (yet?)
1190     }
1191     else
1192     {
1193       fr.orderFeatures(featureSettings);
1194     }
1195     fr.setTransparency(featureSettings.getTransparency());
1196
1197     fr.notifyFeaturesChanged();
1198   }
1199
1200   public String getViewName()
1201   {
1202     return viewName;
1203   }
1204
1205   public void setViewName(String viewName)
1206   {
1207     this.viewName = viewName;
1208   }
1209
1210 }