2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.viewmodel.seqfeatures;
23 import jalview.api.AlignViewportI;
24 import jalview.api.FeatureColourI;
25 import jalview.api.FeaturesDisplayedI;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.renderer.seqfeatures.FeatureRenderer;
30 import jalview.schemes.FeatureColour;
31 import jalview.util.ColorUtils;
33 import java.awt.Color;
34 import java.beans.PropertyChangeListener;
35 import java.beans.PropertyChangeSupport;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collections;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Hashtable;
42 import java.util.Iterator;
43 import java.util.List;
46 import java.util.concurrent.ConcurrentHashMap;
48 public abstract class FeatureRendererModel implements
49 jalview.api.FeatureRenderer
53 * global transparency for feature
55 protected float transparency = 1.0f;
57 protected Map<String, FeatureColourI> featureColours = new ConcurrentHashMap<String, FeatureColourI>();
59 protected Map<String, Boolean> featureGroups = new ConcurrentHashMap<String, Boolean>();
61 protected String[] renderOrder;
63 Map<String, Float> featureOrder = null;
65 protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
68 protected AlignViewportI av;
71 public AlignViewportI getViewport()
76 public FeatureRendererSettings getSettings()
78 return new FeatureRendererSettings(this);
81 public void transferSettings(FeatureRendererSettings fr)
83 this.renderOrder = fr.renderOrder;
84 this.featureGroups = fr.featureGroups;
85 this.featureColours = fr.featureColours;
86 this.transparency = fr.transparency;
87 this.featureOrder = fr.featureOrder;
91 * update from another feature renderer
96 public void transferSettings(jalview.api.FeatureRenderer _fr)
98 FeatureRenderer fr = (FeatureRenderer) _fr;
99 FeatureRendererSettings frs = new FeatureRendererSettings(fr);
100 this.renderOrder = frs.renderOrder;
101 this.featureGroups = frs.featureGroups;
102 this.featureColours = frs.featureColours;
103 this.transparency = frs.transparency;
104 this.featureOrder = frs.featureOrder;
105 if (av != null && av != fr.getViewport())
107 // copy over the displayed feature settings
108 if (_fr.getFeaturesDisplayed() != null)
110 FeaturesDisplayedI fd = getFeaturesDisplayed();
113 setFeaturesDisplayedFrom(_fr.getFeaturesDisplayed());
120 java.util.Iterator<String> fdisp = _fr.getFeaturesDisplayed()
121 .getVisibleFeatures();
122 while (fdisp.hasNext())
124 fd.setVisible(fdisp.next());
132 public void setFeaturesDisplayedFrom(FeaturesDisplayedI featuresDisplayed)
134 av.setFeaturesDisplayed(new FeaturesDisplayed(featuresDisplayed));
138 public void setVisible(String featureType)
140 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
143 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
145 if (!fdi.isRegistered(featureType))
147 pushFeatureType(Arrays.asList(new String[] { featureType }));
149 fdi.setVisible(featureType);
153 public void setAllVisible(List<String> featureTypes)
155 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
158 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
160 List<String> nft = new ArrayList<String>();
161 for (String featureType : featureTypes)
163 if (!fdi.isRegistered(featureType))
165 nft.add(featureType);
170 pushFeatureType(nft);
172 fdi.setAllVisible(featureTypes);
176 * push a set of new types onto the render order stack. Note - this is a
177 * direct mechanism rather than the one employed in updateRenderOrder
181 private void pushFeatureType(List<String> types)
184 int ts = types.size();
185 String neworder[] = new String[(renderOrder == null ? 0
186 : renderOrder.length) + ts];
187 types.toArray(neworder);
188 if (renderOrder != null)
190 System.arraycopy(neworder, 0, neworder, renderOrder.length, ts);
191 System.arraycopy(renderOrder, 0, neworder, 0, renderOrder.length);
193 renderOrder = neworder;
196 protected Map<String, float[][]> minmax = new Hashtable<String, float[][]>();
198 public Map<String, float[][]> getMinMax()
204 * normalise a score against the max/min bounds for the feature type.
206 * @param sequenceFeature
207 * @return byte[] { signed, normalised signed (-127 to 127) or unsigned
210 protected final byte[] normaliseScore(SequenceFeature sequenceFeature)
212 float[] mm = minmax.get(sequenceFeature.type)[0];
213 final byte[] r = new byte[] { 0, (byte) 255 };
216 if (r[0] != 0 || mm[0] < 0.0)
219 r[1] = (byte) ((int) 128.0 + 127.0 * (sequenceFeature.score / mm[1]));
223 r[1] = (byte) ((int) 255.0 * (sequenceFeature.score / mm[1]));
229 boolean newFeatureAdded = false;
231 boolean findingFeatures = false;
233 protected boolean updateFeatures()
235 if (av.getFeaturesDisplayed() == null || renderOrder == null
239 if (av.getFeaturesDisplayed().getVisibleFeatureCount() < 1)
244 // TODO: decide if we should check for the visible feature count first
249 * search the alignment for all new features, give them a colour and display
250 * them. Then fires a PropertyChangeEvent on the changeSupport object.
253 protected void findAllFeatures()
255 synchronized (firing)
257 if (firing.equals(Boolean.FALSE))
259 firing = Boolean.TRUE;
260 findAllFeatures(true); // add all new features as visible
261 changeSupport.firePropertyChange("changeSupport", null, null);
262 firing = Boolean.FALSE;
268 public List<SequenceFeature> findFeaturesAtRes(SequenceI sequence, int res)
270 ArrayList<SequenceFeature> tmp = new ArrayList<SequenceFeature>();
271 SequenceFeature[] features = sequence.getSequenceFeatures();
273 if (features != null)
275 for (int i = 0; i < features.length; i++)
277 if (!av.areFeaturesDisplayed()
278 || !av.getFeaturesDisplayed().isVisible(
279 features[i].getType()))
284 if (features[i].featureGroup != null
285 && featureGroups != null
286 && featureGroups.containsKey(features[i].featureGroup)
287 && !featureGroups.get(features[i].featureGroup)
293 // check if start/end are at res, and if not a contact feature, that res
294 // lies between start and end
295 if ((features[i].getBegin() == res || features[i].getEnd() == res)
296 || (!features[i].isContactFeature()
297 && (features[i].getBegin() < res) && (features[i]
300 tmp.add(features[i]);
308 * Searches alignment for all features and updates colours
310 * @param newMadeVisible
311 * if true newly added feature types will be rendered immediately
312 * TODO: check to see if this method should actually be proxied so
313 * repaint events can be propagated by the renderer code
316 public synchronized void findAllFeatures(boolean newMadeVisible)
318 newFeatureAdded = false;
322 newFeatureAdded = true;
326 findingFeatures = true;
327 if (av.getFeaturesDisplayed() == null)
329 av.setFeaturesDisplayed(new FeaturesDisplayed());
331 FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
333 Set<String> oldfeatures = new HashSet<String>();
334 if (renderOrder != null)
336 for (int i = 0; i < renderOrder.length; i++)
338 if (renderOrder[i] != null)
340 oldfeatures.add(renderOrder[i]);
345 AlignmentI alignment = av.getAlignment();
346 List<String> allfeatures = new ArrayList<String>(); // or HashSet?
348 for (int i = 0; i < alignment.getHeight(); i++)
350 SequenceI asq = alignment.getSequenceAt(i);
351 for (String group : asq.getFeatures().getFeatureGroups(true))
357 Boolean groupDisplayed = featureGroups.get(group);
358 if (groupDisplayed == null)
360 groupDisplayed = Boolean.valueOf(newMadeVisible);
361 featureGroups.put(group, groupDisplayed);
365 Set<String> types = asq.getFeatures().getFeatureTypesForGroups(
367 for (String type : types)
369 if (!allfeatures.contains(type)) // or use HashSet and no test?
371 allfeatures.add(type);
373 updateMinMax(asq, type, true); // todo: for all features?
380 * mark any new feature types as visible
382 Collections.sort(allfeatures, String.CASE_INSENSITIVE_ORDER);
385 for (String type : allfeatures)
387 if (!oldfeatures.contains(type))
389 featuresDisplayed.setVisible(type);
395 updateRenderOrder(allfeatures);
396 findingFeatures = false;
400 * Updates the global (alignment) min and max values for a feature type from
401 * the score for a sequence, if the score is not NaN. Values are stored
402 * separately for positional and non-positional features.
408 protected void updateMinMax(SequenceI seq, String featureType,
411 float min = seq.getFeatures().getMinimumScore(featureType, positional);
412 if (Float.isNaN(min))
417 float max = seq.getFeatures().getMaximumScore(featureType, positional);
421 * { {positionalMin, positionalMax}, {nonPositionalMin, nonPositionalMax} }
425 minmax = new Hashtable<String, float[][]>();
427 synchronized (minmax)
429 float[][] mm = minmax.get(featureType);
430 int index = positional ? 0 : 1;
433 mm = new float[][] { null, null };
434 minmax.put(featureType, mm);
436 if (mm[index] == null)
438 mm[index] = new float[] { min, max };
442 mm[index][0] = Math.min(mm[index][0], min);
443 mm[index][1] = Math.max(mm[index][1], max);
447 protected Boolean firing = Boolean.FALSE;
450 * replaces the current renderOrder with the unordered features in
451 * allfeatures. The ordering of any types in both renderOrder and allfeatures
452 * is preserved, and all new feature types are rendered on top of the existing
453 * types, in the order given by getOrder or the order given in allFeatures.
454 * Note. this operates directly on the featureOrder hash for efficiency. TODO:
455 * eliminate the float storage for computing/recalling the persistent ordering
456 * New Cability: updates min/max for colourscheme range if its dynamic
460 private void updateRenderOrder(List<String> allFeatures)
462 List<String> allfeatures = new ArrayList<String>(allFeatures);
463 String[] oldRender = renderOrder;
464 renderOrder = new String[allfeatures.size()];
465 boolean initOrders = (featureOrder == null);
467 if (oldRender != null && oldRender.length > 0)
469 for (int j = 0; j < oldRender.length; j++)
471 if (oldRender[j] != null)
475 setOrder(oldRender[j], (1 - (1 + (float) j) / oldRender.length));
477 if (allfeatures.contains(oldRender[j]))
479 renderOrder[opos++] = oldRender[j]; // existing features always
480 // appear below new features
481 allfeatures.remove(oldRender[j]);
484 float[][] mmrange = minmax.get(oldRender[j]);
487 FeatureColourI fc = featureColours.get(oldRender[j]);
488 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
490 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
498 if (allfeatures.size() == 0)
500 // no new features - leave order unchanged.
503 int i = allfeatures.size() - 1;
505 boolean sort = false;
506 String[] newf = new String[allfeatures.size()];
507 float[] sortOrder = new float[allfeatures.size()];
508 for (String newfeat : allfeatures)
513 // update from new features minmax if necessary
514 float[][] mmrange = minmax.get(newf[i]);
517 FeatureColourI fc = featureColours.get(newf[i]);
518 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
520 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
524 if (initOrders || !featureOrder.containsKey(newf[i]))
526 int denom = initOrders ? allfeatures.size() : featureOrder.size();
527 // new unordered feature - compute persistent ordering at head of
528 // existing features.
529 setOrder(newf[i], i / (float) denom);
531 // set order from newly found feature from persisted ordering.
532 sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
535 // only sort if we need to
536 sort = sort || sortOrder[i] > sortOrder[i + 1];
540 if (iSize > 1 && sort)
542 jalview.util.QuickSort.sort(sortOrder, newf);
545 System.arraycopy(newf, 0, renderOrder, opos, newf.length);
549 * get a feature style object for the given type string. Creates a
550 * java.awt.Color for a featureType with no existing colourscheme.
556 public FeatureColourI getFeatureStyle(String featureType)
558 FeatureColourI fc = featureColours.get(featureType);
561 Color col = ColorUtils.createColourFromName(featureType);
562 fc = new FeatureColour(col);
563 featureColours.put(featureType, fc);
569 * Returns the configured colour for a particular feature instance. This
570 * includes calculation of 'colour by label', or of a graduated score colour,
571 * if applicable. It does not take into account feature visibility or colour
577 public Color getColour(SequenceFeature feature)
579 FeatureColourI fc = getFeatureStyle(feature.getType());
580 return fc.getColor(feature);
584 * Answers true unless the feature has a graduated colour scheme and the
585 * feature value lies outside the current threshold for display
587 * @param sequenceFeature
590 protected boolean showFeature(SequenceFeature sequenceFeature)
592 FeatureColourI fc = getFeatureStyle(sequenceFeature.type);
593 return fc.isColored(sequenceFeature);
597 * Answers true if the feature type is currently selected to be displayed,
603 protected boolean showFeatureOfType(String type)
605 return type == null ? false : av.getFeaturesDisplayed().isVisible(type);
609 public void setColour(String featureType, FeatureColourI col)
611 featureColours.put(featureType, col);
615 public void setTransparency(float value)
617 transparency = value;
621 public float getTransparency()
627 * analogous to colour - store a normalized ordering for all feature types in
628 * this rendering context.
631 * Feature type string
633 * normalized priority - 0 means always appears on top, 1 means
636 public float setOrder(String type, float position)
638 if (featureOrder == null)
640 featureOrder = new Hashtable<String, Float>();
642 featureOrder.put(type, new Float(position));
647 * get the global priority (0 (top) to 1 (bottom))
650 * @return [0,1] or -1 for a type without a priority
652 public float getOrder(String type)
654 if (featureOrder != null)
656 if (featureOrder.containsKey(type))
658 return featureOrder.get(type).floatValue();
665 public Map<String, FeatureColourI> getFeatureColours()
667 return featureColours;
671 * Replace current ordering with new ordering
674 * { String(Type), Colour(Type), Boolean(Displayed) }
675 * @return true if any visible features have been reordered, else false
677 public boolean setFeaturePriority(Object[][] data)
679 return setFeaturePriority(data, true);
683 * Sets the priority order for features, with the highest priority (displayed
684 * on top) at the start of the data array
687 * { String(Type), Colour(Type), Boolean(Displayed) }
689 * when true current featureDisplay list will be cleared
690 * @return true if any visible features have been reordered or recoloured,
691 * else false (i.e. no need to repaint)
693 public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
696 * note visible feature ordering and colours before update
698 List<String> visibleFeatures = getDisplayedFeatureTypes();
699 Map<String, FeatureColourI> visibleColours = new HashMap<String, FeatureColourI>(
700 getFeatureColours());
702 FeaturesDisplayedI av_featuresdisplayed = null;
705 if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
707 av.getFeaturesDisplayed().clear();
711 av.setFeaturesDisplayed(av_featuresdisplayed = new FeaturesDisplayed());
716 av_featuresdisplayed = av.getFeaturesDisplayed();
722 // The feature table will display high priority
723 // features at the top, but these are the ones
724 // we need to render last, so invert the data
725 renderOrder = new String[data.length];
729 for (int i = 0; i < data.length; i++)
731 String type = data[i][0].toString();
732 setColour(type, (FeatureColourI) data[i][1]);
733 if (((Boolean) data[i][2]).booleanValue())
735 av_featuresdisplayed.setVisible(type);
738 renderOrder[data.length - i - 1] = type;
743 * get the new visible ordering and return true if it has changed
744 * order or any colour has changed
746 List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
747 if (!visibleFeatures.equals(reorderedVisibleFeatures))
750 * the list of ordered visible features has changed
756 * return true if any feature colour has changed
758 for (String feature : visibleFeatures)
760 if (visibleColours.get(feature) != getFeatureStyle(feature))
770 * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
772 public void addPropertyChangeListener(PropertyChangeListener listener)
774 changeSupport.addPropertyChangeListener(listener);
779 * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
781 public void removePropertyChangeListener(PropertyChangeListener listener)
783 changeSupport.removePropertyChangeListener(listener);
786 public Set<String> getAllFeatureColours()
788 return featureColours.keySet();
791 public void clearRenderOrder()
796 public boolean hasRenderOrder()
798 return renderOrder != null;
802 * Returns feature types in ordering of rendering, where last means on top
804 public List<String> getRenderOrder()
806 if (renderOrder == null)
808 return Arrays.asList(new String[] {});
810 return Arrays.asList(renderOrder);
813 public int getFeatureGroupsSize()
815 return featureGroups != null ? 0 : featureGroups.size();
819 public List<String> getFeatureGroups()
821 // conflict between applet and desktop - featureGroups returns the map in
822 // the desktop featureRenderer
823 return (featureGroups == null) ? Arrays.asList(new String[0]) : Arrays
824 .asList(featureGroups.keySet().toArray(new String[0]));
827 public boolean checkGroupVisibility(String group, boolean newGroupsVisible)
829 if (featureGroups == null)
831 // then an exception happens next..
833 if (featureGroups.containsKey(group))
835 return featureGroups.get(group).booleanValue();
837 if (newGroupsVisible)
839 featureGroups.put(group, new Boolean(true));
846 * get visible or invisible groups
849 * true to return visible groups, false to return hidden ones.
850 * @return list of groups
853 public List<String> getGroups(boolean visible)
855 if (featureGroups != null)
857 List<String> gp = new ArrayList<String>();
859 for (String grp : featureGroups.keySet())
861 Boolean state = featureGroups.get(grp);
862 if (state.booleanValue() == visible)
873 public void setGroupVisibility(String group, boolean visible)
875 featureGroups.put(group, new Boolean(visible));
879 public void setGroupVisibility(List<String> toset, boolean visible)
881 if (toset != null && toset.size() > 0 && featureGroups != null)
883 boolean rdrw = false;
884 for (String gst : toset)
886 Boolean st = featureGroups.get(gst);
887 featureGroups.put(gst, new Boolean(visible));
890 rdrw = rdrw || (visible != st.booleanValue());
895 // set local flag indicating redraw needed ?
901 public Map<String, FeatureColourI> getDisplayedFeatureCols()
903 Map<String, FeatureColourI> fcols = new Hashtable<String, FeatureColourI>();
904 if (getViewport().getFeaturesDisplayed() == null)
908 Iterator<String> features = getViewport().getFeaturesDisplayed()
909 .getVisibleFeatures();
910 while (features.hasNext())
912 String feature = features.next();
913 fcols.put(feature, getFeatureStyle(feature));
919 public FeaturesDisplayedI getFeaturesDisplayed()
921 return av.getFeaturesDisplayed();
925 * Returns a (possibly empty) list of visible feature types, in render order
929 public List<String> getDisplayedFeatureTypes()
931 List<String> typ = getRenderOrder();
932 List<String> displayed = new ArrayList<String>();
933 FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
934 if (feature_disp != null)
936 synchronized (feature_disp)
938 for (String type : typ)
940 if (feature_disp.isVisible(type))
951 public List<String> getDisplayedFeatureGroups()
953 List<String> _gps = new ArrayList<String>();
954 boolean valid = false;
955 for (String gp : getFeatureGroups())
957 if (checkGroupVisibility(gp, false))
968 // gps = new String[_gps.size()];
969 // _gps.toArray(gps);