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.GraduatedColor;
31 import jalview.viewmodel.AlignmentViewport;
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.HashMap;
39 import java.util.Hashtable;
40 import java.util.Iterator;
41 import java.util.List;
44 import java.util.concurrent.ConcurrentHashMap;
46 public abstract class FeatureRendererModel implements
47 jalview.api.FeatureRenderer
51 * global transparency for feature
53 protected float transparency = 1.0f;
55 protected Map<String, Object> featureColours = new ConcurrentHashMap<String, Object>();
57 protected Map<String, Boolean> featureGroups = new ConcurrentHashMap<String, Boolean>();
59 protected Object currentColour;
62 * feature types in ordering of rendering, where last means on top
64 protected String[] renderOrder;
66 protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
69 protected AlignmentViewport av;
72 public AlignViewportI getViewport()
77 public FeatureRendererSettings getSettings()
79 return new FeatureRendererSettings(this);
82 public void transferSettings(FeatureRendererSettings fr)
84 this.renderOrder = fr.renderOrder;
85 this.featureGroups = fr.featureGroups;
86 this.featureColours = fr.featureColours;
87 this.transparency = fr.transparency;
88 this.featureOrder = fr.featureOrder;
92 * update from another feature renderer
97 public void transferSettings(jalview.api.FeatureRenderer _fr)
99 FeatureRenderer fr = (FeatureRenderer) _fr;
100 FeatureRendererSettings frs = new FeatureRendererSettings(fr);
101 this.renderOrder = frs.renderOrder;
102 this.featureGroups = frs.featureGroups;
103 this.featureColours = frs.featureColours;
104 this.transparency = frs.transparency;
105 this.featureOrder = frs.featureOrder;
106 if (av != null && av != fr.getViewport())
108 // copy over the displayed feature settings
109 if (_fr.getFeaturesDisplayed() != null)
111 FeaturesDisplayedI fd = getFeaturesDisplayed();
114 setFeaturesDisplayedFrom(_fr.getFeaturesDisplayed());
121 java.util.Iterator<String> fdisp = _fr.getFeaturesDisplayed()
122 .getVisibleFeatures();
123 while (fdisp.hasNext())
125 fd.setVisible(fdisp.next());
133 public void setFeaturesDisplayedFrom(FeaturesDisplayedI featuresDisplayed)
135 av.setFeaturesDisplayed(new FeaturesDisplayed(featuresDisplayed));
139 public void setVisible(String featureType)
141 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
144 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
146 if (!fdi.isRegistered(featureType))
148 pushFeatureType(Arrays.asList(new String[] { featureType }));
150 fdi.setVisible(featureType);
154 public void setAllVisible(List<String> featureTypes)
156 FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
159 av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
161 List<String> nft = new ArrayList<String>();
162 for (String featureType : featureTypes)
164 if (!fdi.isRegistered(featureType))
166 nft.add(featureType);
171 pushFeatureType(nft);
173 fdi.setAllVisible(featureTypes);
177 * push a set of new types onto the render order stack. Note - this is a
178 * direct mechanism rather than the one employed in updateRenderOrder
182 private void pushFeatureType(List<String> types)
185 int ts = types.size();
186 String neworder[] = new String[(renderOrder == null ? 0
187 : renderOrder.length) + ts];
188 types.toArray(neworder);
189 if (renderOrder != null)
191 System.arraycopy(neworder, 0, neworder, renderOrder.length, ts);
192 System.arraycopy(renderOrder, 0, neworder, 0, renderOrder.length);
194 renderOrder = neworder;
197 protected Hashtable minmax = new Hashtable();
199 public Hashtable getMinMax()
205 * normalise a score against the max/min bounds for the feature type.
207 * @param sequenceFeature
208 * @return byte[] { signed, normalised signed (-127 to 127) or unsigned
211 protected final byte[] normaliseScore(SequenceFeature sequenceFeature)
213 float[] mm = ((float[][]) minmax.get(sequenceFeature.type))[0];
214 final byte[] r = new byte[] { 0, (byte) 255 };
217 if (r[0] != 0 || mm[0] < 0.0)
220 r[1] = (byte) ((int) 128.0 + 127.0 * (sequenceFeature.score / mm[1]));
224 r[1] = (byte) ((int) 255.0 * (sequenceFeature.score / mm[1]));
230 boolean newFeatureAdded = false;
232 boolean findingFeatures = false;
234 protected boolean updateFeatures()
236 if (av.getFeaturesDisplayed() == null || renderOrder == null
240 if (av.getFeaturesDisplayed().getVisibleFeatureCount() < 1)
245 // TODO: decide if we should check for the visible feature count first
250 * search the alignment for all new features, give them a colour and display
251 * them. Then fires a PropertyChangeEvent on the changeSupport object.
254 protected void findAllFeatures()
256 synchronized (firing)
258 if (firing.equals(Boolean.FALSE))
260 firing = Boolean.TRUE;
261 findAllFeatures(true); // add all new features as visible
262 changeSupport.firePropertyChange("changeSupport", null, null);
263 firing = Boolean.FALSE;
269 public List<SequenceFeature> findFeaturesAtRes(SequenceI sequence, int res)
271 ArrayList<SequenceFeature> tmp = new ArrayList<SequenceFeature>();
272 SequenceFeature[] features = sequence.getSequenceFeatures();
274 if (features != null)
276 for (int i = 0; i < features.length; i++)
278 if (!av.areFeaturesDisplayed()
279 || !av.getFeaturesDisplayed().isVisible(
280 features[i].getType()))
285 if (features[i].featureGroup != null
286 && featureGroups != null
287 && featureGroups.containsKey(features[i].featureGroup)
288 && !featureGroups.get(features[i].featureGroup)
294 if ((features[i].getBegin() <= res)
295 && (features[i].getEnd() >= res))
297 tmp.add(features[i]);
305 * Searches alignment for all features and updates colours
307 * @param newMadeVisible
308 * if true newly added feature types will be rendered immediatly
309 * TODO: check to see if this method should actually be proxied so
310 * repaint events can be propagated by the renderer code
313 public synchronized void findAllFeatures(boolean newMadeVisible)
315 newFeatureAdded = false;
319 newFeatureAdded = true;
323 findingFeatures = true;
324 if (av.getFeaturesDisplayed() == null)
326 av.setFeaturesDisplayed(new FeaturesDisplayed());
328 FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
330 ArrayList<String> allfeatures = new ArrayList<String>();
331 ArrayList<String> oldfeatures = new ArrayList<String>();
332 if (renderOrder != null)
334 for (int i = 0; i < renderOrder.length; i++)
336 if (renderOrder[i] != null)
338 oldfeatures.add(renderOrder[i]);
344 minmax = new Hashtable();
346 AlignmentI alignment = av.getAlignment();
347 for (int i = 0; i < alignment.getHeight(); i++)
349 SequenceI asq = alignment.getSequenceAt(i);
350 SequenceFeature[] features = asq.getSequenceFeatures();
352 if (features == null)
358 while (index < features.length)
360 if (!featuresDisplayed.isRegistered(features[index].getType()))
362 String fgrp = features[index].getFeatureGroup();
365 Boolean groupDisplayed = featureGroups.get(fgrp);
366 if (groupDisplayed == null)
368 groupDisplayed = Boolean.valueOf(newMadeVisible);
369 featureGroups.put(fgrp, groupDisplayed);
371 if (!groupDisplayed.booleanValue())
377 if (!(features[index].begin == 0 && features[index].end == 0))
379 // If beginning and end are 0, the feature is for the whole sequence
380 // and we don't want to render the feature in the normal way
383 && !oldfeatures.contains(features[index].getType()))
385 // this is a new feature type on the alignment. Mark it for
387 featuresDisplayed.setVisible(features[index].getType());
388 setOrder(features[index].getType(), 0);
392 if (!allfeatures.contains(features[index].getType()))
394 allfeatures.add(features[index].getType());
396 if (!Float.isNaN(features[index].score))
398 int nonpos = features[index].getBegin() >= 1 ? 0 : 1;
399 float[][] mm = (float[][]) minmax.get(features[index].getType());
402 mm = new float[][] { null, null };
403 minmax.put(features[index].getType(), mm);
405 if (mm[nonpos] == null)
407 mm[nonpos] = new float[] { features[index].score,
408 features[index].score };
413 if (mm[nonpos][0] > features[index].score)
415 mm[nonpos][0] = features[index].score;
417 if (mm[nonpos][1] < features[index].score)
419 mm[nonpos][1] = features[index].score;
426 updateRenderOrder(allfeatures);
427 findingFeatures = false;
430 protected Boolean firing = Boolean.FALSE;
433 * replaces the current renderOrder with the unordered features in
434 * allfeatures. The ordering of any types in both renderOrder and allfeatures
435 * is preserved, and all new feature types are rendered on top of the existing
436 * types, in the order given by getOrder or the order given in allFeatures.
437 * Note. this operates directly on the featureOrder hash for efficiency. TODO:
438 * eliminate the float storage for computing/recalling the persistent ordering
439 * New Cability: updates min/max for colourscheme range if its dynamic
443 private void updateRenderOrder(List<String> allFeatures)
445 List<String> allfeatures = new ArrayList<String>(allFeatures);
446 String[] oldRender = renderOrder;
447 renderOrder = new String[allfeatures.size()];
448 Object mmrange, fc = null;
449 boolean initOrders = (featureOrder == null);
451 if (oldRender != null && oldRender.length > 0)
453 for (int j = 0; j < oldRender.length; j++)
455 if (oldRender[j] != null)
459 setOrder(oldRender[j], (1 - (1 + (float) j) / oldRender.length));
461 if (allfeatures.contains(oldRender[j]))
463 renderOrder[opos++] = oldRender[j]; // existing features always
464 // appear below new features
465 allfeatures.remove(oldRender[j]);
468 mmrange = minmax.get(oldRender[j]);
471 fc = featureColours.get(oldRender[j]);
472 if (fc != null && fc instanceof GraduatedColor
473 && ((GraduatedColor) fc).isAutoScale())
475 ((GraduatedColor) fc).updateBounds(
476 ((float[][]) mmrange)[0][0],
477 ((float[][]) mmrange)[0][1]);
485 if (allfeatures.size() == 0)
487 // no new features - leave order unchanged.
490 int i = allfeatures.size() - 1;
492 boolean sort = false;
493 String[] newf = new String[allfeatures.size()];
494 float[] sortOrder = new float[allfeatures.size()];
495 for (String newfeat : allfeatures)
500 // update from new features minmax if necessary
501 mmrange = minmax.get(newf[i]);
504 fc = featureColours.get(newf[i]);
505 if (fc != null && fc instanceof GraduatedColor
506 && ((GraduatedColor) fc).isAutoScale())
508 ((GraduatedColor) fc).updateBounds(((float[][]) mmrange)[0][0],
509 ((float[][]) mmrange)[0][1]);
513 if (initOrders || !featureOrder.containsKey(newf[i]))
515 int denom = initOrders ? allfeatures.size() : featureOrder.size();
516 // new unordered feature - compute persistent ordering at head of
517 // existing features.
518 setOrder(newf[i], i / (float) denom);
520 // set order from newly found feature from persisted ordering.
521 sortOrder[i] = 2 - ((Float) featureOrder.get(newf[i])).floatValue();
524 // only sort if we need to
525 sort = sort || sortOrder[i] > sortOrder[i + 1];
529 if (iSize > 1 && sort)
531 jalview.util.QuickSort.sort(sortOrder, newf);
534 System.arraycopy(newf, 0, renderOrder, opos, newf.length);
538 * get a feature style object for the given type string. Creates a
539 * java.awt.Color for a featureType with no existing colourscheme. TODO:
540 * replace return type with object implementing standard abstract colour/style
544 * @return java.awt.Color or GraduatedColor
547 public Object getFeatureStyle(String featureType)
549 Object fc = featureColours.get(featureType);
552 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme();
553 Color col = ucs.createColourFromName(featureType);
554 featureColours.put(featureType, fc = col);
560 * return a nominal colour for this feature
563 * @return standard color, or maximum colour for graduated colourscheme
565 public Color getColour(String featureType)
567 Object fc = getFeatureStyle(featureType);
569 if (fc instanceof Color)
575 if (fc instanceof GraduatedColor)
577 return ((GraduatedColor) fc).getMaxColor();
580 throw new Error("Implementation Error: Unrecognised render object "
581 + fc.getClass() + " for features of type " + featureType);
585 * calculate the render colour for a specific feature using current feature
589 * @return render colour for the given feature
591 public Color getColour(SequenceFeature feature)
593 Object fc = getFeatureStyle(feature.getType());
594 if (fc instanceof Color)
600 if (fc instanceof GraduatedColor)
602 return ((GraduatedColor) fc).findColor(feature);
605 throw new Error("Implementation Error: Unrecognised render object "
606 + fc.getClass() + " for features of type " + feature.getType());
609 protected boolean showFeature(SequenceFeature sequenceFeature)
611 Object fc = getFeatureStyle(sequenceFeature.type);
612 if (fc instanceof GraduatedColor)
614 return ((GraduatedColor) fc).isColored(sequenceFeature);
622 protected boolean showFeatureOfType(String type)
624 return av.getFeaturesDisplayed().isVisible(type);
628 public void setColour(String featureType, Object col)
631 // Color _col = (col instanceof Color) ? ((Color) col) : (col instanceof
632 // GraduatedColor) ? ((GraduatedColor) col).getMaxColor() : null;
633 // Object c = featureColours.get(featureType);
634 // if (c == null || c instanceof Color || (c instanceof GraduatedColor &&
635 // !((GraduatedColor)c).getMaxColor().equals(_col)))
636 if (col instanceof FeatureColourI)
638 if (((FeatureColourI) col).isGraduatedColour())
640 col = new GraduatedColor((FeatureColourI) col);
644 col = ((FeatureColourI) col).getColour();
647 featureColours.put(featureType, col);
650 public void setTransparency(float value)
652 transparency = value;
655 public float getTransparency()
660 Map featureOrder = null;
663 * analogous to colour - store a normalized ordering for all feature types in
664 * this rendering context.
667 * Feature type string
669 * normalized priority - 0 means always appears on top, 1 means
672 public float setOrder(String type, float position)
674 if (featureOrder == null)
676 featureOrder = new Hashtable();
678 featureOrder.put(type, new Float(position));
683 * get the global priority (0 (top) to 1 (bottom))
686 * @return [0,1] or -1 for a type without a priority
688 public float getOrder(String type)
690 if (featureOrder != null)
692 if (featureOrder.containsKey(type))
694 return ((Float) featureOrder.get(type)).floatValue();
701 public Map<String, Object> getFeatureColours()
703 return featureColours;
707 * Replace current ordering with new ordering
710 * { String(Type), Colour(Type), Boolean(Displayed) }
711 * @return true if any visible features have been reordered, else false
713 public boolean setFeaturePriority(Object[][] data)
715 return setFeaturePriority(data, true);
719 * Sets the priority order for features
722 * { String(Type), Colour(Type), Boolean(Displayed) }
724 * when true current featureDisplay list will be cleared
725 * @return true if any visible features have been reordered or recoloured,
726 * else false (i.e. no need to repaint)
728 public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
731 * note visible feature ordering and colours before update
733 List<String> visibleFeatures = getDisplayedFeatureTypes();
734 Map<String, Object> visibleColours = new HashMap<String, Object>(
735 getFeatureColours());
737 FeaturesDisplayedI av_featuresdisplayed = null;
740 if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
742 av.getFeaturesDisplayed().clear();
746 av.setFeaturesDisplayed(av_featuresdisplayed = new FeaturesDisplayed());
751 av_featuresdisplayed = av.getFeaturesDisplayed();
757 // The feature table will display high priority
758 // features at the top, but these are the ones
759 // we need to render last, so invert the data
760 renderOrder = new String[data.length];
764 for (int i = 0; i < data.length; i++)
766 String type = data[i][0].toString();
767 setColour(type, data[i][1]); // todo : typesafety - feature color
769 if (((Boolean) data[i][2]).booleanValue())
771 av_featuresdisplayed.setVisible(type);
774 renderOrder[data.length - i - 1] = type;
779 * get the new visible ordering and return true if it has changed
780 * order or any colour has changed
782 List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
783 if (!visibleFeatures.equals(reorderedVisibleFeatures))
786 * the list of ordered visible features has changed
792 * return true if any feature colour has changed
794 for (String feature : visibleFeatures)
796 if (visibleColours.get(feature) != getFeatureStyle(feature))
806 * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
808 public void addPropertyChangeListener(PropertyChangeListener listener)
810 changeSupport.addPropertyChangeListener(listener);
815 * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
817 public void removePropertyChangeListener(PropertyChangeListener listener)
819 changeSupport.removePropertyChangeListener(listener);
822 public Set getAllFeatureColours()
824 return featureColours.keySet();
827 public void clearRenderOrder()
832 public boolean hasRenderOrder()
834 return renderOrder != null;
837 public List<String> getRenderOrder()
839 if (renderOrder == null)
841 return Arrays.asList(new String[] {});
843 return Arrays.asList(renderOrder);
846 public int getFeatureGroupsSize()
848 return featureGroups != null ? 0 : featureGroups.size();
852 public List<String> getFeatureGroups()
854 // conflict between applet and desktop - featureGroups returns the map in
855 // the desktop featureRenderer
856 return (featureGroups == null) ? Arrays.asList(new String[0]) : Arrays
857 .asList(featureGroups.keySet().toArray(new String[0]));
860 public boolean checkGroupVisibility(String group, boolean newGroupsVisible)
862 if (featureGroups == null)
864 // then an exception happens next..
866 if (featureGroups.containsKey(group))
868 return featureGroups.get(group).booleanValue();
870 if (newGroupsVisible)
872 featureGroups.put(group, new Boolean(true));
879 * get visible or invisible groups
882 * true to return visible groups, false to return hidden ones.
883 * @return list of groups
886 public List getGroups(boolean visible)
888 if (featureGroups != null)
890 ArrayList gp = new ArrayList();
892 for (Object grp : featureGroups.keySet())
894 Boolean state = featureGroups.get(grp);
895 if (state.booleanValue() == visible)
906 public void setGroupVisibility(String group, boolean visible)
908 featureGroups.put(group, new Boolean(visible));
912 public void setGroupVisibility(List<String> toset, boolean visible)
914 if (toset != null && toset.size() > 0 && featureGroups != null)
916 boolean rdrw = false;
917 for (String gst : toset)
919 Boolean st = featureGroups.get(gst);
920 featureGroups.put(gst, new Boolean(visible));
923 rdrw = rdrw || (visible != st.booleanValue());
928 // set local flag indicating redraw needed ?
934 public Hashtable getDisplayedFeatureCols()
936 Hashtable fcols = new Hashtable();
937 if (getViewport().getFeaturesDisplayed() == null)
941 Iterator<String> en = getViewport().getFeaturesDisplayed()
942 .getVisibleFeatures();
945 String col = en.next();
946 fcols.put(col, getColour(col));
952 public FeaturesDisplayedI getFeaturesDisplayed()
954 return av.getFeaturesDisplayed();
958 * Returns a (possibly empty) list of visible feature types, in render order
962 public List<String> getDisplayedFeatureTypes()
964 List<String> typ = getRenderOrder();
965 List<String> displayed = new ArrayList<String>();
966 FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
967 if (feature_disp != null)
969 synchronized (feature_disp)
971 for (String type : typ)
973 if (feature_disp.isVisible(type))
984 public List<String> getDisplayedFeatureGroups()
986 List<String> _gps = new ArrayList<String>();
987 boolean valid = false;
988 for (String gp : getFeatureGroups())
990 if (checkGroupVisibility(gp, false))
1001 // gps = new String[_gps.size()];
1002 // _gps.toArray(gps);