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