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