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