Merge branch 'develop' into features/JAL-2446NCList
[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
49         implements 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
219                 + 127.0 * (sequenceFeature.score / mm[1]));
220       }
221       else
222       {
223         r[1] = (byte) ((int) 255.0 * (sequenceFeature.score / mm[1]));
224       }
225     }
226     return r;
227   }
228
229   boolean newFeatureAdded = false;
230
231   boolean findingFeatures = false;
232
233   protected boolean updateFeatures()
234   {
235     if (av.getFeaturesDisplayed() == null || renderOrder == null
236             || newFeatureAdded)
237     {
238       findAllFeatures();
239       if (av.getFeaturesDisplayed().getVisibleFeatureCount() < 1)
240       {
241         return false;
242       }
243     }
244     // TODO: decide if we should check for the visible feature count first
245     return true;
246   }
247
248   /**
249    * search the alignment for all new features, give them a colour and display
250    * them. Then fires a PropertyChangeEvent on the changeSupport object.
251    * 
252    */
253   protected void findAllFeatures()
254   {
255     synchronized (firing)
256     {
257       if (firing.equals(Boolean.FALSE))
258       {
259         firing = Boolean.TRUE;
260         findAllFeatures(true); // add all new features as visible
261         changeSupport.firePropertyChange("changeSupport", null, null);
262         firing = Boolean.FALSE;
263       }
264     }
265   }
266
267   @Override
268   public List<SequenceFeature> findFeaturesAtColumn(SequenceI sequence, int column)
269   {
270     /*
271      * include features at the position provided their feature type is 
272      * displayed, and feature group is null or marked for display
273      */
274     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
275     if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
276     {
277       return result;
278     }
279
280     Set<String> visibleFeatures = getFeaturesDisplayed()
281             .getVisibleFeatures();
282     String[] visibleTypes = visibleFeatures
283             .toArray(new String[visibleFeatures.size()]);
284     List<SequenceFeature> features = sequence.findFeatures(column, column,
285             visibleTypes);
286
287     for (SequenceFeature sf : features)
288     {
289       if (!featureGroupNotShown(sf))
290       {
291         result.add(sf);
292       }
293     }
294     return result;
295   }
296
297   /**
298    * Searches alignment for all features and updates colours
299    * 
300    * @param newMadeVisible
301    *          if true newly added feature types will be rendered immediately
302    *          TODO: check to see if this method should actually be proxied so
303    *          repaint events can be propagated by the renderer code
304    */
305   @Override
306   public synchronized void findAllFeatures(boolean newMadeVisible)
307   {
308     newFeatureAdded = false;
309
310     if (findingFeatures)
311     {
312       newFeatureAdded = true;
313       return;
314     }
315
316     findingFeatures = true;
317     if (av.getFeaturesDisplayed() == null)
318     {
319       av.setFeaturesDisplayed(new FeaturesDisplayed());
320     }
321     FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
322
323     Set<String> oldfeatures = new HashSet<String>();
324     if (renderOrder != null)
325     {
326       for (int i = 0; i < renderOrder.length; i++)
327       {
328         if (renderOrder[i] != null)
329         {
330           oldfeatures.add(renderOrder[i]);
331         }
332       }
333     }
334
335     AlignmentI alignment = av.getAlignment();
336     List<String> allfeatures = new ArrayList<String>();
337
338     for (int i = 0; i < alignment.getHeight(); i++)
339     {
340       SequenceI asq = alignment.getSequenceAt(i);
341       for (String group : asq.getFeatures().getFeatureGroups(true))
342       {
343         boolean groupDisplayed = true;
344         if (group != null)
345         {
346           if (featureGroups.containsKey(group))
347           {
348             groupDisplayed = featureGroups.get(group);
349           }
350           else
351           {
352             groupDisplayed = newMadeVisible;
353             featureGroups.put(group, groupDisplayed);
354           }
355         }
356         if (groupDisplayed)
357         {
358           Set<String> types = asq.getFeatures().getFeatureTypesForGroups(
359                   true, group);
360           for (String type : types)
361           {
362             if (!allfeatures.contains(type)) // or use HashSet and no test?
363             {
364               allfeatures.add(type);
365             }
366             updateMinMax(asq, type, true); // todo: for all features?
367           }
368         }
369       }
370     }
371
372     // uncomment to add new features in alphebetical order (but JAL-2575)
373     // Collections.sort(allfeatures, String.CASE_INSENSITIVE_ORDER);
374     if (newMadeVisible)
375     {
376       for (String type : allfeatures)
377       {
378         if (!oldfeatures.contains(type))
379         {
380           featuresDisplayed.setVisible(type);
381           setOrder(type, 0);
382         }
383       }
384     }
385
386     updateRenderOrder(allfeatures);
387     findingFeatures = false;
388   }
389
390   /**
391    * Updates the global (alignment) min and max values for a feature type from
392    * the score for a sequence, if the score is not NaN. Values are stored
393    * separately for positional and non-positional features.
394    * 
395    * @param seq
396    * @param featureType
397    * @param positional
398    */
399   protected void updateMinMax(SequenceI seq, String featureType,
400           boolean positional)
401   {
402     float min = seq.getFeatures().getMinimumScore(featureType, positional);
403     if (Float.isNaN(min))
404     {
405       return;
406     }
407
408     float max = seq.getFeatures().getMaximumScore(featureType, positional);
409
410     /*
411      * stored values are 
412      * { {positionalMin, positionalMax}, {nonPositionalMin, nonPositionalMax} }
413      */
414     if (minmax == null)
415     {
416       minmax = new Hashtable<String, float[][]>();
417     }
418     synchronized (minmax)
419     {
420       float[][] mm = minmax.get(featureType);
421       int index = positional ? 0 : 1;
422       if (mm == null)
423       {
424         mm = new float[][] { null, null };
425         minmax.put(featureType, mm);
426       }
427       if (mm[index] == null)
428       {
429         mm[index] = new float[] { min, max };
430       }
431       else
432       {
433         mm[index][0] = Math.min(mm[index][0], min);
434         mm[index][1] = Math.max(mm[index][1], max);
435       }
436     }
437   }
438   protected Boolean firing = Boolean.FALSE;
439
440   /**
441    * replaces the current renderOrder with the unordered features in
442    * allfeatures. The ordering of any types in both renderOrder and allfeatures
443    * is preserved, and all new feature types are rendered on top of the existing
444    * types, in the order given by getOrder or the order given in allFeatures.
445    * Note. this operates directly on the featureOrder hash for efficiency. TODO:
446    * eliminate the float storage for computing/recalling the persistent ordering
447    * New Cability: updates min/max for colourscheme range if its dynamic
448    * 
449    * @param allFeatures
450    */
451   private void updateRenderOrder(List<String> allFeatures)
452   {
453     List<String> allfeatures = new ArrayList<String>(allFeatures);
454     String[] oldRender = renderOrder;
455     renderOrder = new String[allfeatures.size()];
456     boolean initOrders = (featureOrder == null);
457     int opos = 0;
458     if (oldRender != null && oldRender.length > 0)
459     {
460       for (int j = 0; j < oldRender.length; j++)
461       {
462         if (oldRender[j] != null)
463         {
464           if (initOrders)
465           {
466             setOrder(oldRender[j],
467                     (1 - (1 + (float) j) / oldRender.length));
468           }
469           if (allfeatures.contains(oldRender[j]))
470           {
471             renderOrder[opos++] = oldRender[j]; // existing features always
472             // appear below new features
473             allfeatures.remove(oldRender[j]);
474             if (minmax != null)
475             {
476               float[][] mmrange = minmax.get(oldRender[j]);
477               if (mmrange != null)
478               {
479                 FeatureColourI fc = featureColours.get(oldRender[j]);
480                 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
481                 {
482                   fc.updateBounds(mmrange[0][0], mmrange[0][1]);
483                 }
484               }
485             }
486           }
487         }
488       }
489     }
490     if (allfeatures.size() == 0)
491     {
492       // no new features - leave order unchanged.
493       return;
494     }
495     int i = allfeatures.size() - 1;
496     int iSize = i;
497     boolean sort = false;
498     String[] newf = new String[allfeatures.size()];
499     float[] sortOrder = new float[allfeatures.size()];
500     for (String newfeat : allfeatures)
501     {
502       newf[i] = newfeat;
503       if (minmax != null)
504       {
505         // update from new features minmax if necessary
506         float[][] mmrange = minmax.get(newf[i]);
507         if (mmrange != null)
508         {
509           FeatureColourI fc = featureColours.get(newf[i]);
510           if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled())
511           {
512             fc.updateBounds(mmrange[0][0], mmrange[0][1]);
513           }
514         }
515       }
516       if (initOrders || !featureOrder.containsKey(newf[i]))
517       {
518         int denom = initOrders ? allfeatures.size() : featureOrder.size();
519         // new unordered feature - compute persistent ordering at head of
520         // existing features.
521         setOrder(newf[i], i / (float) denom);
522       }
523       // set order from newly found feature from persisted ordering.
524       sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
525       if (i < iSize)
526       {
527         // only sort if we need to
528         sort = sort || sortOrder[i] > sortOrder[i + 1];
529       }
530       i--;
531     }
532     if (iSize > 1 && sort)
533     {
534       jalview.util.QuickSort.sort(sortOrder, newf);
535     }
536     sortOrder = null;
537     System.arraycopy(newf, 0, renderOrder, opos, newf.length);
538   }
539
540   /**
541    * get a feature style object for the given type string. Creates a
542    * java.awt.Color for a featureType with no existing colourscheme.
543    * 
544    * @param featureType
545    * @return
546    */
547   @Override
548   public FeatureColourI getFeatureStyle(String featureType)
549   {
550     FeatureColourI fc = featureColours.get(featureType);
551     if (fc == null)
552     {
553       Color col = ColorUtils.createColourFromName(featureType);
554       fc = new FeatureColour(col);
555       featureColours.put(featureType, fc);
556     }
557     return fc;
558   }
559
560   /**
561    * Returns the configured colour for a particular feature instance. This
562    * includes calculation of 'colour by label', or of a graduated score colour,
563    * if applicable. It does not take into account feature visibility or colour
564    * transparency. Returns null for a score feature whose score value lies
565    * outside any colour threshold.
566    * 
567    * @param feature
568    * @return
569    */
570   public Color getColour(SequenceFeature feature)
571   {
572     FeatureColourI fc = getFeatureStyle(feature.getType());
573     return fc.getColor(feature);
574   }
575
576   /**
577    * Answers true if the feature type is currently selected to be displayed,
578    * else false
579    * 
580    * @param type
581    * @return
582    */
583   protected boolean showFeatureOfType(String type)
584   {
585     return type == null ? false : av.getFeaturesDisplayed().isVisible(type);
586   }
587
588   @Override
589   public void setColour(String featureType, FeatureColourI col)
590   {
591     featureColours.put(featureType, col);
592   }
593
594   @Override
595   public void setTransparency(float value)
596   {
597     transparency = value;
598   }
599
600   @Override
601   public float getTransparency()
602   {
603     return transparency;
604   }
605
606   /**
607    * analogous to colour - store a normalized ordering for all feature types in
608    * this rendering context.
609    * 
610    * @param type
611    *          Feature type string
612    * @param position
613    *          normalized priority - 0 means always appears on top, 1 means
614    *          always last.
615    */
616   public float setOrder(String type, float position)
617   {
618     if (featureOrder == null)
619     {
620       featureOrder = new Hashtable<String, Float>();
621     }
622     featureOrder.put(type, new Float(position));
623     return position;
624   }
625
626   /**
627    * get the global priority (0 (top) to 1 (bottom))
628    * 
629    * @param type
630    * @return [0,1] or -1 for a type without a priority
631    */
632   public float getOrder(String type)
633   {
634     if (featureOrder != null)
635     {
636       if (featureOrder.containsKey(type))
637       {
638         return featureOrder.get(type).floatValue();
639       }
640     }
641     return -1;
642   }
643
644   @Override
645   public Map<String, FeatureColourI> getFeatureColours()
646   {
647     return featureColours;
648   }
649
650   /**
651    * Replace current ordering with new ordering
652    * 
653    * @param data
654    *          { String(Type), Colour(Type), Boolean(Displayed) }
655    * @return true if any visible features have been reordered, else false
656    */
657   public boolean setFeaturePriority(Object[][] data)
658   {
659     return setFeaturePriority(data, true);
660   }
661
662   /**
663    * Sets the priority order for features, with the highest priority (displayed
664    * on top) at the start of the data array
665    * 
666    * @param data
667    *          { String(Type), Colour(Type), Boolean(Displayed) }
668    * @param visibleNew
669    *          when true current featureDisplay list will be cleared
670    * @return true if any visible features have been reordered or recoloured,
671    *         else false (i.e. no need to repaint)
672    */
673   public boolean setFeaturePriority(Object[][] data, boolean visibleNew)
674   {
675     /*
676      * note visible feature ordering and colours before update
677      */
678     List<String> visibleFeatures = getDisplayedFeatureTypes();
679     Map<String, FeatureColourI> visibleColours = new HashMap<String, FeatureColourI>(
680             getFeatureColours());
681
682     FeaturesDisplayedI av_featuresdisplayed = null;
683     if (visibleNew)
684     {
685       if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
686       {
687         av.getFeaturesDisplayed().clear();
688       }
689       else
690       {
691         av.setFeaturesDisplayed(
692                 av_featuresdisplayed = new FeaturesDisplayed());
693       }
694     }
695     else
696     {
697       av_featuresdisplayed = av.getFeaturesDisplayed();
698     }
699     if (data == null)
700     {
701       return false;
702     }
703     // The feature table will display high priority
704     // features at the top, but these are the ones
705     // we need to render last, so invert the data
706     renderOrder = new String[data.length];
707
708     if (data.length > 0)
709     {
710       for (int i = 0; i < data.length; i++)
711       {
712         String type = data[i][0].toString();
713         setColour(type, (FeatureColourI) data[i][1]);
714         if (((Boolean) data[i][2]).booleanValue())
715         {
716           av_featuresdisplayed.setVisible(type);
717         }
718
719         renderOrder[data.length - i - 1] = type;
720       }
721     }
722
723     /*
724      * get the new visible ordering and return true if it has changed
725      * order or any colour has changed
726      */
727     List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
728     if (!visibleFeatures.equals(reorderedVisibleFeatures))
729     {
730       /*
731        * the list of ordered visible features has changed
732        */
733       return true;
734     }
735
736     /*
737      * return true if any feature colour has changed
738      */
739     for (String feature : visibleFeatures)
740     {
741       if (visibleColours.get(feature) != getFeatureStyle(feature))
742       {
743         return true;
744       }
745     }
746     return false;
747   }
748
749   /**
750    * @param listener
751    * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
752    */
753   public void addPropertyChangeListener(PropertyChangeListener listener)
754   {
755     changeSupport.addPropertyChangeListener(listener);
756   }
757
758   /**
759    * @param listener
760    * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
761    */
762   public void removePropertyChangeListener(PropertyChangeListener listener)
763   {
764     changeSupport.removePropertyChangeListener(listener);
765   }
766
767   public Set<String> getAllFeatureColours()
768   {
769     return featureColours.keySet();
770   }
771
772   public void clearRenderOrder()
773   {
774     renderOrder = null;
775   }
776
777   public boolean hasRenderOrder()
778   {
779     return renderOrder != null;
780   }
781
782   /**
783    * Returns feature types in ordering of rendering, where last means on top
784    */
785   public List<String> getRenderOrder()
786   {
787     if (renderOrder == null)
788     {
789       return Arrays.asList(new String[] {});
790     }
791     return Arrays.asList(renderOrder);
792   }
793
794   public int getFeatureGroupsSize()
795   {
796     return featureGroups != null ? 0 : featureGroups.size();
797   }
798
799   @Override
800   public List<String> getFeatureGroups()
801   {
802     // conflict between applet and desktop - featureGroups returns the map in
803     // the desktop featureRenderer
804     return (featureGroups == null) ? Arrays.asList(new String[0])
805             : Arrays.asList(featureGroups.keySet().toArray(new String[0]));
806   }
807
808   public boolean checkGroupVisibility(String group,
809           boolean newGroupsVisible)
810   {
811     if (featureGroups == null)
812     {
813       // then an exception happens next..
814     }
815     if (featureGroups.containsKey(group))
816     {
817       return featureGroups.get(group).booleanValue();
818     }
819     if (newGroupsVisible)
820     {
821       featureGroups.put(group, new Boolean(true));
822       return true;
823     }
824     return false;
825   }
826
827   /**
828    * get visible or invisible groups
829    * 
830    * @param visible
831    *          true to return visible groups, false to return hidden ones.
832    * @return list of groups
833    */
834   @Override
835   public List<String> getGroups(boolean visible)
836   {
837     if (featureGroups != null)
838     {
839       List<String> gp = new ArrayList<String>();
840
841       for (String grp : featureGroups.keySet())
842       {
843         Boolean state = featureGroups.get(grp);
844         if (state.booleanValue() == visible)
845         {
846           gp.add(grp);
847         }
848       }
849       return gp;
850     }
851     return null;
852   }
853
854   @Override
855   public void setGroupVisibility(String group, boolean visible)
856   {
857     featureGroups.put(group, new Boolean(visible));
858   }
859
860   @Override
861   public void setGroupVisibility(List<String> toset, boolean visible)
862   {
863     if (toset != null && toset.size() > 0 && featureGroups != null)
864     {
865       boolean rdrw = false;
866       for (String gst : toset)
867       {
868         Boolean st = featureGroups.get(gst);
869         featureGroups.put(gst, new Boolean(visible));
870         if (st != null)
871         {
872           rdrw = rdrw || (visible != st.booleanValue());
873         }
874       }
875       if (rdrw)
876       {
877         // set local flag indicating redraw needed ?
878       }
879     }
880   }
881
882   @Override
883   public Map<String, FeatureColourI> getDisplayedFeatureCols()
884   {
885     Map<String, FeatureColourI> fcols = new Hashtable<String, FeatureColourI>();
886     if (getViewport().getFeaturesDisplayed() == null)
887     {
888       return fcols;
889     }
890     Set<String> features = getViewport().getFeaturesDisplayed()
891             .getVisibleFeatures();
892     for (String feature : features)
893     {
894       fcols.put(feature, getFeatureStyle(feature));
895     }
896     return fcols;
897   }
898
899   @Override
900   public FeaturesDisplayedI getFeaturesDisplayed()
901   {
902     return av.getFeaturesDisplayed();
903   }
904
905   /**
906    * Returns a (possibly empty) list of visible feature types, in render order
907    * (last is on top)
908    */
909   @Override
910   public List<String> getDisplayedFeatureTypes()
911   {
912     List<String> typ = getRenderOrder();
913     List<String> displayed = new ArrayList<String>();
914     FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
915     if (feature_disp != null)
916     {
917       synchronized (feature_disp)
918       {
919         for (String type : typ)
920         {
921           if (feature_disp.isVisible(type))
922           {
923             displayed.add(type);
924           }
925         }
926       }
927     }
928     return displayed;
929   }
930
931   @Override
932   public List<String> getDisplayedFeatureGroups()
933   {
934     List<String> _gps = new ArrayList<String>();
935     for (String gp : getFeatureGroups())
936     {
937       if (checkGroupVisibility(gp, false))
938       {
939         _gps.add(gp);
940       }
941     }
942     return _gps;
943   }
944
945   /**
946    * Answers true if the feature belongs to a feature group which is not
947    * currently displayed, else false
948    * 
949    * @param sequenceFeature
950    * @return
951    */
952   protected boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
953   {
954     return featureGroups != null
955             && sequenceFeature.featureGroup != null
956             && sequenceFeature.featureGroup.length() != 0
957             && featureGroups.containsKey(sequenceFeature.featureGroup)
958             && !featureGroups.get(sequenceFeature.featureGroup)
959                     .booleanValue();
960   }
961
962   /**
963    * {@inheritDoc}
964    */
965   @Override
966   public List<SequenceFeature> findFeaturesAtResidue(SequenceI sequence,
967           int resNo)
968   {
969     List<SequenceFeature> result = new ArrayList<SequenceFeature>();
970     if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
971     {
972       return result;
973     }
974
975     /*
976      * include features at the position provided their feature type is 
977      * displayed, and feature group is null or the empty string
978      * or marked for display
979      */
980     Set<String> visibleFeatures = getFeaturesDisplayed()
981             .getVisibleFeatures();
982     String[] visibleTypes = visibleFeatures
983             .toArray(new String[visibleFeatures.size()]);
984     List<SequenceFeature> features = sequence.getFeatures().findFeatures(
985             resNo, resNo, visibleTypes);
986   
987     for (SequenceFeature sf : features)
988     {
989       if (!featureGroupNotShown(sf))
990       {
991         result.add(sf);
992       }
993     }
994     return result;
995   }
996
997   /**
998    * Removes from the list of features any that have a feature group that is not
999    * displayed, or duplicate the location of a feature of the same type (unless
1000    * a graduated colour scheme or colour by label is applied). Should be used
1001    * only for features of the same feature colour (which normally implies the
1002    * same feature type).
1003    * 
1004    * @param features
1005    * @param fc
1006    */
1007   public void filterFeaturesForDisplay(List<SequenceFeature> features,
1008           FeatureColourI fc)
1009   {
1010     if (features.isEmpty())
1011     {
1012       return;
1013     }
1014     SequenceFeatures.sortFeatures(features, true);
1015     boolean simpleColour = fc == null || fc.isSimpleColour();
1016     SequenceFeature lastFeature = null;
1017
1018     Iterator<SequenceFeature> it = features.iterator();
1019     while (it.hasNext())
1020     {
1021       SequenceFeature sf = it.next();
1022       if (featureGroupNotShown(sf))
1023       {
1024         it.remove();
1025         continue;
1026       }
1027
1028       /*
1029        * a feature is redundant for rendering purposes if it has the
1030        * same extent as another (so would just redraw the same colour);
1031        * (checking type and isContactFeature as a fail-safe here, although
1032        * currently they are guaranteed to match in this context)
1033        */
1034       if (simpleColour)
1035       {
1036         if (lastFeature != null && sf.getBegin() == lastFeature.getBegin()
1037                 && sf.getEnd() == lastFeature.getEnd()
1038                 && sf.isContactFeature() == lastFeature.isContactFeature()
1039                 && sf.getType().equals(lastFeature.getType()))
1040         {
1041           it.remove();
1042         }
1043       }
1044       lastFeature = sf;
1045     }
1046   }
1047
1048 }