Bamboo test #13 AlignViewport resize and jscrollbar set
[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.MessageManager;
51 import jalview.viewmodel.AlignmentViewport;
52 import jalview.viewmodel.ViewportRanges;
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.Hashtable;
61 import java.util.Iterator;
62 import java.util.List;
63
64 import javax.swing.JInternalFrame;
65
66 /**
67  * DOCUMENT ME!
68  * 
69  * @author $author$
70  * @version $Revision: 1.141 $
71  */
72 public class AlignViewport extends AlignmentViewport
73         implements SelectionSource
74 {
75   Font font;
76
77   boolean cursorMode = false;
78
79   boolean antiAlias = false;
80
81   private Rectangle explodedGeometry;
82
83   private String viewName;
84
85   /*
86    * Flag set true on the view that should 'gather' multiple views of the same
87    * sequence set id when a project is reloaded. Set false on all views when
88    * they are 'exploded' into separate windows. Set true on the current view
89    * when 'Gather' is performed, and also on the first tab when the first new
90    * view is created.
91    */
92   private boolean gatherViewsHere = false;
93
94   private AnnotationColumnChooser annotationColumnSelectionState;
95
96   /**
97    * Creates a new AlignViewport object.
98    * 
99    * @param al
100    *          alignment to view
101    */
102   public AlignViewport(AlignmentI al)
103   {
104     super(al);
105     init();
106   }
107
108   /**
109    * Create a new AlignViewport object with a specific sequence set ID
110    * 
111    * @param al
112    * @param seqsetid
113    *          (may be null - but potential for ambiguous constructor exception)
114    */
115   public AlignViewport(AlignmentI al, String seqsetid)
116   {
117     this(al, seqsetid, null);
118   }
119
120   public AlignViewport(AlignmentI al, String seqsetid, String viewid)
121   {
122     super(al);
123     sequenceSetID = seqsetid;
124     viewId = viewid;
125     // TODO remove these once 2.4.VAMSAS release finished
126     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
127     {
128       Cache.log.debug(
129               "Setting viewport's sequence set id : " + sequenceSetID);
130     }
131     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
132     {
133       Cache.log.debug("Setting viewport's view id : " + viewId);
134     }
135     init();
136
137   }
138
139   /**
140    * Create a new AlignViewport with hidden regions
141    * 
142    * @param al
143    *          AlignmentI
144    * @param hiddenColumns
145    *          ColumnSelection
146    */
147   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns)
148   {
149     super(al);
150     if (hiddenColumns != null)
151     {
152       al.setHiddenColumns(hiddenColumns);
153     }
154     init();
155   }
156
157   /**
158    * New viewport with hidden columns and an existing sequence set id
159    * 
160    * @param al
161    * @param hiddenColumns
162    * @param seqsetid
163    *          (may be null)
164    */
165   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
166           String seqsetid)
167   {
168     this(al, hiddenColumns, seqsetid, null);
169   }
170
171   /**
172    * New viewport with hidden columns and an existing sequence set id and viewid
173    * 
174    * @param al
175    * @param hiddenColumns
176    * @param seqsetid
177    *          (may be null)
178    * @param viewid
179    *          (may be null)
180    */
181   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
182           String seqsetid, String viewid)
183   {
184     super(al);
185     sequenceSetID = seqsetid;
186     viewId = viewid;
187     // TODO remove these once 2.4.VAMSAS release finished
188     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
189     {
190       Cache.log.debug(
191               "Setting viewport's sequence set id : " + sequenceSetID);
192     }
193     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
194     {
195       Cache.log.debug("Setting viewport's view id : " + viewId);
196     }
197
198     if (hiddenColumns != null)
199     {
200       al.setHiddenColumns(hiddenColumns);
201     }
202     init();
203   }
204
205   /**
206    * Apply any settings saved in user preferences
207    */
208   private void applyViewProperties()
209   {
210     antiAlias = Cache.getDefault(Preferences.ANTI_ALIAS, false);
211
212     viewStyle.setShowJVSuffix(
213             Cache.getDefault(Preferences.SHOW_JVSUFFIX, true));
214     setShowAnnotation(Cache.getDefault(Preferences.SHOW_ANNOTATIONS, true));
215
216     setRightAlignIds(Cache.getDefault(Preferences.RIGHT_ALIGN_IDS, false));
217     setCentreColumnLabels(Cache.getDefault(Preferences.CENTRE_COLUMN_LABELS, false));
218     autoCalculateConsensusAndConservation = Cache.getDefault(Preferences.AUTO_CALC_CONSENSUS, true);
219
220     setPadGaps(Cache.getDefault(Preferences.PAD_GAPS, true));
221     setShowNPFeats(Cache.getDefault(Preferences.SHOW_NPFEATS_TOOLTIP, true));
222     setShowDBRefs(Cache.getDefault(Preferences.SHOW_DBREFS_TOOLTIP, true));
223     viewStyle.setSeqNameItalics(Cache.getDefault(Preferences.ID_ITALICS, true));
224     viewStyle.setWrapAlignment(
225             Cache.getDefault(Preferences.WRAP_ALIGNMENT, false));
226     viewStyle.setShowUnconserved(
227             Cache.getDefault(Preferences.SHOW_UNCONSERVED, false));
228     sortByTree = Cache.getDefault(Preferences.SORT_BY_TREE, false);
229     followSelection = Cache.getDefault(Preferences.FOLLOW_SELECTIONS, true);
230     sortAnnotationsBy = SequenceAnnotationOrder
231             .valueOf(Cache.getDefault(Preferences.SORT_ANNOTATIONS,
232                     SequenceAnnotationOrder.NONE.name()));
233     showAutocalculatedAbove = Cache
234             .getDefault(Preferences.SHOW_AUTOCALC_ABOVE, false);
235     viewStyle.setScaleProteinAsCdna(
236             Cache.getDefault(Preferences.SCALE_PROTEIN_TO_CDNA, true));
237   }
238
239   void init()
240   {
241     applyViewProperties();
242
243     String fontName = Cache.getDefault(Preferences.FONT_NAME, "SansSerif");
244     String fontStyle = Cache.getDefault(Preferences.FONT_STYLE,
245             Font.PLAIN + "");
246     String fontSize = Cache.getDefault(Preferences.FONT_SIZE, "10");
247
248     int style = 0;
249
250     if (fontStyle.equals("bold"))
251     {
252       style = 1;
253     }
254     else if (fontStyle.equals("italic"))
255     {
256       style = 2;
257     }
258
259     setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
260
261     alignment
262             .setGapCharacter(Cache.getDefault(Preferences.GAP_SYMBOL, "-")
263                     .charAt(0));
264
265     // We must set conservation and consensus before setting colour,
266     // as Blosum and Clustal require this to be done
267     if (hconsensus == null && !isDataset)
268     {
269       if (!alignment.isNucleotide())
270       {
271         showConservation = Cache.getDefault(Preferences.SHOW_CONSERVATION,
272                 true);
273         showQuality = Cache.getDefault(Preferences.SHOW_QUALITY, true);
274         showGroupConservation = Cache
275                 .getDefault(Preferences.SHOW_GROUP_CONSERVATION, false);
276       }
277       showConsensusHistogram = Cache
278               .getDefault(Preferences.SHOW_CONSENSUS_HISTOGRAM, true);
279       showSequenceLogo = Cache.getDefault(Preferences.SHOW_CONSENSUS_LOGO,
280               false);
281
282       normaliseSequenceLogo = Cache
283               .getDefault(Preferences.NORMALISE_CONSENSUS_LOGO, false);
284       showGroupConsensus = Cache
285               .getDefault(Preferences.SHOW_GROUP_CONSENSUS, false);
286       showConsensus = Cache.getDefault(Preferences.SHOW_IDENTITY, true);
287
288       showOccupancy = Cache.getDefault(Preferences.SHOW_OCCUPANCY, true);
289     }
290     initAutoAnnotation();
291     String colourProperty = alignment.isNucleotide()
292             ? Preferences.DEFAULT_COLOUR_NUC
293             : Preferences.DEFAULT_COLOUR_PROT;
294     String schemeName = Cache.getProperty(colourProperty);
295     if (schemeName == null)
296     {
297       // only DEFAULT_COLOUR available in Jalview before 2.9
298       schemeName = Cache.getDefault(Preferences.DEFAULT_COLOUR,
299               ResidueColourScheme.NONE);
300     }
301     ColourSchemeI colourScheme = ColourSchemeProperty.getColourScheme(this,
302             alignment, schemeName);
303     residueShading = new ResidueShader(colourScheme);
304
305     if (colourScheme instanceof UserColourScheme)
306     {
307       residueShading = new ResidueShader(
308               UserDefinedColours.loadDefaultColours());
309       residueShading.setThreshold(0, isIgnoreGapsConsensus());
310     }
311
312     if (residueShading != null)
313     {
314       residueShading.setConsensus(hconsensus);
315     }
316     setColourAppliesToAllGroups(true);
317   }
318
319   boolean validCharWidth;
320
321   /**
322    * {@inheritDoc}
323    */
324   @Override
325   public void setFont(Font f, boolean setGrid)
326   {
327     font = f;
328
329     Container c = new Container();
330
331     if (setGrid)
332     {
333       FontMetrics fm = c.getFontMetrics(font);
334       ViewportRanges.sTest += ("AlignViewport.setFont " + fm.getHeight()
335               + " "
336               + font + "\n");
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       Desktop.getStructureSelectionManager()
399               .registerMappings(align.getCodonFrames());
400     }
401
402     /*
403      * replace mappings on our alignment
404      */
405     if (alignment != null && align != null)
406     {
407       alignment.setCodonFrames(align.getCodonFrames());
408     }
409   }
410
411   protected void deregisterMappings()
412   {
413     AlignmentI al = getAlignment();
414     if (al != null)
415     {
416       List<AlignedCodonFrame> mappings = al.getCodonFrames();
417       if (mappings != null)
418       {
419         StructureSelectionManager ssm = Desktop
420                 .getStructureSelectionManager();
421         for (AlignedCodonFrame acf : mappings)
422         {
423           if (noReferencesTo(acf))
424           {
425             ssm.deregisterMapping(acf);
426           }
427         }
428       }
429     }
430   }
431
432   /**
433    * DOCUMENT ME!
434    * 
435    * @return DOCUMENT ME!
436    */
437   @Override
438   public char getGapCharacter()
439   {
440     return getAlignment().getGapCharacter();
441   }
442
443   /**
444    * DOCUMENT ME!
445    * 
446    * @param gap
447    *          DOCUMENT ME!
448    */
449   public void setGapCharacter(char gap)
450   {
451     if (getAlignment() != null)
452     {
453       getAlignment().setGapCharacter(gap);
454     }
455   }
456
457   /**
458    * returns the visible column regions of the alignment
459    * 
460    * @param selectedRegionOnly
461    *          true to just return the contigs intersecting with the selected
462    *          area
463    * @return
464    */
465   public Iterator<int[]> getViewAsVisibleContigs(boolean selectedRegionOnly)
466   {
467     int start = 0;
468     int end = 0;
469     if (selectedRegionOnly && selectionGroup != null)
470     {
471       start = selectionGroup.getStartRes();
472       end = selectionGroup.getEndRes() + 1;
473     }
474     else
475     {
476       end = alignment.getWidth();
477     }
478     return (alignment.getHiddenColumns().getVisContigsIterator(start, end,
479             false));
480   }
481
482   /**
483    * get hash of undo and redo list for the alignment
484    * 
485    * @return long[] { historyList.hashCode, redoList.hashCode };
486    */
487   public long[] getUndoRedoHash()
488   {
489     // TODO: JAL-1126
490     if (historyList == null || redoList == null)
491     {
492       return new long[] { -1, -1 };
493     }
494     return new long[] { historyList.hashCode(), this.redoList.hashCode() };
495   }
496
497   /**
498    * test if a particular set of hashcodes are different to the hashcodes for
499    * the undo and redo list.
500    * 
501    * @param undoredo
502    *          the stored set of hashcodes as returned by getUndoRedoHash
503    * @return true if the hashcodes differ (ie the alignment has been edited) or
504    *         the stored hashcode array differs in size
505    */
506   public boolean isUndoRedoHashModified(long[] undoredo)
507   {
508     if (undoredo == null)
509     {
510       return true;
511     }
512     long[] cstate = getUndoRedoHash();
513     if (cstate.length != undoredo.length)
514     {
515       return true;
516     }
517
518     for (int i = 0; i < cstate.length; i++)
519     {
520       if (cstate[i] != undoredo[i])
521       {
522         return true;
523       }
524     }
525     return false;
526   }
527
528   public boolean followSelection = true;
529
530   /**
531    * @return true if view selection should always follow the selections
532    *         broadcast by other selection sources
533    */
534   public boolean getFollowSelection()
535   {
536     return followSelection;
537   }
538
539   /**
540    * Send the current selection to be broadcast to any selection listeners.
541    */
542   @Override
543   public void sendSelection()
544   {
545     Desktop.getStructureSelectionManager().sendSelection(
546             new SequenceGroup(getSelectionGroup()),
547             new ColumnSelection(getColumnSelection()),
548             new HiddenColumns(getAlignment().getHiddenColumns()), this);
549   }
550
551   /**
552    * return the alignPanel containing the given viewport. Use this to get the
553    * components currently handling the given viewport.
554    * 
555    * @param av
556    * @return null or an alignPanel guaranteed to have non-null alignFrame
557    *         reference
558    */
559   public AlignmentPanel getAlignPanel()
560   {
561     AlignmentPanel[] aps = PaintRefresher
562             .getAssociatedPanels(this.getSequenceSetId());
563     for (int p = 0; aps != null && p < aps.length; p++)
564     {
565       if (aps[p].av == this)
566       {
567         return aps[p];
568       }
569     }
570     return null;
571   }
572
573   public boolean getSortByTree()
574   {
575     return sortByTree;
576   }
577
578   public void setSortByTree(boolean sort)
579   {
580     sortByTree = sort;
581   }
582
583   /**
584    * Returns the (Desktop) instance of the StructureSelectionManager
585    */
586   @Override
587   public StructureSelectionManager getStructureSelectionManager()
588   {
589     return Desktop.getStructureSelectionManager();
590   }
591
592   @Override
593   public boolean isNormaliseSequenceLogo()
594   {
595     return normaliseSequenceLogo;
596   }
597
598   public void setNormaliseSequenceLogo(boolean state)
599   {
600     normaliseSequenceLogo = state;
601   }
602
603   /**
604    * 
605    * @return true if alignment characters should be displayed
606    */
607   @Override
608   public boolean isValidCharWidth()
609   {
610     return validCharWidth;
611   }
612
613   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<>();
614
615   public AutoCalcSetting getCalcIdSettingsFor(String calcId)
616   {
617     return calcIdParams.get(calcId);
618   }
619
620   public void setCalcIdSettingsFor(String calcId, AutoCalcSetting settings,
621           boolean needsUpdate)
622   {
623     calcIdParams.put(calcId, settings);
624     // TODO: create a restart list to trigger any calculations that need to be
625     // restarted after load
626     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
627     if (needsUpdate)
628     {
629       Cache.log.debug("trigger update for " + calcId);
630     }
631   }
632
633   /**
634    * Method called when another alignment's edit (or possibly other) command is
635    * broadcast to here.
636    *
637    * To allow for sequence mappings (e.g. protein to cDNA), we have to first
638    * 'unwind' the command on the source sequences (in simulation, not in fact),
639    * and then for each edit in turn:
640    * <ul>
641    * <li>compute the equivalent edit on the mapped sequences</li>
642    * <li>apply the mapped edit</li>
643    * <li>'apply' the source edit to the working copy of the source
644    * sequences</li>
645    * </ul>
646    * 
647    * @param command
648    * @param undo
649    * @param ssm
650    */
651   @Override
652   public void mirrorCommand(CommandI command, boolean undo,
653           StructureSelectionManager ssm, VamsasSource source)
654   {
655     /*
656      * Do nothing unless we are a 'complement' of the source. May replace this
657      * with direct calls not via SSM.
658      */
659     if (source instanceof AlignViewportI
660             && ((AlignViewportI) source).getCodingComplement() == this)
661     {
662       // ok to continue;
663     }
664     else
665     {
666       return;
667     }
668
669     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
670             getGapCharacter());
671     if (mappedCommand != null)
672     {
673       AlignmentI[] views = getAlignPanel().alignFrame.getViewAlignments();
674       mappedCommand.doCommand(views);
675       getAlignPanel().alignmentChanged();
676     }
677   }
678
679   /**
680    * Add the sequences from the given alignment to this viewport. Optionally,
681    * may give the user the option to open a new frame, or split panel, with cDNA
682    * and protein linked.
683    * 
684    * @param toAdd
685    * @param title
686    */
687   public void addAlignment(AlignmentI toAdd, String title)
688   {
689     // TODO: promote to AlignViewportI? applet CutAndPasteTransfer is different
690
691     // JBPComment: title is a largely redundant parameter at the moment
692     // JBPComment: this really should be an 'insert/pre/append' controller
693     // JBPComment: but the DNA/Protein check makes it a bit more complex
694
695     // refactored from FileLoader / CutAndPasteTransfer / SequenceFetcher with
696     // this comment:
697     // TODO: create undo object for this JAL-1101
698
699     /*
700      * Ensure datasets are created for the new alignment as
701      * mappings operate on dataset sequences
702      */
703     toAdd.setDataset(null);
704
705     /*
706      * Check if any added sequence could be the object of a mapping or
707      * cross-reference; if so, make the mapping explicit 
708      */
709     getAlignment().realiseMappings(toAdd.getSequences());
710
711     /*
712      * If any cDNA/protein mappings exist or can be made between the alignments, 
713      * offer to open a split frame with linked alignments
714      */
715     if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
716     {
717       if (AlignmentUtils.isMappable(toAdd, getAlignment()))
718       {
719         openLinkedAlignment(toAdd, title);
720         return;
721       }
722     }
723     addDataToAlignment(toAdd);
724   }
725
726   /**
727    * adds sequences to this alignment
728    * 
729    * @param toAdd
730    */
731   void addDataToAlignment(AlignmentI toAdd)
732   {
733     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
734     // provenance) should share the same dataset sequence
735
736     AlignmentI al = getAlignment();
737     String gap = String.valueOf(al.getGapCharacter());
738     for (int i = 0; i < toAdd.getHeight(); i++)
739     {
740       SequenceI seq = toAdd.getSequenceAt(i);
741       /*
742        * experimental!
743        * - 'align' any mapped sequences as per existing 
744        *    e.g. cdna to genome, domain hit to protein sequence
745        * very experimental! (need a separate menu option for this)
746        * - only add mapped sequences ('select targets from a dataset')
747        */
748       if (true /*AlignmentUtils.alignSequenceAs(seq, al, gap, true, true)*/)
749       {
750         al.addSequence(seq);
751       }
752     }
753
754     ranges.setEndSeq(getAlignment().getHeight() - 1); // BH 2019.04.18
755     firePropertyChange("alignment", null, getAlignment().getSequences());
756   }
757
758   public final static int NO_SPLIT = 0;
759
760   public final static int SPLIT_FRAME = 1;
761
762   public final static int NEW_WINDOW = 2;
763
764   /**
765    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
766    * alignment, either as a standalone alignment or in a split frame. Returns
767    * true if the new alignment was opened, false if not, because the user
768    * declined the offer.
769    * 
770    * @param al
771    * @param title
772    */
773   protected void openLinkedAlignment(AlignmentI al, String title)
774   {
775     String[] options = new String[] { MessageManager.getString("action.no"),
776         MessageManager.getString("label.split_window"),
777         MessageManager.getString("label.new_window"), };
778     final String question = JvSwingUtils.wrapTooltip(true,
779             MessageManager.getString("label.open_split_window?"));
780
781     /*
782      * options No, Split Window, New Window correspond to
783      * dialog responses 0, 1, 2 (even though JOptionPane shows them
784      * in reverse order)
785      */
786     JvOptionPane dialog = JvOptionPane
787             .newOptionDialog(Desktop.getDesktopPane())
788             .setResponseHandler(NO_SPLIT, new Runnable()
789             {
790               @Override
791               public void run()
792               {
793                 addDataToAlignment(al);
794               }
795             }).setResponseHandler(SPLIT_FRAME, new Runnable()
796             {
797               @Override
798               public void run()
799               {
800                 openLinkedAlignmentAs(getAlignPanel().alignFrame,
801                         new Alignment(getAlignment()), al, title,
802                         SPLIT_FRAME);
803               }
804             }).setResponseHandler(NEW_WINDOW, new Runnable()
805             {
806               @Override
807               public void run()
808               {
809                 openLinkedAlignmentAs(null, getAlignment(), al, title,
810                         NEW_WINDOW);
811               }
812             });
813     dialog.showDialog(question,
814             MessageManager.getString("label.open_split_window"),
815             JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
816             options, options[0]);
817   }
818
819   /**
820    * Open a split frame or a new window
821    * 
822    * @param al
823    * @param title
824    * @param mode
825    *          SPLIT_FRAME or NEW_WINDOW
826    */
827   public static void openLinkedAlignmentAs(AlignFrame thisFrame,
828           AlignmentI thisAlignment, AlignmentI al, String title, int mode)
829   {
830     /*
831      * Identify protein and dna alignments. Make a copy of this one if opening
832      * in a new split pane.
833      */
834     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
835     AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
836
837     /*
838      * Map sequences. At least one should get mapped as we have already passed
839      * the test for 'mappability'. Any mappings made will be added to the
840      * protein alignment. Note creating dataset sequences on the new alignment
841      * is a pre-requisite for building mappings.
842      */
843     al.setDataset(null);
844     AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna);
845
846     /*
847      * Create the AlignFrame for the added alignment. If it is protein, mappings
848      * are registered with StructureSelectionManager as a side-effect.
849      */
850     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
851             AlignFrame.DEFAULT_HEIGHT);
852     newAlignFrame.setTitle(title);
853     newAlignFrame.setStatus(MessageManager
854             .formatMessage("label.successfully_loaded_file", new Object[]
855             { title }));
856
857     // TODO if we want this (e.g. to enable reload of the alignment from file),
858     // we will need to add parameters to the stack.
859     // if (!protocol.equals(DataSourceType.PASTE))
860     // {
861     // alignFrame.setFileName(file, format);
862     // }
863
864     if (mode == NEW_WINDOW)
865     {
866       Desktop.addInternalFrame(newAlignFrame, title,
867               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
868     }
869
870     try
871     {
872       newAlignFrame.setMaximum(jalview.bin.Cache
873               .getDefault(Preferences.SHOW_FULLSCREEN, false));
874     } catch (java.beans.PropertyVetoException ex)
875     {
876     }
877
878     if (mode == SPLIT_FRAME)
879     {
880       al.alignAs(thisAlignment);
881       openSplitFrame(thisFrame, newAlignFrame, thisAlignment);
882     }
883   }
884
885   /**
886    * Helper method to open a new SplitFrame holding linked dna and protein
887    * alignments.
888    * 
889    * @param newAlignFrame
890    *          containing a new alignment to be shown
891    * @param complement
892    *          cdna/protein complement alignment to show in the other split half
893    * @return the protein alignment in the split frame
894    */
895   static protected AlignmentI openSplitFrame(AlignFrame thisFrame,
896           AlignFrame newAlignFrame, AlignmentI complement)
897   {
898     /*
899      * Make a new frame with a copy of the alignment we are adding to. If this
900      * is protein, the mappings to cDNA will be registered with
901      * StructureSelectionManager as a side-effect.
902      */
903     AlignFrame copyMe = new AlignFrame(complement, AlignFrame.DEFAULT_WIDTH,
904             AlignFrame.DEFAULT_HEIGHT);
905     copyMe.setTitle(thisFrame.getTitle());
906
907     AlignmentI al = newAlignFrame.viewport.getAlignment();
908     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
909             : newAlignFrame;
910     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame : copyMe;
911     cdnaFrame.setVisible(true);
912     proteinFrame.setVisible(true);
913     String linkedTitle = MessageManager
914             .getString("label.linked_view_title");
915
916     /*
917      * Open in split pane. DNA sequence above, protein below.
918      */
919     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
920     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
921
922     return proteinFrame.viewport.getAlignment();
923   }
924
925   public AnnotationColumnChooser getAnnotationColumnSelectionState()
926   {
927     return annotationColumnSelectionState;
928   }
929
930   public void setAnnotationColumnSelectionState(
931           AnnotationColumnChooser currentAnnotationColumnSelectionState)
932   {
933     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
934   }
935
936   @Override
937   public void setIdWidth(int i)
938   {
939     super.setIdWidth(i);
940     AlignmentPanel ap = getAlignPanel();
941     if (ap != null)
942     {
943       // modify GUI elements to reflect geometry change
944       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
945               .getPreferredSize();
946       idw.width = i;
947       getAlignPanel().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.getAlignFrames();
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     if (featureSettings == null)
1037     {
1038       return;
1039     }
1040
1041     FeatureRenderer fr = getAlignPanel().getSeqPanel().seqCanvas
1042             .getFeatureRenderer();
1043     fr.findAllFeatures(true);
1044     List<String> renderOrder = fr.getRenderOrder();
1045     FeaturesDisplayedI displayed = fr.getFeaturesDisplayed();
1046     displayed.clear();
1047     // TODO this clears displayed.featuresRegistered - do we care?
1048
1049     /*
1050      * set feature colour if specified by feature settings
1051      * set visibility of all features
1052      */
1053     for (String type : renderOrder)
1054     {
1055       FeatureColourI preferredColour = featureSettings
1056               .getFeatureColour(type);
1057       if (preferredColour != null)
1058       {
1059         fr.setColour(type, preferredColour);
1060       }
1061       if (featureSettings.isFeatureDisplayed(type))
1062       {
1063         displayed.setVisible(type);
1064       }
1065     }
1066
1067     /*
1068      * set visibility of feature groups
1069      */
1070     for (String group : fr.getFeatureGroups())
1071     {
1072       fr.setGroupVisibility(group, featureSettings.isGroupDisplayed(group));
1073     }
1074
1075     /*
1076      * order the features
1077      */
1078     if (featureSettings.optimiseOrder())
1079     {
1080       // TODO not supported (yet?)
1081     }
1082     else
1083     {
1084       fr.orderFeatures(featureSettings);
1085     }
1086     fr.setTransparency(featureSettings.getTransparency());
1087   }
1088
1089   public String getViewName()
1090   {
1091     return viewName;
1092   }
1093
1094   public void setViewName(String viewName)
1095   {
1096     this.viewName = viewName;
1097   }
1098 }