QGIS API Documentation  3.13.0-Master (b73bd58cfb)
qgis.h
Go to the documentation of this file.
1 /***************************************************************************
2  qgis.h - QGIS namespace
3  -------------------
4  begin : Sat Jun 30 2002
5  copyright : (C) 2002 by Gary E.Sherman
6  email : sherman at mrcc.com
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
18 #ifndef QGIS_H
19 #define QGIS_H
20 
21 #include <QMetaEnum>
22 #include <cfloat>
23 #include <memory>
24 #include <cmath>
25 
26 #include "qgstolerance.h"
27 #include "qgis_core.h"
28 #include "qgis_sip.h"
29 
30 #ifdef SIP_RUN
31 % ModuleHeaderCode
32 #include <qgis.h>
33 % End
34 
35 % ModuleCode
36 int QgisEvent = QEvent::User + 1;
37 % End
38 #endif
39 
40 
45 class CORE_EXPORT Qgis
46 {
47  Q_GADGET
48  public:
49 
55  static QString version();
56 
62  static int versionInt();
63 
69  static QString releaseName();
70 
72  static const char *QGIS_DEV_VERSION;
73 
79  static QString devVersion();
80 
81  // Enumerations
82  //
83 
89  {
90  Info = 0,
91  Warning = 1,
92  Critical = 2,
93  Success = 3,
94  None = 4
95  };
96 
101  enum DataType
102  {
103  UnknownDataType = 0,
104  Byte = 1,
105  UInt16 = 2,
106  Int16 = 3,
107  UInt32 = 4,
108  Int32 = 5,
109  Float32 = 6,
110  Float64 = 7,
111  CInt16 = 8,
112  CInt32 = 9,
113  CFloat32 = 10,
114  CFloat64 = 11,
115  ARGB32 = 12,
116  ARGB32_Premultiplied = 13
117  };
118 
124  {
125  Never = 0,
126  Ask = 1,
127  SessionOnly = 2,
128  Always = 3,
130  };
131  Q_ENUM( PythonMacroMode )
132 
133 
137  static const double DEFAULT_SEARCH_RADIUS_MM;
138 
140  static const float DEFAULT_MAPTOPIXEL_THRESHOLD;
141 
148  static const QColor DEFAULT_HIGHLIGHT_COLOR;
149 
154  static const double DEFAULT_HIGHLIGHT_BUFFER_MM;
155 
160  static const double DEFAULT_HIGHLIGHT_MIN_WIDTH_MM;
161 
168  static const double SCALE_PRECISION;
169 
175  static const double DEFAULT_Z_COORDINATE;
176 
182  static const double UI_SCALE_FACTOR;
183 
188  static const double DEFAULT_SNAP_TOLERANCE;
189 
194  static const QgsTolerance::UnitType DEFAULT_SNAP_UNITS;
195 
201  static QString defaultProjectScales();
202 };
203 
204 // hack to workaround warnings when casting void pointers
205 // retrieved from QLibrary::resolve to function pointers.
206 // It's assumed that this works on all systems supporting
207 // QLibrary
208 #define cast_to_fptr(f) f
209 
210 
219 // based on Boojum's code from http://stackoverflow.com/questions/3556687/prevent-firing-signals-in-qt
220 template<class Object> class QgsSignalBlocker SIP_SKIP SIP_SKIP // clazy:exclude=rule-of-three
221 {
222  public:
223 
228  explicit QgsSignalBlocker( Object *object )
229  : mObject( object )
230  , mPreviousState( object->blockSignals( true ) )
231  {}
232 
234  {
235  mObject->blockSignals( mPreviousState );
236  }
237 
239  Object *operator->() { return mObject; }
240 
241  private:
242 
243  Object *mObject = nullptr;
244  bool mPreviousState;
245 
246 };
247 
261 // based on Boojum's code from http://stackoverflow.com/questions/3556687/prevent-firing-signals-in-qt
262 template<class Object> inline QgsSignalBlocker<Object> whileBlocking( Object *object ) SIP_SKIP SIP_SKIP
263 {
264  return QgsSignalBlocker<Object>( object );
265 }
266 
268 CORE_EXPORT uint qHash( const QVariant &variant );
269 
275 inline QString qgsDoubleToString( double a, int precision = 17 )
276 {
277  if ( precision )
278  {
279  QString str = QString::number( a, 'f', precision );
280  if ( str.contains( QLatin1Char( '.' ) ) )
281  {
282  // remove ending 0s
283  int idx = str.length() - 1;
284  while ( str.at( idx ) == '0' && idx > 1 )
285  {
286  idx--;
287  }
288  if ( idx < str.length() - 1 )
289  str.truncate( str.at( idx ) == '.' ? idx : idx + 1 );
290  }
291  return str;
292  }
293  else
294  {
295  // avoid printing -0
296  // see https://bugreports.qt.io/browse/QTBUG-71439
297  const QString str( QString::number( a, 'f', precision ) );
298  if ( str == QLatin1String( "-0" ) )
299  {
300  return QLatin1String( "0" );
301  }
302  else
303  {
304  return str;
305  }
306  }
307 }
308 
315 inline bool qgsDoubleNear( double a, double b, double epsilon = 4 * std::numeric_limits<double>::epsilon() )
316 {
317  if ( std::isnan( a ) || std::isnan( b ) )
318  return std::isnan( a ) && std::isnan( b ) ;
319 
320  const double diff = a - b;
321  return diff > -epsilon && diff <= epsilon;
322 }
323 
330 inline bool qgsFloatNear( float a, float b, float epsilon = 4 * FLT_EPSILON )
331 {
332  if ( std::isnan( a ) || std::isnan( b ) )
333  return std::isnan( a ) && std::isnan( b ) ;
334 
335  const float diff = a - b;
336  return diff > -epsilon && diff <= epsilon;
337 }
338 
340 inline bool qgsDoubleNearSig( double a, double b, int significantDigits = 10 )
341 {
342  if ( std::isnan( a ) || std::isnan( b ) )
343  return std::isnan( a ) && std::isnan( b ) ;
344 
345  // The most simple would be to print numbers as %.xe and compare as strings
346  // but that is probably too costly
347  // Then the fastest would be to set some bits directly, but little/big endian
348  // has to be considered (maybe TODO)
349  // Is there a better way?
350  int aexp, bexp;
351  double ar = std::frexp( a, &aexp );
352  double br = std::frexp( b, &bexp );
353 
354  return aexp == bexp &&
355  std::round( ar * std::pow( 10.0, significantDigits ) ) == std::round( br * std::pow( 10.0, significantDigits ) );
356 }
357 
363 inline double qgsRound( double number, int places )
364 {
365  double m = ( number < 0.0 ) ? -1.0 : 1.0;
366  double scaleFactor = std::pow( 10.0, places );
367  return ( std::round( number * m * scaleFactor ) / scaleFactor ) * m;
368 }
369 
370 
371 #ifndef SIP_RUN
372 
374 
384 namespace qgis
385 {
386  // as_const
387 
396  template <typename T> struct QgsAddConst { typedef const T Type; };
397 
398  template <typename T>
399  constexpr typename QgsAddConst<T>::Type &as_const( T &t ) noexcept { return t; }
400 
401  template <typename T>
402  void as_const( const T && ) = delete;
403 
404  // make_unique - from https://stackoverflow.com/a/17902439/1861260
405 
406  template<class T> struct _Unique_if
407  {
408  typedef std::unique_ptr<T> _Single_object;
409  };
410 
411  template<class T> struct _Unique_if<T[]>
412  {
413  typedef std::unique_ptr<T[]> _Unknown_bound;
414  };
415 
416  template<class T, size_t N> struct _Unique_if<T[N]>
417  {
418  typedef void _Known_bound;
419  };
420 
421  template<class T, class... Args>
422  typename _Unique_if<T>::_Single_object
423  make_unique( Args &&... args )
424  {
425  return std::unique_ptr<T>( new T( std::forward<Args>( args )... ) );
426  }
427 
428  template<class T>
429  typename _Unique_if<T>::_Unknown_bound
430  make_unique( size_t n )
431  {
432  typedef typename std::remove_extent<T>::type U;
433  return std::unique_ptr<T>( new U[n]() );
434  }
435 
436  template<class T, class... Args>
437  typename _Unique_if<T>::_Known_bound
438  make_unique( Args &&... ) = delete;
439 
452  template<typename... Args> struct overload
453  {
454  template<typename C, typename R>
455  static constexpr auto of( R( C::*pmf )( Args... ) ) -> decltype( pmf )
456  {
457  return pmf;
458  }
459  };
460 }
462 #endif
463 
469 template<class T> const QMap<T, QString> qgsEnumMap() SIP_SKIP
470 {
471  QMetaEnum metaEnum = QMetaEnum::fromType<T>();
472  Q_ASSERT( metaEnum.isValid() );
473  QMap<T, QString> enumMap;
474  for ( int idx = 0; idx < metaEnum.keyCount(); ++idx )
475  {
476  const char *enumKey = metaEnum.key( idx );
477  enumMap.insert( static_cast<T>( metaEnum.keyToValue( enumKey ) ), QString( enumKey ) );
478  }
479  return enumMap;
480 }
481 
486 template<class T> QString qgsEnumValueToKey( const T &value ) SIP_SKIP
487 {
488  QMetaEnum metaEnum = QMetaEnum::fromType<T>();
489  Q_ASSERT( metaEnum.isValid() );
490  return QString::fromUtf8( metaEnum.valueToKey( static_cast<int>( value ) ) );
491 }
492 
498 template<class T> T qgsEnumKeyToValue( const QString &key, const T &defaultValue ) SIP_SKIP
499 {
500  QMetaEnum metaEnum = QMetaEnum::fromType<T>();
501  Q_ASSERT( metaEnum.isValid() );
502  bool ok = false;
503  T v = static_cast<T>( metaEnum.keyToValue( key.toUtf8().data(), &ok ) );
504  if ( ok )
505  return v;
506  else
507  return defaultValue;
508 }
509 
510 
520 CORE_EXPORT double qgsPermissiveToDouble( QString string, bool &ok );
521 
531 CORE_EXPORT int qgsPermissiveToInt( QString string, bool &ok );
532 
542 CORE_EXPORT qlonglong qgsPermissiveToLongLong( QString string, bool &ok );
543 
553 CORE_EXPORT bool qgsVariantLessThan( const QVariant &lhs, const QVariant &rhs );
554 
563 CORE_EXPORT bool qgsVariantEqual( const QVariant &lhs, const QVariant &rhs );
564 
565 
572 CORE_EXPORT bool qgsVariantGreaterThan( const QVariant &lhs, const QVariant &rhs );
573 
577 template<> CORE_EXPORT bool qMapLessThanKey<QVariantList>( const QVariantList &key1, const QVariantList &key2 ) SIP_SKIP;
578 
579 
580 CORE_EXPORT QString qgsVsiPrefix( const QString &path );
581 
587 void CORE_EXPORT *qgsMalloc( size_t size ) SIP_SKIP;
588 
596 void CORE_EXPORT *qgsCalloc( size_t nmemb, size_t size ) SIP_SKIP;
597 
602 void CORE_EXPORT qgsFree( void *ptr ) SIP_SKIP;
603 
604 #ifndef SIP_RUN
605 
606 #ifdef _MSC_VER
607 #define CONSTLATIN1STRING inline const QLatin1String
608 #else
609 #define CONSTLATIN1STRING constexpr QLatin1String
610 #endif
611 
617 {
618 #if PROJ_VERSION_MAJOR>=6
619  return QLatin1String(
620  R"""(GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["geodetic latitude (Lat)",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["geodetic longitude (Lon)",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],USAGE[SCOPE["unknown"],AREA["World"],BBOX[-90,-180,90,180]],ID["EPSG",4326]] )"""
621  );
622 #else
623  return QLatin1String(
624  "GEOGCS[\"WGS 84\", "
625  " DATUM[\"WGS_1984\", "
626  " SPHEROID[\"WGS 84\",6378137,298.257223563, "
627  " AUTHORITY[\"EPSG\",\"7030\"]], "
628  " TOWGS84[0,0,0,0,0,0,0], "
629  " AUTHORITY[\"EPSG\",\"6326\"]], "
630  " PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]], "
631  " UNIT[\"DMSH\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9108\"]], "
632  " AXIS[\"Lat\",NORTH], "
633  " AXIS[\"Long\",EAST], "
634  " AUTHORITY[\"EPSG\",\"4326\"]]"
635  );
636 #endif
637 }
638 
641 {
642  return QLatin1String( "+proj=longlat +datum=WGS84 +no_defs" );
643 }
644 
647 {
648  return QLatin1String( "EPSG:4326" );
649 }
650 
653 {
654  return QLatin1String( "NONE" );
655 }
656 
658 
660 const int PREVIEW_JOB_DELAY_MS = 250;
661 
663 const int MAXIMUM_LAYER_PREVIEW_TIME_MS = 250;
664 
666 
667 #endif
668 
670 const long GEOSRID = 4326;
671 
673 const long GEOCRS_ID = 3452;
674 
676 const long GEO_EPSG_CRS_ID = 4326;
677 
681 const int USER_CRS_START_ID = 100000;
682 
683 //
684 // Constants for point symbols
685 //
686 
688 const double DEFAULT_POINT_SIZE = 2.0;
689 const double DEFAULT_LINE_WIDTH = 0.26;
690 
692 const double DEFAULT_SEGMENT_EPSILON = 1e-8;
693 
694 typedef QMap<QString, QString> QgsStringMap SIP_SKIP;
695 
703 typedef unsigned long long qgssize;
704 
705 #ifndef SIP_RUN
706 #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) || defined(__clang__)
707 
708 #define Q_NOWARN_DEPRECATED_PUSH \
709  _Pragma("GCC diagnostic push") \
710  _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"");
711 #define Q_NOWARN_DEPRECATED_POP \
712  _Pragma("GCC diagnostic pop");
713 #define Q_NOWARN_UNREACHABLE_PUSH
714 #define Q_NOWARN_UNREACHABLE_POP
715 
716 #elif defined(_MSC_VER)
717 
718 #define Q_NOWARN_DEPRECATED_PUSH \
719  __pragma(warning(push)) \
720  __pragma(warning(disable:4996))
721 #define Q_NOWARN_DEPRECATED_POP \
722  __pragma(warning(pop))
723 #define Q_NOWARN_UNREACHABLE_PUSH \
724  __pragma(warning(push)) \
725  __pragma(warning(disable:4702))
726 #define Q_NOWARN_UNREACHABLE_POP \
727  __pragma(warning(pop))
728 
729 #else
730 
731 #define Q_NOWARN_DEPRECATED_PUSH
732 #define Q_NOWARN_DEPRECATED_POP
733 #define Q_NOWARN_UNREACHABLE_PUSH
734 #define Q_NOWARN_UNREACHABLE_POP
735 
736 #endif
737 #endif
738 
739 #ifndef QGISEXTERN
740 #ifdef Q_OS_WIN
741 # define QGISEXTERN extern "C" __declspec( dllexport )
742 # ifdef _MSC_VER
743 // do not warn about C bindings returning QString
744 # pragma warning(disable:4190)
745 # endif
746 #else
747 # if defined(__GNUC__) || defined(__clang__)
748 # define QGISEXTERN extern "C" __attribute__ ((visibility ("default")))
749 # else
750 # define QGISEXTERN extern "C"
751 # endif
752 #endif
753 #endif
754 #endif
755 
756 #if __cplusplus >= 201500
757 #define FALLTHROUGH [[fallthrough]];
758 #elif defined(__clang__)
759 #define FALLTHROUGH [[clang::fallthrough]];
760 #elif defined(__GNUC__) && __GNUC__ >= 7
761 #define FALLTHROUGH [[gnu::fallthrough]];
762 #else
763 #define FALLTHROUGH
764 #endif
765 
766 // see https://infektor.net/posts/2017-01-19-using-cpp17-attributes-today.html#using-the-nodiscard-attribute
767 #if __cplusplus >= 201703L
768 #define NODISCARD [[nodiscard]]
769 #elif defined(__clang__)
770 #define NODISCARD [[nodiscard]]
771 #elif defined(_MSC_VER)
772 #define NODISCARD // no support
773 #elif defined(__has_cpp_attribute)
774 #if __has_cpp_attribute(nodiscard)
775 #define NODISCARD [[nodiscard]]
776 #elif __has_cpp_attribute(gnu::warn_unused_result)
777 #define NODISCARD [[gnu::warn_unused_result]]
778 #else
779 #define NODISCARD Q_REQUIRED_RESULT
780 #endif
781 #else
782 #define NODISCARD Q_REQUIRED_RESULT
783 #endif
784 
785 #if __cplusplus >= 201703L
786 #define MAYBE_UNUSED [[maybe_unused]]
787 #elif defined(__clang__)
788 #define MAYBE_UNUSED [[maybe_unused]]
789 #elif defined(_MSC_VER)
790 #define MAYBE_UNUSED // no support
791 #elif defined(__has_cpp_attribute)
792 #if __has_cpp_attribute(gnu::unused)
793 #define MAYBE_UNUSED [[gnu::unused]]
794 #else
795 #define MAYBE_UNUSED
796 #endif
797 #else
798 #define MAYBE_UNUSED
799 #endif
800 
801 #ifndef FINAL
802 #define FINAL final
803 #endif
804 
805 #ifdef SIP_RUN
806 
811 QString CORE_EXPORT geoWkt();
812 
814 QString CORE_EXPORT geoProj4();
815 
817 QString CORE_EXPORT geoEpsgCrsAuthId();
818 
820 QString CORE_EXPORT geoNone();
821 
822 #endif
CORE_EXPORT QString qgsVsiPrefix(const QString &path)
Definition: qgis.cpp:194
int precision
static const char * QGIS_DEV_VERSION
The development version.
Definition: qgis.h:72
bool qgsFloatNear(float a, float b, float epsilon=4 *FLT_EPSILON)
Compare two floats (but allow some difference)
Definition: qgis.h:330
CORE_EXPORT bool qgsVariantEqual(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether they are equal, two NULL values are always treated a...
Definition: qgis.cpp:265
QString qgsEnumValueToKey(const T &value)
Returns the value for the given key of an enum.
Definition: qgis.h:486
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:315
CONSTLATIN1STRING geoWkt()
Wkt string that represents a geographic coord sys.
Definition: qgis.h:616
CONSTLATIN1STRING geoNone()
Constant that holds the string representation for "No ellips/No CRS".
Definition: qgis.h:652
DataType
Raster data types.
Definition: qgis.h:101
void CORE_EXPORT * qgsCalloc(size_t nmemb, size_t size)
Allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the alloc...
Definition: qgis.cpp:101
MessageLevel
Level for messages This will be used both for message log and message bar in application.
Definition: qgis.h:88
QMap< QString, QString > QgsStringMap
Definition: qgis.h:694
~QgsSignalBlocker()
Definition: qgis.h:233
The Qgis class provides global constants for use throughout the application.
Definition: qgis.h:45
CORE_EXPORT bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
Definition: qgis.cpp:121
CORE_EXPORT bool qMapLessThanKey< QVariantList >(const QVariantList &key1, const QVariantList &key2)
Compares two QVariantList values and returns whether the first is less than the second.
Definition: qgis.cpp:299
QgsSignalBlocker(Object *object)
Constructor for QgsSignalBlocker.
Definition: qgis.h:228
#define CONSTLATIN1STRING
Definition: qgis.h:609
T qgsEnumKeyToValue(const QString &key, const T &defaultValue)
Returns the value corresponding to the given key of an enum.
Definition: qgis.h:498
const double DEFAULT_SEGMENT_EPSILON
Default snapping tolerance for segments.
Definition: qgis.h:692
Macros will not be run for this session.
Definition: qgis.h:129
#define SIP_SKIP
Definition: qgis_sip.h:126
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition: qgis.h:275
This is the class is providing tolerance value in map unit values.
Definition: qgstolerance.h:32
const long GEOCRS_ID
Magic number for a geographic coord sys in QGIS srs.db tbl_srs.srs_id.
Definition: qgis.h:673
CORE_EXPORT double qgsPermissiveToDouble(QString string, bool &ok)
Converts a string to a double in a permissive way, e.g., allowing for incorrect numbers of digits bet...
Definition: qgis.cpp:65
RAII signal blocking class.
Definition: qgis.h:220
void CORE_EXPORT qgsFree(void *ptr)
Frees the memory space pointed to by ptr.
Definition: qgis.cpp:116
CORE_EXPORT qlonglong qgsPermissiveToLongLong(QString string, bool &ok)
Converts a string to an qlonglong in a permissive way, e.g., allowing for incorrect numbers of digits...
Definition: qgis.cpp:79
unsigned long long qgssize
Qgssize is used instead of size_t, because size_t is stdlib type, unknown by SIP, and it would be har...
Definition: qgis.h:703
const double DEFAULT_POINT_SIZE
Magic number that determines the default point size for point symbols.
Definition: qgis.h:688
CONSTLATIN1STRING geoProj4()
PROJ4 string that represents a geographic coord sys.
Definition: qgis.h:640
const int USER_CRS_START_ID
Magick number that determines whether a projection crsid is a system (srs.db) or user (~/...
Definition: qgis.h:681
const QMap< T, QString > qgsEnumMap()
Returns a map of all enum entries.
Definition: qgis.h:469
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
Definition: qgis.h:262
const long GEOSRID
Magic number for a geographic coord sys in POSTGIS SRID.
Definition: qgis.h:670
double qgsRound(double number, int places)
Returns a double number, rounded (as close as possible) to the specified number of places...
Definition: qgis.h:363
bool qgsDoubleNearSig(double a, double b, int significantDigits=10)
Compare two doubles using specified number of significant digits.
Definition: qgis.h:340
const double DEFAULT_LINE_WIDTH
Definition: qgis.h:689
PythonMacroMode
Authorisation to run Python Macros.
Definition: qgis.h:123
CORE_EXPORT uint qHash(const QVariant &variant)
Hash for QVariant.
Definition: qgis.cpp:219
CORE_EXPORT int qgsPermissiveToInt(QString string, bool &ok)
Converts a string to an integer in a permissive way, e.g., allowing for incorrect numbers of digits b...
Definition: qgis.cpp:72
CONSTLATIN1STRING geoEpsgCrsAuthId()
Geographic coord sys from EPSG authority.
Definition: qgis.h:646
CORE_EXPORT bool qgsVariantGreaterThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is greater than the second.
Definition: qgis.cpp:189
void CORE_EXPORT * qgsMalloc(size_t size)
Allocates size bytes and returns a pointer to the allocated memory.
Definition: qgis.cpp:86
Object * operator->()
Returns pointer to blocked QObject.
Definition: qgis.h:239
const long GEO_EPSG_CRS_ID
Magic number for a geographic coord sys in EpsgCrsId ID format.
Definition: qgis.h:676