Revision 89 org.gvsig.vectorediting/trunk/org.gvsig.vectorediting/org.gvsig.vectorediting.swing/org.gvsig.vectorediting.swing.impl/src/main/java/org/gvsig/vectorediting/swing/impl/DefaultEditingBehavior.java

View differences:

DefaultEditingBehavior.java
6 6
 */
7 7
package org.gvsig.vectorediting.swing.impl;
8 8

  
9
import java.awt.BorderLayout;
10 9
import java.awt.Color;
11 10
import java.awt.Graphics;
12 11
import java.awt.Image;
......
18 17
import java.util.Map;
19 18
import java.util.Stack;
20 19

  
21
import org.gvsig.fmap.dal.exception.DataException;
22 20
import org.gvsig.fmap.dal.feature.FeatureStore;
23 21
import org.gvsig.fmap.geom.Geometry;
24 22
import org.gvsig.fmap.geom.primitive.Point;
25
import org.gvsig.fmap.mapcontext.MapContext;
26 23
import org.gvsig.fmap.mapcontext.ViewPort;
27
import org.gvsig.fmap.mapcontext.layers.CancelationException;
28
import org.gvsig.fmap.mapcontext.layers.FLayer;
29 24
import org.gvsig.fmap.mapcontext.layers.FLayers;
30
import org.gvsig.fmap.mapcontext.layers.LayerCollectionEvent;
31
import org.gvsig.fmap.mapcontext.layers.LayerCollectionListener;
32
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
33
import org.gvsig.fmap.mapcontext.layers.LayerListener;
34
import org.gvsig.fmap.mapcontext.layers.LayerPositionEvent;
35 25
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
36
import org.gvsig.fmap.mapcontrol.MapControl;
37 26
import org.gvsig.fmap.mapcontrol.MapControlDrawer;
38 27
import org.gvsig.fmap.mapcontrol.MapControlLocator;
39 28
import org.gvsig.fmap.mapcontrol.tools.BehaviorException;
......
41 30
import org.gvsig.fmap.mapcontrol.tools.Listeners.ToolListener;
42 31
import org.gvsig.tools.ToolsLocator;
43 32
import org.gvsig.tools.i18n.I18nManager;
44
import org.gvsig.utils.console.JConsole;
45
import org.gvsig.utils.console.JDockPanel;
46
import org.gvsig.utils.console.ResponseListener;
47
import org.gvsig.utils.console.jedit.JEditTextArea;
48 33
import org.gvsig.vectorediting.lib.api.DrawingStatus;
49 34
import org.gvsig.vectorediting.lib.api.EditingLocator;
50 35
import org.gvsig.vectorediting.lib.api.EditingManager;
......
60 45
import org.gvsig.vectorediting.lib.api.exceptions.StopServiceException;
61 46
import org.gvsig.vectorediting.lib.api.exceptions.VectorEditingException;
62 47
import org.gvsig.vectorediting.swing.api.EditingBehavior;
48
import org.gvsig.vectorediting.swing.api.EditingContext;
63 49
import org.slf4j.Logger;
64 50
import org.slf4j.LoggerFactory;
65 51

  
......
72 58

  
73 59
  private Stack<EditingService> serviceStack;
74 60

  
75
  private MapControl mapControl;
61
  private EditingContext editingContext;
76 62

  
77 63
  private FLyrVect currentLayer;
78 64

  
79
  private FeatureStore featureStore;
80

  
81 65
  private EditingServiceParameter currentParam;
82 66

  
67
  private FeatureStore featureStore;
68

  
83 69
  private Point adjustedPoint;
84 70

  
85
  private JConsole console;
86

  
87
  private JDockPanel dockConsole = null;
88

  
89
  private boolean isShowConsole;
90

  
91
  protected ResponseAdapter consoleResponseAdapter;
92

  
93 71
  private I18nManager i18nManager = ToolsLocator.getI18nManager();
94 72

  
95
  private EditingCompoundBehavior compoundBehavior;
96

  
97 73
  private static final Image imageCursor = new BufferedImage(32, 32,
98 74
      BufferedImage.TYPE_INT_ARGB);
99 75
  static {
......
108 84
    g.drawRect((x - 3), (y - 3), 6, 6);
109 85
  }
110 86

  
111
  private LayerListener layerListener = new LayerListener() {
112

  
113
    public void activationChanged(LayerEvent e) {
114
      FLayer layer = e.getSource();
115
      if (layer instanceof FLyrVect) {
116

  
117
        if (layer.isActive() && layer.isEditing()) {
118
          showConsole();
119
          getMapControl().setTool("VectorEditing");
120
        }
121
        else if (!layer.isEditing() && layer.isActive()) {
122
          hideConsole();
123
          getMapControl().setTool("zoomIn");
124
        }
125
          changeCurrentLayer((FLyrVect) layer);
126
      }
127

  
128
    }
129

  
130
    public void drawValueChanged(LayerEvent e) {}
131

  
132
    public void editionChanged(LayerEvent e) {}
133

  
134
    public void nameChanged(LayerEvent e) {}
135

  
136
    public void visibilityChanged(LayerEvent e) {}
137
  };
138

  
139
  public void cleanBehavior() {
140
    serviceStack.clear();
141
    currentParam = null;
142
    this.enableSelection(false);
143

  
144
    showConsoleMessage("\n" + i18nManager.getTranslation("select_new_tool")
145
        + "\n");
146
  }
147

  
148
  public DefaultEditingBehavior(MapControl mapControl)
149
      throws CreateEditingBehaviorException {
150
    if (mapControl != null) {
151
      this.mapControl = mapControl;
87
  public DefaultEditingBehavior(EditingContext editingContext) throws CreateEditingBehaviorException {
88
    if (editingContext.getMapControl() != null) {
89
      this.editingContext = editingContext;
152 90
      serviceRegistration = new HashMap<FLyrVect, EditingService>();
153 91
      serviceStack = new Stack<EditingService>();
154
      // sbl = new StatusBarListener(mapControl);
155
      initMapControlListeners(mapControl);
156
      initConsolePanelListeners(getConsolePanel());
157
      FLayers layers = mapControl.getMapContext().getLayers();
92

  
93
      FLayers layers = editingContext.getMapControl().getMapContext().getLayers();
158 94
      for (int i = 0; i < layers.getLayersCount(); i++) {
159 95
        if (layers.getLayer(i) instanceof FLyrVect
160 96
            && layers.getLayer(i).isActive())
......
163 99
    }
164 100
  }
165 101

  
166
  private void initConsolePanelListeners(JConsole jConsole) {
167
    consoleResponseAdapter = new ResponseAdapter();
168
    jConsole.addResponseListener(consoleResponseAdapter);
169
    addConsoleListener("ViewEditing", new ResponseListener() {
170

  
171
      public void acceptResponse(String response) {
172
        try {
173
          textEntered(response);
174
        }
175
        catch (InvalidEntryException e) {
176
          showConsoleMessage(i18nManager.getTranslation("invalid_option"));
177
        }
178
        catch (StopServiceException e) {
179
          logger.error(i18nManager.getTranslation("cant_stop_the_service")
180
              + " " + getActiveService().getName(), e);
181
        }
182
        finally {
183
          if (getActiveService() != null) {
184
            getNextParameter();
185
          }
186
        }
187
      }
188
    });
189

  
190
  }
191

  
192 102
  public void activateService(String name) {
193 103

  
194 104
    EditingManager manager = EditingLocator.getManager();
......
228 138
   * Shows description of parameter on console.
229 139
   */
230 140
  private void askQuestion(EditingServiceParameter param) {
231
    if (getConsolePanel() != null) {
232
      showConsoleMessage("\n#" + param.getDescription() + " > ");
233
    }
141
    showConsoleMessage("\n#" + param.getDescription() + " > ");
234 142
  }
235 143

  
144
  public void cleanBehavior() {
145
    serviceStack.clear();
146
    currentParam = null;
147
    this.enableSelection(false);
148

  
149
    showConsoleMessage("\n" + i18nManager.getTranslation("select_new_tool")
150
        + "\n");
151
  }
152

  
236 153
  private void showConsoleMessage(String text) {
237
    getConsolePanel().addText(text, JConsole.MESSAGE);
154
    editingContext.showConsoleMessage(text);
238 155
  }
239 156

  
240 157
  @Override
......
273 190
          EditingServiceParameter.TYPE.SELECTION)) {
274 191
        enableSelection(true);
275 192
      }
276
      setCaretPosition();
193
      // setCaretPosition();
277 194
    }
278 195

  
279 196
  }
......
289 206
    serviceStack.add(service);
290 207
  }
291 208

  
292
  private void initMapControlListeners(MapControl mapControl) {
293

  
294
    MapContext context = mapControl.getMapContext();
295
    FLayers layers = context.getLayers();
296
    layers.addLayerListener(layerListener);
297

  
298
    layers.addLayerCollectionListener(new LayerCollectionListener() {
299

  
300
      public void layerAdded(LayerCollectionEvent e) {
301
        FLayers layers2 = e.getLayers();
302
        for (int i = 0; i < layers2.getLayersCount(); i++) {
303
          FLayer layer = layers2.getLayer(i);
304
          if (layer instanceof FLyrVect) {
305
            ((FLyrVect) layer).addLayerListener(layerListener);
306
          }
307
        }
308
      }
309

  
310
      public void layerAdding(LayerCollectionEvent e)
311
          throws CancelationException {}
312

  
313
      public void layerMoved(LayerPositionEvent e) {}
314

  
315
      public void layerMoving(LayerPositionEvent e) throws CancelationException {}
316

  
317
      public void layerRemoved(LayerCollectionEvent e) {
318
        FLayers layers2 = e.getLayers();
319
        for (int i = 0; i < layers2.getLayersCount(); i++) {
320
          FLayer layer = layers2.getLayer(i);
321
          if (layer instanceof FLyrVect) {
322
            ((FLyrVect) layer).removeLayerListener(layerListener);
323
          }
324
        }
325
      }
326

  
327
      public void layerRemoving(LayerCollectionEvent e)
328
          throws CancelationException {}
329

  
330
      public void visibilityChanged(LayerCollectionEvent e)
331
          throws CancelationException {}
332
    });
333
  }
334

  
335 209
  public void mouseClicked(MouseEvent e) {
336
    ViewPort vp = mapControl.getViewPort();
210
    ViewPort vp = editingContext.getMapControl().getViewPort();
337 211
    if (getActiveService() != null) {
338 212
      if (currentParam != null) {
339 213
        List<TYPE> typesOfParam = currentParam.getTypes();
340
        if (typesOfParam.contains(TYPE.LIST_POSITIONS)) {
341
          if (e.getClickCount() == 2) {
342
            finishService();
343
            return;
214
        if (typesOfParam.contains(TYPE.LIST_POSITIONS) || typesOfParam.contains(TYPE.POSITION)) {
215
          if(typesOfParam.contains(TYPE.LIST_POSITIONS)){
216
            if (e.getClickCount() == 2) {
217
              finishService();
218
              return;
219
            }
344 220
          }
345 221
          Point point;
346 222
          point = vp.convertToMapPoint(e.getX(), e.getY());
......
351 227
            logger.error("Invalid value %s", new Object[] { point });
352 228
          }
353 229
        }
354
        if (typesOfParam.contains(TYPE.POSITION)) {
355
          Point point;
356
          point = vp.convertToMapPoint(e.getX(), e.getY());
357
          try {
358
            getActiveService().setValue(point);
359
          }
360
          catch (VectorEditingException ex) {
361
            logger.error("Invalid value %s", new Object[] { point });
362
          }
363
        }
364 230
        if (typesOfParam.contains(TYPE.SELECTION)) {
365 231
          // Do nothing
366 232
        }
......
373 239
    EditingService lastService = serviceStack.pop();
374 240
    try {
375 241
      if (serviceStack.isEmpty() || !getActiveService().next().getTypes()
376
          .contains(EditingServiceParameter.TYPE.GEOMETRY)) {
242
              .contains(EditingServiceParameter.TYPE.GEOMETRY)) {
377 243
        lastService.finishAndStore();
378
        mapControl.rePaintDirtyLayers();
244
        editingContext.getMapControl().rePaintDirtyLayers();
379 245
        setActiveService(lastService);
380 246
      }
381 247
      else if (!serviceStack.isEmpty() && getActiveService().next().getTypes()
382
          .contains(EditingServiceParameter.TYPE.GEOMETRY)) {
248
              .contains(EditingServiceParameter.TYPE.GEOMETRY)) {
383 249
        Geometry geometry = lastService.finish();
384
        if(geometry != null){
250
        if (geometry != null) {
385 251
          getActiveService().setValue(geometry);
386 252
        } else {
387 253
          lastService.finishAndStore();
388
          mapControl.rePaintDirtyLayers();
254
          editingContext.getMapControl().rePaintDirtyLayers();
389 255
          setActiveService(lastService);
390 256
        }
391 257
      }
......
396 262
      showConsoleMessage(i18nManager.getTranslation("invalid_option"));
397 263
    }
398 264
    catch (FinishServiceException ex) {
399
      logger.error("Can't finish "+ lastService.getName(), ex);
265
      logger.error("Can't finish " + lastService.getName(), ex);
400 266
    }
401 267
    catch (StopServiceException ex) {
402
      logger.error("Can't stop "+ lastService.getName(), ex);
268
      logger.error("Can't stop " + lastService.getName(), ex);
403 269
    }
404 270
    catch (StartServiceException ex) {
405
      logger.error("Can't start "+ lastService.getName(), ex);
271
      logger.error("Can't start " + lastService.getName(), ex);
406 272
    }
407 273
    getNextParameter();
408 274
  }
......
410 276
  public void mouseEntered(MouseEvent e) throws BehaviorException {}
411 277

  
412 278
  public void mouseMoved(MouseEvent e) throws BehaviorException {
413
    ViewPort vp = mapControl.getViewPort();
279
    ViewPort vp = editingContext.getMapControl().getViewPort();
414 280
    adjustedPoint = vp.convertToMapPoint(e.getX(), e.getY());
415
    // showCoords(e.getPoint());
416 281
    getMapControl().repaint();
417 282
  }
418 283

  
......
438 303
      Iterator iterator = helperGeo.getGeometries().iterator(); iterator
439 304
          .hasNext();) {
440 305
        Geometry geometry = (Geometry) iterator.next();
441
        mapControl.getMapControlDrawer().draw(geometry,
306
        editingContext.getMapControl().getMapControlDrawer().draw(geometry,
442 307
            MapControlLocator.getMapControlManager().getAxisReferenceSymbol());
443 308
      }
444 309
    }
445 310
  }
446 311

  
447
  private void setCaretPosition() {
448

  
449
    JEditTextArea jeta = getConsolePanel().getTxt();
450
    jeta.requestFocusInWindow();
451
    jeta.setCaretPosition(jeta.getText().length());
452

  
453
  }
454

  
455 312
  /**
456 313
   * Sets the layer received as parameter as {@link #currentLayer}
457
   *
314
   * 
458 315
   * @param layer
459 316
   */
460
  private void changeCurrentLayer(FLyrVect layer)
461
       {
317
  public void changeCurrentLayer(FLyrVect layer) {
462 318
    this.currentLayer = layer;
463 319
    if (currentLayer != null) {
464 320
      this.featureStore = (FeatureStore) currentLayer.getFeatureStore();
......
478 334
   * of {@link #currentParam}. If there is some error, It will continue
479 335
   * checking. If entry has been processed, It will set value in
480 336
   * {@link #activeService}.
481
   *
337
   * 
482 338
   * @param response Console entry.
483 339
   * @throws InvalidEntryException If console entries has not been able to
484 340
   *           process, it will throw an exception to indicate that entry is not
485 341
   *           valid.
486 342
   * @throws StopServiceException If there are some errors stopping service.
487 343
   */
488
  private void textEntered(String response) throws InvalidEntryException,
489
      StopServiceException {
344
  public void textEntered(String response) {
490 345
    if (response == null) {
491 346
      if (getActiveService() != null) {
492
        getActiveService().stop();
347
        try {
348
          getActiveService().stop();
349
        }
350
        catch (StopServiceException e) {
351
          // TODO Auto-generated catch block
352
        }
493 353
        cleanBehavior();
494 354
      }
495 355
    }
......
538 398
        }
539 399
      }
540 400
      if (!insertedValue && types.contains(TYPE.SELECTION)) {
541
        if (response.equalsIgnoreCase("\n")
542
            && currentParam.getTypes().contains(
543
                EditingServiceParameter.TYPE.SELECTION)) {
401
        if (response.equalsIgnoreCase("\n")){
544 402
          enableSelection(false);
545 403
          insertedValue = true;
546 404
          try {
547 405
            getActiveService()
548 406
                .setValue(featureStore.getFeatureSelection().clone());
549 407
          }
550
          catch (DataException e) {
551
            getActiveService().stop();
552
            cleanBehavior();
408
          catch (InvalidEntryException e) {
409
            // TODO Auto-generated catch block
410
            e.printStackTrace();
411
          }
412
          catch (Exception e) {
413
//            getActiveService().stop();
414
//            cleanBehavior();
553 415
            logger.error("Can't access to selecction.", e);
554 416
          }
555
          catch (CloneNotSupportedException e) {
556
            // Do nothing to try other types
557
          }
558 417
        }
559 418
      }
560 419
      if (!insertedValue) {
561
        throw new InvalidEntryException(null);
420
//        throw new InvalidEntryException(null);
421
        //TODO
562 422
      }
423
      getNextParameter();
563 424
    }
564 425
  }
565 426

  
566 427
  /**
567 428
   * Parse String to value.
568
   *
429
   * 
569 430
   * @param response String to be parsed.
570 431
   * @return Values of string.
571 432
   * @throws ParseValueException If there is error trying to parse
......
583 444

  
584 445
  /**
585 446
   * Parse String to point. Formats accepted: (x,y) and x,y.
586
   *
447
   * 
587 448
   * @param response String to be parsed.
588 449
   * @return Point of string.
589 450
   * @throws ParsePointException If there is error trying to parse
......
625 486
    }
626 487
  }
627 488

  
628
  private JDockPanel getDockConsole() {
629
    if (dockConsole == null) {
630
      dockConsole = new JDockPanel(getConsolePanel());
631
    }
632
    return dockConsole;
633
  }
634

  
635
  public void showConsole() {
636
    if (isShowConsole) {
637
      return;
638
    }
639
    isShowConsole = true;
640
    getMapControl().remove(getDockConsole());
641
    getMapControl().setLayout(new BorderLayout());
642
    getMapControl().add(getDockConsole(), BorderLayout.SOUTH);
643
    getDockConsole().setVisible(true);
644
    setCaretPosition();
645
  }
646

  
647
  public void hideConsole() {
648
    isShowConsole = false;
649
    getDockConsole().setVisible(false);
650

  
651
  }
652

  
653
  private JConsole getConsolePanel() {
654
    if (console == null) {
655
      console = new JConsole(true);
656
      // Para distinguir cuando se est? escribiendo sobre la consola y
657
      // cuando no.
658
      console.setJTextName("VectorEditingConsole");
659
    }
660
    return console;
661
  }
662

  
663
  private void addConsoleListener(String prefix, ResponseListener listener) {
664
    consoleResponseAdapter.putSpaceListener(prefix, listener);
665

  
666
  }
667

  
668
  static class ResponseAdapter implements ResponseListener {
669

  
670
    private HashMap<String, ResponseListener> spaceListener = new HashMap<String, ResponseListener>();
671

  
672
    public void putSpaceListener(String namespace, ResponseListener listener) {
673
      spaceListener.put(namespace, listener);
674
    }
675

  
676
    public void acceptResponse(String response) {
677
      boolean nameSpace = false;
678
      int n = -1;
679
      if (response != null) {
680
        if ((n = response.indexOf(':')) != -1) {
681
          nameSpace = true;
682
        }
683
      }
684

  
685
      if (nameSpace) {
686
        ResponseListener listener = spaceListener.get(response.substring(0, n));
687
        if (listener != null) {
688
          listener.acceptResponse(response.substring(n + 1));
689
        }
690
      }
691
      else {
692
        Iterator<ResponseListener> i = spaceListener.values().iterator();
693
        while (i.hasNext()) {
694
          ResponseListener listener = i.next();
695
          listener.acceptResponse(response);
696
        }
697
      }
698
    }
699
  }
700

  
701
  public void setCompoundBehavior(EditingCompoundBehavior compoundBehavior) {
702
    this.compoundBehavior = compoundBehavior;
703
  }
704

  
705 489
  public void enableSelection(boolean enableSelection) {
706
    this.compoundBehavior.setDrawnBehavior(
707
        EditingCompoundBehavior.SELECTION_INDEX, enableSelection);
490
     editingContext.enableSelection(enableSelection);
708 491
  }
709 492
}

Also available in: Unified diff