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