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