e434825a8e94f029d272696b1174b35d3120ae3b
[jalview.git] / src / jalview / appletgui / 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.appletgui;
22
23 import jalview.analysis.NJTree;
24 import jalview.api.AlignViewportI;
25 import jalview.bin.JalviewLite;
26 import jalview.commands.CommandI;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.SearchResults;
30 import jalview.datamodel.Sequence;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.schemes.ColourSchemeProperty;
34 import jalview.schemes.UserColourScheme;
35 import jalview.structure.CommandListener;
36 import jalview.structure.SelectionSource;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.structure.VamsasSource;
39 import jalview.viewmodel.AlignmentViewport;
40
41 import java.awt.Font;
42
43 public class AlignViewport extends AlignmentViewport implements
44         SelectionSource, VamsasSource, CommandListener
45 {
46   boolean cursorMode = false;
47
48   Font font = new Font("SansSerif", Font.PLAIN, 10);
49
50   boolean validCharWidth = true;
51
52   NJTree currentTree = null;
53
54   public jalview.bin.JalviewLite applet;
55
56   boolean MAC = false;
57
58   private AnnotationColumnChooser annotationColumnSelectionState;
59
60   public void finalize()
61   {
62     applet = null;
63     quality = null;
64     alignment = null;
65     colSel = null;
66   }
67
68   public AlignViewport(AlignmentI al, JalviewLite applet)
69   {
70     super();
71     calculator = new jalview.workers.AlignCalcManager();
72     this.applet = applet;
73     alignment = al;
74     // we always pad gaps
75     this.setPadGaps(true);
76     this.startRes = 0;
77     this.endRes = al.getWidth() - 1;
78     this.startSeq = 0;
79     this.endSeq = al.getHeight() - 1;
80     if (applet != null)
81     {
82       // get the width and height scaling factors if they were specified
83       String param = applet.getParameter("widthScale");
84       if (param != null)
85       {
86         try
87         {
88           widthScale = new Float(param).floatValue();
89         } catch (Exception e)
90         {
91         }
92         if (widthScale <= 1.0)
93         {
94           System.err
95                   .println("Invalid alignment character width scaling factor ("
96                           + widthScale + "). Ignoring.");
97           widthScale = 1;
98         }
99         if (JalviewLite.debug)
100         {
101           System.err
102                   .println("Alignment character width scaling factor is now "
103                           + widthScale);
104         }
105       }
106       param = applet.getParameter("heightScale");
107       if (param != null)
108       {
109         try
110         {
111           heightScale = new Float(param).floatValue();
112         } catch (Exception e)
113         {
114         }
115         if (heightScale <= 1.0)
116         {
117           System.err
118                   .println("Invalid alignment character height scaling factor ("
119                           + heightScale + "). Ignoring.");
120           heightScale = 1;
121         }
122         if (JalviewLite.debug)
123         {
124           System.err
125                   .println("Alignment character height scaling factor is now "
126                           + heightScale);
127         }
128       }
129     }
130     setFont(font);
131
132     MAC = new jalview.util.Platform().isAMac();
133
134     if (applet != null)
135     {
136       setShowJVSuffix(applet.getDefaultParameter("showFullId",
137               getShowJVSuffix()));
138
139       setShowAnnotation(applet.getDefaultParameter("showAnnotation",
140               isShowAnnotation()));
141
142       showConservation = applet.getDefaultParameter("showConservation",
143               showConservation);
144
145       showQuality = applet.getDefaultParameter("showQuality", showQuality);
146
147       showConsensus = applet.getDefaultParameter("showConsensus",
148               showConsensus);
149
150       setShowUnconserved(applet.getDefaultParameter("showUnconserved",
151               getShowUnconserved()));
152
153       setScaleProteinAsCdna(applet.getDefaultParameter(
154               "scaleProteinAsCdna", isScaleProteinAsCdna()));
155
156       String param = applet.getParameter("upperCase");
157       if (param != null)
158       {
159         if (param.equalsIgnoreCase("bold"))
160         {
161           setUpperCasebold(true);
162         }
163       }
164       sortByTree = applet.getDefaultParameter("sortByTree", sortByTree);
165
166       setFollowHighlight(applet.getDefaultParameter("automaticScrolling",
167               isFollowHighlight()));
168       followSelection = isFollowHighlight();
169
170       showSequenceLogo = applet.getDefaultParameter("showSequenceLogo",
171               showSequenceLogo);
172
173       normaliseSequenceLogo = applet.getDefaultParameter(
174               "normaliseSequenceLogo", applet.getDefaultParameter(
175                       "normaliseLogo", normaliseSequenceLogo));
176
177       showGroupConsensus = applet.getDefaultParameter("showGroupConsensus",
178               showGroupConsensus);
179
180       showGroupConservation = applet.getDefaultParameter(
181               "showGroupConservation", showGroupConservation);
182
183       showConsensusHistogram = applet.getDefaultParameter(
184               "showConsensusHistogram", showConsensusHistogram);
185
186     }
187
188     if (applet != null)
189     {
190       String colour = applet.getParameter("defaultColour");
191
192       if (colour == null)
193       {
194         colour = applet.getParameter("userDefinedColour");
195         if (colour != null)
196         {
197           colour = "User Defined";
198         }
199       }
200
201       if (colour != null)
202       {
203         globalColourScheme = ColourSchemeProperty.getColour(alignment,
204                 colour);
205         if (globalColourScheme != null)
206         {
207           globalColourScheme.setConsensus(hconsensus);
208         }
209       }
210
211       if (applet.getParameter("userDefinedColour") != null)
212       {
213         ((UserColourScheme) globalColourScheme).parseAppletParameter(applet
214                 .getParameter("userDefinedColour"));
215       }
216     }
217     initAutoAnnotation();
218
219   }
220
221   /**
222    * get the consensus sequence as displayed under the PID consensus annotation
223    * row.
224    * 
225    * @return consensus sequence as a new sequence object
226    */
227   public SequenceI getConsensusSeq()
228   {
229     if (consensus == null)
230     {
231       updateConsensus(null);
232     }
233     if (consensus == null)
234     {
235       return null;
236     }
237     StringBuilder seqs = new StringBuilder(consensus.annotations.length);
238     for (int i = 0; i < consensus.annotations.length; i++)
239     {
240       if (consensus.annotations[i] != null)
241       {
242         if (consensus.annotations[i].description.charAt(0) == '[')
243         {
244           seqs.append(consensus.annotations[i].description.charAt(1));
245         }
246         else
247         {
248           seqs.append(consensus.annotations[i].displayCharacter);
249         }
250       }
251     }
252     SequenceI sq = new Sequence("Consensus", seqs.toString());
253     sq.setDescription("Percentage Identity Consensus "
254             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
255     return sq;
256   }
257
258   java.awt.Frame nullFrame;
259
260   protected FeatureSettings featureSettings = null;
261
262   private float heightScale = 1, widthScale = 1;
263
264   public void setFont(Font f)
265   {
266     font = f;
267     if (nullFrame == null)
268     {
269       nullFrame = new java.awt.Frame();
270       nullFrame.addNotify();
271     }
272
273     java.awt.FontMetrics fm = nullFrame.getGraphics().getFontMetrics(font);
274     setCharHeight((int) (heightScale * fm.getHeight()));
275     setCharWidth((int) (widthScale * fm.charWidth('M')));
276
277     if (isUpperCasebold())
278     {
279       Font f2 = new Font(f.getName(), Font.BOLD, f.getSize());
280       fm = nullFrame.getGraphics().getFontMetrics(f2);
281       setCharWidth((int) (widthScale * (fm.stringWidth("MMMMMMMMMMM") / 10)));
282     }
283   }
284
285   public Font getFont()
286   {
287     return font;
288   }
289
290   public void resetSeqLimits(int height)
291   {
292     setEndSeq(height / getCharHeight());
293   }
294
295   public void setCurrentTree(NJTree tree)
296   {
297     currentTree = tree;
298   }
299
300   public NJTree getCurrentTree()
301   {
302     return currentTree;
303   }
304
305   boolean centreColumnLabels;
306
307   public boolean getCentreColumnLabels()
308   {
309     return centreColumnLabels;
310   }
311
312   public boolean followSelection = true;
313
314   /**
315    * @return true if view selection should always follow the selections
316    *         broadcast by other selection sources
317    */
318   public boolean getFollowSelection()
319   {
320     return followSelection;
321   }
322
323   public void sendSelection()
324   {
325     getStructureSelectionManager().sendSelection(
326             new SequenceGroup(getSelectionGroup()),
327             new ColumnSelection(getColumnSelection()), this);
328   }
329
330   /**
331    * Returns an instance of the StructureSelectionManager scoped to this applet
332    * instance.
333    * 
334    * @return
335    */
336   @Override
337   public StructureSelectionManager getStructureSelectionManager()
338   {
339     return jalview.structure.StructureSelectionManager
340             .getStructureSelectionManager(applet);
341   }
342
343   /**
344    * synthesize a column selection if none exists so it covers the given
345    * selection group. if wholewidth is false, no column selection is made if the
346    * selection group covers the whole alignment width.
347    * 
348    * @param sg
349    * @param wholewidth
350    */
351   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
352   {
353     int sgs, sge;
354     if (sg != null
355             && (sgs = sg.getStartRes()) >= 0
356             && sg.getStartRes() <= (sge = sg.getEndRes())
357             && (colSel == null || colSel.getSelected() == null || colSel
358                     .getSelected().size() == 0))
359     {
360       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
361       {
362         // do nothing
363         return;
364       }
365       if (colSel == null)
366       {
367         colSel = new ColumnSelection();
368       }
369       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
370       {
371         colSel.addElement(cspos);
372       }
373     }
374   }
375
376   public boolean isNormaliseSequenceLogo()
377   {
378     return normaliseSequenceLogo;
379   }
380
381   public void setNormaliseSequenceLogo(boolean state)
382   {
383     normaliseSequenceLogo = state;
384   }
385
386   /**
387    * 
388    * @return true if alignment characters should be displayed
389    */
390   public boolean isValidCharWidth()
391   {
392     return validCharWidth;
393   }
394
395   public AnnotationColumnChooser getAnnotationColumnSelectionState()
396   {
397     return annotationColumnSelectionState;
398   }
399
400   public void setAnnotationColumnSelectionState(
401           AnnotationColumnChooser annotationColumnSelectionState)
402   {
403     this.annotationColumnSelectionState = annotationColumnSelectionState;
404   }
405
406   @Override
407   public void mirrorCommand(CommandI command, boolean undo,
408           StructureSelectionManager ssm, VamsasSource source)
409   {
410     // TODO refactor so this can be pulled up to superclass or controller
411     /*
412      * Do nothing unless we are a 'complement' of the source. May replace this
413      * with direct calls not via SSM.
414      */
415     if (source instanceof AlignViewportI
416             && ((AlignViewportI) source).getCodingComplement() == this)
417     {
418       // ok to continue;
419     }
420     else
421     {
422       return;
423     }
424
425     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
426             getGapCharacter());
427     if (mappedCommand != null)
428     {
429       mappedCommand.doCommand(null);
430       firePropertyChange("alignment", null, getAlignment().getSequences());
431
432       // ap.scalePanelHolder.repaint();
433       // ap.repaint();
434     }
435   }
436
437   @Override
438   public VamsasSource getVamsasSource()
439   {
440     return this;
441   }
442
443   /**
444    * If this viewport has a (Protein/cDNA) complement, then scroll the
445    * complementary alignment to match this one.
446    */
447   public void scrollComplementaryAlignment(AlignmentPanel complementPanel)
448   {
449     if (complementPanel == null)
450     {
451       return;
452     }
453
454     /*
455      * Populate a SearchResults object with the mapped location to scroll to. If
456      * there is no complement, or it is not following highlights, or no mapping
457      * is found, the result will be empty.
458      */
459     SearchResults sr = new SearchResults();
460     int seqOffset = findComplementScrollTarget(sr);
461     if (!sr.isEmpty())
462     {
463       complementPanel.setFollowingComplementScroll(true);
464       complementPanel.scrollToCentre(sr, seqOffset);
465     }
466   }
467
468 }