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