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.datamodel.features.SequenceFeatures;
30 import jalview.renderer.seqfeatures.FeatureRenderer;
31 import jalview.schemes.FeatureColour;
32 import jalview.util.ColorUtils;
34 import java.awt.Color;
35 import java.beans.PropertyChangeListener;
36 import java.beans.PropertyChangeSupport;
37 import java.util.ArrayList;
38 import java.util.Arrays;
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
49 implements 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 for (String type : _fr.getFeaturesDisplayed()
121 .getVisibleFeatures())
131 public void setFeaturesDisplayedFrom(FeaturesDisplayedI featuresDisplayed)
133 av.setFeaturesDisplayed(new FeaturesDisplayed(featuresDisplayed));
137 public void setVisible(String featureType)
139 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
142 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
144 if (!fdi.isRegistered(featureType))
146 pushFeatureType(Arrays.asList(new String[] { featureType }));
148 fdi.setVisible(featureType);
152 public void setAllVisible(List<String> featureTypes)
154 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
157 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
159 List<String> nft = new ArrayList<String>();
160 for (String featureType : featureTypes)
162 if (!fdi.isRegistered(featureType))
164 nft.add(featureType);
169 pushFeatureType(nft);
171 fdi.setAllVisible(featureTypes);
175 * push a set of new types onto the render order stack. Note - this is a
176 * direct mechanism rather than the one employed in updateRenderOrder
180 private void pushFeatureType(List<String> types)
183 int ts = types.size();
184 String neworder[] = new String[(renderOrder == null ? 0
185 : renderOrder.length) + ts];
186 types.toArray(neworder);
187 if (renderOrder != null)
189 System.arraycopy(neworder, 0, neworder, renderOrder.length, ts);
190 System.arraycopy(renderOrder, 0, neworder, 0, renderOrder.length);
192 renderOrder = neworder;
195 protected Map<String, float[][]> minmax = new Hashtable<String, float[][]>();
197 public Map<String, float[][]> getMinMax()
203 * normalise a score against the max/min bounds for the feature type.
205 * @param sequenceFeature
206 * @return byte[] { signed, normalised signed (-127 to 127) or unsigned
209 protected final byte[] normaliseScore(SequenceFeature sequenceFeature)
211 float[] mm = minmax.get(sequenceFeature.type)[0];
212 final byte[] r = new byte[] { 0, (byte) 255 };
215 if (r[0] != 0 || mm[0] < 0.0)
218 r[1] = (byte) ((int) 128.0
219 + 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> findFeaturesAtColumn(SequenceI sequence, int column)
271 * include features at the position provided their feature type is
272 * displayed, and feature group is null or marked for display
274 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
275 if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
280 Set<String> visibleFeatures = getFeaturesDisplayed()
281 .getVisibleFeatures();
282 String[] visibleTypes = visibleFeatures
283 .toArray(new String[visibleFeatures.size()]);
284 List<SequenceFeature> features = sequence.findFeatures(column, column,
287 for (SequenceFeature sf : features)
289 if (!featureGroupNotShown(sf))
298 * Searches alignment for all features and updates colours
300 * @param newMadeVisible
301 * if true newly added feature types will be rendered immediately
302 * TODO: check to see if this method should actually be proxied so
303 * repaint events can be propagated by the renderer code
306 public synchronized void findAllFeatures(boolean newMadeVisible)
308 newFeatureAdded = false;
312 newFeatureAdded = true;
316 findingFeatures = true;
317 if (av.getFeaturesDisplayed() == null)
319 av.setFeaturesDisplayed(new FeaturesDisplayed());
321 FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
323 Set<String> oldfeatures = new HashSet<String>();
324 if (renderOrder != null)
326 for (int i = 0; i < renderOrder.length; i++)
328 if (renderOrder[i] != null)
330 oldfeatures.add(renderOrder[i]);
335 AlignmentI alignment = av.getAlignment();
336 List<String> allfeatures = new ArrayList<String>();
338 for (int i = 0; i < alignment.getHeight(); i++)
340 SequenceI asq = alignment.getSequenceAt(i);
341 for (String group : asq.getFeatures().getFeatureGroups(true))
343 boolean groupDisplayed = true;
346 if (featureGroups.containsKey(group))
348 groupDisplayed = featureGroups.get(group);
352 groupDisplayed = newMadeVisible;
353 featureGroups.put(group, groupDisplayed);
358 Set<String> types = asq.getFeatures().getFeatureTypesForGroups(
360 for (String type : types)
362 if (!allfeatures.contains(type)) // or use HashSet and no test?
364 allfeatures.add(type);
366 updateMinMax(asq, type, true); // todo: for all features?
372 // uncomment to add new features in alphebetical order (but JAL-2575)
373 // Collections.sort(allfeatures, String.CASE_INSENSITIVE_ORDER);
376 for (String type : allfeatures)
378 if (!oldfeatures.contains(type))
380 featuresDisplayed.setVisible(type);
386 updateRenderOrder(allfeatures);
387 findingFeatures = false;
391 * Updates the global (alignment) min and max values for a feature type from
392 * the score for a sequence, if the score is not NaN. Values are stored
393 * separately for positional and non-positional features.
399 protected void updateMinMax(SequenceI seq, String featureType,
402 float min = seq.getFeatures().getMinimumScore(featureType, positional);
403 if (Float.isNaN(min))
408 float max = seq.getFeatures().getMaximumScore(featureType, positional);
412 * { {positionalMin, positionalMax}, {nonPositionalMin, nonPositionalMax} }
416 minmax = new Hashtable<String, float[][]>();
418 synchronized (minmax)
420 float[][] mm = minmax.get(featureType);
421 int index = positional ? 0 : 1;
424 mm = new float[][] { null, null };
425 minmax.put(featureType, mm);
427 if (mm[index] == null)
429 mm[index] = new float[] { min, max };
433 mm[index][0] = Math.min(mm[index][0], min);
434 mm[index][1] = Math.max(mm[index][1], max);
438 protected Boolean firing = Boolean.FALSE;
441 * replaces the current renderOrder with the unordered features in
442 * allfeatures. The ordering of any types in both renderOrder and allfeatures
443 * is preserved, and all new feature types are rendered on top of the existing
444 * types, in the order given by getOrder or the order given in allFeatures.
445 * Note. this operates directly on the featureOrder hash for efficiency. TODO:
446 * eliminate the float storage for computing/recalling the persistent ordering
447 * New Cability: updates min/max for colourscheme range if its dynamic
451 private void updateRenderOrder(List<String> allFeatures)
453 List<String> allfeatures = new ArrayList<String>(allFeatures);
454 String[] oldRender = renderOrder;
455 renderOrder = new String[allfeatures.size()];
456 boolean initOrders = (featureOrder == null);
458 if (oldRender != null && oldRender.length > 0)
460 for (int j = 0; j < oldRender.length; j++)
462 if (oldRender[j] != null)
466 setOrder(oldRender[j],
467 (1 - (1 + (float) j) / oldRender.length));
469 if (allfeatures.contains(oldRender[j]))
471 renderOrder[opos++] = oldRender[j]; // existing features always
472 // appear below new features
473 allfeatures.remove(oldRender[j]);
476 float[][] mmrange = minmax.get(oldRender[j]);
479 FeatureColourI fc = featureColours.get(oldRender[j]);
480 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
482 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
490 if (allfeatures.size() == 0)
492 // no new features - leave order unchanged.
495 int i = allfeatures.size() - 1;
497 boolean sort = false;
498 String[] newf = new String[allfeatures.size()];
499 float[] sortOrder = new float[allfeatures.size()];
500 for (String newfeat : allfeatures)
505 // update from new features minmax if necessary
506 float[][] mmrange = minmax.get(newf[i]);
509 FeatureColourI fc = featureColours.get(newf[i]);
510 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
512 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
516 if (initOrders || !featureOrder.containsKey(newf[i]))
518 int denom = initOrders ? allfeatures.size() : featureOrder.size();
519 // new unordered feature - compute persistent ordering at head of
520 // existing features.
521 setOrder(newf[i], i / (float) denom);
523 // set order from newly found feature from persisted ordering.
524 sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
527 // only sort if we need to
528 sort = sort || sortOrder[i] > sortOrder[i + 1];
532 if (iSize > 1 && sort)
534 jalview.util.QuickSort.sort(sortOrder, newf);
537 System.arraycopy(newf, 0, renderOrder, opos, newf.length);
541 * get a feature style object for the given type string. Creates a
542 * java.awt.Color for a featureType with no existing colourscheme.
548 public FeatureColourI getFeatureStyle(String featureType)
550 FeatureColourI fc = featureColours.get(featureType);
553 Color col = ColorUtils.createColourFromName(featureType);
554 fc = new FeatureColour(col);
555 featureColours.put(featureType, fc);
561 * Returns the configured colour for a particular feature instance. This
562 * includes calculation of 'colour by label', or of a graduated score colour,
563 * if applicable. It does not take into account feature visibility or colour
564 * transparency. Returns null for a score feature whose score value lies
565 * outside any colour threshold.
570 public Color getColour(SequenceFeature feature)
572 FeatureColourI fc = getFeatureStyle(feature.getType());
573 return fc.getColor(feature);
577 * Answers true if the feature type is currently selected to be displayed,
583 protected boolean showFeatureOfType(String type)
585 return type == null ? false : av.getFeaturesDisplayed().isVisible(type);
589 public void setColour(String featureType, FeatureColourI col)
591 featureColours.put(featureType, col);
595 public void setTransparency(float value)
597 transparency = value;
601 public float getTransparency()
607 * analogous to colour - store a normalized ordering for all feature types in
608 * this rendering context.
611 * Feature type string
613 * normalized priority - 0 means always appears on top, 1 means
616 public float setOrder(String type, float position)
618 if (featureOrder == null)
620 featureOrder = new Hashtable<String, Float>();
622 featureOrder.put(type, new Float(position));
627 * get the global priority (0 (top) to 1 (bottom))
630 * @return [0,1] or -1 for a type without a priority
632 public float getOrder(String type)
634 if (featureOrder != null)
636 if (featureOrder.containsKey(type))
638 return featureOrder.get(type).floatValue();
645 public Map<String, FeatureColourI> getFeatureColours()
647 return featureColours;
651 * Replace current ordering with new ordering
654 * { String(Type), Colour(Type), Boolean(Displayed) }
655 * @return true if any visible features have been reordered, else false
657 public boolean setFeaturePriority(Object[][] data)
659 return setFeaturePriority(data, true);
663 * Sets the priority order for features, with the highest priority (displayed
664 * on top) at the start of the data array
667 * { String(Type), Colour(Type), Boolean(Displayed) }
669 * when true current featureDisplay list will be cleared
670 * @return true if any visible features have been reordered or recoloured,
671 * else false (i.e. no need to repaint)
673 public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
676 * note visible feature ordering and colours before update
678 List<String> visibleFeatures = getDisplayedFeatureTypes();
679 Map<String, FeatureColourI> visibleColours = new HashMap<String, FeatureColourI>(
680 getFeatureColours());
682 FeaturesDisplayedI av_featuresdisplayed = null;
685 if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
687 av.getFeaturesDisplayed().clear();
691 av.setFeaturesDisplayed(
692 av_featuresdisplayed = new FeaturesDisplayed());
697 av_featuresdisplayed = av.getFeaturesDisplayed();
703 // The feature table will display high priority
704 // features at the top, but these are the ones
705 // we need to render last, so invert the data
706 renderOrder = new String[data.length];
710 for (int i = 0; i < data.length; i++)
712 String type = data[i][0].toString();
713 setColour(type, (FeatureColourI) data[i][1]);
714 if (((Boolean) data[i][2]).booleanValue())
716 av_featuresdisplayed.setVisible(type);
719 renderOrder[data.length - i - 1] = type;
724 * get the new visible ordering and return true if it has changed
725 * order or any colour has changed
727 List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
728 if (!visibleFeatures.equals(reorderedVisibleFeatures))
731 * the list of ordered visible features has changed
737 * return true if any feature colour has changed
739 for (String feature : visibleFeatures)
741 if (visibleColours.get(feature) != getFeatureStyle(feature))
751 * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
753 public void addPropertyChangeListener(PropertyChangeListener listener)
755 changeSupport.addPropertyChangeListener(listener);
760 * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
762 public void removePropertyChangeListener(PropertyChangeListener listener)
764 changeSupport.removePropertyChangeListener(listener);
767 public Set<String> getAllFeatureColours()
769 return featureColours.keySet();
772 public void clearRenderOrder()
777 public boolean hasRenderOrder()
779 return renderOrder != null;
783 * Returns feature types in ordering of rendering, where last means on top
785 public List<String> getRenderOrder()
787 if (renderOrder == null)
789 return Arrays.asList(new String[] {});
791 return Arrays.asList(renderOrder);
794 public int getFeatureGroupsSize()
796 return featureGroups != null ? 0 : featureGroups.size();
800 public List<String> getFeatureGroups()
802 // conflict between applet and desktop - featureGroups returns the map in
803 // the desktop featureRenderer
804 return (featureGroups == null) ? Arrays.asList(new String[0])
805 : Arrays.asList(featureGroups.keySet().toArray(new String[0]));
808 public boolean checkGroupVisibility(String group,
809 boolean newGroupsVisible)
811 if (featureGroups == null)
813 // then an exception happens next..
815 if (featureGroups.containsKey(group))
817 return featureGroups.get(group).booleanValue();
819 if (newGroupsVisible)
821 featureGroups.put(group, new Boolean(true));
828 * get visible or invisible groups
831 * true to return visible groups, false to return hidden ones.
832 * @return list of groups
835 public List<String> getGroups(boolean visible)
837 if (featureGroups != null)
839 List<String> gp = new ArrayList<String>();
841 for (String grp : featureGroups.keySet())
843 Boolean state = featureGroups.get(grp);
844 if (state.booleanValue() == visible)
855 public void setGroupVisibility(String group, boolean visible)
857 featureGroups.put(group, new Boolean(visible));
861 public void setGroupVisibility(List<String> toset, boolean visible)
863 if (toset != null && toset.size() > 0 && featureGroups != null)
865 boolean rdrw = false;
866 for (String gst : toset)
868 Boolean st = featureGroups.get(gst);
869 featureGroups.put(gst, new Boolean(visible));
872 rdrw = rdrw || (visible != st.booleanValue());
877 // set local flag indicating redraw needed ?
883 public Map<String, FeatureColourI> getDisplayedFeatureCols()
885 Map<String, FeatureColourI> fcols = new Hashtable<String, FeatureColourI>();
886 if (getViewport().getFeaturesDisplayed() == null)
890 Set<String> features = getViewport().getFeaturesDisplayed()
891 .getVisibleFeatures();
892 for (String feature : features)
894 fcols.put(feature, getFeatureStyle(feature));
900 public FeaturesDisplayedI getFeaturesDisplayed()
902 return av.getFeaturesDisplayed();
906 * Returns a (possibly empty) list of visible feature types, in render order
910 public List<String> getDisplayedFeatureTypes()
912 List<String> typ = getRenderOrder();
913 List<String> displayed = new ArrayList<String>();
914 FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
915 if (feature_disp != null)
917 synchronized (feature_disp)
919 for (String type : typ)
921 if (feature_disp.isVisible(type))
932 public List<String> getDisplayedFeatureGroups()
934 List<String> _gps = new ArrayList<String>();
935 for (String gp : getFeatureGroups())
937 if (checkGroupVisibility(gp, false))
946 * Answers true if the feature belongs to a feature group which is not
947 * currently displayed, else false
949 * @param sequenceFeature
952 protected boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
954 return featureGroups != null
955 && sequenceFeature.featureGroup != null
956 && sequenceFeature.featureGroup.length() != 0
957 && featureGroups.containsKey(sequenceFeature.featureGroup)
958 && !featureGroups.get(sequenceFeature.featureGroup)
966 public List<SequenceFeature> findFeaturesAtResidue(SequenceI sequence,
969 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
970 if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
976 * include features at the position provided their feature type is
977 * displayed, and feature group is null or the empty string
978 * or marked for display
980 Set<String> visibleFeatures = getFeaturesDisplayed()
981 .getVisibleFeatures();
982 String[] visibleTypes = visibleFeatures
983 .toArray(new String[visibleFeatures.size()]);
984 List<SequenceFeature> features = sequence.getFeatures().findFeatures(
985 resNo, resNo, visibleTypes);
987 for (SequenceFeature sf : features)
989 if (!featureGroupNotShown(sf))
998 * Removes from the list of features any that have a feature group that is not
999 * displayed, or duplicate the location of a feature of the same type (unless
1000 * a graduated colour scheme or colour by label is applied). Should be used
1001 * only for features of the same feature colour (which normally implies the
1002 * same feature type).
1007 public void filterFeaturesForDisplay(List<SequenceFeature> features,
1010 if (features.isEmpty())
1014 SequenceFeatures.sortFeatures(features, true);
1015 boolean simpleColour = fc == null || fc.isSimpleColour();
1016 SequenceFeature lastFeature = null;
1018 Iterator<SequenceFeature> it = features.iterator();
1019 while (it.hasNext())
1021 SequenceFeature sf = it.next();
1022 if (featureGroupNotShown(sf))
1029 * a feature is redundant for rendering purposes if it has the
1030 * same extent as another (so would just redraw the same colour);
1031 * (checking type and isContactFeature as a fail-safe here, although
1032 * currently they are guaranteed to match in this context)
1036 if (lastFeature != null && sf.getBegin() == lastFeature.getBegin()
1037 && sf.getEnd() == lastFeature.getEnd()
1038 && sf.isContactFeature() == lastFeature.isContactFeature()
1039 && sf.getType().equals(lastFeature.getType()))