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