libgeos.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. """
  2. This module houses the ctypes initialization procedures, as well
  3. as the notice and error handler function callbacks (get called
  4. when an error occurs in GEOS).
  5. This module also houses GEOS Pointer utilities, including
  6. get_pointer_arr(), and GEOM_PTR.
  7. """
  8. import logging
  9. import os
  10. import re
  11. from ctypes import c_char_p, Structure, CDLL, CFUNCTYPE, POINTER
  12. from ctypes.util import find_library
  13. from django.contrib.gis.geos.error import GEOSException
  14. from django.core.exceptions import ImproperlyConfigured
  15. logger = logging.getLogger('django.contrib.gis')
  16. # Custom library path set?
  17. try:
  18. from django.conf import settings
  19. lib_path = settings.GEOS_LIBRARY_PATH
  20. except (AttributeError, EnvironmentError,
  21. ImportError, ImproperlyConfigured):
  22. lib_path = None
  23. # Setting the appropriate names for the GEOS-C library.
  24. if lib_path:
  25. lib_names = None
  26. elif os.name == 'nt':
  27. # Windows NT libraries
  28. lib_names = ['geos_c', 'libgeos_c-1']
  29. elif os.name == 'posix':
  30. # *NIX libraries
  31. lib_names = ['geos_c', 'GEOS']
  32. else:
  33. raise ImportError('Unsupported OS "%s"' % os.name)
  34. # Using the ctypes `find_library` utility to find the path to the GEOS
  35. # shared library. This is better than manually specifying each library name
  36. # and extension (e.g., libgeos_c.[so|so.1|dylib].).
  37. if lib_names:
  38. for lib_name in lib_names:
  39. lib_path = find_library(lib_name)
  40. if lib_path is not None:
  41. break
  42. # No GEOS library could be found.
  43. if lib_path is None:
  44. raise ImportError(
  45. 'Could not find the GEOS library (tried "%s"). '
  46. 'Try setting GEOS_LIBRARY_PATH in your settings.' %
  47. '", "'.join(lib_names)
  48. )
  49. # Getting the GEOS C library. The C interface (CDLL) is used for
  50. # both *NIX and Windows.
  51. # See the GEOS C API source code for more details on the library function calls:
  52. # http://geos.refractions.net/ro/doxygen_docs/html/geos__c_8h-source.html
  53. lgeos = CDLL(lib_path)
  54. # The notice and error handler C function callback definitions.
  55. # Supposed to mimic the GEOS message handler (C below):
  56. # typedef void (*GEOSMessageHandler)(const char *fmt, ...);
  57. NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
  58. def notice_h(fmt, lst):
  59. fmt, lst = fmt.decode(), lst.decode()
  60. try:
  61. warn_msg = fmt % lst
  62. except TypeError:
  63. warn_msg = fmt
  64. logger.warning('GEOS_NOTICE: %s\n' % warn_msg)
  65. notice_h = NOTICEFUNC(notice_h)
  66. ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
  67. def error_h(fmt, lst):
  68. fmt, lst = fmt.decode(), lst.decode()
  69. try:
  70. err_msg = fmt % lst
  71. except TypeError:
  72. err_msg = fmt
  73. logger.error('GEOS_ERROR: %s\n' % err_msg)
  74. error_h = ERRORFUNC(error_h)
  75. #### GEOS Geometry C data structures, and utility functions. ####
  76. # Opaque GEOS geometry structures, used for GEOM_PTR and CS_PTR
  77. class GEOSGeom_t(Structure):
  78. pass
  79. class GEOSPrepGeom_t(Structure):
  80. pass
  81. class GEOSCoordSeq_t(Structure):
  82. pass
  83. class GEOSContextHandle_t(Structure):
  84. pass
  85. # Pointers to opaque GEOS geometry structures.
  86. GEOM_PTR = POINTER(GEOSGeom_t)
  87. PREPGEOM_PTR = POINTER(GEOSPrepGeom_t)
  88. CS_PTR = POINTER(GEOSCoordSeq_t)
  89. CONTEXT_PTR = POINTER(GEOSContextHandle_t)
  90. # Used specifically by the GEOSGeom_createPolygon and GEOSGeom_createCollection
  91. # GEOS routines
  92. def get_pointer_arr(n):
  93. "Gets a ctypes pointer array (of length `n`) for GEOSGeom_t opaque pointer."
  94. GeomArr = GEOM_PTR * n
  95. return GeomArr()
  96. # Returns the string version of the GEOS library. Have to set the restype
  97. # explicitly to c_char_p to ensure compatibility across 32 and 64-bit platforms.
  98. geos_version = lgeos.GEOSversion
  99. geos_version.argtypes = None
  100. geos_version.restype = c_char_p
  101. # Regular expression should be able to parse version strings such as
  102. # '3.0.0rc4-CAPI-1.3.3', '3.0.0-CAPI-1.4.1', '3.4.0dev-CAPI-1.8.0' or '3.4.0dev-CAPI-1.8.0 r0'
  103. version_regex = re.compile(
  104. r'^(?P<version>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<subminor>\d+))'
  105. r'((rc(?P<release_candidate>\d+))|dev)?-CAPI-(?P<capi_version>\d+\.\d+\.\d+)( r\d+)?$'
  106. )
  107. def geos_version_info():
  108. """
  109. Returns a dictionary containing the various version metadata parsed from
  110. the GEOS version string, including the version number, whether the version
  111. is a release candidate (and what number release candidate), and the C API
  112. version.
  113. """
  114. ver = geos_version().decode()
  115. m = version_regex.match(ver)
  116. if not m:
  117. raise GEOSException('Could not parse version info string "%s"' % ver)
  118. return dict((key, m.group(key)) for key in (
  119. 'version', 'release_candidate', 'capi_version', 'major', 'minor', 'subminor'))
  120. # Version numbers and whether or not prepared geometry support is available.
  121. _verinfo = geos_version_info()
  122. GEOS_MAJOR_VERSION = int(_verinfo['major'])
  123. GEOS_MINOR_VERSION = int(_verinfo['minor'])
  124. GEOS_SUBMINOR_VERSION = int(_verinfo['subminor'])
  125. del _verinfo
  126. GEOS_VERSION = (GEOS_MAJOR_VERSION, GEOS_MINOR_VERSION, GEOS_SUBMINOR_VERSION)
  127. # Here we set up the prototypes for the initGEOS_r and finishGEOS_r
  128. # routines. These functions aren't actually called until they are
  129. # attached to a GEOS context handle -- this actually occurs in
  130. # geos/prototypes/threadsafe.py.
  131. lgeos.initGEOS_r.restype = CONTEXT_PTR
  132. lgeos.finishGEOS_r.argtypes = [CONTEXT_PTR]