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