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