6461748ac607a1813f6f8dfbb9ec6be9cc8571e3
[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().isVisible(type);
590   }
591
592   @Override
593   public void setColour(String featureType, FeatureColourI col)
594   {
595     featureColours.put(featureType, col);
596   }
597
598   @Override
599   public void setTransparency(float value)
600   {
601     transparency = value;
602   }
603
604   @Override
605   public float getTransparency()
606   {
607     return transparency;
608   }
609
610   /**
611    * analogous to colour - store a normalized ordering for all feature types in
612    * this rendering context.
613    * 
614    * @param type
615    *          Feature type string
616    * @param position
617    *          normalized priority - 0 means always appears on top, 1 means
618    *          always last.
619    */
620   public float setOrder(String type, float position)
621   {
622     if (featureOrder == null)
623     {
624       featureOrder = new Hashtable<String, Float>();
625     }
626     featureOrder.put(type, new Float(position));
627     return position;
628   }
629
630   /**
631    * get the global priority (0 (top) to 1 (bottom))
632    * 
633    * @param type
634    * @return [0,1] or -1 for a type without a priority
635    */
636   public float getOrder(String type)
637   {
638     if (featureOrder != null)
639     {
640       if (featureOrder.containsKey(type))
641       {
642         return featureOrder.get(type).floatValue();
643       }
644     }
645     return -1;
646   }
647
648   @Override
649   public Map<String, FeatureColourI> getFeatureColours()
650   {
651     return featureColours;
652   }
653
654   /**
655    * Replace current ordering with new ordering
656    * 
657    * @param data
658    *          { String(Type), Colour(Type), Boolean(Displayed) }
659    * @return true if any visible features have been reordered, else false
660    */
661   public boolean setFeaturePriority(Object[][] data)
662   {
663     return setFeaturePriority(data, true);
664   }
665
666   /**
667    * Sets the priority order for features, with the highest priority (displayed
668    * on top) at the start of the data array
669    * 
670    * @param data
671    *          { String(Type), Colour(Type), Boolean(Displayed) }
672    * @param visibleNew
673    *          when true current featureDisplay list will be cleared
674    * @return true if any visible features have been reordered or recoloured,
675    *         else false (i.e. no need to repaint)
676    */
677   public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
678   {
679     /*
680      * note visible feature ordering and colours before update
681      */
682     List<String> visibleFeatures = getDisplayedFeatureTypes();
683     Map<String, FeatureColourI> visibleColours = new HashMap<String, FeatureColourI>(
684             getFeatureColours());
685
686     FeaturesDisplayedI av_featuresdisplayed = null;
687     if (visibleNew)
688     {
689       if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
690       {
691         av.getFeaturesDisplayed().clear();
692       }
693       else
694       {
695         av.setFeaturesDisplayed(
696                 av_featuresdisplayed = new FeaturesDisplayed());
697       }
698     }
699     else
700     {
701       av_featuresdisplayed = av.getFeaturesDisplayed();
702     }
703     if (data == null)
704     {
705       return false;
706     }
707     // The feature table will display high priority
708     // features at the top, but these are the ones
709     // we need to render last, so invert the data
710     renderOrder = new String[data.length];
711
712     if (data.length > 0)
713     {
714       for (int i = 0; i < data.length; i++)
715       {
716         String type = data[i][0].toString();
717         setColour(type, (FeatureColourI) data[i][1]);
718         if (((Boolean) data[i][2]).booleanValue())
719         {
720           av_featuresdisplayed.setVisible(type);
721         }
722
723         renderOrder[data.length - i - 1] = type;
724       }
725     }
726
727     /*
728      * get the new visible ordering and return true if it has changed
729      * order or any colour has changed
730      */
731     List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
732     if (!visibleFeatures.equals(reorderedVisibleFeatures))
733     {
734       /*
735        * the list of ordered visible features has changed
736        */
737       return true;
738     }
739
740     /*
741      * return true if any feature colour has changed
742      */
743     for (String feature : visibleFeatures)
744     {
745       if (visibleColours.get(feature) != getFeatureStyle(feature))
746       {
747         return true;
748       }
749     }
750     return false;
751   }
752
753   /**
754    * @param listener
755    * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
756    */
757   public void addPropertyChangeListener(PropertyChangeListener listener)
758   {
759     changeSupport.addPropertyChangeListener(listener);
760   }
761
762   /**
763    * @param listener
764    * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
765    */
766   public void removePropertyChangeListener(PropertyChangeListener listener)
767   {
768     changeSupport.removePropertyChangeListener(listener);
769   }
770
771   public Set<String> getAllFeatureColours()
772   {
773     return featureColours.keySet();
774   }
775
776   public void clearRenderOrder()
777   {
778     renderOrder = null;
779   }
780
781   public boolean hasRenderOrder()
782   {
783     return renderOrder != null;
784   }
785
786   /**
787    * Returns feature types in ordering of rendering, where last means on top
788    */
789   public List<String> getRenderOrder()
790   {
791     if (renderOrder == null)
792     {
793       return Arrays.asList(new String[] {});
794     }
795     return Arrays.asList(renderOrder);
796   }
797
798   public int getFeatureGroupsSize()
799   {
800     return featureGroups != null ? 0 : featureGroups.size();
801   }
802
803   @Override
804   public List<String> getFeatureGroups()
805   {
806     // conflict between applet and desktop - featureGroups returns the map in
807     // the desktop featureRenderer
808     return (featureGroups == null) ? Arrays.asList(new String[0])
809             : Arrays.asList(featureGroups.keySet().toArray(new String[0]));
810   }
811
812   public boolean checkGroupVisibility(String group,
813           boolean newGroupsVisible)
814   {
815     if (featureGroups == null)
816     {
817       // then an exception happens next..
818     }
819     if (featureGroups.containsKey(group))
820     {
821       return featureGroups.get(group).booleanValue();
822     }
823     if (newGroupsVisible)
824     {
825       featureGroups.put(group, new Boolean(true));
826       return true;
827     }
828     return false;
829   }
830
831   /**
832    * get visible or invisible groups
833    * 
834    * @param visible
835    *          true to return visible groups, false to return hidden ones.
836    * @return list of groups
837    */
838   @Override
839   public List<String> getGroups(boolean visible)
840   {
841     if (featureGroups != null)
842     {
843       List<String> gp = new ArrayList<String>();
844
845       for (String grp : featureGroups.keySet())
846       {
847         Boolean state = featureGroups.get(grp);
848         if (state.booleanValue() == visible)
849         {
850           gp.add(grp);
851         }
852       }
853       return gp;
854     }
855     return null;
856   }
857
858   @Override
859   public void setGroupVisibility(String group, boolean visible)
860   {
861     featureGroups.put(group, new Boolean(visible));
862   }
863
864   @Override
865   public void setGroupVisibility(List<String> toset, boolean visible)
866   {
867     if (toset != null && toset.size() > 0 && featureGroups != null)
868     {
869       boolean rdrw = false;
870       for (String gst : toset)
871       {
872         Boolean st = featureGroups.get(gst);
873         featureGroups.put(gst, new Boolean(visible));
874         if (st != null)
875         {
876           rdrw = rdrw || (visible != st.booleanValue());
877         }
878       }
879       if (rdrw)
880       {
881         // set local flag indicating redraw needed ?
882       }
883     }
884   }
885
886   @Override
887   public Map<String, FeatureColourI> getDisplayedFeatureCols()
888   {
889     Map<String, FeatureColourI> fcols = new Hashtable<String, FeatureColourI>();
890     if (getViewport().getFeaturesDisplayed() == null)
891     {
892       return fcols;
893     }
894     Set<String> features = getViewport().getFeaturesDisplayed()
895             .getVisibleFeatures();
896     for (String feature : features)
897     {
898       fcols.put(feature, getFeatureStyle(feature));
899     }
900     return fcols;
901   }
902
903   @Override
904   public FeaturesDisplayedI getFeaturesDisplayed()
905   {
906     return av.getFeaturesDisplayed();
907   }
908
909   /**
910    * Returns a (possibly empty) list of visible feature types, in render order
911    * (last is on top)
912    */
913   @Override
914   public List<String> getDisplayedFeatureTypes()
915   {
916     List<String> typ = getRenderOrder();
917     List<String> displayed = new ArrayList<String>();
918     FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
919     if (feature_disp != null)
920     {
921       synchronized (feature_disp)
922       {
923         for (String type : typ)
924         {
925           if (feature_disp.isVisible(type))
926           {
927             displayed.add(type);
928           }
929         }
930       }
931     }
932     return displayed;
933   }
934
935   @Override
936   public List<String> getDisplayedFeatureGroups()
937   {
938     List<String> _gps = new ArrayList<String>();
939     for (String gp : getFeatureGroups())
940     {
941       if (checkGroupVisibility(gp, false))
942       {
943         _gps.add(gp);
944       }
945     }
946     return _gps;
947   }
948
949   /**
950    * Answers true if the feature belongs to a feature group which is not
951    * currently displayed, else false
952    * 
953    * @param sequenceFeature
954    * @return
955    */
956   protected boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
957   {
958     return featureGroups != null
959             && sequenceFeature.featureGroup != null
960             && sequenceFeature.featureGroup.length() != 0
961             && featureGroups.containsKey(sequenceFeature.featureGroup)
962             && !featureGroups.get(sequenceFeature.featureGroup)
963                     .booleanValue();
964   }
965
966   /**
967    * {@inheritDoc}
968    */
969   @Override
970   public List<SequenceFeature> findFeaturesAtResidue(SequenceI sequence,
971           int resNo)
972   {
973     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
974     if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
975     {
976       return result;
977     }
978
979     /*
980      * include features at the position provided their feature type is 
981      * displayed, and feature group is null or the empty string
982      * or marked for display
983      */
984     Set<String> visibleFeatures = getFeaturesDisplayed()
985             .getVisibleFeatures();
986     String[] visibleTypes = visibleFeatures
987             .toArray(new String[visibleFeatures.size()]);
988     List<SequenceFeature> features = sequence.getFeatures().findFeatures(
989             resNo, resNo, visibleTypes);
990   
991     for (SequenceFeature sf : features)
992     {
993       if (!featureGroupNotShown(sf))
994       {
995         result.add(sf);
996       }
997     }
998     return result;
999   }
1000
1001   /**
1002    * Removes from the list of features any that duplicate the location of a
1003    * feature of the same type (unless feature is filtered out, or a graduated
1004    * colour scheme or colour by label is applied). Should be used only for
1005    * features of the same feature colour (which normally implies the same
1006    * feature type).
1007    * 
1008    * @param features
1009    * @param fc
1010    */
1011   public void filterFeaturesForDisplay(List<SequenceFeature> features,
1012           FeatureColourI fc)
1013   {
1014     if (features.isEmpty())
1015     {
1016       return;
1017     }
1018     SequenceFeatures.sortFeatures(features, true);
1019     boolean simpleColour = fc == null || fc.isSimpleColour();
1020     SequenceFeature lastFeature = null;
1021
1022     Iterator<SequenceFeature> it = features.iterator();
1023     while (it.hasNext())
1024     {
1025       SequenceFeature sf = it.next();
1026
1027       /*
1028        * a feature is redundant for rendering purposes if it has the
1029        * same extent as another (so would just redraw the same colour);
1030        * (checking type and isContactFeature as a fail-safe here, although
1031        * currently they are guaranteed to match in this context)
1032        */
1033       if (simpleColour)
1034       {
1035         if (lastFeature != null && sf.getBegin() == lastFeature.getBegin()
1036                 && sf.getEnd() == lastFeature.getEnd()
1037                 && sf.isContactFeature() == lastFeature.isContactFeature()
1038                 && sf.getType().equals(lastFeature.getType()))
1039         {
1040           it.remove();
1041         }
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 }