QGIS API Documentation  3.8.0-Zanzibar (11aff65)
qgsquickutils.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsquickutils.cpp
3  --------------------------------------
4  Date : Nov 2017
5  Copyright : (C) 2017 by Peter Petrik
6  Email : zilolv at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
16 #include <QApplication>
17 #include <QDesktopWidget>
18 #include <QString>
19 
20 #include "qgis.h"
22 #include "qgscoordinatetransform.h"
23 #include "qgsdistancearea.h"
24 #include "qgslogger.h"
25 #include "qgsvectorlayer.h"
26 #include "qgsfeature.h"
27 #include "qgsapplication.h"
29 
31 #include "qgsquickmapsettings.h"
32 #include "qgsquickutils.h"
33 #include "qgsunittypes.h"
34 
35 
36 QgsQuickUtils::QgsQuickUtils( QObject *parent )
37  : QObject( parent )
38  , mScreenDensity( calculateScreenDensity() )
39 {
40 }
41 
46 {
48 }
49 
50 QgsPointXY QgsQuickUtils::pointXY( double x, double y )
51 {
52  return QgsPointXY( x, y );
53 }
54 
55 QgsPoint QgsQuickUtils::point( double x, double y, double z, double m )
56 {
57  return QgsPoint( x, y, z, m );
58 }
59 
60 QgsPoint QgsQuickUtils::coordinateToPoint( const QGeoCoordinate &coor )
61 {
62  return QgsPoint( coor.longitude(), coor.latitude(), coor.altitude() );
63 }
64 
66  const QgsCoordinateReferenceSystem &destCrs,
67  const QgsCoordinateTransformContext &context,
68  const QgsPointXY &srcPoint )
69 {
70  QgsCoordinateTransform mTransform( srcCrs, destCrs, context );
71  QgsPointXY pt = mTransform.transform( srcPoint );
72  return pt;
73 }
74 
75 double QgsQuickUtils::screenUnitsToMeters( QgsQuickMapSettings *mapSettings, int baseLengthPixels )
76 {
77  if ( mapSettings == nullptr ) return 0.0;
78 
79  QgsDistanceArea mDistanceArea;
80  mDistanceArea.setEllipsoid( QStringLiteral( "WGS84" ) );
81  mDistanceArea.setSourceCrs( mapSettings->destinationCrs(), mapSettings->transformContext() );
82 
83  // calculate the geographic distance from the central point of extent
84  // to the specified number of points on the right side
85  QSize s = mapSettings->outputSize();
86  QPoint pointCenter( s.width() / 2, s.height() / 2 );
87  QgsPointXY p1 = mapSettings->screenToCoordinate( pointCenter );
88  QgsPointXY p2 = mapSettings->screenToCoordinate( pointCenter + QPoint( baseLengthPixels, 0 ) );
89  return mDistanceArea.measureLine( p1, p2 );
90 }
91 
92 bool QgsQuickUtils::fileExists( const QString &path )
93 {
94  QFileInfo check_file( path );
95  // check if file exists and if yes: Is it really a file and no directory?
96  return ( check_file.exists() && check_file.isFile() );
97 }
98 
99 QString QgsQuickUtils::getRelativePath( const QString &path, const QString &prefixPath )
100 {
101  QString resultPath = path;
102  QString prefixPathWithSlash;
103  if ( !prefixPath.endsWith( "/" ) )
104  prefixPathWithSlash = QStringLiteral( "%1/" ).arg( prefixPath );
105  else
106  prefixPathWithSlash = prefixPath;
107 
108  if ( resultPath.startsWith( prefixPathWithSlash ) )
109  return resultPath.replace( prefixPathWithSlash, QString() );
110  QString filePrefixPath = QStringLiteral( "file://%1" ).arg( prefixPathWithSlash );
111  if ( resultPath.startsWith( filePrefixPath ) )
112  return resultPath.replace( filePrefixPath, QString() );
113 
114  return QString();
115 }
116 
117 void QgsQuickUtils::logMessage( const QString &message, const QString &tag, Qgis::MessageLevel level )
118 {
119  QgsMessageLog::logMessage( message, tag, level );
120 }
121 
123 {
124  return QgsQuickFeatureLayerPair( feature, layer );
125 }
126 
127 const QUrl QgsQuickUtils::getThemeIcon( const QString &name )
128 {
129  QString path = QStringLiteral( "qrc:/%1.svg" ).arg( name );
130  QgsDebugMsg( QStringLiteral( "Using icon %1 from %2" ).arg( name, path ) );
131  return QUrl( path );
132 }
133 
134 const QUrl QgsQuickUtils::getEditorComponentSource( const QString &widgetName )
135 {
136  QString path( "qgsquick%1.qml" );
137  QStringList supportedWidgets = { QStringLiteral( "textedit" ),
138  QStringLiteral( "valuemap" ),
139  QStringLiteral( "valuerelation" ),
140  QStringLiteral( "checkbox" ),
141  QStringLiteral( "externalresource" ),
142  QStringLiteral( "datetime" )
143  };
144  if ( supportedWidgets.contains( widgetName ) )
145  {
146  return QUrl( path.arg( widgetName ) );
147  }
148  else
149  {
150  return QUrl( path.arg( QStringLiteral( "textedit" ) ) );
151  }
152 }
153 
155  const QgsPoint &point,
157  int decimals,
158  QgsCoordinateFormatter::FormatFlags flags )
159 {
160  return QgsCoordinateFormatter::format( point, format, decimals, flags );
161 }
162 
163 QString QgsQuickUtils::formatDistance( double distance,
165  int decimals,
167 {
168  double destDistance;
169  QgsUnitTypes::DistanceUnit destUnits;
170 
171  humanReadableDistance( distance, units, destSystem, destDistance, destUnits );
172 
173  return QStringLiteral( "%1 %2" )
174  .arg( QString::number( destDistance, 'f', decimals ) )
175  .arg( QgsUnitTypes::toAbbreviatedString( destUnits ) );
176 }
177 
178 bool QgsQuickUtils::removeFile( const QString &filePath )
179 {
180  QFile file( filePath );
181  return file.remove( filePath );
182 }
183 
184 
187  double &destDistance, QgsUnitTypes::DistanceUnit &destUnits )
188 {
189  if ( ( destSystem == QgsUnitTypes::MetricSystem ) || ( destSystem == QgsUnitTypes::UnknownSystem ) )
190  {
191  return formatToMetricDistance( srcDistance, srcUnits, destDistance, destUnits );
192  }
193  else if ( destSystem == QgsUnitTypes::ImperialSystem )
194  {
195  return formatToImperialDistance( srcDistance, srcUnits, destDistance, destUnits );
196  }
197  else if ( destSystem == QgsUnitTypes::USCSSystem )
198  {
199  return formatToUSCSDistance( srcDistance, srcUnits, destDistance, destUnits );
200  }
201  else
202  {
203  Q_ASSERT( false ); //should never happen
204  }
205 }
206 
207 void QgsQuickUtils::formatToMetricDistance( double srcDistance,
209  double &destDistance,
210  QgsUnitTypes::DistanceUnit &destUnits )
211 {
212  double dist = srcDistance * QgsUnitTypes::fromUnitToUnitFactor( srcUnits, QgsUnitTypes::DistanceMillimeters );
213  if ( dist < 0 )
214  {
215  destDistance = 0;
217  return;
218  }
219 
221  if ( dist > mmToKm )
222  {
223  destDistance = dist / mmToKm;
225  return;
226  }
227 
229  if ( dist > mmToM )
230  {
231  destDistance = dist / mmToM;
232  destUnits = QgsUnitTypes::DistanceMeters;
233  return;
234  }
235 
237  if ( dist > mmToCm )
238  {
239  destDistance = dist / mmToCm;
241  return;
242  }
243 
244  destDistance = dist;
246 }
247 
248 void QgsQuickUtils::formatToImperialDistance( double srcDistance,
250  double &destDistance,
251  QgsUnitTypes::DistanceUnit &destUnits )
252 {
253  double dist = srcDistance * QgsUnitTypes::fromUnitToUnitFactor( srcUnits, QgsUnitTypes::DistanceFeet );
254  if ( dist < 0 )
255  {
256  destDistance = 0;
257  destUnits = QgsUnitTypes::DistanceFeet;
258  return;
259  }
260 
262  if ( dist > feetToMile )
263  {
264  destDistance = dist / feetToMile;
265  destUnits = QgsUnitTypes::DistanceMiles;
266  return;
267  }
268 
270  if ( dist > feetToYard )
271  {
272  destDistance = dist / feetToYard;
273  destUnits = QgsUnitTypes::DistanceYards;
274  return;
275  }
276 
277  destDistance = dist;
278  destUnits = QgsUnitTypes::DistanceFeet;
279  return;
280 }
281 
282 void QgsQuickUtils::formatToUSCSDistance( double srcDistance,
284  double &destDistance,
285  QgsUnitTypes::DistanceUnit &destUnits )
286 {
287  double dist = srcDistance * QgsUnitTypes::fromUnitToUnitFactor( srcUnits, QgsUnitTypes::DistanceFeet );
288  if ( dist < 0 )
289  {
290  destDistance = 0;
291  destUnits = QgsUnitTypes::DistanceFeet;
292  return;
293  }
294 
296  if ( dist > feetToMile )
297  {
298  destDistance = dist / feetToMile;
300  return;
301  }
302 
304  if ( dist > feetToYard )
305  {
306  destDistance = dist / feetToYard;
307  destUnits = QgsUnitTypes::DistanceYards;
308  return;
309  }
310 
311  destDistance = dist;
312  destUnits = QgsUnitTypes::DistanceFeet;
313  return;
314 }
315 
317 {
318  QRect rec = QApplication::desktop()->screenGeometry();
319  int dpiX = QApplication::desktop()->physicalDpiX();
320  int dpiY = QApplication::desktop()->physicalDpiY();
321  int height = rec.height();
322  int width = rec.width();
323  double sizeX = static_cast<double>( width ) / dpiX * 25.4;
324  double sizeY = static_cast<double>( height ) / dpiY * 25.4;
325 
326  QString msg;
327  msg += tr( "screen resolution: %1x%2 px\n" ).arg( width ).arg( height );
328  msg += tr( "screen DPI: %1x%2\n" ).arg( dpiX ).arg( dpiY );
329  msg += tr( "screen size: %1x%2 mm\n" ).arg( QString::number( sizeX, 'f', 0 ), QString::number( sizeY, 'f', 0 ) );
330  msg += tr( "screen density: %1" ).arg( mScreenDensity );
331  return msg;
332 }
333 
334 QVariantMap QgsQuickUtils::createValueRelationCache( const QVariantMap &config, const QgsFeature &formFeature )
335 {
336  QVariantMap valueMap;
338 
339  for ( const QgsValueRelationFieldFormatter::ValueRelationItem &item : qgis::as_const( cache ) )
340  {
341  valueMap.insert( item.key.toString(), item.value );
342  }
343  return valueMap;
344 }
345 
347 {
348  return mScreenDensity;
349 }
350 
351 qreal QgsQuickUtils::calculateScreenDensity()
352 {
353  // calculate screen density for calculation of real pixel sizes from density-independent pixels
354  int dpiX = QApplication::desktop()->physicalDpiX();
355  int dpiY = QApplication::desktop()->physicalDpiY();
356  int dpi = dpiX < dpiY ? dpiX : dpiY; // In case of asymmetrical DPI. Improbable
357  return dpi / 160.; // 160 DPI is baseline for density-independent pixels in Android
358 }
static Q_INVOKABLE const QUrl getEditorComponentSource(const QString &widgetName)
Returns url to field editor component for a feature form.
static Q_INVOKABLE QgsPoint coordinateToPoint(const QGeoCoordinate &coor)
Converts QGeoCoordinate to QgsPoint.
SystemOfMeasurement
Systems of unit measurement.
Definition: qgsunittypes.h:44
static Q_INVOKABLE QgsCoordinateReferenceSystem coordinateReferenceSystemFromEpsgId(long epsg)
Creates crs from epsg code in QML.
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
QgsPointXY transform(const QgsPointXY &point, TransformDirection direction=ForwardTransform) const SIP_THROW(QgsCsException)
Transform the point from the source CRS to the destination CRS.
A class to represent a 2D point.
Definition: qgspointxy.h:43
static Q_INVOKABLE QgsPoint point(double x, double y, double z=std::numeric_limits< double >::quiet_NaN(), double m=std::numeric_limits< double >::quiet_NaN())
Creates QgsPoint in QML.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:55
MessageLevel
Level for messages This will be used both for message log and message bar in application.
Definition: qgis.h:66
The QgsQuickMapSettings class encapsulates QgsMapSettings class to offer settings of configuration of...
static Q_INVOKABLE double screenUnitsToMeters(QgsQuickMapSettings *mapSettings, int baseLengthPixels)
Calculates the distance in meter representing baseLengthPixels pixels on the screen based on the curr...
Format
Available formats for displaying coordinates.
QVector< QgsValueRelationFieldFormatter::ValueRelationItem > ValueRelationCache
static Q_INVOKABLE QString getRelativePath(const QString &path, const QString &prefixPath)
Returns relative path of the file to given prefixPath.
British Imperial.
Definition: qgsunittypes.h:48
qreal screenDensity() const
"dp" is useful for building building components that work well with different screen densities...
static Q_INVOKABLE QgsPointXY transformPoint(const QgsCoordinateReferenceSystem &srcCrs, const QgsCoordinateReferenceSystem &destCrs, const QgsCoordinateTransformContext &context, const QgsPointXY &srcPoint)
Transforms point between different crs from QML.
static Q_INVOKABLE QgsCoordinateReferenceSystem fromEpsgId(long epsg)
Creates a CRS from a given EPSG ID.
Q_INVOKABLE QgsPoint screenToCoordinate(const QPointF &point) const
Convert a screen coordinate to a map coordinate.
static Q_INVOKABLE QString toAbbreviatedString(QgsUnitTypes::DistanceUnit unit)
Returns a translated abbreviation representing a distance unit.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
Unknown system of measurement.
Definition: qgsunittypes.h:46
static void humanReadableDistance(double srcDistance, QgsUnitTypes::DistanceUnit srcUnits, QgsUnitTypes::SystemOfMeasurement destSystem, double &destDistance, QgsUnitTypes::DistanceUnit &destUnits)
Converts distance to human readable distance in destination system of measurement.
International System of Units (SI)
Definition: qgsunittypes.h:47
Contains information about the context in which a coordinate transform is executed.
static Q_INVOKABLE const QUrl getThemeIcon(const QString &name)
Returns QUrl to image from library&#39;s /images folder.
QgsQuickUtils(QObject *parent=nullptr)
Create new utilities.
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:37
QVariant createCache(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config) const override
Create a cache for a given field.
United States customary system.
Definition: qgsunittypes.h:49
DistanceUnit
Units of distance.
Definition: qgsunittypes.h:54
QgsCoordinateReferenceSystem destinationCrs
CRS of destination coordinate reference system.
QSize outputSize
The size of the resulting map image.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations...
This class represents a coordinate reference system (CRS).
Class for doing transforms between two map coordinate systems.
static Q_INVOKABLE bool removeFile(const QString &filePath)
Deletes file from a given path.
QString dumpScreenInfo() const
Returns a string with information about screen size and resolution - useful for debugging.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
static Q_INVOKABLE QString formatDistance(double distance, QgsUnitTypes::DistanceUnit units, int decimals, QgsUnitTypes::SystemOfMeasurement destSystem=QgsUnitTypes::MetricSystem)
Converts distance to human readable distance.
static Q_INVOKABLE QgsQuickFeatureLayerPair featureFactory(const QgsFeature &feature, QgsVectorLayer *layer=nullptr)
QgsQuickFeatureLayerPair factory for tuple of QgsFeature and QgsVectorLayer used in QgsQUick library...
Pair of QgsFeature and QgsVectorLayer.
static Q_INVOKABLE QgsPointXY pointXY(double x, double y)
Creates QgsPointXY in QML.
Terrestrial miles.
Definition: qgsunittypes.h:61
static Q_INVOKABLE QString formatPoint(const QgsPoint &point, QgsCoordinateFormatter::Format format=QgsCoordinateFormatter::FormatPair, int decimals=3, QgsCoordinateFormatter::FormatFlags flags=QgsCoordinateFormatter::FlagDegreesUseStringSuffix)
Formats a point according to the specified parameters.
static Q_INVOKABLE double fromUnitToUnitFactor(QgsUnitTypes::DistanceUnit fromUnit, QgsUnitTypes::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
Represents a vector layer which manages a vector based data sets.
Q_INVOKABLE QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
static Q_INVOKABLE bool fileExists(const QString &path)
Returns whether file on path exists.
double measureLine(const QVector< QgsPointXY > &points) const
Measures the length of a line with multiple segments.
static Q_INVOKABLE QVariantMap createValueRelationCache(const QVariantMap &config, const QgsFeature &formFeature=QgsFeature())
Creates a cache for a value relation field.
static Q_INVOKABLE void logMessage(const QString &message, const QString &tag=QString("QgsQuick"), Qgis::MessageLevel level=Qgis::Warning)
Log message in QgsMessageLog.
static QString format(const QgsPointXY &point, Format format, int precision=12, FormatFlags flags=FlagDegreesUseStringSuffix)
Formats a point according to the specified parameters.