libgeos.py 4.9 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." % '", "'.join(lib_names)
  47. )
  48. # Getting the GEOS C library. The C interface (CDLL) is used for
  49. # both *NIX and Windows.
  50. # See the GEOS C API source code for more details on the library function calls:
  51. # https://libgeos.org/doxygen/geos__c_8h_source.html
  52. _lgeos = CDLL(lib_path)
  53. # Here we set up the prototypes for the initGEOS_r and finishGEOS_r
  54. # routines. These functions aren't actually called until they are
  55. # attached to a GEOS context handle -- this actually occurs in
  56. # geos/prototypes/threadsafe.py.
  57. _lgeos.initGEOS_r.restype = CONTEXT_PTR
  58. _lgeos.finishGEOS_r.argtypes = [CONTEXT_PTR]
  59. # Set restype for compatibility across 32 and 64-bit platforms.
  60. _lgeos.GEOSversion.restype = c_char_p
  61. return _lgeos
  62. # The notice and error handler C function callback definitions.
  63. # Supposed to mimic the GEOS message handler (C below):
  64. # typedef void (*GEOSMessageHandler)(const char *fmt, ...);
  65. NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
  66. def notice_h(fmt, lst):
  67. fmt, lst = fmt.decode(), lst.decode()
  68. try:
  69. warn_msg = fmt % lst
  70. except TypeError:
  71. warn_msg = fmt
  72. logger.warning("GEOS_NOTICE: %s\n", warn_msg)
  73. notice_h = NOTICEFUNC(notice_h)
  74. ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
  75. def error_h(fmt, lst):
  76. fmt, lst = fmt.decode(), lst.decode()
  77. try:
  78. err_msg = fmt % lst
  79. except TypeError:
  80. err_msg = fmt
  81. logger.error("GEOS_ERROR: %s\n", err_msg)
  82. error_h = ERRORFUNC(error_h)
  83. # #### GEOS Geometry C data structures, and utility functions. ####
  84. # Opaque GEOS geometry structures, used for GEOM_PTR and CS_PTR
  85. class GEOSGeom_t(Structure):
  86. pass
  87. class GEOSPrepGeom_t(Structure):
  88. pass
  89. class GEOSCoordSeq_t(Structure):
  90. pass
  91. class GEOSContextHandle_t(Structure):
  92. pass
  93. # Pointers to opaque GEOS geometry structures.
  94. GEOM_PTR = POINTER(GEOSGeom_t)
  95. PREPGEOM_PTR = POINTER(GEOSPrepGeom_t)
  96. CS_PTR = POINTER(GEOSCoordSeq_t)
  97. CONTEXT_PTR = POINTER(GEOSContextHandle_t)
  98. lgeos = SimpleLazyObject(load_geos)
  99. class GEOSFuncFactory:
  100. """
  101. Lazy loading of GEOS functions.
  102. """
  103. argtypes = None
  104. restype = None
  105. errcheck = None
  106. def __init__(self, func_name, *, restype=None, errcheck=None, argtypes=None):
  107. self.func_name = func_name
  108. if restype is not None:
  109. self.restype = restype
  110. if errcheck is not None:
  111. self.errcheck = errcheck
  112. if argtypes is not None:
  113. self.argtypes = argtypes
  114. def __call__(self, *args):
  115. return self.func(*args)
  116. @cached_property
  117. def func(self):
  118. from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
  119. func = GEOSFunc(self.func_name)
  120. func.argtypes = self.argtypes or []
  121. func.restype = self.restype
  122. if self.errcheck:
  123. func.errcheck = self.errcheck
  124. return func
  125. def geos_version():
  126. """Return the string version of the GEOS library."""
  127. return lgeos.GEOSversion()
  128. def geos_version_tuple():
  129. """Return the GEOS version as a tuple (major, minor, subminor)."""
  130. return get_version_tuple(geos_version().decode())