libgeos.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. from ctypes import CDLL, CFUNCTYPE, POINTER, Structure, c_char_p
  11. from ctypes.util import find_library
  12. from django.core.exceptions import ImproperlyConfigured
  13. from django.utils.functional import SimpleLazyObject, cached_property
  14. from django.utils.version import get_version_tuple
  15. logger = logging.getLogger('django.contrib.gis')
  16. def load_geos():
  17. # Custom library path set?
  18. try:
  19. from django.conf import settings
  20. lib_path = settings.GEOS_LIBRARY_PATH
  21. except (AttributeError, ImportError, ImproperlyConfigured, OSError):
  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. # Here we set up the prototypes for the initGEOS_r and finishGEOS_r
  55. # routines. These functions aren't actually called until they are
  56. # attached to a GEOS context handle -- this actually occurs in
  57. # geos/prototypes/threadsafe.py.
  58. _lgeos.initGEOS_r.restype = CONTEXT_PTR
  59. _lgeos.finishGEOS_r.argtypes = [CONTEXT_PTR]
  60. # Set restype for compatibility across 32 and 64-bit platforms.
  61. _lgeos.GEOSversion.restype = c_char_p
  62. return _lgeos
  63. # The notice and error handler C function callback definitions.
  64. # Supposed to mimic the GEOS message handler (C below):
  65. # typedef void (*GEOSMessageHandler)(const char *fmt, ...);
  66. NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
  67. def notice_h(fmt, lst):
  68. fmt, lst = fmt.decode(), lst.decode()
  69. try:
  70. warn_msg = fmt % lst
  71. except TypeError:
  72. warn_msg = fmt
  73. logger.warning('GEOS_NOTICE: %s\n', warn_msg)
  74. notice_h = NOTICEFUNC(notice_h)
  75. ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
  76. def error_h(fmt, lst):
  77. fmt, lst = fmt.decode(), lst.decode()
  78. try:
  79. err_msg = fmt % lst
  80. except TypeError:
  81. err_msg = fmt
  82. logger.error('GEOS_ERROR: %s\n', err_msg)
  83. error_h = ERRORFUNC(error_h)
  84. # #### GEOS Geometry C data structures, and utility functions. ####
  85. # Opaque GEOS geometry structures, used for GEOM_PTR and CS_PTR
  86. class GEOSGeom_t(Structure):
  87. pass
  88. class GEOSPrepGeom_t(Structure):
  89. pass
  90. class GEOSCoordSeq_t(Structure):
  91. pass
  92. class GEOSContextHandle_t(Structure):
  93. pass
  94. # Pointers to opaque GEOS geometry structures.
  95. GEOM_PTR = POINTER(GEOSGeom_t)
  96. PREPGEOM_PTR = POINTER(GEOSPrepGeom_t)
  97. CS_PTR = POINTER(GEOSCoordSeq_t)
  98. CONTEXT_PTR = POINTER(GEOSContextHandle_t)
  99. lgeos = SimpleLazyObject(load_geos)
  100. class GEOSFuncFactory:
  101. """
  102. Lazy loading of GEOS functions.
  103. """
  104. argtypes = None
  105. restype = None
  106. errcheck = None
  107. def __init__(self, func_name, *args, restype=None, errcheck=None, argtypes=None, **kwargs):
  108. self.func_name = func_name
  109. if restype is not None:
  110. self.restype = restype
  111. if errcheck is not None:
  112. self.errcheck = errcheck
  113. if argtypes is not None:
  114. self.argtypes = argtypes
  115. self.args = args
  116. self.kwargs = kwargs
  117. def __call__(self, *args, **kwargs):
  118. return self.func(*args, **kwargs)
  119. @cached_property
  120. def func(self):
  121. from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
  122. func = GEOSFunc(self.func_name)
  123. func.argtypes = self.argtypes or []
  124. func.restype = self.restype
  125. if self.errcheck:
  126. func.errcheck = self.errcheck
  127. return func
  128. def geos_version():
  129. """Return the string version of the GEOS library."""
  130. return lgeos.GEOSversion()
  131. def geos_version_tuple():
  132. """Return the GEOS version as a tuple (major, minor, subminor)."""
  133. return get_version_tuple(geos_version().decode())