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