JAL-2388 Hidden cols separated from column selection (almost complete)
[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 import jalview.viewmodel.ViewportRanges;
44
45 import java.awt.Font;
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   NJTree 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);
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       setShowUnconserved(applet.getDefaultParameter("showUnconserved",
154               getShowUnconserved()));
155
156       setScaleProteinAsCdna(applet.getDefaultParameter(
157               "scaleProteinAsCdna", isScaleProteinAsCdna()));
158
159       String param = applet.getParameter("upperCase");
160       if (param != null)
161       {
162         if (param.equalsIgnoreCase("bold"))
163         {
164           setUpperCasebold(true);
165         }
166       }
167       sortByTree = applet.getDefaultParameter("sortByTree", sortByTree);
168
169       setFollowHighlight(applet.getDefaultParameter("automaticScrolling",
170               isFollowHighlight()));
171       followSelection = isFollowHighlight();
172
173       showSequenceLogo = applet.getDefaultParameter("showSequenceLogo",
174               showSequenceLogo);
175
176       normaliseSequenceLogo = applet.getDefaultParameter(
177               "normaliseSequenceLogo", applet.getDefaultParameter(
178                       "normaliseLogo", normaliseSequenceLogo));
179
180       showGroupConsensus = applet.getDefaultParameter("showGroupConsensus",
181               showGroupConsensus);
182
183       showGroupConservation = applet.getDefaultParameter(
184               "showGroupConservation", showGroupConservation);
185
186       showConsensusHistogram = applet.getDefaultParameter(
187               "showConsensusHistogram", showConsensusHistogram);
188
189     }
190
191     if (applet != null)
192     {
193       String colour = al.isNucleotide() ? applet
194               .getParameter("defaultColourNuc") : applet
195               .getParameter("defaultColourProt");
196       if (colour == null)
197       {
198         colour = applet.getParameter("defaultColour");
199       }
200       if (colour == null)
201       {
202         colour = applet.getParameter("userDefinedColour");
203         if (colour != null)
204         {
205           colour = "User Defined";
206         }
207       }
208
209       if (colour != null)
210       {
211         residueShading = new ResidueShader(
212                 ColourSchemeProperty.getColourScheme(alignment, colour));
213         if (residueShading != null)
214         {
215           residueShading.setConsensus(hconsensus);
216         }
217       }
218
219       if (applet.getParameter("userDefinedColour") != null)
220       {
221         residueShading = new ResidueShader(
222                 new UserColourScheme(
223                         applet.getParameter("userDefinedColour")));
224       }
225     }
226     initAutoAnnotation();
227
228   }
229
230   /**
231    * get the consensus sequence as displayed under the PID consensus annotation
232    * row.
233    * 
234    * @return consensus sequence as a new sequence object
235    */
236   public SequenceI getConsensusSeq()
237   {
238     if (consensus == null)
239     {
240       updateConsensus(null);
241     }
242     if (consensus == null)
243     {
244       return null;
245     }
246     StringBuilder seqs = new StringBuilder(consensus.annotations.length);
247     for (int i = 0; i < consensus.annotations.length; i++)
248     {
249       if (consensus.annotations[i] != null)
250       {
251         if (consensus.annotations[i].description.charAt(0) == '[')
252         {
253           seqs.append(consensus.annotations[i].description.charAt(1));
254         }
255         else
256         {
257           seqs.append(consensus.annotations[i].displayCharacter);
258         }
259       }
260     }
261     SequenceI sq = new Sequence("Consensus", seqs.toString());
262     sq.setDescription("Percentage Identity Consensus "
263             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
264     return sq;
265   }
266
267   java.awt.Frame nullFrame;
268
269   protected FeatureSettings featureSettings = null;
270
271   private float heightScale = 1, widthScale = 1;
272
273   public void setFont(Font f)
274   {
275     font = f;
276     if (nullFrame == null)
277     {
278       nullFrame = new java.awt.Frame();
279       nullFrame.addNotify();
280     }
281
282     java.awt.FontMetrics fm = nullFrame.getGraphics().getFontMetrics(font);
283     setCharHeight((int) (heightScale * fm.getHeight()));
284     setCharWidth((int) (widthScale * fm.charWidth('M')));
285
286     if (isUpperCasebold())
287     {
288       Font f2 = new Font(f.getName(), Font.BOLD, f.getSize());
289       fm = nullFrame.getGraphics().getFontMetrics(f2);
290       setCharWidth((int) (widthScale * (fm.stringWidth("MMMMMMMMMMM") / 10)));
291     }
292   }
293
294   public Font getFont()
295   {
296     return font;
297   }
298
299   public void resetSeqLimits(int height)
300   {
301     ranges.setEndSeq(height / getCharHeight());
302   }
303
304   public void setCurrentTree(NJTree tree)
305   {
306     currentTree = tree;
307   }
308
309   public NJTree getCurrentTree()
310   {
311     return currentTree;
312   }
313
314   boolean centreColumnLabels;
315
316   public boolean getCentreColumnLabels()
317   {
318     return centreColumnLabels;
319   }
320
321   public boolean followSelection = true;
322
323   /**
324    * @return true if view selection should always follow the selections
325    *         broadcast by other selection sources
326    */
327   public boolean getFollowSelection()
328   {
329     return followSelection;
330   }
331
332   @Override
333   public void sendSelection()
334   {
335     getStructureSelectionManager().sendSelection(
336             new SequenceGroup(getSelectionGroup()),
337             new ColumnSelection(getColumnSelection()),
338             new HiddenColumns(getAlignment().getHiddenColumns()), 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 }