Revision 424 org.gvsig.scripting.app/trunk/org.gvsig.scripting.app/org.gvsig.scripting.app.extension/src/main/resources/scripting/lib/gvsig.py

View differences:

gvsig.py
26 26
"""
27 27
This module contains classes and functions to manage gvSIG Project, 
28 28
gvSIG DocumentView, gvSIG TableDocument and Layers.
29
Also contais functions to manage vectorial data and other utility 
30
functions
29 31
"""
30 32

  
31 33
__author__ = """Antonio Carrasco Valero
......
53 55
from org.gvsig.fmap.mapcontext.layers import FLayers
54 56

  
55 57
from org.gvsig.fmap.dal import DALLocator, DataTypes
56
from org.gvsig.fmap.dal.feature import EditableFeature,  EditableFeatureType, FeatureQueryOrder
58
from org.gvsig.fmap.dal.feature import EditableFeature, \
59
    EditableFeatureType, FeatureQueryOrder
57 60
from org.gvsig.fmap.dal.feature.impl import DefaultEditableFeature
58 61

  
59 62
from org.gvsig.fmap.geom import Geometry
......
79 82
     
80 83

  
81 84
class WrapperToJava(object):
82
  """
83
  Create a wrapper that allows python object access to the Java object
85
  """Creates a wrapper that allows python object access to the Java object
84 86
  properties and methods
85 87
  """
86 88
  def __init__(self, javaobj):
......
95 97
    return getattr(self._javaobj,name)
96 98

  
97 99
class Project(WrapperToJava):
98
  """
99
  Represents a gvSIG project
100
  """
100
  """Represents a gvSIG project (org.gvsig.app.project.DefaultProject)"""
101

  
101 102
  def __init__(self, project):
102 103
    WrapperToJava.__init__(self, project)
103 104
  
104 105
  def getView(self, name=None):
105 106
    """
106
    Return active view, or view called 'name'  or None
107
    
108
      :param name: view name
109
      :type name: string
107
    Returns active view, or view called 'name'  or None
108
    :param name: view name
109
    :type name: string    
110 110
    """
111 111
    if name == None:
112 112
      try:
......
128 128
    
129 129
  def getTable(self, name=None):
130 130
    """
131
    Return active Table Document, or Table Document called 'name'  or None
132
    
133
      :param name: Table Document name
134
      :type name: string
131
    Returns active Table Document, or Table Document called 'name'  or None
132
    :param name: Table Document name
133
    :type name: string
135 134
    """
136 135
    if name == None:
137 136
      try:
......
152 151
    return None   
153 152
    
154 153
  def getProjectionCode(self):
154
    """Returns Project projection code name string. This value is the 
155
    projects default projection that is fixed in Preferences tool, View 
156
    options. It's used when no view projection is defined.
157
    
158
    """
155 159
    return self.getProjection().getFullCode()
160
    
156 161

  
157 162
class View(WrapperToJava):
158 163
  """
159
  Represents gvSIG view document.
164
  Represents gvSIG view document 
165
  (org.gvsig.app.project.documents.view.DefaultViewDocument).  
160 166
  """
161 167
  def __init__(self,view):
162 168
    WrapperToJava.__init__(self,view)
163 169
    
164 170
  def getLayer(self, name=None):
165 171
    """
166
    Return one of the view layers documents. If name is None return view active 
167
    layer if the view has one, if name is not None return view called name else 
168
    return None.
169
      
170
      :param name: view name in Table Of Contents
171
      :type name: string
172
      :return: View
173
      :return: None
174
      
172
    Returns one view layer. If name is None returns active 
173
    layer if the view has one, if name is not None returns layer called name 
174
    else returns None.
175
    :param name: view name in Table Of Contents
176
    :type name: string
177
    :return: View
178
    :return: None  
175 179
    """
176 180
    map = self.getMapContext();
177 181
    if name == None:
178 182
      activeLayers = map.getLayers().getActives()
179 183
      if len(activeLayers) != 1 :
180
        #raise RuntimeException("The view has not an active layer")
181 184
        return None
182 185
      for layer in activeLayers:
183 186
        if not isinstance(layer, FLayers):
184 187
          return Layer(layer)
185
      #raise RuntimeException("The view has not an active layer")
186 188
      return None
187 189
    
188 190
    ls = self.getLayers()
......
194 196
    return None
195 197
    
196 198
  def getMap(self):
197
    """
198
    Return view mapContext
199
    """
199
    # org.gvsig.fmap.mapcontext.MapContext
200
    """Returns view mapContext"""
200 201
    return self.getMapContext();
201 202
 
202 203
  def addLayer(self, layer):
204
    """
205
    Adds a new layer to the view
206
    :param layer: layer to add
207
    :type layer: Layer  
208
    """
203 209
    if isinstance(layer, Layer):
204 210
      layer =layer()
205 211
    self.getMapContext().getLayers().addLayer(layer)
206 212
  
207 213
  def getLayers(self):
208
    """
209
    Return iterable view layers set
210
    """
214
    """Returns iterable view layers set"""
211 215
    map = self.getMapContext()
212 216
    return Layers(map.getLayers())
213 217
    
214 218
  def getGraphicsLayer(self):
219
    """Returns view graphics layer 
220
    org.gvsig.fmap.mapcontext.layers.vectorial.impl.DefaultGraphicLayer
215 221
    """
216
    Return view graphics layer
217
    """
218 222
    return self.getMapContext().getGraphicsLayer()
219 223
    
220 224
  def getProjectionCode(self):
225
    """Returns string view projection code name"""
221 226
    return self.getProjection().getFullCode()
222 227
    
228
  def isProjected(self):
229
    """Returns if view projection is projected."""
230
    self.getProjection().isProjected():
231
      
223 232
class Layers(WrapperToJava):
233
  """Iterable layers set 
234
  (org.gvsig.fmap.mapcontext.layers.FLayers)  
224 235
  """
225
  Iterable layers set
226
  """
227 236
  def __init__(self,layers):
228 237
    WrapperToJava.__init__(self, layers)
229 238

  
......
249 258
    return Layer(self.__layers.getLayer(self.__index))    
250 259
  
251 260
class Store(WrapperToJava):
261
  """Represents gvsig store. It's used as Table/Layer objects store  
262
  (org.gvsig.fmap.dal.feature.impl.DefaultFeatureStore)
252 263
  """
253
  Represents gvsig store
254
  """
255 264
  def __init__(self,store):
256 265
    WrapperToJava.__init__(self, store)
257 266
    #self.data = None
258 267
    self.fset = None
259 268
  
260 269
  def features(self, expresion = None, sortBy="", asc=True):
261
    """
262
    Return layer features set (FeatureSet)
263
    
264
        :param expresion: filter to apply to the feature set to select
270
    """Returns layer features set (FeatureSet class), with all layer features, 
271
    or selected featured if there are (could be empty feature set) or None if
272
    gets an Exception.
273
    :param expresion: filter to apply to the feature set to select
265 274
        determinates features that match with expression
266
        :type expresion: string
267
        :param sortBy: name of attribute to sort
268
        :type sortby: string
269
        :param: asc: order
270
        :type asc: boolean
271
        :return: FeatureSet
272
    """
273
    
275
    :type expresion: string
276
    :param sortBy: name of attribute to sort
277
    :type sortby: string
278
    :param: asc: order
279
    :type asc: boolean
280
    :return: FeatureSet
281
    """   
274 282
    if expresion == None and sortBy =="":
275 283
      self.fset = self.getFeatureSet()         
276 284
    else:
277
      application = ApplicationLocator.getManager()
278
      datamanager =  application.getDataManager()
279
      query = self.createFeatureQuery()
280
      if sortBy != "":
281
        order = FeatureQueryOrder()
282
        order.add(sortBy, asc)
283
        query.setOrder(order)
284
      if expresion != None:
285
        query.setFilter(datamanager.createExpresion(expresion))
286
      #self.fset = data.getFeatureSet(query)    
287
      self.fset = self.getFeatureSet(query)
285
      try:
286
        application = ApplicationLocator.getManager()
287
        datamanager =  application.getDataManager()
288
        query = self.createFeatureQuery()
289
        if sortBy != "":
290
            order = FeatureQueryOrder()
291
            order.add(sortBy, asc)
292
            query.setOrder(order)
293
        if expresion != None:
294
            query.setFilter(datamanager.createExpresion(expresion))
295
        self.fset = self.getFeatureSet(query)
296
      except Exception, e:
297
        return None
288 298
    
289 299
    return FeatureSet(self.fset)    
290 300

  
291 301
  def edit(self):
292
    """
293
    Set layer data store in edition mode
294
    """
295
     
302
    """Set store in edition mode"""     
296 303
    if not self.isEditing():
297 304
        self().edit() 
298 305
     
299 306
  def append(self, *valuesList, **values):
300 307
    """
301
    Create a new feature from given values and insert it in the feature set
302
    
303
      :param values: dictionary with name property value or list named params
304
      :type values: dict
305
    
308
    Creates a new feature from given values and insert it in the feature 
309
    set. If an error occurs raises RuntimeException.
310
    :param values: dictionary with name property value or list named params
311
    :type values: dict
306 312
    """
307 313
    try:
308 314
      if len(valuesList) ==1:
......
326 332
      )
327 333

  
328 334
  def updateSchema(self, schema):
335
    """
336
    Updates store FeatureType. If an error occurs raises 
337
    RuntimeException.
338
    """
329 339
    try:
330 340
      self().update(schema._javaobj)
331 341
    except Throwable, ex:
......
333 343
    
334 344
  def update(self, feature):
335 345
    """
336
    Update exist feature in the layer featureSet
346
    Updates exist feature in the layer featureSet
347
    :param editableFeature: editableFeature
348
    :type editableFeature: Java editableFeature
349
    """
350
    if not self.isEditing():
351
      self.edit() 
337 352
    
338
      :param editableFeature: editableFeature
339
      :type editableFeature: Java editableFeature
340
    """
341 353
    if not isinstance(feature, EditableFeature):
342 354
      feature = feature._javaobj
343 355
    self.fset.update(feature)
344 356
  
345 357
  def getSchema(self):
346
    """
347
    Return layer schema definition
348
    """
358
    """Returns store data attributtes"""
349 359
    return Schema(self.getDefaultFeatureType())
350 360

  
351 361
  def commit(self):
352 362
    """
353
    Finish layer edition
363
    Finish store edition saving changes. If an error occurs raises Throwable 
364
    Exception.
354 365
    """
355 366
    try:
356 367
      self.finishEditing()          
......
359 370
      raise Throwable("Can't finish layer edition, cancelling changes. %s" % repr(ex))
360 371
  
361 372
  def abort(self):
362
    """
363
    Cancel layer edition
364
    """
373
    """Finish store edition withoout saving changes and disposes itself"""
365 374
    self.cancelEditing() 
366 375
    self.dispose()
367 376

  
368 377
  def getSelection(self):
369
    """
370
    Return layer feature selected set
371
    """
378
    """Returns store features selected set"""
372 379
    return FeatureSet(self().getSelection())
373 380

  
374 381
class __DefaultTable__(WrapperToJava):
......
379 386

  
380 387
  def features(self, expresion = None, sortBy="", asc=True):
381 388
    """
382
    Return data features set
383
    
384
        :param expresion: filter to apply to the feature set to select
389
    Returns data features set
390
    :param expresion: filter to apply to the feature set to select
385 391
         determinates features that match with expression
386
        :type expresion: string
387
        :return: FeatureSet
392
    :type expresion: string
393
    :return: FeatureSet
388 394
    """
389
    
390 395
    return self.data.features(expresion, sortBy, asc)
391 396

  
392 397
  def edit(self):
393
    """
394
    Set data in edition mode
395
    """
398
    """Sets data in edition mode"""
396 399
     
397 400
    self.data.edit() 
398 401
     
399 402
  def append(self, *valuesList, **values):
400 403
    """
401
    Create a new feature from given values and insert it in the feature set
402
    
403
      :param values: dictionary with name property value or list named params
404
      :type values: dict
405
    
404
    Creates a new feature from given values and insert it in the feature set
405
    :param values: dictionary with name property value or list named params
406
    :type values: dict
406 407
    """
407 408
    self.data.append(*valuesList, **values)
408 409
    
409 410
  def updateSchema(self, schema):
410 411
    """
411
    Update data schema definition with the given schema
412
    Updates data data attributes properties with the given schema
412 413
    """
413 414
    self.data.updateSchema(schema)
414 415
    
415 416
  def update(self, feature):
416 417
    """
417
    Update exist feature in the featureSet
418
    
419
      :param editableFeature: editableFeature
420
      :type editableFeature: Java editableFeature
418
    Updates exist feature in the featureSet with the given feature
419
    :param editableFeature: editableFeature
420
    :type editableFeature: Java editableFeature
421 421
    """
422 422
    self.data.update(feature)
423 423
  
424 424
  def getSchema(self):
425
    """
426
    Return schema definition
427
    """
425
    """Returns data attributes definition"""
428 426
    return self.data.getSchema()
429 427

  
430 428
  def commit(self):
431
    """
432
    Finish edition
433
    """
429
    """Finish edition saving changes"""
434 430
    self.data.commit()
435 431
  
436 432
  def abort(self):
437
    """
438
    Cancel edition
439
    """
433
    """Finish edition without saving changes"""
440 434
    self.data.abort()
441 435
    
442 436
  def getSelection(self):
443
    """
444
    Return features selected set
445
    """
437
    """Returns features selected set"""
446 438
    if self.selection == None:
447
      self.selection = self.data.getSelection()
439
      self.selection = Selection(self.data.getSelection())
448 440
      
449 441
    return self.selection
450 442
  
451 443
  def select(self, selection):
452
    """
453
    Insert features in the features selection set
454
    """
455
    if isinstance(selection,Feature) or isinstance(selection, FeatureSet):
456
      self.data.getSelection().select(selection._javaobj)
457
    else:
458
      self.data.getSelection().select(selection)
444
    """Inserts features in the features selection set"""
445
    self.getSelection().select(selection)
459 446

  
460 447
  def deselect(self, selection):
461
    """
462
    Remove features in the features selection set
463
    """
464
    if isinstance(selection,Feature) or isinstance(selection, FeatureSet):
465
      self.data.getSelection().deselect(selection._javaobj)
466
    else:
467
      self.data.getSelection().deselect(selection)
448
    """Remove features in the features selection set"""
449
    self.getSelection().deselect(selection)
468 450

  
469 451
  def isSelected(feature):
470
    """
471
    Returns if feature is selected
472
    """
473
    if isinstance(feature, Feature):
474
      self.data.getSelection().deselect(feature._javaobj)
475
    else:
476
      self.data.getSelection().deselect(feature)
452
    """Returns True if given feature is selected"""
453
    self.getSelection().isSelect(feature)
477 454

  
478 455
  def getProjectionCode(self):
479
    """
480
    Return layer projection code
481
    """
456
    """Returns projection code name"""
482 457
    return self.getProjection().getFullCode()
483 458

  
484 459

  
485 460
class Table(__DefaultTable__):
461
  """Represents gvsig table document 
462
  (org.gvsig.app.project.documents.table.TableDocument)
486 463
  """
487
  Represents gvsig layer document
488
  """
489 464
  def __init__(self,table):
490 465
    __DefaultTable__.__init__(self, table, table.getStore())
466
    
467
  def getAssociatedLayer(self):
468
    """Returns table associated layer or None if there're not associated 
469
    layer
470
    """    
471
    if self._javaobj.getAssociatedLayer():
472
      return Layer(self._javaobj.getAssociatedLayer())
473
        
474
    return None
491 475

  
492 476
class Layer(__DefaultTable__):
477
  """Represents gvsig layer document. It's a wrapper from 
478
  org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect class
493 479
  """
494
  Represents gvsig layer document
495
  """
496 480
  def __init__(self,layer):
497 481
    __DefaultTable__.__init__(self, layer, layer.getFeatureStore())
498
    #WrapperToJava.__init__(self,layer)
499 482
    
500 483
  def getTypeVectorLayer(self):
484
    """
485
    Returns layer DefaultGeometryType class 
486
    To get the geometryType use DefaultGeometryType getType() method
487
    To get the geometrySubType use DefaultGeometryType getSubType() method
488
    """
501 489
    return self().getTypeVectorLayer()
502 490
        
503 491
class FeatureSet(WrapperToJava):
492
  """Represents gvSIG FeatureSet 
493
  (org.gvsig.fmap.dal.feature.impl.featureset.DefaultFeatureSet)
494
  """
504 495
  def __init__(self,featureSet):
505 496
    WrapperToJava.__init__(self,featureSet)
506 497
    
507 498
  def getCount(self):
499
    """Returns the number of elements in the featureSet"""
508 500
    return self.getSize()
509 501
  
510 502
  def update(self, feature):
511 503
    """
512
    Update exist feature in the featureSet
513
    
514
      :param editableFeature: editableFeature
515
      :type editableFeature: Java editableFeature
504
    Updates exist feature in the featureSet
505
    :param editableFeature: editableFeature
506
    :type editableFeature: Java editableFeature
516 507
    """
517
    if not isinstance(feature, EditableFeature) and not isinstance(feature, DefaultEditableFeature):
508
    if not isinstance(feature, EditableFeature) and \
509
            not isinstance(feature, DefaultEditableFeature):
518 510
      feature = feature._javaobj
519 511
    self().update(feature)
520 512
  
521 513
  def __iter__(self):
522 514
    return  Iterator(self.fastIterator())
523
   
515
    
516
class Selection(FeatureSet):
517
  """Manage selected features set from a store. Represents gvSIG 
518
  org.gvsig.fmap.dal.feature.impl.DefaultFeatureSelection.  
519
  """
520
  def __init__(self, featureSet):
521
    FeatureSet.__init__(self, featureSet)
522
      
523
  def select(self, selection):
524
    """Inserts features in the features selection set"""
525
    if isinstance(selection,Feature) or isinstance(selection, FeatureSet):
526
      self._javaobj.select(selection._javaobj)
527
    else:
528
      self._javaobj.select(selection)
529

  
530
  def deselect(self, selection):
531
    """Removes features in the features selection set"""
532
    if isinstance(selection,Feature) or isinstance(selection, FeatureSet):
533
      self._javaobj.deselect(selection._javaobj)
534
    else:
535
      self._javaobj.deselect(selection)
536

  
537
  def isSelected(feature):
538
    """Returns True if given feature is selected"""
539
    if isinstance(feature, Feature):
540
      self._javaobj.isSelect(feature._javaobj)
541
    else:
542
      self._javaobj.isSelect(feature)
543
      
544
  def getCount(self):
545
    """Returns the number of elements in the selection"""
546
    return self.getSelectedCount()
547
    
548
    
524 549
class Iterator(WrapperToJava):
525 550

  
526 551
  def __init__(self,iterator):
......
532 557
    return Feature(self().next())
533 558
    
534 559
class Feature(WrapperToJava):
560
  """Represents feature data It's a wrapper from gvSIG 
561
  org.gvsig.fmap.dal.feature.impl.DefaultFeature class
535 562
  """
536
  Represents layer feature data
537
  """
538 563
  def __init__(self,feature):
539 564
    WrapperToJava.__init__(self,feature)
540 565
    self.featureNoEditable = None
541 566

  
542 567
  def geometry(self):
543
    """
544
    Return feature default geometry
545
    """
568
    """Returns feature geometry"""
546 569
    return self.getDefaultGeometry()
547 570
   
548 571
  def getValues(self):
549
    """
550
    Return dictionary with name value attributes
551
    """
572
    """Returns dictionary with the pair name, value, feature attributes"""
552 573
    descriptor = self.getType()
553 574
    items = dict()
554 575
    for attr in descriptor.getAttributeDescriptors():
......
558 579
    return items 
559 580
  
560 581
  def edit(self):
561
    """
562
    Return editable feature
563
    """
582
    """Returns editable feature instance"""
564 583
    if not isinstance(self._javaobj, EditableFeature):
565 584
      self.featureNoEditable = self._javaobj
566 585
      self._javaobj = self._javaobj.getEditable()
......
587 606
      raise RuntimeException("Can't access to attribute %s of feature (%s)" % (name, str(ex)))    
588 607

  
589 608
class Schema(WrapperToJava):
609
  """Stores data properties definition. Represents gvSIG FeatureType
610
  (org.gvsig.fmap.dal.feature.impl.DefaultFeatureType)
590 611
  """
591
  Layer feature definition
592
  """
593 612

  
594 613
  def __init__(self, featureType):
595 614
    WrapperToJava.__init__(self,featureType)
596 615
    self.featureTypeNoEditable = None
597 616
  
598 617
  def append(self, name, type, size=None, default=None, precision=4):
618
    """Adds new property to feature properties definition. If error occurs 
619
    raises RuntimeError.    
620
    :param name: Feature property name
621
    :type name: String
622
    :param type: Feature property type
623
    :type name: String
624
    :param size: Feature property size
625
    :type size: int
626
    :param default: Feature property default value
627
    :return: new atribute
599 628
    """
600
    Adds property to feature properties definition.
601
    
602
        :param name: Feature property name
603
        :type name: String
604
        :param type: Feature property type
605
        :type name: String
606
        :param size: Feature property size
607
        :type size: int
608
        :param default: Feature property default value
609
        :return: new atribute
610

  
611
    """
612 629
    if not isinstance(self._javaobj, EditableFeatureType):
613
      self.modify()
614
      #self.featureTypeNoEditable = self._javaobj
615
      #self._javaobj = self._javaobj.getEditable()
630
        self.modify()
616 631
    
617 632
    if isinstance(type, str):
618 633
      try:
......
664 679
    return self.getAttributeDescriptor(name)
665 680

  
666 681
  def get(self, name, default=None):
682
    """Returns a feature attribute descriptor that contains information about 
683
    one feature attribute, such as its name, data type or precision. 
684
    :param name: Attribute name
685
    :type name: string
686
    :param default: Value to return if no attribute name found. 
687
    :return: AttributeDescriptor
667 688
    """
668
    Return a feature attribute descriptor that contains information about 
669
    one of the attributes in a feature, such as its name, data type or 
670
    precision. 
671
      :param name: Attribute name
672
      :type name: string
673
      :param default: Value to return if no attribute name found. 
674
      :return: AttributeDescriptor
675
    """
676 689
    x = self.getAttributeDescriptor(name)
677 690
    if x == None:
678 691
      return default
679 692
    return x
680 693
  
681 694
  def getAttrNames(self):
682
    """
683
    Return list with definition schema atribute names 
684
    """
685
    names = list(attr.getName() for attr in self.getAttributeDescriptors())
686
    return names
695
    """Returns a list with attributes names"""
696
    if not self.getAttributeDescriptors():
697
      return None
698
        
699
    return [attr.getName() for attr in self.getAttributeDescriptors()]
687 700
    
701
    
688 702
  def getCopy(self):
703
    """Returns a itself clone"""
689 704
    return Schema(self().getCopy())
690 705
  
691 706
  def modify(self):
707
    """Sets edit mode"""
692 708
    if not isinstance(self._javaobj, EditableFeatureType):
693 709
      self.featureTypeNoEditable = self._javaobj
694 710
      self._javaobj = self._javaobj.getEditable()
......
699 715
#=====================#
700 716

  
701 717
def createSchema(schema = None):
718
  """Returns attributes definition. If Schema is recived then makes a copy and 
719
  returns editable instance. Otherwise returns empty Schema.
720
  :param schema: Schema to make a copy
721
  :type schema: Schema
702 722
  """
703
  Return empty layer definition
704
  """
705
  if schema != None:
706
    s = schema.getCopy()
707
    s.modify()
708
    return s
723
  if isinstance(schema, Schema):
724
    try:  
725
      s = schema.getCopy()
726
      s.modify()
727
      return s
728
    except:
729
      pass
709 730
    
710 731
  application = ApplicationLocator.getManager()
711 732
  datamanager =  application.getDataManager()
712 733
  return Schema(datamanager.createFeatureType())
713 734

  
714 735
def createLayer(schema, servertype, layertype=None, **parameters):
715
  """ 
716
  Create a new layer and return it 
717
  
718
      :param schema: layer data definition
719
      :type schema: Schema
720
      :param servertype: 
721
      :type servertype: string
722
      :return: new layer
723
      :rtype: Layer
724
      :raise: RuntimeException
725
  
726 736
  """
737
  Returns new layer
738
  :param schema: layer data definition
739
  :type schema: Schema
740
  :param servertype: 
741
  :type servertype: string
742
  :return: new layer
743
  :rtype: Layer
744
  :raise: RuntimeException
745
  """
727 746
  if layertype == None:
728 747
    layertype = servertype
729 748
    servertype = "FilesystemExplorer"
......
731 750
  if layertype == "Shape" :
732 751
    if schema.get("GEOMETRY",None) == None:
733 752
      raise RuntimeException("Shape need a field named GEOMETRY in the schema")
734
  
735
  #parameters["geometryType"] = getGeometryType(parameters["geometryType"])
736 753
    
737 754
  if parameters["geometryType"] == None:
738 755
    raise RuntimeException("Invalid geometry type for new layer")
......
764 781

  
765 782
def loadShapeFile(shpFile, CRS="CRS:84"):
766 783
    """
767
    Add existing shape file to the view
768
    Return Layer
769
      :param shpFile: absolute file path
770
      :type: shpFile: string
771
      :param CRS: projection code
772
      :type CRS: string
773
      :return: the shape
774
      :type return: Layer
784
    Add existing shape file to the view. Returns Layer shape file
785
    :param shpFile: absolute file path
786
    :type: shpFile: string
787
    :param CRS: projection code
788
    :type CRS: string
789
    :return: the shape
790
    :type return: Layer
775 791
    """
776 792
    layer = loadLayer('Shape', shpFile=shpFile, CRS=CRS)
777 793
    currentView().addLayer(layer)
778
    #return currentView().getLayer(layer.getName())
779 794
    layer.setActive(True)
780 795
    return Layer(layer)
781 796
    
......
794 809
    return layer
795 810
    
796 811
def createShape(definition, filename, geometryType, CRS="CRS:84"):
797
  """ 
798
  Create a new shape layer 
799
      
800
      :param definition: layer data definition
801
      :type definition: Schema
802
      :param filename: absolute path for shape files. 
803
      :type filename: string
804
      :param geometryType: geometry type for shape
805
      :type geometryType: string
806
      :return: new shape layer
807
      :rtype: Layer
808 812
  """
813
  Return new shape layer 
814
  :param definition: layer data definition
815
  :type definition: Schema
816
  :param filename: absolute path for shape files. 
817
  :type filename: string
818
  :param geometryType: geometry type for shape
819
  :type geometryType: string
820
  :return: new shape layer
821
  :rtype: Layer
822
  """
809 823
  return createLayer(
810 824
    definition, 
811 825
    "FilesystemExplorer", 
......
816 830
  )
817 831

  
818 832
def createTable(schema, servertype, tableType=None, **parameters):
833
  """Creates a new Table document"""
819 834
  if tableType == None:
820 835
    tableType = servertype
821 836
    servertype = "FilesystemExplorer"
......
842 857
  except Throwable, ex:
843 858
    raise RuntimeException("Can't create table, "+ str(ex))
844 859
  
845
def createDBF(definition, DbfFile, CRS="wsg86"):
846
  """ 
847
  Create a new dbf document 
848
      
849
      :param definition: layer data definition
850
      :type definition: Schema
851
      :param DbfFile: absolute path for shape files. 
852
      :type DbfFile: string
853
      :return: new dbf
854
      :rtype: Table
860
def createDBF(definition, DbfFile, CRS="CRS:84"):
855 861
  """
862
  Creates a new dbf document 
863
  :param definition: layer data definition
864
  :type definition: Schema
865
  :param DbfFile: absolute path for shape files. 
866
  :type DbfFile: string
867
  :return: new dbf
868
  :rtype: Table    
869
  """
856 870
  return createTable(
857 871
    definition, 
858 872
    "FilesystemExplorer", 
......
867 881

  
868 882
def currentProject():
869 883
  """
870
  Return the current gvSIG proyect
871
    :return: Proyect
884
  Returns current gvSIG proyect
885
  :return: Proyect
872 886
  """
873

  
874 887
  application = ApplicationLocator.getManager()
875 888
  project = application.getCurrentProject()
876 889
  return Project(project)
877 890

  
878 891
def currentDocument(documentClass = None):
879 892
  """
880
  Return the current active document if it's a DocumentTable or DocumentView2D
881
  
882
    :return: Active document, None
893
  Returns the current active document if it's a DocumentTable or 
894
  DocumentView2D return None
895
  :return: Active document, None
883 896
  """
884

  
885 897
  application = ApplicationLocator.getManager()
886 898
  
887 899
  if documentClass == None:
888 900
    doc = application.getActiveDocument()
889 901
  else:
890 902
    doc = application.getActiveDocument(documentClass)
891
  if isinstance(doc, TableDocument): #doc.getTypeName() == "project.document.table":
903
  if isinstance(doc, TableDocument):
892 904
    return Table(doc)
893
  if isinstance(doc, ViewDocument): #doc.getTypeName() == "project.document.view2d": 
905
  if isinstance(doc, ViewDocument):
894 906
    return View(doc)  
895 907

  
896 908
  return None  
897 909
  
898 910
def currentTable():
899 911
  """
900
  Return the current active table document or None 
901
  
902
    :return: Table or None
912
  Returns active table document or None 
913
  :return: Table or None
903 914
  """  
904 915
  return currentDocument(TableDocument)
905 916
  
906 917
def currentView():
907 918
  """
908
  Return the current active view document or None 
909
  
910
    :return: View or None
919
  Returns the current active view document or None 
920
  :return: View or None
911 921
  """ 
912 922
  return currentDocument(ViewDocument)
913 923

  
914 924
def currentLayer():
915
  """ 
916
  Return current view active layer
917
  
918
    :return: gvSIG active layer
919 925
  """
926
  Returns current view active layer or None
927
  :return: gvSIG active layer
928
  """
920 929
  try:
921 930
    return currentView().getLayer()
922 931
  except:
......
925 934
#=====================#
926 935
# Simbology Functions #
927 936
#=====================#  
937
COLORS = {
938
    'black': Color.black,
939
    'blue': Color.blue,
940
    'cyan': Color.cyan,
941
    'darkGray': Color.darkGray,
942
    'gray': Color.gray,
943
    'green': Color.green,
944
    'lightGray': Color.lightGray,
945
    'magenta': Color.magenta,
946
    'orange': Color.orange,
947
    'pink': Color.pink,
948
    'red': Color.red,
949
    'white': Color.white,
950
    'yellow': Color.yellow,
951
}
928 952
  
929 953
def simplePointSymbol(color=None):
930 954
  """
931
  Return simple point symbol using parameter color. If no color use a ramdom color
932
  
933
    :param color: Java awt Color
934
    :return: gvSIG point symbol
955
  Returns simple point symbol using parameter color. If no color 
956
  use a ramdom color
957
  :param color: String color name or Java awt Color
958
  :return: gvSIG point symbol
935 959
  """
960
  if isinstance(color, str) and COLORS.has_key(color.lower()):
961
    color = COLORS.get(color)
962
    
936 963
  if not isinstance(color, Color):
937
      color = getColor()
964
      color = getDefaultColor()
938 965
      
939
  return MapContextLocator.getSymbolManager().createSymbol(Geometry.TYPES.POINT, color)
966
  return MapContextLocator.getSymbolManager().createSymbol(
967
        Geometry.TYPES.POINT, color)
940 968

  
941 969
def simpleLineSymbol(color=None):
942 970
  """
943
  Return simple line symbol using parameter color. If no color use a ramdom color
971
  Returns simple line symbol using parameter color. If no color use a 
972
  ramdom color  
973
  :param color: String color name or Java awt Color
974
  :return: gvSIG line symbol
944 975
  
945
    :param color: Java awt Color
946
    :return: gvSIG line symbol
947 976
  """
977
  if isinstance(color, str) and COLORS.has_key(color.lower()):
978
    color = COLORS.get(color)
979

  
948 980
  if not isinstance(color, Color):
949
      color = getColor()
981
      color = getDefaultColor()
950 982
      
951
  return MapContextLocator.getSymbolManager().createSymbol(Geometry.TYPES.CURVE, color)
983
  return MapContextLocator.getSymbolManager().createSymbol(
984
        Geometry.TYPES.CURVE, color)
952 985

  
953 986
def simplePolygonSymbol(color = None):
954 987
  """
955
  Return simple polygon symbol using parameter color. If no color use a ramdom color.
956
  
957
    :param color: Java awt Color
958
    :return: gvSIG poligon symbol
988
  Returns simple polygon symbol using parameter color. If no color 
989
  use a ramdom color.  
990
  :param color: String color name or Java awt Color
991
  :return: gvSIG polygon symbol
959 992
  """
993
  if isinstance(color, str) and COLORS.has_key(color.lower()):
994
    color = COLORS.get(color)
995

  
960 996
  if not isinstance(color, Color):
961
      color = getColor()
997
      color = getDefaultColor()
962 998
  
963
  return MapContextLocator.getSymbolManager().createSymbol(Geometry.TYPES.SURFACE, color)
999
  return MapContextLocator.getSymbolManager().createSymbol(
1000
        Geometry.TYPES.SURFACE, color)
964 1001
  
965 1002

  
966 1003
#=========================================#
......
969 1006

  
970 1007
def getDataFolder():
971 1008
  """
972
  Return gvSIG data folder. This folder is defined in application preferences
973
  If not defined return None
1009
  Returns gvSIG data folder. This folder is defined in application 
1010
  preferences. If is not defined returns None.
974 1011
  """
975
  
976 1012
  return Preferences.userRoot().node("gvsig.foldering").get('DataFolder', None)
977 1013
  
978 1014
def getProjectsFolder():
979 1015
  """
980
  Return gvSIG projects folder. This folder is defined in application preferences.
981
  If not defined return None
1016
  Returns gvSIG projects folder. This folder is defined in application 
1017
  preferences. If is not defined returns None.
982 1018
  """
1019
  return Preferences.userRoot().node("gvsig.foldering").get(
1020
        'ProjectsFolder', None)
1021

  
1022
def getColorFromRGB(r, g, b, a=None):
1023
  """
1024
  Returns an sRGB color with the specified red, green, blue, and alpha 
1025
  (optional) values in the range (0 - 255).
1026
  """
1027
  if a:
1028
    color = Color(r, g, b, a)
1029
  else:
1030
    color = Color(r, g, b)
983 1031
  
984
  return Preferences.userRoot().node("gvsig.foldering").get('ProjectsFolder', None)
985

  
986

  
987
def getColor():
1032
  return color
1033
  
1034
def getDefaultColor(c = None):
1035
  """Returns gvsig default symbol fill color or ramdom color"""
988 1036
  if MapContextLocator.getSymbolManager().isDefaultSymbolFillColorAleatory():
989 1037
    color = Color(random.randint(0-255), 
990
              random.randint(0-255), 
991
              random.randint(0-255)
1038
                random.randint(0-255), 
1039
                random.randint(0-255)
992 1040
            )
993 1041
  else:
994
    color = MapContextLocator.getSymbolManager().getSymbolPreferences().getDefaultSymbolFillColor()
1042
    sp = MapContextLocator.getSymbolManager().getSymbolPreferences()
1043
    color = sp.getDefaultSymbolFillColor()    
1044

  
995 1045
  return color  
996 1046
  
997 1047
#================#
......
999 1049
#================#
1000 1050

  
1001 1051
def getCRS(crs):
1052
  """Returns Projection from string code (i.e. CRS:84) if exist or None if 
1053
  not.  
1002 1054
  """
1003
  Return Projection from string code (i.e. CRS:84) if exist.
1004
  """
1005 1055
  try:
1006 1056
    return CRSFactory.getCRS(crs)
1007 1057
  except:

Also available in: Unified diff