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