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