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