Merge branch 'task/JAL-3763_newDatasetForCds' into merge/develop_task/JAL-3763_newDat...
[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 java.awt.Color;
24 import java.beans.PropertyChangeListener;
25 import java.beans.PropertyChangeSupport;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Comparator;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Hashtable;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.concurrent.ConcurrentHashMap;
37
38 import jalview.api.AlignViewportI;
39 import jalview.api.FeatureColourI;
40 import jalview.api.FeaturesDisplayedI;
41 import jalview.datamodel.AlignedCodonFrame;
42 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
43 import jalview.datamodel.AlignmentI;
44 import jalview.datamodel.MappedFeatures;
45 import jalview.datamodel.SearchResultMatchI;
46 import jalview.datamodel.SearchResults;
47 import jalview.datamodel.SearchResultsI;
48 import jalview.datamodel.SequenceFeature;
49 import jalview.datamodel.SequenceI;
50 import jalview.datamodel.features.FeatureMatcherSetI;
51 import jalview.datamodel.features.SequenceFeatures;
52 import jalview.renderer.seqfeatures.FeatureRenderer;
53 import jalview.schemes.FeatureColour;
54 import jalview.util.ColorUtils;
55 import jalview.util.Platform;
56
57 public abstract class FeatureRendererModel
58         implements jalview.api.FeatureRenderer
59 {
60   /*
61    * a data bean to hold one row of feature settings from the gui
62    */
63   public static class FeatureSettingsBean
64   {
65     public final String featureType;
66
67     public final FeatureColourI featureColour;
68
69     public final FeatureMatcherSetI filter;
70
71     public final Boolean show;
72
73     public FeatureSettingsBean(String type, FeatureColourI colour,
74             FeatureMatcherSetI theFilter, Boolean isShown)
75     {
76       featureType = type;
77       featureColour = colour;
78       filter = theFilter;
79       show = isShown;
80     }
81   }
82
83   /*
84    * global transparency for feature
85    */
86   protected float transparency = 1.0f;
87
88   /*
89    * colour scheme for each feature type
90    */
91   protected Map<String, FeatureColourI> featureColours = new ConcurrentHashMap<>();
92
93   /*
94    * visibility flag for each feature group
95    */
96   protected Map<String, Boolean> featureGroups = new ConcurrentHashMap<>();
97
98   /*
99    * filters for each feature type
100    */
101   protected Map<String, FeatureMatcherSetI> featureFilters = new HashMap<>();
102
103   protected String[] renderOrder;
104
105   Map<String, Float> featureOrder = null;
106
107   protected AlignViewportI av;
108
109   private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
110           this);
111
112   @Override
113   public AlignViewportI getViewport()
114   {
115     return av;
116   }
117
118   public FeatureRendererSettings getSettings()
119   {
120     return new FeatureRendererSettings(this);
121   }
122
123   public void transferSettings(FeatureRendererSettings fr)
124   {
125     this.renderOrder = fr.renderOrder;
126     this.featureGroups = fr.featureGroups;
127     this.featureColours = fr.featureColours;
128     this.transparency = fr.transparency;
129     this.featureOrder = fr.featureOrder;
130   }
131
132   /**
133    * update from another feature renderer
134    * 
135    * @param fr
136    *          settings to copy
137    */
138   public void transferSettings(jalview.api.FeatureRenderer _fr)
139   {
140     FeatureRenderer fr = (FeatureRenderer) _fr;
141     FeatureRendererSettings frs = new FeatureRendererSettings(fr);
142     this.renderOrder = frs.renderOrder;
143     this.featureGroups = frs.featureGroups;
144     this.featureColours = frs.featureColours;
145     this.featureFilters = frs.featureFilters;
146     this.transparency = frs.transparency;
147     this.featureOrder = frs.featureOrder;
148     if (av != null && av != fr.getViewport())
149     {
150       // copy over the displayed feature settings
151       if (_fr.getFeaturesDisplayed() != null)
152       {
153         FeaturesDisplayedI fd = getFeaturesDisplayed();
154         if (fd == null)
155         {
156           setFeaturesDisplayedFrom(_fr.getFeaturesDisplayed());
157         }
158         else
159         {
160           synchronized (fd)
161           {
162             fd.clear();
163             for (String type : _fr.getFeaturesDisplayed()
164                     .getVisibleFeatures())
165             {
166               fd.setVisible(type);
167             }
168           }
169         }
170       }
171     }
172   }
173
174   public void setFeaturesDisplayedFrom(FeaturesDisplayedI featuresDisplayed)
175   {
176     av.setFeaturesDisplayed(new FeaturesDisplayed(featuresDisplayed));
177   }
178
179   @Override
180   public void setVisible(String featureType)
181   {
182     FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
183     if (fdi == null)
184     {
185       av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
186     }
187     if (!fdi.isRegistered(featureType))
188     {
189       pushFeatureType(Arrays.asList(new String[] { featureType }));
190     }
191     fdi.setVisible(featureType);
192   }
193
194   @Override
195   public void setAllVisible(List<String> featureTypes)
196   {
197     FeaturesDisplayedI fdi = av.getFeaturesDisplayed();
198     if (fdi == null)
199     {
200       av.setFeaturesDisplayed(fdi = new FeaturesDisplayed());
201     }
202     List<String> nft = new ArrayList<>();
203     for (String featureType : featureTypes)
204     {
205       if (!fdi.isRegistered(featureType))
206       {
207         nft.add(featureType);
208       }
209     }
210     if (nft.size() > 0)
211     {
212       pushFeatureType(nft);
213     }
214     fdi.setAllVisible(featureTypes);
215   }
216
217   /**
218    * push a set of new types onto the render order stack. Note - this is a
219    * direct mechanism rather than the one employed in updateRenderOrder
220    * 
221    * @param types
222    */
223   private void pushFeatureType(List<String> types)
224   {
225
226     int ts = types.size();
227     String neworder[] = new String[(renderOrder == null ? 0
228             : renderOrder.length) + ts];
229     types.toArray(neworder);
230     if (renderOrder != null)
231     {
232       System.arraycopy(neworder, 0, neworder, renderOrder.length, ts);
233       System.arraycopy(renderOrder, 0, neworder, 0, renderOrder.length);
234     }
235     renderOrder = neworder;
236   }
237
238   protected Map<String, float[][]> minmax = new Hashtable<>();
239
240   public Map<String, float[][]> getMinMax()
241   {
242     return minmax;
243   }
244
245   /**
246    * normalise a score against the max/min bounds for the feature type.
247    * 
248    * @param sequenceFeature
249    * @return byte[] { signed, normalised signed (-127 to 127) or unsigned
250    *         (0-255) value.
251    */
252   protected final byte[] normaliseScore(SequenceFeature sequenceFeature)
253   {
254     float[] mm = minmax.get(sequenceFeature.type)[0];
255     final byte[] r = new byte[] { 0, (byte) 255 };
256     if (mm != null)
257     {
258       if (r[0] != 0 || mm[0] < 0.0)
259       {
260         r[0] = 1;
261         r[1] = (byte) ((int) 128.0
262                 + 127.0 * (sequenceFeature.score / mm[1]));
263       }
264       else
265       {
266         r[1] = (byte) ((int) 255.0 * (sequenceFeature.score / mm[1]));
267       }
268     }
269     return r;
270   }
271
272   boolean newFeatureAdded = false;
273
274   boolean findingFeatures = false;
275
276   protected boolean updateFeatures()
277   {
278     if (av.getFeaturesDisplayed() == null || renderOrder == null
279             || newFeatureAdded)
280     {
281       findAllFeatures();
282       if (av.getFeaturesDisplayed().getVisibleFeatureCount() < 1)
283       {
284         return false;
285       }
286     }
287     // TODO: decide if we should check for the visible feature count first
288     return true;
289   }
290
291   /**
292    * search the alignment for all new features, give them a colour and display
293    * them. Then fires a PropertyChangeEvent on the changeSupport object.
294    * 
295    */
296   protected void findAllFeatures()
297   {
298     synchronized (firing)
299     {
300       if (firing.equals(Boolean.FALSE))
301       {
302         firing = Boolean.TRUE;
303         findAllFeatures(true); // add all new features as visible
304         notifyFeaturesChanged();
305         firing = Boolean.FALSE;
306       }
307     }
308   }
309
310   @Override
311   public void notifyFeaturesChanged()
312   {
313     changeSupport.firePropertyChange("changeSupport", null, null);
314   }
315
316   @Override
317   public List<SequenceFeature> findFeaturesAtColumn(SequenceI sequence, int column)
318   {
319     /*
320      * include features at the position provided their feature type is 
321      * displayed, and feature group is null or marked for display
322      */
323     List<SequenceFeature> result = new ArrayList<>();
324     if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
325     {
326       return result;
327     }
328
329     Set<String> visibleFeatures = getFeaturesDisplayed()
330             .getVisibleFeatures();
331     String[] visibleTypes = visibleFeatures
332             .toArray(new String[visibleFeatures.size()]);
333     List<SequenceFeature> features = sequence.findFeatures(column, column,
334             visibleTypes);
335
336     /*
337      * include features unless they are hidden (have no colour), based on 
338      * feature group visibility, or a filter or colour threshold
339      */
340     for (SequenceFeature sf : features)
341     {
342       if (getColour(sf) != null)
343       {
344         result.add(sf);
345       }
346     }
347     return result;
348   }
349
350   /**
351    * Searches alignment for all features and updates colours
352    * 
353    * @param newMadeVisible
354    *          if true newly added feature types will be rendered immediately
355    *          TODO: check to see if this method should actually be proxied so
356    *          repaint events can be propagated by the renderer code
357    */
358   @Override
359   public synchronized void findAllFeatures(boolean newMadeVisible)
360   {
361     newFeatureAdded = false;
362
363     if (findingFeatures)
364     {
365       newFeatureAdded = true;
366       return;
367     }
368
369     findingFeatures = true;
370     if (av.getFeaturesDisplayed() == null)
371     {
372       av.setFeaturesDisplayed(new FeaturesDisplayed());
373     }
374     FeaturesDisplayedI featuresDisplayed = av.getFeaturesDisplayed();
375
376     Set<String> oldfeatures = new HashSet<>();
377     if (renderOrder != null)
378     {
379       for (int i = 0; i < renderOrder.length; i++)
380       {
381         if (renderOrder[i] != null)
382         {
383           oldfeatures.add(renderOrder[i]);
384         }
385       }
386     }
387
388     AlignmentI alignment = av.getAlignment();
389     List<String> allfeatures = new ArrayList<>();
390
391     for (int i = 0; i < alignment.getHeight(); i++)
392     {
393       SequenceI asq = alignment.getSequenceAt(i);
394       for (String group : asq.getFeatures().getFeatureGroups(true))
395       {
396         boolean groupDisplayed = true;
397         if (group != null)
398         {
399           if (featureGroups.containsKey(group))
400           {
401             groupDisplayed = featureGroups.get(group);
402           }
403           else
404           {
405             groupDisplayed = newMadeVisible;
406             featureGroups.put(group, groupDisplayed);
407           }
408         }
409         if (groupDisplayed)
410         {
411           Set<String> types = asq.getFeatures().getFeatureTypesForGroups(
412                   true, group);
413           for (String type : types)
414           {
415             if (!allfeatures.contains(type)) // or use HashSet and no test?
416             {
417               allfeatures.add(type);
418             }
419             updateMinMax(asq, type, true); // todo: for all features?
420           }
421         }
422       }
423     }
424
425     // uncomment to add new features in alphebetical order (but JAL-2575)
426     // Collections.sort(allfeatures, String.CASE_INSENSITIVE_ORDER);
427     if (newMadeVisible)
428     {
429       for (String type : allfeatures)
430       {
431         if (!oldfeatures.contains(type))
432         {
433           featuresDisplayed.setVisible(type);
434           setOrder(type, 0);
435         }
436       }
437     }
438
439     updateRenderOrder(allfeatures);
440     findingFeatures = false;
441   }
442
443   /**
444    * Updates the global (alignment) min and max values for a feature type from
445    * the score for a sequence, if the score is not NaN. Values are stored
446    * separately for positional and non-positional features.
447    * 
448    * @param seq
449    * @param featureType
450    * @param positional
451    */
452   protected void updateMinMax(SequenceI seq, String featureType,
453           boolean positional)
454   {
455     float min = seq.getFeatures().getMinimumScore(featureType, positional);
456     if (Float.isNaN(min))
457     {
458       return;
459     }
460
461     float max = seq.getFeatures().getMaximumScore(featureType, positional);
462
463     /*
464      * stored values are 
465      * { {positionalMin, positionalMax}, {nonPositionalMin, nonPositionalMax} }
466      */
467     if (minmax == null)
468     {
469       minmax = new Hashtable<>();
470     }
471     synchronized (minmax)
472     {
473       float[][] mm = minmax.get(featureType);
474       int index = positional ? 0 : 1;
475       if (mm == null)
476       {
477         mm = new float[][] { null, null };
478         minmax.put(featureType, mm);
479       }
480       if (mm[index] == null)
481       {
482         mm[index] = new float[] { min, max };
483       }
484       else
485       {
486         mm[index][0] = Math.min(mm[index][0], min);
487         mm[index][1] = Math.max(mm[index][1], max);
488       }
489     }
490   }
491   protected Boolean firing = Boolean.FALSE;
492
493   /**
494    * replaces the current renderOrder with the unordered features in
495    * allfeatures. The ordering of any types in both renderOrder and allfeatures
496    * is preserved, and all new feature types are rendered on top of the existing
497    * types, in the order given by getOrder or the order given in allFeatures.
498    * Note. this operates directly on the featureOrder hash for efficiency. TODO:
499    * eliminate the float storage for computing/recalling the persistent ordering
500    * New Cability: updates min/max for colourscheme range if its dynamic
501    * 
502    * @param allFeatures
503    */
504   private void updateRenderOrder(List<String> allFeatures)
505   {
506     List<String> allfeatures = new ArrayList<>(allFeatures);
507     String[] oldRender = renderOrder;
508     renderOrder = new String[allfeatures.size()];
509     boolean initOrders = (featureOrder == null);
510     int opos = 0;
511     if (oldRender != null && oldRender.length > 0)
512     {
513       for (int j = 0; j < oldRender.length; j++)
514       {
515         if (oldRender[j] != null)
516         {
517           if (initOrders)
518           {
519             setOrder(oldRender[j],
520                     (1 - (1 + (float) j) / oldRender.length));
521           }
522           if (allfeatures.contains(oldRender[j]))
523           {
524             renderOrder[opos++] = oldRender[j]; // existing features always
525             // appear below new features
526             allfeatures.remove(oldRender[j]);
527             if (minmax != null)
528             {
529               float[][] mmrange = minmax.get(oldRender[j]);
530               if (mmrange != null)
531               {
532                 FeatureColourI fc = featureColours.get(oldRender[j]);
533                 if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled()
534                         && !fc.isColourByAttribute())
535                 {
536                   fc.updateBounds(mmrange[0][0], mmrange[0][1]);
537                 }
538               }
539             }
540           }
541         }
542       }
543     }
544     if (allfeatures.size() == 0)
545     {
546       // no new features - leave order unchanged.
547       return;
548     }
549     int i = allfeatures.size() - 1;
550     int iSize = i;
551     boolean sort = false;
552     String[] newf = new String[allfeatures.size()];
553     float[] sortOrder = new float[allfeatures.size()];
554     for (String newfeat : allfeatures)
555     {
556       newf[i] = newfeat;
557       if (minmax != null)
558       {
559         // update from new features minmax if necessary
560         float[][] mmrange = minmax.get(newf[i]);
561         if (mmrange != null)
562         {
563           FeatureColourI fc = featureColours.get(newf[i]);
564           if (fc != null && !fc.isSimpleColour() && fc.isAutoScaled()
565                   && !fc.isColourByAttribute())
566           {
567             fc.updateBounds(mmrange[0][0], mmrange[0][1]);
568           }
569         }
570       }
571       if (initOrders || !featureOrder.containsKey(newf[i]))
572       {
573         int denom = initOrders ? allfeatures.size() : featureOrder.size();
574         // new unordered feature - compute persistent ordering at head of
575         // existing features.
576         setOrder(newf[i], i / (float) denom);
577       }
578       // set order from newly found feature from persisted ordering.
579       sortOrder[i] = 2 - featureOrder.get(newf[i]).floatValue();
580       if (i < iSize)
581       {
582         // only sort if we need to
583         sort = sort || sortOrder[i] > sortOrder[i + 1];
584       }
585       i--;
586     }
587     if (iSize > 1 && sort)
588     {
589       jalview.util.QuickSort.sort(sortOrder, newf);
590     }
591     sortOrder = null;
592     System.arraycopy(newf, 0, renderOrder, opos, newf.length);
593   }
594
595   /**
596    * get a feature style object for the given type string. Creates a
597    * java.awt.Color for a featureType with no existing colourscheme.
598    * 
599    * @param featureType
600    * @return
601    */
602   @Override
603   public FeatureColourI getFeatureStyle(String featureType)
604   {
605     FeatureColourI fc = featureColours.get(featureType);
606     if (fc == null)
607     {
608       Color col = ColorUtils.createColourFromName(featureType);
609       fc = new FeatureColour(col);
610       featureColours.put(featureType, fc);
611     }
612     return fc;
613   }
614
615   @Override
616   public Color getColour(SequenceFeature feature)
617   {
618     FeatureColourI fc = getFeatureStyle(feature.getType());
619     return getColor(feature, fc);
620   }
621
622   /**
623    * Answers true if the feature type is currently selected to be displayed,
624    * else false
625    * 
626    * @param type
627    * @return
628    */
629   public boolean showFeatureOfType(String type)
630   {
631     return type == null ? false : (av.getFeaturesDisplayed() == null ? true
632             : av.getFeaturesDisplayed().isVisible(type));
633   }
634
635   @Override
636   public void setColour(String featureType, FeatureColourI col)
637   {
638     featureColours.put(featureType, col);
639   }
640
641   @Override
642   public void setTransparency(float value)
643   {
644     transparency = value;
645   }
646
647   @Override
648   public float getTransparency()
649   {
650     return transparency;
651   }
652
653   /**
654    * analogous to colour - store a normalized ordering for all feature types in
655    * this rendering context.
656    * 
657    * @param type
658    *          Feature type string
659    * @param position
660    *          normalized priority - 0 means always appears on top, 1 means
661    *          always last.
662    */
663   public float setOrder(String type, float position)
664   {
665     if (featureOrder == null)
666     {
667       featureOrder = new Hashtable<>();
668     }
669     featureOrder.put(type, Float.valueOf(position));
670     return position;
671   }
672
673   /**
674    * get the global priority (0 (top) to 1 (bottom))
675    * 
676    * @param type
677    * @return [0,1] or -1 for a type without a priority
678    */
679   public float getOrder(String type)
680   {
681     if (featureOrder != null)
682     {
683       if (featureOrder.containsKey(type))
684       {
685         return featureOrder.get(type).floatValue();
686       }
687     }
688     return -1;
689   }
690
691   @Override
692   public Map<String, FeatureColourI> getFeatureColours()
693   {
694     return featureColours;
695   }
696
697   /**
698    * Replace current ordering with new ordering
699    * 
700    * @param data
701    *          an array of { Type, Colour, Filter, Boolean }
702    * @return true if any visible features have been reordered, else false
703    */
704   public boolean setFeaturePriority(FeatureSettingsBean[] data)
705   {
706     return setFeaturePriority(data, true);
707   }
708
709   /**
710    * Sets the priority order for features, with the highest priority (displayed on
711    * top) at the start of the data array
712    * 
713    * @param data
714    *          an array of { Type, Colour, Filter, Boolean }
715    * @param visibleNew
716    *          when true current featureDisplay list will be cleared
717    * @return true if any visible features have been reordered or recoloured, else
718    *         false (i.e. no need to repaint)
719    */
720   public boolean setFeaturePriority(FeatureSettingsBean[] data,
721           boolean visibleNew)
722   {
723     /*
724      * note visible feature ordering and colours before update
725      */
726     List<String> visibleFeatures = getDisplayedFeatureTypes();
727     Map<String, FeatureColourI> visibleColours = new HashMap<>(
728             getFeatureColours());
729
730     FeaturesDisplayedI av_featuresdisplayed = null;
731     if (visibleNew)
732     {
733       if ((av_featuresdisplayed = av.getFeaturesDisplayed()) != null)
734       {
735         av.getFeaturesDisplayed().clear();
736       }
737       else
738       {
739         av.setFeaturesDisplayed(
740                 av_featuresdisplayed = new FeaturesDisplayed());
741       }
742     }
743     else
744     {
745       av_featuresdisplayed = av.getFeaturesDisplayed();
746     }
747     if (data == null)
748     {
749       return false;
750     }
751     // The feature table will display high priority
752     // features at the top, but these are the ones
753     // we need to render last, so invert the data
754     renderOrder = new String[data.length];
755
756     if (data.length > 0)
757     {
758       for (int i = 0; i < data.length; i++)
759       {
760         String type = data[i].featureType;
761         setColour(type, data[i].featureColour);
762         if (data[i].show)
763         {
764           av_featuresdisplayed.setVisible(type);
765         }
766
767         renderOrder[data.length - i - 1] = type;
768       }
769     }
770
771     /*
772      * get the new visible ordering and return true if it has changed
773      * order or any colour has changed
774      */
775     List<String> reorderedVisibleFeatures = getDisplayedFeatureTypes();
776     if (!visibleFeatures.equals(reorderedVisibleFeatures))
777     {
778       /*
779        * the list of ordered visible features has changed
780        */
781       return true;
782     }
783
784     /*
785      * return true if any feature colour has changed
786      */
787     for (String feature : visibleFeatures)
788     {
789       if (visibleColours.get(feature) != getFeatureStyle(feature))
790       {
791         return true;
792       }
793     }
794     return false;
795   }
796
797   /**
798    * @param listener
799    * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
800    */
801   public void addPropertyChangeListener(PropertyChangeListener listener)
802   {
803     changeSupport.addPropertyChangeListener(listener);
804   }
805
806   /**
807    * @param listener
808    * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
809    */
810   public void removePropertyChangeListener(PropertyChangeListener listener)
811   {
812     changeSupport.removePropertyChangeListener(listener);
813   }
814
815   public Set<String> getAllFeatureColours()
816   {
817     return featureColours.keySet();
818   }
819
820   public void clearRenderOrder()
821   {
822     renderOrder = null;
823   }
824
825   public boolean hasRenderOrder()
826   {
827     return renderOrder != null;
828   }
829
830   /**
831    * Returns feature types in ordering of rendering, where last means on top
832    */
833   public List<String> getRenderOrder()
834   {
835     if (renderOrder == null)
836     {
837       return Arrays.asList(new String[] {});
838     }
839     return Arrays.asList(renderOrder);
840   }
841
842   public int getFeatureGroupsSize()
843   {
844     return featureGroups != null ? 0 : featureGroups.size();
845   }
846
847   @Override
848   public List<String> getFeatureGroups()
849   {
850     // conflict between applet and desktop - featureGroups returns the map in
851     // the desktop featureRenderer
852     return (featureGroups == null) ? Arrays.asList(new String[0])
853             : Arrays.asList(featureGroups.keySet().toArray(new String[0]));
854   }
855
856   public boolean checkGroupVisibility(String group,
857           boolean newGroupsVisible)
858   {
859     if (featureGroups == null)
860     {
861       // then an exception happens next..
862     }
863     if (featureGroups.containsKey(group))
864     {
865       return featureGroups.get(group).booleanValue();
866     }
867     if (newGroupsVisible)
868     {
869       featureGroups.put(group, Boolean.valueOf(true));
870       return true;
871     }
872     return false;
873   }
874
875   /**
876    * get visible or invisible groups
877    * 
878    * @param visible
879    *          true to return visible groups, false to return hidden ones.
880    * @return list of groups
881    */
882   @Override
883   public List<String> getGroups(boolean visible)
884   {
885     if (featureGroups != null)
886     {
887       List<String> gp = new ArrayList<>();
888
889       for (String grp : featureGroups.keySet())
890       {
891         Boolean state = featureGroups.get(grp);
892         if (state.booleanValue() == visible)
893         {
894           gp.add(grp);
895         }
896       }
897       return gp;
898     }
899     return null;
900   }
901
902   @Override
903   public void setGroupVisibility(String group, boolean visible)
904   {
905     featureGroups.put(group, Boolean.valueOf(visible));
906   }
907
908   @Override
909   public void setGroupVisibility(List<String> toset, boolean visible)
910   {
911     if (toset != null && toset.size() > 0 && featureGroups != null)
912     {
913       boolean rdrw = false;
914       for (String gst : toset)
915       {
916         Boolean st = featureGroups.get(gst);
917         featureGroups.put(gst, Boolean.valueOf(visible));
918         if (st != null)
919         {
920           rdrw = rdrw || (visible != st.booleanValue());
921         }
922       }
923       if (rdrw)
924       {
925         // set local flag indicating redraw needed ?
926       }
927     }
928   }
929
930   @Override
931   public Map<String, FeatureColourI> getDisplayedFeatureCols()
932   {
933     Map<String, FeatureColourI> fcols = new Hashtable<>();
934     if (getViewport().getFeaturesDisplayed() == null)
935     {
936       return fcols;
937     }
938     Set<String> features = getViewport().getFeaturesDisplayed()
939             .getVisibleFeatures();
940     for (String feature : features)
941     {
942       fcols.put(feature, getFeatureStyle(feature));
943     }
944     return fcols;
945   }
946
947   @Override
948   public FeaturesDisplayedI getFeaturesDisplayed()
949   {
950     return av.getFeaturesDisplayed();
951   }
952
953   /**
954    * Returns a (possibly empty) list of visible feature types, in render order
955    * (last is on top)
956    */
957   @Override
958   public List<String> getDisplayedFeatureTypes()
959   {
960     List<String> typ = getRenderOrder();
961     List<String> displayed = new ArrayList<>();
962     FeaturesDisplayedI feature_disp = av.getFeaturesDisplayed();
963     if (feature_disp != null)
964     {
965       synchronized (feature_disp)
966       {
967         for (String type : typ)
968         {
969           if (feature_disp.isVisible(type))
970           {
971             displayed.add(type);
972           }
973         }
974       }
975     }
976     return displayed;
977   }
978
979   @Override
980   public List<String> getDisplayedFeatureGroups()
981   {
982     List<String> _gps = new ArrayList<>();
983     for (String gp : getFeatureGroups())
984     {
985       if (checkGroupVisibility(gp, false))
986       {
987         _gps.add(gp);
988       }
989     }
990     return _gps;
991   }
992
993   /**
994    * Answers true if the feature belongs to a feature group which is not
995    * currently displayed, else false
996    * 
997    * @param sequenceFeature
998    * @return
999    */
1000   public boolean featureGroupNotShown(final SequenceFeature sequenceFeature)
1001   {
1002     return featureGroups != null
1003             && sequenceFeature.featureGroup != null
1004             && sequenceFeature.featureGroup.length() != 0
1005             && featureGroups.containsKey(sequenceFeature.featureGroup)
1006             && !featureGroups.get(sequenceFeature.featureGroup)
1007                     .booleanValue();
1008   }
1009
1010   /**
1011    * {@inheritDoc}
1012    */
1013   @Override
1014   public List<SequenceFeature> findFeaturesAtResidue(SequenceI sequence,
1015           int fromResNo, int toResNo)
1016   {
1017     List<SequenceFeature> result = new ArrayList<>();
1018     if (!av.areFeaturesDisplayed() || getFeaturesDisplayed() == null)
1019     {
1020       return result;
1021     }
1022
1023     /*
1024      * include features at the position provided their feature type is 
1025      * displayed, and feature group is null or the empty string
1026      * or marked for display
1027      */
1028     List<String> visibleFeatures = getDisplayedFeatureTypes();
1029     String[] visibleTypes = visibleFeatures
1030             .toArray(new String[visibleFeatures.size()]);
1031     List<SequenceFeature> features = sequence.getFeatures().findFeatures(
1032             fromResNo, toResNo, visibleTypes);
1033   
1034     for (SequenceFeature sf : features)
1035     {
1036       if (!featureGroupNotShown(sf) && getColour(sf) != null)
1037       {
1038         result.add(sf);
1039       }
1040     }
1041     return result;
1042   }
1043
1044   /**
1045    * Removes from the list of features any whose group is not shown, or that are
1046    * visible and duplicate the location of a visible feature of the same type.
1047    * Should be used only for features of the same, simple, feature colour (which
1048    * normally implies the same feature type). No filtering is done if
1049    * transparency, or any feature filters, are in force.
1050    * 
1051    * @param features
1052    */
1053   public void filterFeaturesForDisplay(List<SequenceFeature> features)
1054   {
1055     /*
1056      * fudge: JalviewJS's IntervalStore lacks the sort method called :-(
1057      */
1058     if (Platform.isJS())
1059     {
1060       return;
1061     }
1062
1063     /*
1064      * don't remove 'redundant' features if 
1065      * - transparency is applied (feature count affects depth of feature colour)
1066      * - filters are applied (not all features may be displayable)
1067      */
1068     if (features.isEmpty() || transparency != 1f
1069             || !featureFilters.isEmpty())
1070     {
1071       return;
1072     }
1073
1074     SequenceFeatures.sortFeatures(features, true);
1075     SequenceFeature lastFeature = null;
1076
1077     Iterator<SequenceFeature> it = features.iterator();
1078     while (it.hasNext())
1079     {
1080       SequenceFeature sf = it.next();
1081       if (featureGroupNotShown(sf))
1082       {
1083         it.remove();
1084         continue;
1085       }
1086
1087       /*
1088        * a feature is redundant for rendering purposes if it has the
1089        * same extent as another (so would just redraw the same colour);
1090        * (checking type and isContactFeature as a fail-safe here, although
1091        * currently they are guaranteed to match in this context)
1092        */
1093       if (lastFeature != null
1094               && sf.getBegin() == lastFeature.getBegin()
1095               && sf.getEnd() == lastFeature.getEnd()
1096               && sf.isContactFeature() == lastFeature.isContactFeature()
1097               && sf.getType().equals(lastFeature.getType()))
1098       {
1099         it.remove();
1100       }
1101       lastFeature = sf;
1102     }
1103   }
1104
1105   @Override
1106   public Map<String, FeatureMatcherSetI> getFeatureFilters()
1107   {
1108     return featureFilters;
1109   }
1110
1111   @Override
1112   public void setFeatureFilters(Map<String, FeatureMatcherSetI> filters)
1113   {
1114     featureFilters = filters;
1115   }
1116
1117   @Override
1118   public FeatureMatcherSetI getFeatureFilter(String featureType)
1119   {
1120     return featureFilters.get(featureType);
1121   }
1122
1123   @Override
1124   public void setFeatureFilter(String featureType, FeatureMatcherSetI filter)
1125   {
1126     if (filter == null || filter.isEmpty())
1127     {
1128       featureFilters.remove(featureType);
1129     }
1130     else
1131     {
1132       featureFilters.put(featureType, filter);
1133     }
1134   }
1135
1136   /**
1137    * Answers the colour for the feature, or null if the feature is excluded by
1138    * feature group visibility, by filters, or by colour threshold settings. This
1139    * method does not take feature type visibility into account.
1140    * 
1141    * @param sf
1142    * @param fc
1143    * @return
1144    */
1145   public Color getColor(SequenceFeature sf, FeatureColourI fc)
1146   {
1147     /*
1148      * is the feature group displayed?
1149      */
1150     if (featureGroupNotShown(sf))
1151     {
1152       return null;
1153     }
1154
1155     /*
1156      * does the feature pass filters?
1157      */
1158     if (!featureMatchesFilters(sf))
1159     {
1160       return null;
1161     }
1162   
1163     return fc.getColor(sf);
1164   }
1165
1166   /**
1167    * Answers true if there no are filters defined for the feature type, or this
1168    * feature matches the filters. Answers false if the feature fails to match
1169    * filters.
1170    * 
1171    * @param sf
1172    * @return
1173    */
1174   protected boolean featureMatchesFilters(SequenceFeature sf)
1175   {
1176     FeatureMatcherSetI filter = featureFilters.get(sf.getType());
1177     return filter == null ? true : filter.matches(sf);
1178   }
1179
1180   /**
1181    * Answers true unless the specified group is set to hidden. Defaults to true
1182    * if group visibility is not set.
1183    * 
1184    * @param group
1185    * @return
1186    */
1187   public boolean isGroupVisible(String group)
1188   {
1189     if (!featureGroups.containsKey(group))
1190     {
1191       return true;
1192     }
1193     return featureGroups.get(group);
1194   }
1195
1196   /**
1197    * Orders features in render precedence (last in order is last to render, so
1198    * displayed on top of other features)
1199    * 
1200    * @param order
1201    */
1202   public void orderFeatures(Comparator<String> order)
1203   {
1204     Arrays.sort(renderOrder, order);
1205   }
1206
1207   @Override
1208   public MappedFeatures findComplementFeaturesAtResidue(
1209           final SequenceI sequence, final int pos)
1210   {
1211     SequenceI ds = sequence.getDatasetSequence();
1212     if (ds == null)
1213     {
1214       ds = sequence;
1215     }
1216     final char residue = ds.getCharAt(pos - ds.getStart());
1217
1218     List<SequenceFeature> found = new ArrayList<>();
1219     List<AlignedCodonFrame> mappings = this.av.getAlignment()
1220             .getCodonFrame(sequence);
1221
1222     /*
1223      * fudge: if no mapping found, check the complementary alignment
1224      * todo: only store in one place? StructureSelectionManager?
1225      */
1226     if (mappings.isEmpty())
1227     {
1228       mappings = this.av.getCodingComplement().getAlignment()
1229               .getCodonFrame(sequence);
1230     }
1231
1232     /*
1233      * todo: direct lookup of CDS for peptide and vice-versa; for now,
1234      * have to search through an unordered list of mappings for a candidate
1235      */
1236     SequenceToSequenceMapping mapping = null;
1237     SequenceI mapFrom = null;
1238
1239     for (AlignedCodonFrame acf : mappings)
1240     {
1241       mapping = acf.getCoveringCodonMapping(ds);
1242       if (mapping == null)
1243       {
1244         continue;
1245       }
1246       SearchResultsI sr = new SearchResults();
1247       mapping.markMappedRegion(ds, pos, sr);
1248       for (SearchResultMatchI match : sr.getResults())
1249       {
1250         int fromRes = match.getStart();
1251         int toRes = match.getEnd();
1252         mapFrom = match.getSequence();
1253         List<SequenceFeature> fs = findFeaturesAtResidue(
1254                 mapFrom, fromRes, toRes);
1255         for (SequenceFeature sf : fs)
1256         {
1257           if (!found.contains(sf))
1258           {
1259             found.add(sf);
1260           }
1261         }
1262       }
1263
1264       /*
1265        * just take the first mapped features we find
1266        */
1267       if (!found.isEmpty())
1268       {
1269         break;
1270       }
1271     }
1272     if (found.isEmpty())
1273     {
1274       return null;
1275     }
1276
1277     /*
1278      * sort by renderorder (inefficiently but ok for small scale);
1279      * NB this sorts 'on top' feature to end, for rendering
1280      */
1281     List<SequenceFeature> result = new ArrayList<>();
1282     final int toAdd = found.size();
1283     int added = 0;
1284     for (String type : renderOrder)
1285     {
1286       for (SequenceFeature sf : found)
1287       {
1288         if (type.equals(sf.getType()))
1289         {
1290           result.add(sf);
1291           added++;
1292         }
1293         if (added == toAdd)
1294         {
1295           break;
1296         }
1297       }
1298     }
1299     
1300     return new MappedFeatures(mapping.getMapping(), mapFrom, pos, residue, result);
1301   }
1302
1303   @Override
1304   public boolean isVisible(SequenceFeature feature)
1305   {
1306     if (feature == null)
1307     {
1308       return false;
1309     }
1310     if (getFeaturesDisplayed() == null
1311             || !getFeaturesDisplayed().isVisible(feature.getType()))
1312     {
1313       return false;
1314     }
1315     if (featureGroupNotShown(feature))
1316     {
1317       return false;
1318     }
1319     FeatureColourI fc = featureColours.get(feature.getType());
1320     if (fc != null && fc.isOutwithThreshold(feature))
1321     {
1322       return false;
1323     }
1324     if (!featureMatchesFilters(feature))
1325     {
1326       return false;
1327     }
1328     return true;
1329   }
1330 }