3a970671e0b2067960ed5c49c73ad75ac0e25d5d
[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                 {
495                   fc.updateBounds(mmrange[0][0], mmrange[0][1]);
496                 }
497               }
498             }
499           }
500         }
501       }
502     }
503     if (allfeatures.size() == 0)
504     {
505       // no new features - leave order unchanged.
506       return;
507     }
508     int i = allfeatures.size() - 1;
509     int iSize = i;
510     boolean sort = false;
511     String[] newf = new String[allfeatures.size()];
512     float[] sortOrder = new float[allfeatures.size()];
513     for (String newfeat : allfeatures)
514     {
515       newf[i] = newfeat;
516       if (minmax != null)
517       {
518         // update from new features minmax if necessary
519         float[][] mmrange = minmax.get(newf[i]);
520         if (mmrange != null)
521         {
522           FeatureColourI fc = featureColours.get(newf[i]);
523           if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
524           {
525             fc.updateBounds(mmrange[0][0], mmrange[0][1]);
526           }
527         }
528       }
529       if (initOrders || !featureOrder.containsKey(newf[i]))
530       {
531         int denom = initOrders ? allfeatures.size() : featureOrder.size();
532         // new unordered feature - compute persistent ordering at head of
533         // existing features.
534         setOrder(newf[i], i / (float) denom);
535       }
536       // set order from newly found feature from persisted ordering.
537       sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
538       if (i < iSize)
539       {
540         // only sort if we need to
541         sort = sort || sortOrder[i] > sortOrder[i + 1];
542       }
543       i--;
544     }
545     if (iSize > 1 && sort)
546     {
547       jalview.util.QuickSort.sort(sortOrder, newf);
548     }
549     sortOrder = null;
550     System.arraycopy(newf, 0, renderOrder, opos, newf.length);
551   }
552
553   /**
554    * get a feature style object for the given type string. Creates a
555    * java.awt.Color for a featureType with no existing colourscheme.
556    * 
557    * @param featureType
558    * @return
559    */
560   @Override
561   public FeatureColourI getFeatureStyle(String featureType)
562   {
563     FeatureColourI fc = featureColours.get(featureType);
564     if (fc == null)
565     {
566       Color col = ColorUtils.createColourFromName(featureType);
567       fc = new FeatureColour(col);
568       featureColours.put(featureType, fc);
569     }
570     return fc;
571   }
572
573   @Override
574   public Color getColour(SequenceFeature feature)
575   {
576     FeatureColourI fc = getFeatureStyle(feature.getType());
577     return getColor(feature, fc);
578   }
579
580   /**
581    * Answers true if the feature type is currently selected to be displayed,
582    * else false
583    * 
584    * @param type
585    * @return
586    */
587   protected boolean showFeatureOfType(String type)
588   {
589     return type == null ? false : (av.getFeaturesDisplayed() == null ? true
590             : av.getFeaturesDisplayed().isVisible(type));
591   }
592
593   @Override
594   public void setColour(String featureType, FeatureColourI col)
595   {
596     featureColours.put(featureType, col);
597   }
598
599   @Override
600   public void setTransparency(float value)
601   {
602     transparency = value;
603   }
604
605   @Override
606   public float getTransparency()
607   {
608     return transparency;
609   }
610
611   /**
612    * analogous to colour - store a normalized ordering for all feature types in
613    * this rendering context.
614    * 
615    * @param type
616    *          Feature type string
617    * @param position
618    *          normalized priority - 0 means always appears on top, 1 means
619    *          always last.
620    */
621   public float setOrder(String type, float position)
622   {
623     if (featureOrder == null)
624     {
625       featureOrder = new Hashtable<String, Float>();
626     }
627     featureOrder.put(type, new Float(position));
628     return position;
629   }
630
631   /**
632    * get the global priority (0 (top) to 1 (bottom))
633    * 
634    * @param type
635    * @return [0,1] or -1 for a type without a priority
636    */
637   public float getOrder(String type)
638   {
639     if (featureOrder != null)
640     {
641       if (featureOrder.containsKey(type))
642       {
643         return featureOrder.get(type).floatValue();
644       }
645     }
646     return -1;
647   }
648
649   @Override
650   public Map<String, FeatureColourI> getFeatureColours()
651   {
652     return featureColours;
653   }
654
655   /**
656    * Replace current ordering with new ordering
657    * 
658    * @param data
659    *          { String(Type), Colour(Type), Boolean(Displayed) }
660    * @return true if any visible features have been reordered, else false
661    */
662   public boolean setFeaturePriority(Object[][] data)
663   {
664     return setFeaturePriority(data, true);
665   }
666
667   /**
668    * Sets the priority order for features, with the highest priority (displayed
669    * on top) at the start of the data array
670    * 
671    * @param data
672    *          { String(Type), Colour(Type), Boolean(Displayed) }
673    * @param visibleNew
674    *          when true current featureDisplay list will be cleared
675    * @return true if any visible features have been reordered or recoloured,
676    *         else false (i.e. no need to repaint)
677    */
678   public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
679   {
680     /*
681      * note visible feature ordering and colours before update
682      */
683     List<String> visibleFeatures = getDisplayedFeatureTypes();
684     Map<String, FeatureColourI> visibleColours = new HashMap<String, FeatureColourI>(
685             getFeatureColours());
686
687     FeaturesDisplayedI av_featuresdisplayed = null;
688     if (visibleNew)
689     {
690       if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
691       {
692         av.getFeaturesDisplayed().clear();
693       }
694       else
695       {
696         av.setFeaturesDisplayed(
697                 av_featuresdisplayed = new FeaturesDisplayed());
698       }
699     }
700     else
701     {
702       av_featuresdisplayed = av.getFeaturesDisplayed();
703     }
704     if (data == null)
705     {
706       return false;
707     }
708     // The feature table will display high priority
709     // features at the top, but these are the ones
710     // we need to render last, so invert the data
711     renderOrder = new String[data.length];
712
713     if (data.length > 0)
714     {
715       for (int i = 0; i < data.length; i++)
716       {
717         String type = data[i][0].toString();
718         setColour(type, (FeatureColourI) data[i][1]);
719         if (((Boolean) data[i][2]).booleanValue())
720         {
721           av_featuresdisplayed.setVisible(type);
722         }
723
724         renderOrder[data.length - i - 1] = type;
725       }
726     }
727
728     /*
729      * get the new visible ordering and return true if it has changed
730      * order or any colour has changed
731      */
732     List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
733     if (!visibleFeatures.equals(reorderedVisibleFeatures))
734     {
735       /*
736        * the list of ordered visible features has changed
737        */
738       return true;
739     }
740
741     /*
742      * return true if any feature colour has changed
743      */
744     for (String feature : visibleFeatures)
745     {
746       if (visibleColours.get(feature) != getFeatureStyle(feature))
747       {
748         return true;
749       }
750     }
751     return false;
752   }
753
754   /**
755    * @param listener
756    * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
757    */
758   public void addPropertyChangeListener(PropertyChangeListener listener)
759   {
760     changeSupport.addPropertyChangeListener(listener);
761   }
762
763   /**
764    * @param listener
765    * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
766    */
767   public void removePropertyChangeListener(PropertyChangeListener listener)
768   {
769     changeSupport.removePropertyChangeListener(listener);
770   }
771
772   public Set<String> getAllFeatureColours()
773   {
774     return featureColours.keySet();
775   }
776
777   public void clearRenderOrder()
778   {
779     renderOrder = null;
780   }
781
782   public boolean hasRenderOrder()
783   {
784     return renderOrder != null;
785   }
786
787   /**
788    * Returns feature types in ordering of rendering, where last means on top
789    */
790   public List<String> getRenderOrder()
791   {
792     if (renderOrder == null)
793     {
794       return Arrays.asList(new String[] {});
795     }
796     return Arrays.asList(renderOrder);
797   }
798
799   public int getFeatureGroupsSize()
800   {
801     return featureGroups != null ? 0 : featureGroups.size();
802   }
803
804   @Override
805   public List<String> getFeatureGroups()
806   {
807     // conflict between applet and desktop - featureGroups returns the map in
808     // the desktop featureRenderer
809     return (featureGroups == null) ? Arrays.asList(new String[0])
810             : Arrays.asList(featureGroups.keySet().toArray(new String[0]));
811   }
812
813   public boolean checkGroupVisibility(String group,
814           boolean newGroupsVisible)
815   {
816     if (featureGroups == null)
817     {
818       // then an exception happens next..
819     }
820     if (featureGroups.containsKey(group))
821     {
822       return featureGroups.get(group).booleanValue();
823     }
824     if (newGroupsVisible)
825     {
826       featureGroups.put(group, new Boolean(true));
827       return true;
828     }
829     return false;
830   }
831
832   /**
833    * get visible or invisible groups
834    * 
835    * @param visible
836    *          true to return visible groups, false to return hidden ones.
837    * @return list of groups
838    */
839   @Override
840   public List<String> getGroups(boolean visible)
841   {
842     if (featureGroups != null)
843     {
844       List<String> gp = new ArrayList<String>();
845
846       for (String grp : featureGroups.keySet())
847       {
848         Boolean state = featureGroups.get(grp);
849         if (state.booleanValue() == visible)
850         {
851           gp.add(grp);
852         }
853       }
854       return gp;
855     }
856     return null;
857   }
858
859   @Override
860   public void setGroupVisibility(String group, boolean visible)
861   {
862     featureGroups.put(group, new Boolean(visible));
863   }
864
865   @Override
866   public void setGroupVisibility(List<String> toset, boolean visible)
867   {
868     if (toset != null && toset.size() > 0 && featureGroups != null)
869     {
870       boolean rdrw = false;
871       for (String gst : toset)
872       {
873         Boolean st = featureGroups.get(gst);
874         featureGroups.put(gst, new Boolean(visible));
875         if (st != null)
876         {
877           rdrw = rdrw || (visible != st.booleanValue());
878         }
879       }
880       if (rdrw)
881       {
882         // set local flag indicating redraw needed ?
883       }
884     }
885   }
886
887   @Override
888   public Map<String, FeatureColourI> getDisplayedFeatureCols()
889   {
890     Map<String, FeatureColourI> fcols = new Hashtable<String, FeatureColourI>();
891     if (getViewport().getFeaturesDisplayed() == null)
892     {
893       return fcols;
894     }
895     Set<String> features = getViewport().getFeaturesDisplayed()
896             .getVisibleFeatures();
897     for (String feature : features)
898     {
899       fcols.put(feature, getFeatureStyle(feature));
900     }
901     return fcols;
902   }
903
904   @Override
905   public FeaturesDisplayedI getFeaturesDisplayed()
906   {
907     return av.getFeaturesDisplayed();
908   }
909
910   /**
911    * Returns a (possibly empty) list of visible feature types, in render order
912    * (last is on top)
913    */
914   @Override
915   public List<String> getDisplayedFeatureTypes()
916   {
917     List<String> typ = getRenderOrder();
918     List<String> displayed = new ArrayList<String>();
919     FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
920     if (feature_disp != null)
921     {
922       synchronized (feature_disp)
923       {
924         for (String type : typ)
925         {
926           if (feature_disp.isVisible(type))
927           {
928             displayed.add(type);
929           }
930         }
931       }
932     }
933     return displayed;
934   }
935
936   @Override
937   public List<String> getDisplayedFeatureGroups()
938   {
939     List<String> _gps = new ArrayList<String>();
940     for (String gp : getFeatureGroups())
941     {
942       if (checkGroupVisibility(gp, false))
943       {
944         _gps.add(gp);
945       }
946     }
947     return _gps;
948   }
949
950   /**
951    * Answers true if the feature belongs to a feature group which is not
952    * currently displayed, else false
953    * 
954    * @param sequenceFeature
955    * @return
956    */
957   protected boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
958   {
959     return featureGroups != null
960             && sequenceFeature.featureGroup != null
961             && sequenceFeature.featureGroup.length() != 0
962             && featureGroups.containsKey(sequenceFeature.featureGroup)
963             && !featureGroups.get(sequenceFeature.featureGroup)
964                     .booleanValue();
965   }
966
967   /**
968    * {@inheritDoc}
969    */
970   @Override
971   public List<SequenceFeature> findFeaturesAtResidue(SequenceI sequence,
972           int resNo)
973   {
974     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
975     if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
976     {
977       return result;
978     }
979
980     /*
981      * include features at the position provided their feature type is 
982      * displayed, and feature group is null or the empty string
983      * or marked for display
984      */
985     Set<String> visibleFeatures = getFeaturesDisplayed()
986             .getVisibleFeatures();
987     String[] visibleTypes = visibleFeatures
988             .toArray(new String[visibleFeatures.size()]);
989     List<SequenceFeature> features = sequence.getFeatures().findFeatures(
990             resNo, resNo, visibleTypes);
991   
992     for (SequenceFeature sf : features)
993     {
994       if (!featureGroupNotShown(sf))
995       {
996         result.add(sf);
997       }
998     }
999     return result;
1000   }
1001
1002   /**
1003    * Removes from the list of features any that duplicate the location of a
1004    * feature of the same type. Should be used only for features of the same,
1005    * simple, feature colour (which normally implies the same feature type). Does
1006    * not check visibility settings for feature type or feature group.
1007    * 
1008    * @param features
1009    */
1010   public void filterFeaturesForDisplay(List<SequenceFeature> features)
1011   {
1012     if (features.isEmpty())
1013     {
1014       return;
1015     }
1016     SequenceFeatures.sortFeatures(features, true);
1017     SequenceFeature lastFeature = null;
1018
1019     Iterator<SequenceFeature> it = features.iterator();
1020     while (it.hasNext())
1021     {
1022       SequenceFeature sf = it.next();
1023
1024       /*
1025        * a feature is redundant for rendering purposes if it has the
1026        * same extent as another (so would just redraw the same colour);
1027        * (checking type and isContactFeature as a fail-safe here, although
1028        * currently they are guaranteed to match in this context)
1029        */
1030       if (lastFeature != null && sf.getBegin() == lastFeature.getBegin()
1031               && sf.getEnd() == lastFeature.getEnd()
1032               && sf.isContactFeature() == lastFeature.isContactFeature()
1033               && sf.getType().equals(lastFeature.getType()))
1034       {
1035         it.remove();
1036       }
1037       lastFeature = sf;
1038     }
1039   }
1040
1041   @Override
1042   public Map<String, KeyedMatcherSetI> getFeatureFilters()
1043   {
1044     return new HashMap<>(featureFilters);
1045   }
1046
1047   @Override
1048   public void setFeatureFilters(Map<String, KeyedMatcherSetI> filters)
1049   {
1050     featureFilters = filters;
1051   }
1052
1053   @Override
1054   public KeyedMatcherSetI getFeatureFilter(String featureType)
1055   {
1056     return featureFilters.get(featureType);
1057   }
1058
1059   @Override
1060   public void setFeatureFilter(String featureType, KeyedMatcherSetI filter)
1061   {
1062     if (filter == null || filter.isEmpty())
1063     {
1064       featureFilters.remove(featureType);
1065     }
1066     else
1067     {
1068       featureFilters.put(featureType, filter);
1069     }
1070   }
1071
1072   /**
1073    * Answers the colour for the feature, or null if the feature is excluded by
1074    * feature type or group visibility, by filters, or by colour threshold
1075    * settings
1076    * 
1077    * @param sf
1078    * @param fc
1079    * @return
1080    */
1081   public Color getColor(SequenceFeature sf, FeatureColourI fc)
1082   {
1083     /*
1084      * is the feature type displayed?
1085      */
1086     if (!showFeatureOfType(sf.getType()))
1087     {
1088       return null;
1089     }
1090
1091     /*
1092      * is the feature group displayed?
1093      */
1094     if (featureGroupNotShown(sf))
1095     {
1096       return null;
1097     }
1098
1099     /*
1100      * does the feature pass filters?
1101      */
1102     if (!featureMatchesFilters(sf))
1103     {
1104       return null;
1105     }
1106   
1107     return fc.getColor(sf);
1108   }
1109
1110   /**
1111    * Answers true if there no are filters defined for the feature type, or this
1112    * feature matches the filters. Answers false if the feature fails to match
1113    * filters.
1114    * 
1115    * @param sf
1116    * @return
1117    */
1118   protected boolean featureMatchesFilters(SequenceFeature sf)
1119   {
1120     KeyedMatcherSetI filter = featureFilters.get(sf.getType());
1121     return filter == null ? true : filter.matches(key -> sf
1122             .getValueAsString(key));
1123   }
1124
1125 }