Merge remote-tracking branch
[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.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.HiddenColumns;
31 import jalview.datamodel.SearchResults;
32 import jalview.datamodel.SearchResultsI;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceGroup;
35 import jalview.datamodel.SequenceI;
36 import jalview.renderer.ResidueShader;
37 import jalview.schemes.ColourSchemeProperty;
38 import jalview.schemes.UserColourScheme;
39 import jalview.structure.SelectionSource;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.structure.VamsasSource;
42 import jalview.viewmodel.AlignmentViewport;
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   NJTree 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(al);
75     calculator = new jalview.workers.AlignCalcManager();
76     this.applet = applet;
77
78     // we always pad gaps
79     this.setPadGaps(true);
80
81     if (applet != null)
82     {
83       // get the width and height scaling factors if they were specified
84       String param = applet.getParameter("widthScale");
85       if (param != null)
86       {
87         try
88         {
89           widthScale = new Float(param).floatValue();
90         } catch (Exception e)
91         {
92         }
93         if (widthScale <= 1.0)
94         {
95           System.err
96                   .println("Invalid alignment character width scaling factor ("
97                           + widthScale + "). Ignoring.");
98           widthScale = 1;
99         }
100         if (JalviewLite.debug)
101         {
102           System.err
103                   .println("Alignment character width scaling factor is now "
104                           + widthScale);
105         }
106       }
107       param = applet.getParameter("heightScale");
108       if (param != null)
109       {
110         try
111         {
112           heightScale = new Float(param).floatValue();
113         } catch (Exception e)
114         {
115         }
116         if (heightScale <= 1.0)
117         {
118           System.err
119                   .println("Invalid alignment character height scaling factor ("
120                           + heightScale + "). Ignoring.");
121           heightScale = 1;
122         }
123         if (JalviewLite.debug)
124         {
125           System.err
126                   .println("Alignment character height scaling factor is now "
127                           + heightScale);
128         }
129       }
130     }
131     setFont(font);
132
133     MAC = new jalview.util.Platform().isAMac();
134
135     if (applet != null)
136     {
137       setShowJVSuffix(applet.getDefaultParameter("showFullId",
138               getShowJVSuffix()));
139
140       setShowAnnotation(applet.getDefaultParameter("showAnnotation",
141               isShowAnnotation()));
142
143       showConservation = applet.getDefaultParameter("showConservation",
144               showConservation);
145
146       showQuality = applet.getDefaultParameter("showQuality", showQuality);
147
148       showConsensus = applet.getDefaultParameter("showConsensus",
149               showConsensus);
150
151       setShowUnconserved(applet.getDefaultParameter("showUnconserved",
152               getShowUnconserved()));
153
154       setScaleProteinAsCdna(applet.getDefaultParameter(
155               "scaleProteinAsCdna", isScaleProteinAsCdna()));
156
157       String param = applet.getParameter("upperCase");
158       if (param != null)
159       {
160         if (param.equalsIgnoreCase("bold"))
161         {
162           setUpperCasebold(true);
163         }
164       }
165       sortByTree = applet.getDefaultParameter("sortByTree", sortByTree);
166
167       setFollowHighlight(applet.getDefaultParameter("automaticScrolling",
168               isFollowHighlight()));
169       followSelection = isFollowHighlight();
170
171       showSequenceLogo = applet.getDefaultParameter("showSequenceLogo",
172               showSequenceLogo);
173
174       normaliseSequenceLogo = applet.getDefaultParameter(
175               "normaliseSequenceLogo", applet.getDefaultParameter(
176                       "normaliseLogo", normaliseSequenceLogo));
177
178       showGroupConsensus = applet.getDefaultParameter("showGroupConsensus",
179               showGroupConsensus);
180
181       showGroupConservation = applet.getDefaultParameter(
182               "showGroupConservation", showGroupConservation);
183
184       showConsensusHistogram = applet.getDefaultParameter(
185               "showConsensusHistogram", showConsensusHistogram);
186
187     }
188
189     if (applet != null)
190     {
191       String colour = al.isNucleotide() ? applet
192               .getParameter("defaultColourNuc") : applet
193               .getParameter("defaultColourProt");
194       if (colour == null)
195       {
196         colour = applet.getParameter("defaultColour");
197       }
198       if (colour == null)
199       {
200         colour = applet.getParameter("userDefinedColour");
201         if (colour != null)
202         {
203           colour = "User Defined";
204         }
205       }
206
207       if (colour != null)
208       {
209         residueShading = new ResidueShader(
210                 ColourSchemeProperty.getColourScheme(alignment, colour));
211         if (residueShading != null)
212         {
213           residueShading.setConsensus(hconsensus);
214         }
215       }
216
217       if (applet.getParameter("userDefinedColour") != null)
218       {
219         residueShading = new ResidueShader(
220                 new UserColourScheme(
221                         applet.getParameter("userDefinedColour")));
222       }
223     }
224     initAutoAnnotation();
225
226   }
227
228   /**
229    * get the consensus sequence as displayed under the PID consensus annotation
230    * row.
231    * 
232    * @return consensus sequence as a new sequence object
233    */
234   public SequenceI getConsensusSeq()
235   {
236     if (consensus == null)
237     {
238       updateConsensus(null);
239     }
240     if (consensus == null)
241     {
242       return null;
243     }
244     StringBuilder seqs = new StringBuilder(consensus.annotations.length);
245     for (int i = 0; i < consensus.annotations.length; i++)
246     {
247       if (consensus.annotations[i] != null)
248       {
249         if (consensus.annotations[i].description.charAt(0) == '[')
250         {
251           seqs.append(consensus.annotations[i].description.charAt(1));
252         }
253         else
254         {
255           seqs.append(consensus.annotations[i].displayCharacter);
256         }
257       }
258     }
259     SequenceI sq = new Sequence("Consensus", seqs.toString());
260     sq.setDescription("Percentage Identity Consensus "
261             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
262     return sq;
263   }
264
265   java.awt.Frame nullFrame;
266
267   protected FeatureSettings featureSettings = null;
268
269   private float heightScale = 1, widthScale = 1;
270
271   public void setFont(Font f)
272   {
273     font = f;
274     if (nullFrame == null)
275     {
276       nullFrame = new java.awt.Frame();
277       nullFrame.addNotify();
278     }
279
280     java.awt.FontMetrics fm = nullFrame.getGraphics().getFontMetrics(font);
281     setCharHeight((int) (heightScale * fm.getHeight()));
282     setCharWidth((int) (widthScale * fm.charWidth('M')));
283
284     if (isUpperCasebold())
285     {
286       Font f2 = new Font(f.getName(), Font.BOLD, f.getSize());
287       fm = nullFrame.getGraphics().getFontMetrics(f2);
288       setCharWidth((int) (widthScale * (fm.stringWidth("MMMMMMMMMMM") / 10)));
289     }
290   }
291
292   public Font getFont()
293   {
294     return font;
295   }
296
297   public void resetSeqLimits(int height)
298   {
299     ranges.setEndSeq(height / getCharHeight());
300   }
301
302   public void setCurrentTree(NJTree tree)
303   {
304     currentTree = tree;
305   }
306
307   public NJTree getCurrentTree()
308   {
309     return currentTree;
310   }
311
312   boolean centreColumnLabels;
313
314   public boolean getCentreColumnLabels()
315   {
316     return centreColumnLabels;
317   }
318
319   public boolean followSelection = true;
320
321   /**
322    * @return true if view selection should always follow the selections
323    *         broadcast by other selection sources
324    */
325   public boolean getFollowSelection()
326   {
327     return followSelection;
328   }
329
330   @Override
331   public void sendSelection()
332   {
333     getStructureSelectionManager().sendSelection(
334             new SequenceGroup(getSelectionGroup()),
335             new ColumnSelection(getColumnSelection()),
336             new HiddenColumns(getAlignment().getHiddenColumns()), 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 }