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