c2f5bb76c1af4a4cd0783da09548831a46727bc2
[jalview.git] / src / jalview / viewmodel / seqfeatures / FeatureRendererModel.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.viewmodel.seqfeatures;
22
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;
33 import jalview.util.matcher.KeyedMatcherSetI;
34
35 import java.awt.Color;
36 import java.beans.PropertyChangeListener;
37 import java.beans.PropertyChangeSupport;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Hashtable;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47 import java.util.concurrent.ConcurrentHashMap;
48
49 public abstract class FeatureRendererModel
50         implements jalview.api.FeatureRenderer
51 {
52
53   /*
54    * global transparency for feature
55    */
56   protected float transparency = 1.0f;
57
58   /*
59    * colour scheme for each feature type
60    */
61   protected Map<String, FeatureColourI> featureColours = new ConcurrentHashMap<>();
62
63   /*
64    * visibility flag for each feature group
65    */
66   protected Map<String, Boolean> featureGroups = new ConcurrentHashMap<>();
67
68   /*
69    * filters for each feature type
70    */
71   protected Map<String, KeyedMatcherSetI> featureFilters = new HashMap<>();
72
73   protected String[] renderOrder;
74
75   Map<String, Float> featureOrder = null;
76
77   protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
78           this);
79
80   protected AlignViewportI av;
81
82   @Override
83   public AlignViewportI getViewport()
84   {
85     return av;
86   }
87
88   public FeatureRendererSettings getSettings()
89   {
90     return new FeatureRendererSettings(this);
91   }
92
93   public void transferSettings(FeatureRendererSettings fr)
94   {
95     this.renderOrder = fr.renderOrder;
96     this.featureGroups = fr.featureGroups;
97     this.featureColours = fr.featureColours;
98     this.transparency = fr.transparency;
99     this.featureOrder = fr.featureOrder;
100   }
101
102   /**
103    * update from another feature renderer
104    * 
105    * @param fr
106    *          settings to copy
107    */
108   public void transferSettings(jalview.api.FeatureRenderer _fr)
109   {
110     FeatureRenderer fr = (FeatureRenderer) _fr;
111     FeatureRendererSettings frs = new FeatureRendererSettings(fr);
112     this.renderOrder = frs.renderOrder;
113     this.featureGroups = frs.featureGroups;
114     this.featureColours = frs.featureColours;
115     this.featureFilters = frs.featureFilters;
116     this.transparency = frs.transparency;
117     this.featureOrder = frs.featureOrder;
118     if (av != null && av != fr.getViewport())
119     {
120       // copy over the displayed feature settings
121       if (_fr.getFeaturesDisplayed() != null)
122       {
123         FeaturesDisplayedI fd = getFeaturesDisplayed();
124         if (fd == null)
125         {
126           setFeaturesDisplayedFrom(_fr.getFeaturesDisplayed());
127         }
128         else
129         {
130           synchronized (fd)
131           {
132             fd.clear();
133             for (String type : _fr.getFeaturesDisplayed()
134                     .getVisibleFeatures())
135             {
136               fd.setVisible(type);
137             }
138           }
139         }
140       }
141     }
142   }
143
144   public void setFeaturesDisplayedFrom(FeaturesDisplayedI featuresDisplayed)
145   {
146     av.setFeaturesDisplayed(new FeaturesDisplayed(featuresDisplayed));
147   }
148
149   @Override
150   public void setVisible(String featureType)
151   {
152     FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
153     if (fdi == null)
154     {
155       av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
156     }
157     if (!fdi.isRegistered(featureType))
158     {
159       pushFeatureType(Arrays.asList(new String[] { featureType }));
160     }
161     fdi.setVisible(featureType);
162   }
163
164   @Override
165   public void setAllVisible(List<String> featureTypes)
166   {
167     FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
168     if (fdi == null)
169     {
170       av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
171     }
172     List<String> nft = new ArrayList<String>();
173     for (String featureType : featureTypes)
174     {
175       if (!fdi.isRegistered(featureType))
176       {
177         nft.add(featureType);
178       }
179     }
180     if (nft.size() > 0)
181     {
182       pushFeatureType(nft);
183     }
184     fdi.setAllVisible(featureTypes);
185   }
186
187   /**
188    * push a set of new types onto the render order stack. Note - this is a
189    * direct mechanism rather than the one employed in updateRenderOrder
190    * 
191    * @param types
192    */
193   private void pushFeatureType(List<String> types)
194   {
195
196     int ts = types.size();
197     String neworder[] = new String[(renderOrder == null ? 0
198             : renderOrder.length) + ts];
199     types.toArray(neworder);
200     if (renderOrder != null)
201     {
202       System.arraycopy(neworder, 0, neworder, renderOrder.length, ts);
203       System.arraycopy(renderOrder, 0, neworder, 0, renderOrder.length);
204     }
205     renderOrder = neworder;
206   }
207
208   protected Map<String, float[][]> minmax = new Hashtable<String, float[][]>();
209
210   public Map<String, float[][]> getMinMax()
211   {
212     return minmax;
213   }
214
215   /**
216    * normalise a score against the max/min bounds for the feature type.
217    * 
218    * @param sequenceFeature
219    * @return byte[] { signed, normalised signed (-127 to 127) or unsigned
220    *         (0-255) value.
221    */
222   protected final byte[] normaliseScore(SequenceFeature sequenceFeature)
223   {
224     float[] mm = minmax.get(sequenceFeature.type)[0];
225     final byte[] r = new byte[] { 0, (byte) 255 };
226     if (mm != null)
227     {
228       if (r[0] != 0 || mm[0] < 0.0)
229       {
230         r[0] = 1;
231         r[1] = (byte) ((int) 128.0
232                 + 127.0 * (sequenceFeature.score / mm[1]));
233       }
234       else
235       {
236         r[1] = (byte) ((int) 255.0 * (sequenceFeature.score / mm[1]));
237       }
238     }
239     return r;
240   }
241
242   boolean newFeatureAdded = false;
243
244   boolean findingFeatures = false;
245
246   protected boolean updateFeatures()
247   {
248     if (av.getFeaturesDisplayed() == null || renderOrder == null
249             || newFeatureAdded)
250     {
251       findAllFeatures();
252       if (av.getFeaturesDisplayed().getVisibleFeatureCount() < 1)
253       {
254         return false;
255       }
256     }
257     // TODO: decide if we should check for the visible feature count first
258     return true;
259   }
260
261   /**
262    * search the alignment for all new features, give them a colour and display
263    * them. Then fires a PropertyChangeEvent on the changeSupport object.
264    * 
265    */
266   protected void findAllFeatures()
267   {
268     synchronized (firing)
269     {
270       if (firing.equals(Boolean.FALSE))
271       {
272         firing = Boolean.TRUE;
273         findAllFeatures(true); // add all new features as visible
274         changeSupport.firePropertyChange("changeSupport", null, null);
275         firing = Boolean.FALSE;
276       }
277     }
278   }
279
280   @Override
281   public List<SequenceFeature> findFeaturesAtColumn(SequenceI sequence, int column)
282   {
283     /*
284      * include features at the position provided their feature type is 
285      * displayed, and feature group is null or marked for display
286      */
287     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
288     if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
289     {
290       return result;
291     }
292
293     Set<String> visibleFeatures = getFeaturesDisplayed()
294             .getVisibleFeatures();
295     String[] visibleTypes = visibleFeatures
296             .toArray(new String[visibleFeatures.size()]);
297     List<SequenceFeature> features = sequence.findFeatures(column, column,
298             visibleTypes);
299
300     for (SequenceFeature sf : features)
301     {
302       if (!featureGroupNotShown(sf))
303       {
304         result.add(sf);
305       }
306     }
307     return result;
308   }
309
310   /**
311    * Searches alignment for all features and updates colours
312    * 
313    * @param newMadeVisible
314    *          if true newly added feature types will be rendered immediately
315    *          TODO: check to see if this method should actually be proxied so
316    *          repaint events can be propagated by the renderer code
317    */
318   @Override
319   public synchronized void findAllFeatures(boolean newMadeVisible)
320   {
321     newFeatureAdded = false;
322
323     if (findingFeatures)
324     {
325       newFeatureAdded = true;
326       return;
327     }
328
329     findingFeatures = true;
330     if (av.getFeaturesDisplayed() == null)
331     {
332       av.setFeaturesDisplayed(new FeaturesDisplayed());
333     }
334     FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
335
336     Set<String> oldfeatures = new HashSet<String>();
337     if (renderOrder != null)
338     {
339       for (int i = 0; i < renderOrder.length; i++)
340       {
341         if (renderOrder[i] != null)
342         {
343           oldfeatures.add(renderOrder[i]);
344         }
345       }
346     }
347
348     AlignmentI alignment = av.getAlignment();
349     List<String> allfeatures = new ArrayList<String>();
350
351     for (int i = 0; i < alignment.getHeight(); i++)
352     {
353       SequenceI asq = alignment.getSequenceAt(i);
354       for (String group : asq.getFeatures().getFeatureGroups(true))
355       {
356         boolean groupDisplayed = true;
357         if (group != null)
358         {
359           if (featureGroups.containsKey(group))
360           {
361             groupDisplayed = featureGroups.get(group);
362           }
363           else
364           {
365             groupDisplayed = newMadeVisible;
366             featureGroups.put(group, groupDisplayed);
367           }
368         }
369         if (groupDisplayed)
370         {
371           Set<String> types = asq.getFeatures().getFeatureTypesForGroups(
372                   true, group);
373           for (String type : types)
374           {
375             if (!allfeatures.contains(type)) // or use HashSet and no test?
376             {
377               allfeatures.add(type);
378             }
379             updateMinMax(asq, type, true); // todo: for all features?
380           }
381         }
382       }
383     }
384
385     // uncomment to add new features in alphebetical order (but JAL-2575)
386     // Collections.sort(allfeatures, String.CASE_INSENSITIVE_ORDER);
387     if (newMadeVisible)
388     {
389       for (String type : allfeatures)
390       {
391         if (!oldfeatures.contains(type))
392         {
393           featuresDisplayed.setVisible(type);
394           setOrder(type, 0);
395         }
396       }
397     }
398
399     updateRenderOrder(allfeatures);
400     findingFeatures = false;
401   }
402
403   /**
404    * Updates the global (alignment) min and max values for a feature type from
405    * the score for a sequence, if the score is not NaN. Values are stored
406    * separately for positional and non-positional features.
407    * 
408    * @param seq
409    * @param featureType
410    * @param positional
411    */
412   protected void updateMinMax(SequenceI seq, String featureType,
413           boolean positional)
414   {
415     float min = seq.getFeatures().getMinimumScore(featureType, positional);
416     if (Float.isNaN(min))
417     {
418       return;
419     }
420
421     float max = seq.getFeatures().getMaximumScore(featureType, positional);
422
423     /*
424      * stored values are 
425      * { {positionalMin, positionalMax}, {nonPositionalMin, nonPositionalMax} }
426      */
427     if (minmax == null)
428     {
429       minmax = new Hashtable<String, float[][]>();
430     }
431     synchronized (minmax)
432     {
433       float[][] mm = minmax.get(featureType);
434       int index = positional ? 0 : 1;
435       if (mm == null)
436       {
437         mm = new float[][] { null, null };
438         minmax.put(featureType, mm);
439       }
440       if (mm[index] == null)
441       {
442         mm[index] = new float[] { min, max };
443       }
444       else
445       {
446         mm[index][0] = Math.min(mm[index][0], min);
447         mm[index][1] = Math.max(mm[index][1], max);
448       }
449     }
450   }
451   protected Boolean firing = Boolean.FALSE;
452
453   /**
454    * replaces the current renderOrder with the unordered features in
455    * allfeatures. The ordering of any types in both renderOrder and allfeatures
456    * is preserved, and all new feature types are rendered on top of the existing
457    * types, in the order given by getOrder or the order given in allFeatures.
458    * Note. this operates directly on the featureOrder hash for efficiency. TODO:
459    * eliminate the float storage for computing/recalling the persistent ordering
460    * New Cability: updates min/max for colourscheme range if its dynamic
461    * 
462    * @param allFeatures
463    */
464   private void updateRenderOrder(List<String> allFeatures)
465   {
466     List<String> allfeatures = new ArrayList<String>(allFeatures);
467     String[] oldRender = renderOrder;
468     renderOrder = new String[allfeatures.size()];
469     boolean initOrders = (featureOrder == null);
470     int opos = 0;
471     if (oldRender != null && oldRender.length > 0)
472     {
473       for (int j = 0; j < oldRender.length; j++)
474       {
475         if (oldRender[j] != null)
476         {
477           if (initOrders)
478           {
479             setOrder(oldRender[j],
480                     (1 - (1 + (float) j) / oldRender.length));
481           }
482           if (allfeatures.contains(oldRender[j]))
483           {
484             renderOrder[opos++] = oldRender[j]; // existing features always
485             // appear below new features
486             allfeatures.remove(oldRender[j]);
487             if (minmax != null)
488             {
489               float[][] mmrange = minmax.get(oldRender[j]);
490               if (mmrange != null)
491               {
492                 FeatureColourI fc = featureColours.get(oldRender[j]);
493                 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled()
494                         && !fc.isColourByAttribute())
495                 {
496                   fc.updateBounds(mmrange[0][0], mmrange[0][1]);
497                 }
498               }
499             }
500           }
501         }
502       }
503     }
504     if (allfeatures.size() == 0)
505     {
506       // no new features - leave order unchanged.
507       return;
508     }
509     int i = allfeatures.size() - 1;
510     int iSize = i;
511     boolean sort = false;
512     String[] newf = new String[allfeatures.size()];
513     float[] sortOrder = new float[allfeatures.size()];
514     for (String newfeat : allfeatures)
515     {
516       newf[i] = newfeat;
517       if (minmax != null)
518       {
519         // update from new features minmax if necessary
520         float[][] mmrange = minmax.get(newf[i]);
521         if (mmrange != null)
522         {
523           FeatureColourI fc = featureColours.get(newf[i]);
524           if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled()
525                   && !fc.isColourByAttribute())
526           {
527             fc.updateBounds(mmrange[0][0], mmrange[0][1]);
528           }
529         }
530       }
531       if (initOrders || !featureOrder.containsKey(newf[i]))
532       {
533         int denom = initOrders ? allfeatures.size() : featureOrder.size();
534         // new unordered feature - compute persistent ordering at head of
535         // existing features.
536         setOrder(newf[i], i / (float) denom);
537       }
538       // set order from newly found feature from persisted ordering.
539       sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
540       if (i < iSize)
541       {
542         // only sort if we need to
543         sort = sort || sortOrder[i] > sortOrder[i + 1];
544       }
545       i--;
546     }
547     if (iSize > 1 && sort)
548     {
549       jalview.util.QuickSort.sort(sortOrder, newf);
550     }
551     sortOrder = null;
552     System.arraycopy(newf, 0, renderOrder, opos, newf.length);
553   }
554
555   /**
556    * get a feature style object for the given type string. Creates a
557    * java.awt.Color for a featureType with no existing colourscheme.
558    * 
559    * @param featureType
560    * @return
561    */
562   @Override
563   public FeatureColourI getFeatureStyle(String featureType)
564   {
565     FeatureColourI fc = featureColours.get(featureType);
566     if (fc == null)
567     {
568       Color col = ColorUtils.createColourFromName(featureType);
569       fc = new FeatureColour(col);
570       featureColours.put(featureType, fc);
571     }
572     return fc;
573   }
574
575   @Override
576   public Color getColour(SequenceFeature feature)
577   {
578     FeatureColourI fc = getFeatureStyle(feature.getType());
579     return getColor(feature, fc);
580   }
581
582   /**
583    * Answers true if the feature type is currently selected to be displayed,
584    * else false
585    * 
586    * @param type
587    * @return
588    */
589   protected boolean showFeatureOfType(String type)
590   {
591     return type == null ? false : (av.getFeaturesDisplayed() == null ? true
592             : av.getFeaturesDisplayed().isVisible(type));
593   }
594
595   @Override
596   public void setColour(String featureType, FeatureColourI col)
597   {
598     featureColours.put(featureType, col);
599   }
600
601   @Override
602   public void setTransparency(float value)
603   {
604     transparency = value;
605   }
606
607   @Override
608   public float getTransparency()
609   {
610     return transparency;
611   }
612
613   /**
614    * analogous to colour - store a normalized ordering for all feature types in
615    * this rendering context.
616    * 
617    * @param type
618    *          Feature type string
619    * @param position
620    *          normalized priority - 0 means always appears on top, 1 means
621    *          always last.
622    */
623   public float setOrder(String type, float position)
624   {
625     if (featureOrder == null)
626     {
627       featureOrder = new Hashtable<String, Float>();
628     }
629     featureOrder.put(type, new Float(position));
630     return position;
631   }
632
633   /**
634    * get the global priority (0 (top) to 1 (bottom))
635    * 
636    * @param type
637    * @return [0,1] or -1 for a type without a priority
638    */
639   public float getOrder(String type)
640   {
641     if (featureOrder != null)
642     {
643       if (featureOrder.containsKey(type))
644       {
645         return featureOrder.get(type).floatValue();
646       }
647     }
648     return -1;
649   }
650
651   @Override
652   public Map<String, FeatureColourI> getFeatureColours()
653   {
654     return featureColours;
655   }
656
657   /**
658    * Replace current ordering with new ordering
659    * 
660    * @param data
661    *          { String(Type), Colour(Type), Boolean(Displayed) }
662    * @return true if any visible features have been reordered, else false
663    */
664   public boolean setFeaturePriority(Object[][] data)
665   {
666     return setFeaturePriority(data, true);
667   }
668
669   /**
670    * Sets the priority order for features, with the highest priority (displayed
671    * on top) at the start of the data array
672    * 
673    * @param data
674    *          { String(Type), Colour(Type), Boolean(Displayed) }
675    * @param visibleNew
676    *          when true current featureDisplay list will be cleared
677    * @return true if any visible features have been reordered or recoloured,
678    *         else false (i.e. no need to repaint)
679    */
680   public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
681   {
682     /*
683      * note visible feature ordering and colours before update
684      */
685     List<String> visibleFeatures = getDisplayedFeatureTypes();
686     Map<String, FeatureColourI> visibleColours = new HashMap<String, FeatureColourI>(
687             getFeatureColours());
688
689     FeaturesDisplayedI av_featuresdisplayed = null;
690     if (visibleNew)
691     {
692       if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
693       {
694         av.getFeaturesDisplayed().clear();
695       }
696       else
697       {
698         av.setFeaturesDisplayed(
699                 av_featuresdisplayed = new FeaturesDisplayed());
700       }
701     }
702     else
703     {
704       av_featuresdisplayed = av.getFeaturesDisplayed();
705     }
706     if (data == null)
707     {
708       return false;
709     }
710     // The feature table will display high priority
711     // features at the top, but these are the ones
712     // we need to render last, so invert the data
713     renderOrder = new String[data.length];
714
715     if (data.length > 0)
716     {
717       for (int i = 0; i < data.length; i++)
718       {
719         String type = data[i][0].toString();
720         setColour(type, (FeatureColourI) data[i][1]);
721         if (((Boolean) data[i][2]).booleanValue())
722         {
723           av_featuresdisplayed.setVisible(type);
724         }
725
726         renderOrder[data.length - i - 1] = type;
727       }
728     }
729
730     /*
731      * get the new visible ordering and return true if it has changed
732      * order or any colour has changed
733      */
734     List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
735     if (!visibleFeatures.equals(reorderedVisibleFeatures))
736     {
737       /*
738        * the list of ordered visible features has changed
739        */
740       return true;
741     }
742
743     /*
744      * return true if any feature colour has changed
745      */
746     for (String feature : visibleFeatures)
747     {
748       if (visibleColours.get(feature) != getFeatureStyle(feature))
749       {
750         return true;
751       }
752     }
753     return false;
754   }
755
756   /**
757    * @param listener
758    * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
759    */
760   public void addPropertyChangeListener(PropertyChangeListener listener)
761   {
762     changeSupport.addPropertyChangeListener(listener);
763   }
764
765   /**
766    * @param listener
767    * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
768    */
769   public void removePropertyChangeListener(PropertyChangeListener listener)
770   {
771     changeSupport.removePropertyChangeListener(listener);
772   }
773
774   public Set<String> getAllFeatureColours()
775   {
776     return featureColours.keySet();
777   }
778
779   public void clearRenderOrder()
780   {
781     renderOrder = null;
782   }
783
784   public boolean hasRenderOrder()
785   {
786     return renderOrder != null;
787   }
788
789   /**
790    * Returns feature types in ordering of rendering, where last means on top
791    */
792   public List<String> getRenderOrder()
793   {
794     if (renderOrder == null)
795     {
796       return Arrays.asList(new String[] {});
797     }
798     return Arrays.asList(renderOrder);
799   }
800
801   public int getFeatureGroupsSize()
802   {
803     return featureGroups != null ? 0 : featureGroups.size();
804   }
805
806   @Override
807   public List<String> getFeatureGroups()
808   {
809     // conflict between applet and desktop - featureGroups returns the map in
810     // the desktop featureRenderer
811     return (featureGroups == null) ? Arrays.asList(new String[0])
812             : Arrays.asList(featureGroups.keySet().toArray(new String[0]));
813   }
814
815   public boolean checkGroupVisibility(String group,
816           boolean newGroupsVisible)
817   {
818     if (featureGroups == null)
819     {
820       // then an exception happens next..
821     }
822     if (featureGroups.containsKey(group))
823     {
824       return featureGroups.get(group).booleanValue();
825     }
826     if (newGroupsVisible)
827     {
828       featureGroups.put(group, new Boolean(true));
829       return true;
830     }
831     return false;
832   }
833
834   /**
835    * get visible or invisible groups
836    * 
837    * @param visible
838    *          true to return visible groups, false to return hidden ones.
839    * @return list of groups
840    */
841   @Override
842   public List<String> getGroups(boolean visible)
843   {
844     if (featureGroups != null)
845     {
846       List<String> gp = new ArrayList<String>();
847
848       for (String grp : featureGroups.keySet())
849       {
850         Boolean state = featureGroups.get(grp);
851         if (state.booleanValue() == visible)
852         {
853           gp.add(grp);
854         }
855       }
856       return gp;
857     }
858     return null;
859   }
860
861   @Override
862   public void setGroupVisibility(String group, boolean visible)
863   {
864     featureGroups.put(group, new Boolean(visible));
865   }
866
867   @Override
868   public void setGroupVisibility(List<String> toset, boolean visible)
869   {
870     if (toset != null && toset.size() > 0 && featureGroups != null)
871     {
872       boolean rdrw = false;
873       for (String gst : toset)
874       {
875         Boolean st = featureGroups.get(gst);
876         featureGroups.put(gst, new Boolean(visible));
877         if (st != null)
878         {
879           rdrw = rdrw || (visible != st.booleanValue());
880         }
881       }
882       if (rdrw)
883       {
884         // set local flag indicating redraw needed ?
885       }
886     }
887   }
888
889   @Override
890   public Map<String, FeatureColourI> getDisplayedFeatureCols()
891   {
892     Map<String, FeatureColourI> fcols = new Hashtable<String, FeatureColourI>();
893     if (getViewport().getFeaturesDisplayed() == null)
894     {
895       return fcols;
896     }
897     Set<String> features = getViewport().getFeaturesDisplayed()
898             .getVisibleFeatures();
899     for (String feature : features)
900     {
901       fcols.put(feature, getFeatureStyle(feature));
902     }
903     return fcols;
904   }
905
906   @Override
907   public FeaturesDisplayedI getFeaturesDisplayed()
908   {
909     return av.getFeaturesDisplayed();
910   }
911
912   /**
913    * Returns a (possibly empty) list of visible feature types, in render order
914    * (last is on top)
915    */
916   @Override
917   public List<String> getDisplayedFeatureTypes()
918   {
919     List<String> typ = getRenderOrder();
920     List<String> displayed = new ArrayList<String>();
921     FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
922     if (feature_disp != null)
923     {
924       synchronized (feature_disp)
925       {
926         for (String type : typ)
927         {
928           if (feature_disp.isVisible(type))
929           {
930             displayed.add(type);
931           }
932         }
933       }
934     }
935     return displayed;
936   }
937
938   @Override
939   public List<String> getDisplayedFeatureGroups()
940   {
941     List<String> _gps = new ArrayList<String>();
942     for (String gp : getFeatureGroups())
943     {
944       if (checkGroupVisibility(gp, false))
945       {
946         _gps.add(gp);
947       }
948     }
949     return _gps;
950   }
951
952   /**
953    * Answers true if the feature belongs to a feature group which is not
954    * currently displayed, else false
955    * 
956    * @param sequenceFeature
957    * @return
958    */
959   protected boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
960   {
961     return featureGroups != null
962             && sequenceFeature.featureGroup != null
963             && sequenceFeature.featureGroup.length() != 0
964             && featureGroups.containsKey(sequenceFeature.featureGroup)
965             && !featureGroups.get(sequenceFeature.featureGroup)
966                     .booleanValue();
967   }
968
969   /**
970    * {@inheritDoc}
971    */
972   @Override
973   public List<SequenceFeature> findFeaturesAtResidue(SequenceI sequence,
974           int resNo)
975   {
976     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
977     if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
978     {
979       return result;
980     }
981
982     /*
983      * include features at the position provided their feature type is 
984      * displayed, and feature group is null or the empty string
985      * or marked for display
986      */
987     Set<String> visibleFeatures = getFeaturesDisplayed()
988             .getVisibleFeatures();
989     String[] visibleTypes = visibleFeatures
990             .toArray(new String[visibleFeatures.size()]);
991     List<SequenceFeature> features = sequence.getFeatures().findFeatures(
992             resNo, resNo, visibleTypes);
993   
994     for (SequenceFeature sf : features)
995     {
996       if (!featureGroupNotShown(sf))
997       {
998         result.add(sf);
999       }
1000     }
1001     return result;
1002   }
1003
1004   /**
1005    * Removes from the list of features any that duplicate the location of a
1006    * feature of the same type. Should be used only for features of the same,
1007    * simple, feature colour (which normally implies the same feature type). Does
1008    * not check visibility settings for feature type or feature group.
1009    * 
1010    * @param features
1011    */
1012   public void filterFeaturesForDisplay(List<SequenceFeature> features)
1013   {
1014     if (features.isEmpty())
1015     {
1016       return;
1017     }
1018     SequenceFeatures.sortFeatures(features, true);
1019     SequenceFeature lastFeature = null;
1020
1021     Iterator<SequenceFeature> it = features.iterator();
1022     while (it.hasNext())
1023     {
1024       SequenceFeature sf = it.next();
1025
1026       /*
1027        * a feature is redundant for rendering purposes if it has the
1028        * same extent as another (so would just redraw the same colour);
1029        * (checking type and isContactFeature as a fail-safe here, although
1030        * currently they are guaranteed to match in this context)
1031        */
1032       if (lastFeature != null && sf.getBegin() == lastFeature.getBegin()
1033               && sf.getEnd() == lastFeature.getEnd()
1034               && sf.isContactFeature() == lastFeature.isContactFeature()
1035               && sf.getType().equals(lastFeature.getType()))
1036       {
1037         it.remove();
1038       }
1039       lastFeature = sf;
1040     }
1041   }
1042
1043   @Override
1044   public Map<String, KeyedMatcherSetI> getFeatureFilters()
1045   {
1046     return new HashMap<>(featureFilters);
1047   }
1048
1049   @Override
1050   public void setFeatureFilters(Map<String, KeyedMatcherSetI> filters)
1051   {
1052     featureFilters = filters;
1053   }
1054
1055   @Override
1056   public KeyedMatcherSetI getFeatureFilter(String featureType)
1057   {
1058     return featureFilters.get(featureType);
1059   }
1060
1061   @Override
1062   public void setFeatureFilter(String featureType, KeyedMatcherSetI filter)
1063   {
1064     if (filter == null || filter.isEmpty())
1065     {
1066       featureFilters.remove(featureType);
1067     }
1068     else
1069     {
1070       featureFilters.put(featureType, filter);
1071     }
1072   }
1073
1074   /**
1075    * Answers the colour for the feature, or null if the feature is excluded by
1076    * feature type or group visibility, by filters, or by colour threshold
1077    * settings
1078    * 
1079    * @param sf
1080    * @param fc
1081    * @return
1082    */
1083   public Color getColor(SequenceFeature sf, FeatureColourI fc)
1084   {
1085     /*
1086      * is the feature type displayed?
1087      */
1088     if (!showFeatureOfType(sf.getType()))
1089     {
1090       return null;
1091     }
1092
1093     /*
1094      * is the feature group displayed?
1095      */
1096     if (featureGroupNotShown(sf))
1097     {
1098       return null;
1099     }
1100
1101     /*
1102      * does the feature pass filters?
1103      */
1104     if (!featureMatchesFilters(sf))
1105     {
1106       return null;
1107     }
1108   
1109     return fc.getColor(sf);
1110   }
1111
1112   /**
1113    * Answers true if there no are filters defined for the feature type, or this
1114    * feature matches the filters. Answers false if the feature fails to match
1115    * filters.
1116    * 
1117    * @param sf
1118    * @return
1119    */
1120   protected boolean featureMatchesFilters(SequenceFeature sf)
1121   {
1122     KeyedMatcherSetI filter = featureFilters.get(sf.getType());
1123     return filter == null ? true : filter.matches(key -> sf
1124             .getValueAsString(key));
1125   }
1126
1127 }