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.List;
45 import java.util.concurrent.ConcurrentHashMap;
47 public abstract class FeatureRendererModel implements
48 jalview.api.FeatureRenderer
52 * global transparency for feature
54 protected float transparency = 1.0f;
56 protected Map<String, FeatureColourI> featureColours = new ConcurrentHashMap<String, FeatureColourI>();
58 protected Map<String, Boolean> featureGroups = new ConcurrentHashMap<String, Boolean>();
60 protected String[] renderOrder;
62 Map<String, Float> featureOrder = null;
64 protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
67 protected AlignViewportI av;
70 public AlignViewportI getViewport()
75 public FeatureRendererSettings getSettings()
77 return new FeatureRendererSettings(this);
80 public void transferSettings(FeatureRendererSettings fr)
82 this.renderOrder = fr.renderOrder;
83 this.featureGroups = fr.featureGroups;
84 this.featureColours = fr.featureColours;
85 this.transparency = fr.transparency;
86 this.featureOrder = fr.featureOrder;
90 * update from another feature renderer
95 public void transferSettings(jalview.api.FeatureRenderer _fr)
97 FeatureRenderer fr = (FeatureRenderer) _fr;
98 FeatureRendererSettings frs = new FeatureRendererSettings(fr);
99 this.renderOrder = frs.renderOrder;
100 this.featureGroups = frs.featureGroups;
101 this.featureColours = frs.featureColours;
102 this.transparency = frs.transparency;
103 this.featureOrder = frs.featureOrder;
104 if (av != null && av != fr.getViewport())
106 // copy over the displayed feature settings
107 if (_fr.getFeaturesDisplayed() != null)
109 FeaturesDisplayedI fd = getFeaturesDisplayed();
112 setFeaturesDisplayedFrom(_fr.getFeaturesDisplayed());
119 for (String type : _fr.getFeaturesDisplayed()
120 .getVisibleFeatures())
130 public void setFeaturesDisplayedFrom(FeaturesDisplayedI featuresDisplayed)
132 av.setFeaturesDisplayed(new FeaturesDisplayed(featuresDisplayed));
136 public void setVisible(String featureType)
138 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
141 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
143 if (!fdi.isRegistered(featureType))
145 pushFeatureType(Arrays.asList(new String[] { featureType }));
147 fdi.setVisible(featureType);
151 public void setAllVisible(List<String> featureTypes)
153 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
156 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
158 List<String> nft = new ArrayList<String>();
159 for (String featureType : featureTypes)
161 if (!fdi.isRegistered(featureType))
163 nft.add(featureType);
168 pushFeatureType(nft);
170 fdi.setAllVisible(featureTypes);
174 * push a set of new types onto the render order stack. Note - this is a
175 * direct mechanism rather than the one employed in updateRenderOrder
179 private void pushFeatureType(List<String> types)
182 int ts = types.size();
183 String neworder[] = new String[(renderOrder == null ? 0
184 : renderOrder.length) + ts];
185 types.toArray(neworder);
186 if (renderOrder != null)
188 System.arraycopy(neworder, 0, neworder, renderOrder.length, ts);
189 System.arraycopy(renderOrder, 0, neworder, 0, renderOrder.length);
191 renderOrder = neworder;
194 protected Map<String, float[][]> minmax = new Hashtable<String, float[][]>();
196 public Map<String, float[][]> getMinMax()
202 * normalise a score against the max/min bounds for the feature type.
204 * @param sequenceFeature
205 * @return byte[] { signed, normalised signed (-127 to 127) or unsigned
208 protected final byte[] normaliseScore(SequenceFeature sequenceFeature)
210 float[] mm = minmax.get(sequenceFeature.type)[0];
211 final byte[] r = new byte[] { 0, (byte) 255 };
214 if (r[0] != 0 || mm[0] < 0.0)
217 r[1] = (byte) ((int) 128.0 + 127.0 * (sequenceFeature.score / mm[1]));
221 r[1] = (byte) ((int) 255.0 * (sequenceFeature.score / mm[1]));
227 boolean newFeatureAdded = false;
229 boolean findingFeatures = false;
231 protected boolean updateFeatures()
233 if (av.getFeaturesDisplayed() == null || renderOrder == null
237 if (av.getFeaturesDisplayed().getVisibleFeatureCount() < 1)
242 // TODO: decide if we should check for the visible feature count first
247 * search the alignment for all new features, give them a colour and display
248 * them. Then fires a PropertyChangeEvent on the changeSupport object.
251 protected void findAllFeatures()
253 synchronized (firing)
255 if (firing.equals(Boolean.FALSE))
257 firing = Boolean.TRUE;
258 findAllFeatures(true); // add all new features as visible
259 changeSupport.firePropertyChange("changeSupport", null, null);
260 firing = Boolean.FALSE;
266 public List<SequenceFeature> findFeaturesAtRes(SequenceI sequence, int res)
268 List<SequenceFeature> result = new ArrayList<SequenceFeature>();
269 if (!av.areFeaturesDisplayed())
274 Set<String> visibleFeatures = getFeaturesDisplayed()
275 .getVisibleFeatures();
276 String[] visibleTypes = visibleFeatures
277 .toArray(new String[visibleFeatures.size()]);
280 * include features at the position provided their feature type is
281 * displayed, and feature group is null or marked for display
283 List<SequenceFeature> features = sequence.getFeatures().findFeatures(
284 res, res, visibleTypes);
286 for (SequenceFeature sf : features)
288 if (!featureGroupNotShown(sf))
297 * Searches alignment for all features and updates colours
299 * @param newMadeVisible
300 * if true newly added feature types will be rendered immediately
301 * TODO: check to see if this method should actually be proxied so
302 * repaint events can be propagated by the renderer code
305 public synchronized void findAllFeatures(boolean newMadeVisible)
307 newFeatureAdded = false;
311 newFeatureAdded = true;
315 findingFeatures = true;
316 if (av.getFeaturesDisplayed() == null)
318 av.setFeaturesDisplayed(new FeaturesDisplayed());
320 FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
322 Set<String> oldfeatures = new HashSet<String>();
323 if (renderOrder != null)
325 for (int i = 0; i < renderOrder.length; i++)
327 if (renderOrder[i] != null)
329 oldfeatures.add(renderOrder[i]);
336 // if (minmax == null)
338 // minmax = new Hashtable<String, float[][]>();
341 // Set<String> oldGroups = new HashSet<String>(featureGroups.keySet());
342 // >>>>>>> refs/heads/develop
343 AlignmentI alignment = av.getAlignment();
344 List<String> allfeatures = new ArrayList<String>(); // or HashSet?
346 for (int i = 0; i < alignment.getHeight(); i++)
348 SequenceI asq = alignment.getSequenceAt(i);
349 for (String group : asq.getFeatures().getFeatureGroups(true))
353 * features in null group are always displayed; other groups
354 * keep their current visibility; new groups as 'newMadeVisible'
356 boolean groupDisplayed = true;
363 // while (index < features.length)
365 // String fgrp = features[index].getFeatureGroup();
366 // oldGroups.remove(fgrp);
367 // if (!featuresDisplayed.isRegistered(features[index].getType()))
368 // >>>>>>> refs/heads/develop
371 if (featureGroups.containsKey(group))
374 // >>>>>>> refs/heads/develop
376 groupDisplayed = featureGroups.get(group);
380 groupDisplayed = newMadeVisible;
381 featureGroups.put(group, groupDisplayed);
386 Set<String> types = asq.getFeatures().getFeatureTypesForGroups(
388 for (String type : types)
390 if (!allfeatures.contains(type)) // or use HashSet and no test?
392 allfeatures.add(type);
394 updateMinMax(asq, type, true); // todo: for all features?
402 * mark any new feature types as visible
404 Collections.sort(allfeatures, String.CASE_INSENSITIVE_ORDER);
407 for (String type : allfeatures)
409 if (!oldfeatures.contains(type))
411 featuresDisplayed.setVisible(type);
416 // * oldGroups now consists of groups that no longer
417 // * have any feature in them - remove these
419 // for (String grp : oldGroups)
421 // featureGroups.remove(grp);
422 // >>>>>>> refs/heads/develop
425 updateRenderOrder(allfeatures);
426 findingFeatures = false;
430 * Updates the global (alignment) min and max values for a feature type from
431 * the score for a sequence, if the score is not NaN. Values are stored
432 * separately for positional and non-positional features.
438 protected void updateMinMax(SequenceI seq, String featureType,
441 float min = seq.getFeatures().getMinimumScore(featureType, positional);
442 if (Float.isNaN(min))
447 float max = seq.getFeatures().getMaximumScore(featureType, positional);
451 * { {positionalMin, positionalMax}, {nonPositionalMin, nonPositionalMax} }
455 minmax = new Hashtable<String, float[][]>();
457 synchronized (minmax)
459 float[][] mm = minmax.get(featureType);
460 int index = positional ? 0 : 1;
463 mm = new float[][] { null, null };
464 minmax.put(featureType, mm);
466 if (mm[index] == null)
468 mm[index] = new float[] { min, max };
472 mm[index][0] = Math.min(mm[index][0], min);
473 mm[index][1] = Math.max(mm[index][1], max);
477 protected Boolean firing = Boolean.FALSE;
480 * replaces the current renderOrder with the unordered features in
481 * allfeatures. The ordering of any types in both renderOrder and allfeatures
482 * is preserved, and all new feature types are rendered on top of the existing
483 * types, in the order given by getOrder or the order given in allFeatures.
484 * Note. this operates directly on the featureOrder hash for efficiency. TODO:
485 * eliminate the float storage for computing/recalling the persistent ordering
486 * New Cability: updates min/max for colourscheme range if its dynamic
490 private void updateRenderOrder(List<String> allFeatures)
492 List<String> allfeatures = new ArrayList<String>(allFeatures);
493 String[] oldRender = renderOrder;
494 renderOrder = new String[allfeatures.size()];
495 boolean initOrders = (featureOrder == null);
497 if (oldRender != null && oldRender.length > 0)
499 for (int j = 0; j < oldRender.length; j++)
501 if (oldRender[j] != null)
505 setOrder(oldRender[j], (1 - (1 + (float) j) / oldRender.length));
507 if (allfeatures.contains(oldRender[j]))
509 renderOrder[opos++] = oldRender[j]; // existing features always
510 // appear below new features
511 allfeatures.remove(oldRender[j]);
514 float[][] mmrange = minmax.get(oldRender[j]);
517 FeatureColourI fc = featureColours.get(oldRender[j]);
518 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
520 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
528 if (allfeatures.size() == 0)
530 // no new features - leave order unchanged.
533 int i = allfeatures.size() - 1;
535 boolean sort = false;
536 String[] newf = new String[allfeatures.size()];
537 float[] sortOrder = new float[allfeatures.size()];
538 for (String newfeat : allfeatures)
543 // update from new features minmax if necessary
544 float[][] mmrange = minmax.get(newf[i]);
547 FeatureColourI fc = featureColours.get(newf[i]);
548 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
550 fc.updateBounds(mmrange[0][0], mmrange[0][1]);
554 if (initOrders || !featureOrder.containsKey(newf[i]))
556 int denom = initOrders ? allfeatures.size() : featureOrder.size();
557 // new unordered feature - compute persistent ordering at head of
558 // existing features.
559 setOrder(newf[i], i / (float) denom);
561 // set order from newly found feature from persisted ordering.
562 sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
565 // only sort if we need to
566 sort = sort || sortOrder[i] > sortOrder[i + 1];
570 if (iSize > 1 && sort)
572 jalview.util.QuickSort.sort(sortOrder, newf);
575 System.arraycopy(newf, 0, renderOrder, opos, newf.length);
579 * get a feature style object for the given type string. Creates a
580 * java.awt.Color for a featureType with no existing colourscheme.
586 public FeatureColourI getFeatureStyle(String featureType)
588 FeatureColourI fc = featureColours.get(featureType);
591 Color col = ColorUtils.createColourFromName(featureType);
592 fc = new FeatureColour(col);
593 featureColours.put(featureType, fc);
599 * Returns the configured colour for a particular feature instance. This
600 * includes calculation of 'colour by label', or of a graduated score colour,
601 * if applicable. It does not take into account feature visibility or colour
607 public Color getColour(SequenceFeature feature)
609 FeatureColourI fc = getFeatureStyle(feature.getType());
610 return fc.getColor(feature);
614 * Answers true unless the feature has a graduated colour scheme and the
615 * feature value lies outside the current threshold for display
617 * @param sequenceFeature
620 protected boolean showFeature(SequenceFeature sequenceFeature)
622 FeatureColourI fc = getFeatureStyle(sequenceFeature.type);
623 return fc.isColored(sequenceFeature);
627 * Answers true if the feature type is currently selected to be displayed,
633 protected boolean showFeatureOfType(String type)
635 return type == null ? false : av.getFeaturesDisplayed().isVisible(type);
639 public void setColour(String featureType, FeatureColourI col)
641 featureColours.put(featureType, col);
645 public void setTransparency(float value)
647 transparency = value;
651 public float getTransparency()
657 * analogous to colour - store a normalized ordering for all feature types in
658 * this rendering context.
661 * Feature type string
663 * normalized priority - 0 means always appears on top, 1 means
666 public float setOrder(String type, float position)
668 if (featureOrder == null)
670 featureOrder = new Hashtable<String, Float>();
672 featureOrder.put(type, new Float(position));
677 * get the global priority (0 (top) to 1 (bottom))
680 * @return [0,1] or -1 for a type without a priority
682 public float getOrder(String type)
684 if (featureOrder != null)
686 if (featureOrder.containsKey(type))
688 return featureOrder.get(type).floatValue();
695 public Map<String, FeatureColourI> getFeatureColours()
697 return featureColours;
701 * Replace current ordering with new ordering
704 * { String(Type), Colour(Type), Boolean(Displayed) }
705 * @return true if any visible features have been reordered, else false
707 public boolean setFeaturePriority(Object[][] data)
709 return setFeaturePriority(data, true);
713 * Sets the priority order for features, with the highest priority (displayed
714 * on top) at the start of the data array
717 * { String(Type), Colour(Type), Boolean(Displayed) }
719 * when true current featureDisplay list will be cleared
720 * @return true if any visible features have been reordered or recoloured,
721 * else false (i.e. no need to repaint)
723 public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
726 * note visible feature ordering and colours before update
728 List<String> visibleFeatures = getDisplayedFeatureTypes();
729 Map<String, FeatureColourI> visibleColours = new HashMap<String, FeatureColourI>(
730 getFeatureColours());
732 FeaturesDisplayedI av_featuresdisplayed = null;
735 if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
737 av.getFeaturesDisplayed().clear();
741 av.setFeaturesDisplayed(av_featuresdisplayed = new FeaturesDisplayed());
746 av_featuresdisplayed = av.getFeaturesDisplayed();
752 // The feature table will display high priority
753 // features at the top, but these are the ones
754 // we need to render last, so invert the data
755 renderOrder = new String[data.length];
759 for (int i = 0; i < data.length; i++)
761 String type = data[i][0].toString();
762 setColour(type, (FeatureColourI) data[i][1]);
763 if (((Boolean) data[i][2]).booleanValue())
765 av_featuresdisplayed.setVisible(type);
768 renderOrder[data.length - i - 1] = type;
773 * get the new visible ordering and return true if it has changed
774 * order or any colour has changed
776 List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
777 if (!visibleFeatures.equals(reorderedVisibleFeatures))
780 * the list of ordered visible features has changed
786 * return true if any feature colour has changed
788 for (String feature : visibleFeatures)
790 if (visibleColours.get(feature) != getFeatureStyle(feature))
800 * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
802 public void addPropertyChangeListener(PropertyChangeListener listener)
804 changeSupport.addPropertyChangeListener(listener);
809 * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
811 public void removePropertyChangeListener(PropertyChangeListener listener)
813 changeSupport.removePropertyChangeListener(listener);
816 public Set<String> getAllFeatureColours()
818 return featureColours.keySet();
821 public void clearRenderOrder()
826 public boolean hasRenderOrder()
828 return renderOrder != null;
832 * Returns feature types in ordering of rendering, where last means on top
834 public List<String> getRenderOrder()
836 if (renderOrder == null)
838 return Arrays.asList(new String[] {});
840 return Arrays.asList(renderOrder);
843 public int getFeatureGroupsSize()
845 return featureGroups != null ? 0 : featureGroups.size();
849 public List<String> getFeatureGroups()
851 // conflict between applet and desktop - featureGroups returns the map in
852 // the desktop featureRenderer
853 return (featureGroups == null) ? Arrays.asList(new String[0]) : Arrays
854 .asList(featureGroups.keySet().toArray(new String[0]));
857 public boolean checkGroupVisibility(String group, boolean newGroupsVisible)
859 if (featureGroups == null)
861 // then an exception happens next..
863 if (featureGroups.containsKey(group))
865 return featureGroups.get(group).booleanValue();
867 if (newGroupsVisible)
869 featureGroups.put(group, new Boolean(true));
876 * get visible or invisible groups
879 * true to return visible groups, false to return hidden ones.
880 * @return list of groups
883 public List<String> getGroups(boolean visible)
885 if (featureGroups != null)
887 List<String> gp = new ArrayList<String>();
889 for (String grp : featureGroups.keySet())
891 Boolean state = featureGroups.get(grp);
892 if (state.booleanValue() == visible)
903 public void setGroupVisibility(String group, boolean visible)
905 featureGroups.put(group, new Boolean(visible));
909 public void setGroupVisibility(List<String> toset, boolean visible)
911 if (toset != null && toset.size() > 0 && featureGroups != null)
913 boolean rdrw = false;
914 for (String gst : toset)
916 Boolean st = featureGroups.get(gst);
917 featureGroups.put(gst, new Boolean(visible));
920 rdrw = rdrw || (visible != st.booleanValue());
925 // set local flag indicating redraw needed ?
931 public Map<String, FeatureColourI> getDisplayedFeatureCols()
933 Map<String, FeatureColourI> fcols = new Hashtable<String, FeatureColourI>();
934 if (getViewport().getFeaturesDisplayed() == null)
938 Set<String> features = getViewport().getFeaturesDisplayed()
939 .getVisibleFeatures();
940 for (String feature : features)
942 fcols.put(feature, getFeatureStyle(feature));
948 public FeaturesDisplayedI getFeaturesDisplayed()
950 return av.getFeaturesDisplayed();
954 * Returns a (possibly empty) list of visible feature types, in render order
958 public List<String> getDisplayedFeatureTypes()
960 List<String> typ = getRenderOrder();
961 List<String> displayed = new ArrayList<String>();
962 FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
963 if (feature_disp != null)
965 synchronized (feature_disp)
967 for (String type : typ)
969 if (feature_disp.isVisible(type))
980 public List<String> getDisplayedFeatureGroups()
982 List<String> _gps = new ArrayList<String>();
983 for (String gp : getFeatureGroups())
985 if (checkGroupVisibility(gp, false))
994 * Answers true if the feature belongs to a feature group which is not
995 * currently displayed, else false
997 * @param sequenceFeature
1000 protected boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
1002 return featureGroups != null
1003 && sequenceFeature.featureGroup != null
1004 && sequenceFeature.featureGroup.length() != 0
1005 && featureGroups.containsKey(sequenceFeature.featureGroup)
1006 && !featureGroups.get(sequenceFeature.featureGroup)