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