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