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