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