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