JAL-1641 Further refactoring of JSON export option, introduction of Viewport to the...
[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.FeatureRenderer;
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.Sequence;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.schemes.ColourSchemeProperty;
35 import jalview.schemes.UserColourScheme;
36 import jalview.structure.CommandListener;
37 import jalview.structure.SelectionSource;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.structure.VamsasSource;
40 import jalview.viewmodel.AlignmentViewport;
41
42 import java.awt.Font;
43
44 public class AlignViewport extends AlignmentViewport implements
45         SelectionSource, VamsasSource, CommandListener
46 {
47   boolean cursorMode = false;
48
49   Font font = new Font("SansSerif", Font.PLAIN, 10);
50
51   boolean validCharWidth = true;
52
53   NJTree currentTree = null;
54
55   public jalview.bin.JalviewLite applet;
56
57   boolean MAC = false;
58
59   private AnnotationColumnChooser annotationColumnSelectionState;
60
61   private FeatureRenderer featureRenderer;
62
63   public void finalize()
64   {
65     applet = null;
66     quality = null;
67     alignment = null;
68     colSel = null;
69   }
70
71   public AlignViewport(AlignmentI al, JalviewLite applet)
72   {
73     super();
74     calculator = new jalview.workers.AlignCalcManager();
75     this.applet = applet;
76     alignment = al;
77     // we always pad gaps
78     this.setPadGaps(true);
79     this.startRes = 0;
80     this.endRes = al.getWidth() - 1;
81     this.startSeq = 0;
82     this.endSeq = al.getHeight() - 1;
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 = applet.getParameter("defaultColour");
194
195       if (colour == null)
196       {
197         colour = applet.getParameter("userDefinedColour");
198         if (colour != null)
199         {
200           colour = "User Defined";
201         }
202       }
203
204       if (colour != null)
205       {
206         globalColourScheme = ColourSchemeProperty.getColour(alignment,
207                 colour);
208         if (globalColourScheme != null)
209         {
210           globalColourScheme.setConsensus(hconsensus);
211         }
212       }
213
214       if (applet.getParameter("userDefinedColour") != null)
215       {
216         ((UserColourScheme) globalColourScheme).parseAppletParameter(applet
217                 .getParameter("userDefinedColour"));
218       }
219     }
220     initAutoAnnotation();
221
222   }
223
224   /**
225    * get the consensus sequence as displayed under the PID consensus annotation
226    * row.
227    * 
228    * @return consensus sequence as a new sequence object
229    */
230   public SequenceI getConsensusSeq()
231   {
232     if (consensus == null)
233     {
234       updateConsensus(null);
235     }
236     if (consensus == null)
237     {
238       return null;
239     }
240     StringBuilder seqs = new StringBuilder(consensus.annotations.length);
241     for (int i = 0; i < consensus.annotations.length; i++)
242     {
243       if (consensus.annotations[i] != null)
244       {
245         if (consensus.annotations[i].description.charAt(0) == '[')
246         {
247           seqs.append(consensus.annotations[i].description.charAt(1));
248         }
249         else
250         {
251           seqs.append(consensus.annotations[i].displayCharacter);
252         }
253       }
254     }
255     SequenceI sq = new Sequence("Consensus", seqs.toString());
256     sq.setDescription("Percentage Identity Consensus "
257             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
258     return sq;
259   }
260
261   java.awt.Frame nullFrame;
262
263   protected FeatureSettings featureSettings = null;
264
265   private float heightScale = 1, widthScale = 1;
266
267   public void setFont(Font f)
268   {
269     font = f;
270     if (nullFrame == null)
271     {
272       nullFrame = new java.awt.Frame();
273       nullFrame.addNotify();
274     }
275
276     java.awt.FontMetrics fm = nullFrame.getGraphics().getFontMetrics(font);
277     setCharHeight((int) (heightScale * fm.getHeight()));
278     setCharWidth((int) (widthScale * fm.charWidth('M')));
279
280     if (isUpperCasebold())
281     {
282       Font f2 = new Font(f.getName(), Font.BOLD, f.getSize());
283       fm = nullFrame.getGraphics().getFontMetrics(f2);
284       setCharWidth((int) (widthScale * (fm.stringWidth("MMMMMMMMMMM") / 10)));
285     }
286   }
287
288   public Font getFont()
289   {
290     return font;
291   }
292
293
294   public void resetSeqLimits(int height)
295   {
296     setEndSeq(height / getCharHeight());
297   }
298
299   public void setCurrentTree(NJTree tree)
300   {
301     currentTree = tree;
302   }
303
304   public NJTree getCurrentTree()
305   {
306     return currentTree;
307   }
308
309
310   boolean centreColumnLabels;
311
312   public boolean getCentreColumnLabels()
313   {
314     return centreColumnLabels;
315   }
316
317   public boolean followSelection = true;
318
319   /**
320    * @return true if view selection should always follow the selections
321    *         broadcast by other selection sources
322    */
323   public boolean getFollowSelection()
324   {
325     return followSelection;
326   }
327
328   public void sendSelection()
329   {
330     getStructureSelectionManager().sendSelection(
331                     new SequenceGroup(getSelectionGroup()),
332                     new ColumnSelection(getColumnSelection()), this);
333   }
334
335   /**
336    * Returns an instance of the StructureSelectionManager scoped to this applet
337    * instance.
338    * 
339    * @return
340    */
341   @Override
342   public StructureSelectionManager getStructureSelectionManager()
343   {
344     return jalview.structure.StructureSelectionManager
345             .getStructureSelectionManager(applet);
346   }
347
348   /**
349    * synthesize a column selection if none exists so it covers the given
350    * selection group. if wholewidth is false, no column selection is made if the
351    * selection group covers the whole alignment width.
352    * 
353    * @param sg
354    * @param wholewidth
355    */
356   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
357   {
358     int sgs, sge;
359     if (sg != null
360             && (sgs = sg.getStartRes()) >= 0
361             && sg.getStartRes() <= (sge = sg.getEndRes())
362             && (colSel == null || colSel.getSelected() == null || colSel
363                     .getSelected().size() == 0))
364     {
365       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
366       {
367         // do nothing
368         return;
369       }
370       if (colSel == null)
371       {
372         colSel = new ColumnSelection();
373       }
374       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
375       {
376         colSel.addElement(cspos);
377       }
378     }
379   }
380
381   public boolean isNormaliseSequenceLogo()
382   {
383     return normaliseSequenceLogo;
384   }
385
386   public void setNormaliseSequenceLogo(boolean state)
387   {
388     normaliseSequenceLogo = state;
389   }
390
391   /**
392    * 
393    * @return true if alignment characters should be displayed
394    */
395   public boolean isValidCharWidth()
396   {
397     return validCharWidth;
398   }
399
400   public AnnotationColumnChooser getAnnotationColumnSelectionState()
401   {
402     return annotationColumnSelectionState;
403   }
404
405   public void setAnnotationColumnSelectionState(
406           AnnotationColumnChooser annotationColumnSelectionState)
407   {
408     this.annotationColumnSelectionState = annotationColumnSelectionState;
409   }
410
411   @Override
412   public void mirrorCommand(CommandI command, boolean undo,
413           StructureSelectionManager ssm, VamsasSource source)
414   {
415     // TODO refactor so this can be pulled up to superclass or controller
416     /*
417      * Do nothing unless we are a 'complement' of the source. May replace this
418      * with direct calls not via SSM.
419      */
420     if (source instanceof AlignViewportI
421             && ((AlignViewportI) source).getCodingComplement() == this)
422     {
423       // ok to continue;
424     }
425     else
426     {
427       return;
428     }
429
430     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
431             getGapCharacter());
432     if (mappedCommand != null)
433     {
434       mappedCommand.doCommand(null);
435       firePropertyChange("alignment", null, getAlignment().getSequences());
436
437       // ap.scalePanelHolder.repaint();
438       // ap.repaint();
439     }
440   }
441
442   @Override
443   public VamsasSource getVamsasSource()
444   {
445     return this;
446   }
447
448   /**
449    * If this viewport has a (Protein/cDNA) complement, then scroll the
450    * complementary alignment to match this one.
451    */
452   public void scrollComplementaryAlignment(AlignmentPanel complementPanel)
453   {
454     if (complementPanel == null)
455     {
456       return;
457     }
458
459     /*
460      * Populate a SearchResults object with the mapped location to scroll to. If
461      * there is no complement, or it is not following highlights, or no mapping
462      * is found, the result will be empty.
463      */
464     SearchResults sr = new SearchResults();
465     int seqOffset = findComplementScrollTarget(sr);
466     if (!sr.isEmpty())
467     {
468       complementPanel.setFollowingComplementScroll(true);
469       complementPanel.scrollToCentre(sr, seqOffset);
470     }
471   }
472
473   @Override
474   public FeatureRenderer getFeatureRenderer()
475   {
476     return featureRenderer;
477   }
478
479   @Override
480   public void setFeatureRenderer(FeatureRenderer featureRenderer)
481   {
482     this.featureRenderer = featureRenderer;
483
484   }
485
486 }