summaryrefslogtreecommitdiff
path: root/src/de/lmu/ifi/dbs/elki/visualization/visualizers/vis2d/ToolBox2DVisualization.java
blob: c2339fe29c19bf17c0c8b281cbe73abe7a164bcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package de.lmu.ifi.dbs.elki.visualization.visualizers.vis2d;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2011
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.batik.util.SVGConstants;
import org.w3c.dom.Element;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;

import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.math.DoubleMinMax;
import de.lmu.ifi.dbs.elki.result.HierarchicalResult;
import de.lmu.ifi.dbs.elki.result.Result;
import de.lmu.ifi.dbs.elki.result.ResultUtil;
import de.lmu.ifi.dbs.elki.utilities.FormatUtil;
import de.lmu.ifi.dbs.elki.utilities.iterator.IterableUtil;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
import de.lmu.ifi.dbs.elki.visualization.VisualizationTask;
import de.lmu.ifi.dbs.elki.visualization.css.CSSClass;
import de.lmu.ifi.dbs.elki.visualization.projector.ScatterPlotProjector;
import de.lmu.ifi.dbs.elki.visualization.style.StyleLibrary;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGUtil;
import de.lmu.ifi.dbs.elki.visualization.visualizers.AbstractVisFactory;
import de.lmu.ifi.dbs.elki.visualization.visualizers.Visualization;
import de.lmu.ifi.dbs.elki.visualization.visualizers.VisualizerUtil;
import de.lmu.ifi.dbs.elki.visualization.visualizers.events.ContextChangedEvent;

/**
 * Renders a tool box on the left of the 2D visualization
 * 
 * @author Heidi Kolb
 * 
 * @apiviz.has VisualizationTask oneway - - visualizes
 * 
 * @param <NV> Type of the NumberVector being visualized.
 */
public class ToolBox2DVisualization<NV extends NumberVector<NV, ?>> extends P2DVisualization<NV> {
  /**
   * A short name characterizing this Visualizer.
   */
  private static final String NAME = "Tool Box";

  /**
   * The logger for this class.
   */
  private static final Logging logger = Logging.getLogger(Factory.class);

  /**
   * CSS class for a tool button
   */
  public static final String CSS_TOOL_BUTTON = "toolButton";

  /**
   * CSS class for the tool button caption
   */
  public static final String CSS_TOOL_CAPTION = "toolCaption";

  /**
   * CSS class for a tool button
   */
  public static final String CSS_TOOL_BUTTON_SELECTED = "toolButtonSelected";

  /**
   * The container
   */
  private Element container;

  /**
   * Constructor.
   * 
   * @param task Task
   */
  public ToolBox2DVisualization(VisualizationTask task) {
    super(task);
    // TODO: which result do we best attach to?
    context.addContextChangeListener(this);
    context.addResultListener(this);
    incrementalRedraw();
  }

  @Override
  public void contextChanged(ContextChangedEvent e) {
    synchronizedRedraw();
  }

  @Override
  protected void redraw() {
    addCSSClasses(svgp);
    container = svgp.svgElement(SVGConstants.SVG_G_TAG);
    buildToolBox();
    layer.appendChild(container);
  }

  /**
   * Deletes the children of the container
   * 
   * @param container Element to delete children
   */
  private void deleteChildren(Element container) {
    while(container.hasChildNodes()) {
      container.removeChild(container.getLastChild());
    }
  }

  /**
   * Build the toolbox
   */
  private void buildToolBox() {
    double scale = StyleLibrary.SCALE;
    deleteChildren(container);

    ArrayList<VisualizationTask> vis = new ArrayList<VisualizationTask>();
    final Iterable<VisualizationTask> visualizers = ResultUtil.filteredResults(task.getResult(), VisualizationTask.class);
    for(VisualizationTask task : visualizers) {
      if(VisualizerUtil.isTool(task) && !vis.contains(task)) {
        vis.add(task);
      }
    }

    // calculate the position of the first tool
    Pair<DoubleMinMax, DoubleMinMax> pt = proj.estimateViewport();
    double x = pt.getFirst().getMin() - 0.17 * scale;
    double width = 0.07 * scale;
    double height = 0.06 * scale;
    double miny = pt.getSecond().getMin();
    double maxy = pt.getSecond().getMax();
    double y = (miny + maxy) / 2 - (vis.size() * height * 1.4) / 2;
    if(y < miny) {
      logger.warning("Too many Tools");
    }

    // add tools
    Element[] toolTags = new Element[vis.size()];
    for(int i = 0; i < vis.size(); i++) {
      VisualizationTask v = vis.get(i);
      toolTags[i] = svgp.svgRect(x, y, width, height);
      String name = v.getLongName();
      // Split
      List<String> lines = FormatUtil.splitAtLastBlank(name, 8);
      // Generate label objects.
      for(int l = 0; l < lines.size(); l++) {
        Element selectRangeText = svgp.svgText(x + 0.01 * scale, y + (0.02 + 0.05 * l / lines.size()) * scale, lines.get(l));
        SVGUtil.setAtt(selectRangeText, SVGConstants.SVG_CLASS_ATTRIBUTE, CSS_TOOL_CAPTION);
        container.appendChild(selectRangeText);
      }

      if(VisualizerUtil.isVisible(v)) {
        SVGUtil.addCSSClass(toolTags[i], CSS_TOOL_BUTTON_SELECTED);
      }
      else {
        SVGUtil.addCSSClass(toolTags[i], CSS_TOOL_BUTTON);
      }
      addEventListener(toolTags[i], v);

      container.appendChild(toolTags[i]);
      y = y + 0.1 * scale;
    }
  }

  /**
   * Adds the required CSS-Classes
   * 
   * @param svgp SVG-Plot
   */
  private void addCSSClasses(SVGPlot svgp) {
    // Class for the not selected tool
    if(!svgp.getCSSClassManager().contains(CSS_TOOL_BUTTON)) {
      final CSSClass modeCls = new CSSClass(this, CSS_TOOL_BUTTON);
      modeCls.setStatement(SVGConstants.CSS_OPACITY_PROPERTY, 0.4);
      modeCls.setStatement(SVGConstants.CSS_FILL_PROPERTY, SVGConstants.CSS_GREEN_VALUE);
      modeCls.setStatement(SVGConstants.CSS_CURSOR_PROPERTY, SVGConstants.CSS_POINTER_VALUE);

      svgp.addCSSClassOrLogError(modeCls);
    }
    // Class for the selected tool
    if(!svgp.getCSSClassManager().contains(CSS_TOOL_BUTTON_SELECTED)) {
      final CSSClass modeCls = new CSSClass(this, CSS_TOOL_BUTTON_SELECTED);
      modeCls.setStatement(SVGConstants.CSS_OPACITY_PROPERTY, 0.4);
      modeCls.setStatement(SVGConstants.CSS_FILL_PROPERTY, SVGConstants.CSS_BLUE_VALUE);
      modeCls.setStatement(SVGConstants.CSS_STROKE_OPACITY_PROPERTY, 0.4);
      modeCls.setStatement(SVGConstants.CSS_STROKE_PROPERTY, SVGConstants.CSS_BLUE_VALUE);
      modeCls.setStatement(SVGConstants.CSS_CURSOR_PROPERTY, SVGConstants.CSS_POINTER_VALUE);

      svgp.addCSSClassOrLogError(modeCls);
    }
    // Class for the text of the tools
    if(!svgp.getCSSClassManager().contains(CSS_TOOL_CAPTION)) {
      final CSSClass label = new CSSClass(svgp, CSS_TOOL_CAPTION);
      label.setStatement(SVGConstants.CSS_FILL_PROPERTY, context.getStyleLibrary().getTextColor(StyleLibrary.AXIS_LABEL));
      label.setStatement(SVGConstants.CSS_FONT_FAMILY_PROPERTY, context.getStyleLibrary().getFontFamily(StyleLibrary.AXIS_LABEL));
      label.setStatement(SVGConstants.CSS_FONT_SIZE_PROPERTY, context.getStyleLibrary().getTextSize(StyleLibrary.AXIS_LABEL) * .8);

      svgp.addCSSClassOrLogError(label);
    }
  }

  /**
   * Add an event listener to the Element
   * 
   * @param tag Element to add the listener
   * @param tool Tool represented by the Element
   */
  private void addEventListener(final Element tag, final VisualizationTask tool) {
    EventTarget targ = (EventTarget) tag;
    targ.addEventListener(SVGConstants.SVG_EVENT_CLICK, new EventListener() {
      @Override
      public void handleEvent(Event evt) {
        handleMouseClick(tool);
      }
    }, false);
  }

  /**
   * Handle the mouseClick - change the selected tool in the context
   * 
   * @param tool Selected Tool
   */
  protected void handleMouseClick(VisualizationTask tool) {
    // TODO: Move this to the selected tool instead?
    if(VisualizerUtil.isVisible(tool)) {
      context.setSelection(null);
    }
    context.setVisualizationVisibility(tool, true);
  }

  @Override
  public void resultAdded(Result child, Result parent) {
    if(child instanceof VisualizationTask) {
      VisualizationTask task = (VisualizationTask) child;
      if(VisualizerUtil.isTool(task)) {
        synchronizedRedraw();
      }
    }
  }

  @Override
  public void resultRemoved(Result child, Result parent) {
    if(child instanceof VisualizationTask) {
      VisualizationTask task = (VisualizationTask) child;
      if(VisualizerUtil.isTool(task)) {
        synchronizedRedraw();
      }
    }
  }

  @Override
  public void resultChanged(Result current) {
    if(current instanceof VisualizationTask) {
      VisualizationTask task = (VisualizationTask) current;
      if(VisualizerUtil.isTool(task)) {
        synchronizedRedraw();
      }
    }
  }

  /**
   * Factory for visualizers for a toolbox
   * 
   * @author Heidi Kolb
   * 
   * @apiviz.stereotype factory
   * @apiviz.uses ToolBox2DVisualization oneway - - «create»
   * 
   * @param <NV> Type of the NumberVector being visualized.
   */
  public static class Factory<NV extends NumberVector<NV, ?>> extends AbstractVisFactory {
    /**
     * Constructor
     */
    public Factory() {
      super();
    }

    @Override
    public Visualization makeVisualization(VisualizationTask task) {
      return new ToolBox2DVisualization<NV>(task);
    }

    @Override
    public void processNewResult(HierarchicalResult baseResult, Result result) {
      Iterator<ScatterPlotProjector<?>> ps = ResultUtil.filteredResults(result, ScatterPlotProjector.class);
      for(ScatterPlotProjector<?> p : IterableUtil.fromIterator(ps)) {
        final VisualizationTask task = new VisualizationTask(NAME, p, p.getRelation(), this);
        task.put(VisualizationTask.META_LEVEL, VisualizationTask.LEVEL_INTERACTIVE);
        task.put(VisualizationTask.META_NOTHUMB, true);
        task.put(VisualizationTask.META_NOEXPORT, true);
        baseResult.getHierarchy().add(p, task);
      }
    }
  }
}