JAL-2816 exclude filtered / thresholded out features when finding
[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<>();
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<>();
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<>();
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     /*
301      * include features unless their feature group is not displayed, or
302      * they are hidden (have no colour) based on a filter or colour threshold
303      */
304     for (SequenceFeature sf : features)
305     {
306       if (!featureGroupNotShown(sf) && getColour(sf) != null)
307       {
308         result.add(sf);
309       }
310     }
311     return result;
312   }
313
314   /**
315    * Searches alignment for all features and updates colours
316    * 
317    * @param newMadeVisible
318    *          if true newly added feature types will be rendered immediately
319    *          TODO: check to see if this method should actually be proxied so
320    *          repaint events can be propagated by the renderer code
321    */
322   @Override
323   public synchronized void findAllFeatures(boolean newMadeVisible)
324   {
325     newFeatureAdded = false;
326
327     if (findingFeatures)
328     {
329       newFeatureAdded = true;
330       return;
331     }
332
333     findingFeatures = true;
334     if (av.getFeaturesDisplayed() == null)
335     {
336       av.setFeaturesDisplayed(new FeaturesDisplayed());
337     }
338     FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
339
340     Set<String> oldfeatures = new HashSet<>();
341     if (renderOrder != null)
342     {
343       for (int i = 0; i < renderOrder.length; i++)
344       {
345         if (renderOrder[i] != null)
346         {
347           oldfeatures.add(renderOrder[i]);
348         }
349       }
350     }
351
352     AlignmentI alignment = av.getAlignment();
353     List<String> allfeatures = new ArrayList<>();
354
355     for (int i = 0; i < alignment.getHeight(); i++)
356     {
357       SequenceI asq = alignment.getSequenceAt(i);
358       for (String group : asq.getFeatures().getFeatureGroups(true))
359       {
360         boolean groupDisplayed = true;
361         if (group != null)
362         {
363           if (featureGroups.containsKey(group))
364           {
365             groupDisplayed = featureGroups.get(group);
366           }
367           else
368           {
369             groupDisplayed = newMadeVisible;
370             featureGroups.put(group, groupDisplayed);
371           }
372         }
373         if (groupDisplayed)
374         {
375           Set<String> types = asq.getFeatures().getFeatureTypesForGroups(
376                   true, group);
377           for (String type : types)
378           {
379             if (!allfeatures.contains(type)) // or use HashSet and no test?
380             {
381               allfeatures.add(type);
382             }
383             updateMinMax(asq, type, true); // todo: for all features?
384           }
385         }
386       }
387     }
388
389     // uncomment to add new features in alphebetical order (but JAL-2575)
390     // Collections.sort(allfeatures, String.CASE_INSENSITIVE_ORDER);
391     if (newMadeVisible)
392     {
393       for (String type : allfeatures)
394       {
395         if (!oldfeatures.contains(type))
396         {
397           featuresDisplayed.setVisible(type);
398           setOrder(type, 0);
399         }
400       }
401     }
402
403     updateRenderOrder(allfeatures);
404     findingFeatures = false;
405   }
406
407   /**
408    * Updates the global (alignment) min and max values for a feature type from
409    * the score for a sequence, if the score is not NaN. Values are stored
410    * separately for positional and non-positional features.
411    * 
412    * @param seq
413    * @param featureType
414    * @param positional
415    */
416   protected void updateMinMax(SequenceI seq, String featureType,
417           boolean positional)
418   {
419     float min = seq.getFeatures().getMinimumScore(featureType, positional);
420     if (Float.isNaN(min))
421     {
422       return;
423     }
424
425     float max = seq.getFeatures().getMaximumScore(featureType, positional);
426
427     /*
428      * stored values are 
429      * { {positionalMin, positionalMax}, {nonPositionalMin, nonPositionalMax} }
430      */
431     if (minmax == null)
432     {
433       minmax = new Hashtable<>();
434     }
435     synchronized (minmax)
436     {
437       float[][] mm = minmax.get(featureType);
438       int index = positional ? 0 : 1;
439       if (mm == null)
440       {
441         mm = new float[][] { null, null };
442         minmax.put(featureType, mm);
443       }
444       if (mm[index] == null)
445       {
446         mm[index] = new float[] { min, max };
447       }
448       else
449       {
450         mm[index][0] = Math.min(mm[index][0], min);
451         mm[index][1] = Math.max(mm[index][1], max);
452       }
453     }
454   }
455   protected Boolean firing = Boolean.FALSE;
456
457   /**
458    * replaces the current renderOrder with the unordered features in
459    * allfeatures. The ordering of any types in both renderOrder and allfeatures
460    * is preserved, and all new feature types are rendered on top of the existing
461    * types, in the order given by getOrder or the order given in allFeatures.
462    * Note. this operates directly on the featureOrder hash for efficiency. TODO:
463    * eliminate the float storage for computing/recalling the persistent ordering
464    * New Cability: updates min/max for colourscheme range if its dynamic
465    * 
466    * @param allFeatures
467    */
468   private void updateRenderOrder(List<String> allFeatures)
469   {
470     List<String> allfeatures = new ArrayList<>(allFeatures);
471     String[] oldRender = renderOrder;
472     renderOrder = new String[allfeatures.size()];
473     boolean initOrders = (featureOrder == null);
474     int opos = 0;
475     if (oldRender != null && oldRender.length > 0)
476     {
477       for (int j = 0; j < oldRender.length; j++)
478       {
479         if (oldRender[j] != null)
480         {
481           if (initOrders)
482           {
483             setOrder(oldRender[j],
484                     (1 - (1 + (float) j) / oldRender.length));
485           }
486           if (allfeatures.contains(oldRender[j]))
487           {
488             renderOrder[opos++] = oldRender[j]; // existing features always
489             // appear below new features
490             allfeatures.remove(oldRender[j]);
491             if (minmax != null)
492             {
493               float[][] mmrange = minmax.get(oldRender[j]);
494               if (mmrange != null)
495               {
496                 FeatureColourI fc = featureColours.get(oldRender[j]);
497                 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled()
498                         && !fc.isColourByAttribute())
499                 {
500                   fc.updateBounds(mmrange[0][0], mmrange[0][1]);
501                 }
502               }
503             }
504           }
505         }
506       }
507     }
508     if (allfeatures.size() == 0)
509     {
510       // no new features - leave order unchanged.
511       return;
512     }
513     int i = allfeatures.size() - 1;
514     int iSize = i;
515     boolean sort = false;
516     String[] newf = new String[allfeatures.size()];
517     float[] sortOrder = new float[allfeatures.size()];
518     for (String newfeat : allfeatures)
519     {
520       newf[i] = newfeat;
521       if (minmax != null)
522       {
523         // update from new features minmax if necessary
524         float[][] mmrange = minmax.get(newf[i]);
525         if (mmrange != null)
526         {
527           FeatureColourI fc = featureColours.get(newf[i]);
528           if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled()
529                   && !fc.isColourByAttribute())
530           {
531             fc.updateBounds(mmrange[0][0], mmrange[0][1]);
532           }
533         }
534       }
535       if (initOrders || !featureOrder.containsKey(newf[i]))
536       {
537         int denom = initOrders ? allfeatures.size() : featureOrder.size();
538         // new unordered feature - compute persistent ordering at head of
539         // existing features.
540         setOrder(newf[i], i / (float) denom);
541       }
542       // set order from newly found feature from persisted ordering.
543       sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
544       if (i < iSize)
545       {
546         // only sort if we need to
547         sort = sort || sortOrder[i] > sortOrder[i + 1];
548       }
549       i--;
550     }
551     if (iSize > 1 && sort)
552     {
553       jalview.util.QuickSort.sort(sortOrder, newf);
554     }
555     sortOrder = null;
556     System.arraycopy(newf, 0, renderOrder, opos, newf.length);
557   }
558
559   /**
560    * get a feature style object for the given type string. Creates a
561    * java.awt.Color for a featureType with no existing colourscheme.
562    * 
563    * @param featureType
564    * @return
565    */
566   @Override
567   public FeatureColourI getFeatureStyle(String featureType)
568   {
569     FeatureColourI fc = featureColours.get(featureType);
570     if (fc == null)
571     {
572       Color col = ColorUtils.createColourFromName(featureType);
573       fc = new FeatureColour(col);
574       featureColours.put(featureType, fc);
575     }
576     return fc;
577   }
578
579   @Override
580   public Color getColour(SequenceFeature feature)
581   {
582     FeatureColourI fc = getFeatureStyle(feature.getType());
583     return getColor(feature, fc);
584   }
585
586   /**
587    * Answers true if the feature type is currently selected to be displayed,
588    * else false
589    * 
590    * @param type
591    * @return
592    */
593   protected boolean showFeatureOfType(String type)
594   {
595     return type == null ? false : (av.getFeaturesDisplayed() == null ? true
596             : av.getFeaturesDisplayed().isVisible(type));
597   }
598
599   @Override
600   public void setColour(String featureType, FeatureColourI col)
601   {
602     featureColours.put(featureType, col);
603   }
604
605   @Override
606   public void setTransparency(float value)
607   {
608     transparency = value;
609   }
610
611   @Override
612   public float getTransparency()
613   {
614     return transparency;
615   }
616
617   /**
618    * analogous to colour - store a normalized ordering for all feature types in
619    * this rendering context.
620    * 
621    * @param type
622    *          Feature type string
623    * @param position
624    *          normalized priority - 0 means always appears on top, 1 means
625    *          always last.
626    */
627   public float setOrder(String type, float position)
628   {
629     if (featureOrder == null)
630     {
631       featureOrder = new Hashtable<>();
632     }
633     featureOrder.put(type, new Float(position));
634     return position;
635   }
636
637   /**
638    * get the global priority (0 (top) to 1 (bottom))
639    * 
640    * @param type
641    * @return [0,1] or -1 for a type without a priority
642    */
643   public float getOrder(String type)
644   {
645     if (featureOrder != null)
646     {
647       if (featureOrder.containsKey(type))
648       {
649         return featureOrder.get(type).floatValue();
650       }
651     }
652     return -1;
653   }
654
655   @Override
656   public Map<String, FeatureColourI> getFeatureColours()
657   {
658     return featureColours;
659   }
660
661   /**
662    * Replace current ordering with new ordering
663    * 
664    * @param data
665    *          { String(Type), Colour(Type), Boolean(Displayed) }
666    * @return true if any visible features have been reordered, else false
667    */
668   public boolean setFeaturePriority(Object[][] data)
669   {
670     return setFeaturePriority(data, true);
671   }
672
673   /**
674    * Sets the priority order for features, with the highest priority (displayed
675    * on top) at the start of the data array
676    * 
677    * @param data
678    *          { String(Type), Colour(Type), Boolean(Displayed) }
679    * @param visibleNew
680    *          when true current featureDisplay list will be cleared
681    * @return true if any visible features have been reordered or recoloured,
682    *         else false (i.e. no need to repaint)
683    */
684   public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
685   {
686     /*
687      * note visible feature ordering and colours before update
688      */
689     List<String> visibleFeatures = getDisplayedFeatureTypes();
690     Map<String, FeatureColourI> visibleColours = new HashMap<>(
691             getFeatureColours());
692
693     FeaturesDisplayedI av_featuresdisplayed = null;
694     if (visibleNew)
695     {
696       if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
697       {
698         av.getFeaturesDisplayed().clear();
699       }
700       else
701       {
702         av.setFeaturesDisplayed(
703                 av_featuresdisplayed = new FeaturesDisplayed());
704       }
705     }
706     else
707     {
708       av_featuresdisplayed = av.getFeaturesDisplayed();
709     }
710     if (data == null)
711     {
712       return false;
713     }
714     // The feature table will display high priority
715     // features at the top, but these are the ones
716     // we need to render last, so invert the data
717     renderOrder = new String[data.length];
718
719     if (data.length > 0)
720     {
721       for (int i = 0; i < data.length; i++)
722       {
723         String type = data[i][0].toString();
724         setColour(type, (FeatureColourI) data[i][1]);
725         if (((Boolean) data[i][2]).booleanValue())
726         {
727           av_featuresdisplayed.setVisible(type);
728         }
729
730         renderOrder[data.length - i - 1] = type;
731       }
732     }
733
734     /*
735      * get the new visible ordering and return true if it has changed
736      * order or any colour has changed
737      */
738     List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
739     if (!visibleFeatures.equals(reorderedVisibleFeatures))
740     {
741       /*
742        * the list of ordered visible features has changed
743        */
744       return true;
745     }
746
747     /*
748      * return true if any feature colour has changed
749      */
750     for (String feature : visibleFeatures)
751     {
752       if (visibleColours.get(feature) != getFeatureStyle(feature))
753       {
754         return true;
755       }
756     }
757     return false;
758   }
759
760   /**
761    * @param listener
762    * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
763    */
764   public void addPropertyChangeListener(PropertyChangeListener listener)
765   {
766     changeSupport.addPropertyChangeListener(listener);
767   }
768
769   /**
770    * @param listener
771    * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
772    */
773   public void removePropertyChangeListener(PropertyChangeListener listener)
774   {
775     changeSupport.removePropertyChangeListener(listener);
776   }
777
778   public Set<String> getAllFeatureColours()
779   {
780     return featureColours.keySet();
781   }
782
783   public void clearRenderOrder()
784   {
785     renderOrder = null;
786   }
787
788   public boolean hasRenderOrder()
789   {
790     return renderOrder != null;
791   }
792
793   /**
794    * Returns feature types in ordering of rendering, where last means on top
795    */
796   public List<String> getRenderOrder()
797   {
798     if (renderOrder == null)
799     {
800       return Arrays.asList(new String[] {});
801     }
802     return Arrays.asList(renderOrder);
803   }
804
805   public int getFeatureGroupsSize()
806   {
807     return featureGroups != null ? 0 : featureGroups.size();
808   }
809
810   @Override
811   public List<String> getFeatureGroups()
812   {
813     // conflict between applet and desktop - featureGroups returns the map in
814     // the desktop featureRenderer
815     return (featureGroups == null) ? Arrays.asList(new String[0])
816             : Arrays.asList(featureGroups.keySet().toArray(new String[0]));
817   }
818
819   public boolean checkGroupVisibility(String group,
820           boolean newGroupsVisible)
821   {
822     if (featureGroups == null)
823     {
824       // then an exception happens next..
825     }
826     if (featureGroups.containsKey(group))
827     {
828       return featureGroups.get(group).booleanValue();
829     }
830     if (newGroupsVisible)
831     {
832       featureGroups.put(group, new Boolean(true));
833       return true;
834     }
835     return false;
836   }
837
838   /**
839    * get visible or invisible groups
840    * 
841    * @param visible
842    *          true to return visible groups, false to return hidden ones.
843    * @return list of groups
844    */
845   @Override
846   public List<String> getGroups(boolean visible)
847   {
848     if (featureGroups != null)
849     {
850       List<String> gp = new ArrayList<>();
851
852       for (String grp : featureGroups.keySet())
853       {
854         Boolean state = featureGroups.get(grp);
855         if (state.booleanValue() == visible)
856         {
857           gp.add(grp);
858         }
859       }
860       return gp;
861     }
862     return null;
863   }
864
865   @Override
866   public void setGroupVisibility(String group, boolean visible)
867   {
868     featureGroups.put(group, new Boolean(visible));
869   }
870
871   @Override
872   public void setGroupVisibility(List<String> toset, boolean visible)
873   {
874     if (toset != null && toset.size() > 0 && featureGroups != null)
875     {
876       boolean rdrw = false;
877       for (String gst : toset)
878       {
879         Boolean st = featureGroups.get(gst);
880         featureGroups.put(gst, new Boolean(visible));
881         if (st != null)
882         {
883           rdrw = rdrw || (visible != st.booleanValue());
884         }
885       }
886       if (rdrw)
887       {
888         // set local flag indicating redraw needed ?
889       }
890     }
891   }
892
893   @Override
894   public Map<String, FeatureColourI> getDisplayedFeatureCols()
895   {
896     Map<String, FeatureColourI> fcols = new Hashtable<>();
897     if (getViewport().getFeaturesDisplayed() == null)
898     {
899       return fcols;
900     }
901     Set<String> features = getViewport().getFeaturesDisplayed()
902             .getVisibleFeatures();
903     for (String feature : features)
904     {
905       fcols.put(feature, getFeatureStyle(feature));
906     }
907     return fcols;
908   }
909
910   @Override
911   public FeaturesDisplayedI getFeaturesDisplayed()
912   {
913     return av.getFeaturesDisplayed();
914   }
915
916   /**
917    * Returns a (possibly empty) list of visible feature types, in render order
918    * (last is on top)
919    */
920   @Override
921   public List<String> getDisplayedFeatureTypes()
922   {
923     List<String> typ = getRenderOrder();
924     List<String> displayed = new ArrayList<>();
925     FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
926     if (feature_disp != null)
927     {
928       synchronized (feature_disp)
929       {
930         for (String type : typ)
931         {
932           if (feature_disp.isVisible(type))
933           {
934             displayed.add(type);
935           }
936         }
937       }
938     }
939     return displayed;
940   }
941
942   @Override
943   public List<String> getDisplayedFeatureGroups()
944   {
945     List<String> _gps = new ArrayList<>();
946     for (String gp : getFeatureGroups())
947     {
948       if (checkGroupVisibility(gp, false))
949       {
950         _gps.add(gp);
951       }
952     }
953     return _gps;
954   }
955
956   /**
957    * Answers true if the feature belongs to a feature group which is not
958    * currently displayed, else false
959    * 
960    * @param sequenceFeature
961    * @return
962    */
963   protected boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
964   {
965     return featureGroups != null
966             && sequenceFeature.featureGroup != null
967             && sequenceFeature.featureGroup.length() != 0
968             && featureGroups.containsKey(sequenceFeature.featureGroup)
969             && !featureGroups.get(sequenceFeature.featureGroup)
970                     .booleanValue();
971   }
972
973   /**
974    * {@inheritDoc}
975    */
976   @Override
977   public List<SequenceFeature> findFeaturesAtResidue(SequenceI sequence,
978           int resNo)
979   {
980     List<SequenceFeature> result = new ArrayList<>();
981     if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
982     {
983       return result;
984     }
985
986     /*
987      * include features at the position provided their feature type is 
988      * displayed, and feature group is null or the empty string
989      * or marked for display
990      */
991     Set<String> visibleFeatures = getFeaturesDisplayed()
992             .getVisibleFeatures();
993     String[] visibleTypes = visibleFeatures
994             .toArray(new String[visibleFeatures.size()]);
995     List<SequenceFeature> features = sequence.getFeatures().findFeatures(
996             resNo, resNo, visibleTypes);
997   
998     for (SequenceFeature sf : features)
999     {
1000       if (!featureGroupNotShown(sf) && getColour(sf) != null)
1001       {
1002         result.add(sf);
1003       }
1004     }
1005     return result;
1006   }
1007
1008   /**
1009    * Removes from the list of features any that duplicate the location of a
1010    * feature of the same type. Should be used only for features of the same,
1011    * simple, feature colour (which normally implies the same feature type). Does
1012    * not check visibility settings for feature type or feature group.
1013    * 
1014    * @param features
1015    */
1016   public void filterFeaturesForDisplay(List<SequenceFeature> features)
1017   {
1018     if (features.isEmpty())
1019     {
1020       return;
1021     }
1022     SequenceFeatures.sortFeatures(features, true);
1023     SequenceFeature lastFeature = null;
1024
1025     Iterator<SequenceFeature> it = features.iterator();
1026     while (it.hasNext())
1027     {
1028       SequenceFeature sf = it.next();
1029
1030       /*
1031        * a feature is redundant for rendering purposes if it has the
1032        * same extent as another (so would just redraw the same colour);
1033        * (checking type and isContactFeature as a fail-safe here, although
1034        * currently they are guaranteed to match in this context)
1035        */
1036       if (lastFeature != null && sf.getBegin() == lastFeature.getBegin()
1037               && sf.getEnd() == lastFeature.getEnd()
1038               && sf.isContactFeature() == lastFeature.isContactFeature()
1039               && sf.getType().equals(lastFeature.getType()))
1040       {
1041         it.remove();
1042       }
1043       lastFeature = sf;
1044     }
1045   }
1046
1047   @Override
1048   public Map<String, KeyedMatcherSetI> getFeatureFilters()
1049   {
1050     return new HashMap<>(featureFilters);
1051   }
1052
1053   @Override
1054   public void setFeatureFilters(Map<String, KeyedMatcherSetI> filters)
1055   {
1056     featureFilters = filters;
1057   }
1058
1059   @Override
1060   public KeyedMatcherSetI getFeatureFilter(String featureType)
1061   {
1062     return featureFilters.get(featureType);
1063   }
1064
1065   @Override
1066   public void setFeatureFilter(String featureType, KeyedMatcherSetI filter)
1067   {
1068     if (filter == null || filter.isEmpty())
1069     {
1070       featureFilters.remove(featureType);
1071     }
1072     else
1073     {
1074       featureFilters.put(featureType, filter);
1075     }
1076   }
1077
1078   /**
1079    * Answers the colour for the feature, or null if the feature is excluded by
1080    * feature type or group visibility, by filters, or by colour threshold
1081    * settings
1082    * 
1083    * @param sf
1084    * @param fc
1085    * @return
1086    */
1087   public Color getColor(SequenceFeature sf, FeatureColourI fc)
1088   {
1089     /*
1090      * is the feature type displayed?
1091      */
1092     if (!showFeatureOfType(sf.getType()))
1093     {
1094       return null;
1095     }
1096
1097     /*
1098      * is the feature group displayed?
1099      */
1100     if (featureGroupNotShown(sf))
1101     {
1102       return null;
1103     }
1104
1105     /*
1106      * does the feature pass filters?
1107      */
1108     if (!featureMatchesFilters(sf))
1109     {
1110       return null;
1111     }
1112   
1113     return fc.getColor(sf);
1114   }
1115
1116   /**
1117    * Answers true if there no are filters defined for the feature type, or this
1118    * feature matches the filters. Answers false if the feature fails to match
1119    * filters.
1120    * 
1121    * @param sf
1122    * @return
1123    */
1124   protected boolean featureMatchesFilters(SequenceFeature sf)
1125   {
1126     KeyedMatcherSetI filter = featureFilters.get(sf.getType());
1127     return filter == null ? true : filter.matches(key -> sf
1128             .getValueAsString(key));
1129   }
1130
1131 }