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