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