29#include <QApplication>
30#include <QDesktopServices>
33#include <QHttpMultiPart>
34#include <QJsonDocument>
35#include <QMimeDatabase>
36#include <QNetworkRequest>
37#include <QTemporaryDir>
60#elif defined(Q_OS_MAC)
88void QgsAction::handleFormSubmitAction(
const QString &expandedAction )
const
92 QApplication::setOverrideCursor( Qt::WaitCursor );
94 QUrl url{ expandedAction };
97 const QString payload { url.query( QUrl::ComponentFormattingOption::FullyEncoded ).replace( QChar(
'+' ), u
"%2B"_s ) };
100 const QUrlQuery queryString { url.query( ) };
101 url.setQuery( QString( ) );
103 QNetworkRequest req { url };
107 if ( url.toString().contains(
"fake_qgis_http_endpoint"_L1 ) )
109 req.setUrl( u
"file://%1"_s.arg( url.path() ) );
112 QNetworkReply *reply =
nullptr;
116 QString contentType { u
"application/x-www-form-urlencoded"_s };
118 QJsonParseError jsonError;
119 QJsonDocument::fromJson( payload.toUtf8(), &jsonError );
120 if ( jsonError.error == QJsonParseError::ParseError::NoError )
122 contentType = u
"application/json"_s;
124 req.setHeader( QNetworkRequest::KnownHeaders::ContentTypeHeader, contentType );
130 QHttpMultiPart *multiPart =
new QHttpMultiPart( QHttpMultiPart::FormDataType );
131 const QList<QPair<QString, QString>> queryItems { queryString.queryItems( QUrl::ComponentFormattingOption::FullyDecoded ) };
132 for (
const QPair<QString, QString> &queryItem : std::as_const( queryItems ) )
135 part.setHeader( QNetworkRequest::ContentDispositionHeader,
136 u
"form-data; name=\"%1\""_s
137 .arg( QString( queryItem.first ).replace(
'"', R
"(\")"_L1 ) ) );
138 part.setBody( queryItem.second.toUtf8() );
139 multiPart->append( part );
142 multiPart->setParent( reply );
145 QObject::connect( reply, &QNetworkReply::finished, reply, [ reply ]
147 if ( reply->error() == QNetworkReply::NoError )
153 const QByteArray replyData = reply->readAll();
155 QString filename {
"download.bin" };
156 if (
const std::string header = reply->header( QNetworkRequest::KnownHeaders::ContentDispositionHeader ).toString().toStdString(); ! header.empty() )
163 const std::string q1 { R
"(filename=)" };
165 if (
size_t pos = header.find( q1 ); pos != std::string::npos )
169 if ( header.find( R
"(filename=")" ) != std::string::npos )
174 const size_t len = pos + q1.size();
176 const std::string q2 { R
"(")" };
177 if (
size_t pos = header.find( q2, len ); pos != std::string::npos )
179 bool escaped =
false;
180 while ( pos != std::string::npos && header[pos - 1] ==
'\\' )
182 pos = header.find( q2, pos + 1 );
185 ascii = header.substr( len, pos - len );
189 for (
size_t i = 0; i < ascii.size(); ++i )
191 if ( ascii[i] ==
'\\' )
193 if ( i > 0 && ascii[i - 1] ==
'\\' )
195 cleaned.push_back( ascii[i] );
200 cleaned.push_back( ascii[i] );
203 ascii = std::move( cleaned );
210 const std::string u { R
"(UTF-8'')" };
211 if (
const size_t pos = header.find( u ); pos != std::string::npos )
213 utf8 = header.substr( pos + u.size() );
219 if ( ! utf8.empty( ) )
221 filename = QString::fromStdString( utf8 );
226 filename = QString::fromStdString( ascii );
231 QString contentTypeHeader { reply->header( QNetworkRequest::KnownHeaders::ContentTypeHeader ).toString() };
233 if ( contentTypeHeader.contains(
';' ) )
235 contentTypeHeader = contentTypeHeader.left( contentTypeHeader.indexOf(
';' ) );
238 QMimeType mimeType { QMimeDatabase().mimeTypeForName( contentTypeHeader ) };
239 if ( mimeType.isValid() )
241 filename = u
"download.%1"_s.arg( mimeType.preferredSuffix() );
245 QTemporaryDir tempDir;
246 tempDir.setAutoRemove(
false );
248 const QString tempFilePath{ tempDir.path() + QDir::separator() + filename };
249 QFile tempFile{ tempFilePath };
250 if ( tempFile.open( QIODevice::WriteOnly ) )
252 tempFile.write( replyData );
254 QDesktopServices::openUrl( QUrl::fromLocalFile( tempFilePath ) );
270 reply->deleteLater();
271 QApplication::restoreOverrideCursor( );
278 mCommand = newCommand;
294 QApplication::setOverrideCursor( Qt::WaitCursor );
296 QApplication::restoreOverrideCursor();
300 const QFileInfo finfo( expandedAction );
301 if ( finfo.exists() && finfo.isFile() )
302 QDesktopServices::openUrl( QUrl::fromLocalFile( expandedAction ) );
304 QDesktopServices::openUrl( QUrl( expandedAction, QUrl::TolerantMode ) );
308 handleFormSubmitAction( expandedAction );
319#ifndef __clang_analyzer__
327 return mActionScopes;
337 QDomElement actionElement = actionNode.toElement();
338 const QDomNodeList actionScopeNodes = actionElement.elementsByTagName( u
"actionScope"_s );
340 if ( actionScopeNodes.isEmpty() )
349 for (
int j = 0; j < actionScopeNodes.length(); ++j )
351 const QDomElement actionScopeElem = actionScopeNodes.item( j ).toElement();
352 mActionScopes << actionScopeElem.attribute( u
"id"_s );
358 QgsDebugMsgLevel(
"context" + u
"project:layers:%1:actiondescriptions"_s.arg( context.
currentLayerId() ) +
" source " + actionElement.attributeNode( u
"name"_s ).value(), 3 );
359 mCommand = actionElement.attributeNode( u
"action"_s ).value();
360 mIcon = actionElement.attributeNode( u
"icon"_s ).value();
361 mCaptureOutput = actionElement.attributeNode( u
"capture"_s ).value().toInt() != 0;
363 QgsDebugMsgLevel(
"context" + u
"project:layers:%1:actionshorttitles"_s.arg( context.
currentLayerId() ) +
" source " + actionElement.attributeNode( u
"shortTitle"_s ).value(), 3 );
364 mNotificationMessage = actionElement.attributeNode( u
"notificationMessage"_s ).value();
365 mIsEnabledOnlyWhenEditable = actionElement.attributeNode( u
"isEnabledOnlyWhenEditable"_s ).value().toInt() != 0;
366 mId = QUuid( actionElement.attributeNode( u
"id"_s ).value() );
368 mId = QUuid::createUuid();
373 QDomElement actionSetting = actionsNode.ownerDocument().createElement( u
"actionsetting"_s );
374 actionSetting.setAttribute( u
"type"_s,
static_cast< int >( mType ) );
375 actionSetting.setAttribute( u
"name"_s, mDescription );
376 actionSetting.setAttribute( u
"shortTitle"_s, mShortTitle );
377 actionSetting.setAttribute( u
"icon"_s, mIcon );
378 actionSetting.setAttribute( u
"action"_s, mCommand );
379 actionSetting.setAttribute( u
"capture"_s, mCaptureOutput );
380 actionSetting.setAttribute( u
"notificationMessage"_s, mNotificationMessage );
381 actionSetting.setAttribute( u
"isEnabledOnlyWhenEditable"_s, mIsEnabledOnlyWhenEditable );
382 actionSetting.setAttribute( u
"id"_s, mId.toString() );
384 const auto constMActionScopes = mActionScopes;
385 for (
const QString &scope : constMActionScopes )
387 QDomElement actionScopeElem = actionsNode.ownerDocument().createElement( u
"actionScope"_s );
388 actionScopeElem.setAttribute( u
"id"_s, scope );
389 actionSetting.appendChild( actionScopeElem );
392 actionsNode.appendChild( actionSetting );
397 mExpressionContextScope = scope;
402 return mExpressionContextScope;
412 typeText = QObject::tr(
"Generic" );
417 typeText = QObject::tr(
"Generic Python" );
422 typeText = QObject::tr(
"macOS" );
427 typeText = QObject::tr(
"Windows" );
432 typeText = QObject::tr(
"Unix" );
437 typeText = QObject::tr(
"Open URL" );
442 typeText = QObject::tr(
"Submit URL (urlencoded or JSON)" );
447 typeText = QObject::tr(
"Submit URL (multipart)" );
451 return { QObject::tr( R
"html(
452<h2>Action Details</h2>
454 <b>Description:</b> %1<br>
455 <b>Short title:</b> %2<br>
461 )html" ).arg( mDescription, mShortTitle, typeText, actionScopes().values().join( ", "_L1 ), mCommand )};
AttributeActionType
Attribute action types.
@ OpenUrl
Open URL action.
@ SubmitUrlMultipart
POST data to an URL using "multipart/form-data".
@ Windows
Windows specific.
@ SubmitUrlEncoded
POST data to an URL, using "application/x-www-form-urlencoded" or "application/json" if the body is v...
@ Critical
Critical/error message.
QSet< QString > actionScopes() const
The action scopes define where an action will be available.
void run(QgsVectorLayer *layer, const QgsFeature &feature, const QgsExpressionContext &expressionContext) const
Run this action.
void setCommand(const QString &newCommand)
Sets the action command.
bool runable() const
Checks if the action is runable on the current platform.
bool isValid() const
Returns true if this action was a default constructed one.
void readXml(const QDomNode &actionNode, const QgsReadWriteContext &context=QgsReadWriteContext())
Reads an XML definition from actionNode into this object.
void setExpressionContextScope(const QgsExpressionContextScope &scope)
Sets an expression context scope to use for running the action.
QString html() const
Returns an HTML table with the basic information about this action.
void writeXml(QDomNode &actionsNode) const
Appends an XML definition for this action as a new child node to actionsNode.
QgsExpressionContextScope expressionContextScope() const
Returns an expression context scope used for running the action.
void setActionScopes(const QSet< QString > &actionScopes)
The action scopes define where an action will be available.
Single scope for storing variables and functions for use within a QgsExpressionContext.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
static QString replaceExpressionText(const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea=nullptr)
This function replaces each expression between [% and %] in the string with the result of its evaluat...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
virtual QString translate(const QString &context, const QString &sourceText, const char *disambiguation=nullptr, int n=-1) const =0
Translates a string using the Qt QTranslator mechanism.
static bool run(const QString &command, const QString &messageOnError=QString())
Execute a Python statement.
A container for the context for various read/write operations on objects.
const QgsProjectTranslator * projectTranslator() const
Returns the project translator.
const QString currentLayerId() const
Returns the currently used layer id as string.
static QgsRunProcess * create(const QString &action, bool capture)
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based dataset.
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)