QGIS API Documentation 3.41.0-Master (3440c17df1d)
Loading...
Searching...
No Matches
qgsactionmanager.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsactionmanager.cpp
3
4 A class that stores and controls the management and execution of actions
5 associated. Actions are defined to be external programs that are run
6 with user-specified inputs that can depend on the value of layer
7 attributes.
8
9 -------------------
10 begin : Oct 24 2004
11 copyright : (C) 2004 by Gavin Macaulay
12 email : gavin at macaulay dot co dot nz
13
14 ***************************************************************************/
15
16/***************************************************************************
17 * *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
22 * *
23 ***************************************************************************/
24
25#include "qgsactionmanager.h"
26#include "moc_qgsactionmanager.cpp"
27#include "qgsrunprocess.h"
28#include "qgsvectorlayer.h"
29#include "qgsproject.h"
30#include "qgslogger.h"
31#include "qgsexpression.h"
32#include "qgsdataprovider.h"
34#include "qgsaction.h"
35
36#include <QList>
37#include <QStringList>
38#include <QDomElement>
39#include <QSettings>
40#include <QDesktopServices>
41#include <QUrl>
42#include <QFileInfo>
43#include <QRegularExpression>
44
46 : mLayer( layer )
47{}
48
49QUuid QgsActionManager::addAction( Qgis::AttributeActionType type, const QString &name, const QString &command, bool capture )
50{
51 QgsAction action( type, name, command, capture );
53 return action.id();
54}
55
56QUuid QgsActionManager::addAction( Qgis::AttributeActionType type, const QString &name, const QString &command, const QString &icon, bool capture )
57{
58 QgsAction action( type, name, command, icon, capture );
60 return action.id();
61}
62
64{
65 QgsDebugMsgLevel( "add action " + action.name(), 3 );
66 mActions.append( action );
67 if ( mLayer && mLayer->dataProvider() && !action.notificationMessage().isEmpty() )
68 {
69 mLayer->dataProvider()->setListening( true );
70 if ( !mOnNotifyConnected )
71 {
72 QgsDebugMsgLevel( QStringLiteral( "connecting to notify" ), 3 );
73 connect( mLayer->dataProvider(), &QgsDataProvider::notify, this, &QgsActionManager::onNotifyRunActions );
74 mOnNotifyConnected = true;
75 }
76 }
77}
78
79void QgsActionManager::onNotifyRunActions( const QString &message )
80{
81 for ( const QgsAction &act : std::as_const( mActions ) )
82 {
83 if ( !act.notificationMessage().isEmpty() && QRegularExpression( act.notificationMessage() ).match( message ).hasMatch() )
84 {
85 if ( !act.isValid() || !act.runable() )
86 continue;
87
88 QgsExpressionContext context = createExpressionContext();
89
90 Q_ASSERT( mLayer ); // if there is no layer, then where is the notification coming from ?
91 context << QgsExpressionContextUtils::layerScope( mLayer );
93
94 QString expandedAction = QgsExpression::replaceExpressionText( act.command(), &context );
95 if ( expandedAction.isEmpty() )
96 continue;
97 runAction( QgsAction( act.type(), act.name(), expandedAction, act.capture() ) );
98 }
99 }
100}
101
102void QgsActionManager::removeAction( QUuid actionId )
103{
104 int i = 0;
105 for ( const QgsAction &action : std::as_const( mActions ) )
106 {
107 if ( action.id() == actionId )
108 {
109 mActions.removeAt( i );
110 break;
111 }
112 ++i;
113 }
114
115 if ( mOnNotifyConnected )
116 {
117 bool hasActionOnNotify = false;
118 for ( const QgsAction &action : std::as_const( mActions ) )
119 hasActionOnNotify |= !action.notificationMessage().isEmpty();
120 if ( !hasActionOnNotify && mLayer && mLayer->dataProvider() )
121 {
122 // note that there is no way of knowing if the provider is listening only because
123 // this class has hasked it to, so we do not reset the provider listening state here
124 disconnect( mLayer->dataProvider(), &QgsDataProvider::notify, this, &QgsActionManager::onNotifyRunActions );
125 mOnNotifyConnected = false;
126 }
127 }
128}
129
130void QgsActionManager::doAction( QUuid actionId, const QgsFeature &feature, int defaultValueIndex, const QgsExpressionContextScope &scope )
131{
132 QgsExpressionContext context = createExpressionContext();
133 QgsExpressionContextScope *actionScope = new QgsExpressionContextScope( scope );
134 actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_index" ), defaultValueIndex, true ) );
135 if ( defaultValueIndex >= 0 && defaultValueIndex < feature.fields().size() )
136 actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_name" ), feature.fields().at( defaultValueIndex ).name(), true ) );
137 actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_value" ), feature.attribute( defaultValueIndex ), true ) );
138 context << actionScope;
139 doAction( actionId, feature, context );
140}
141
142void QgsActionManager::doAction( QUuid actionId, const QgsFeature &feat, const QgsExpressionContext &context )
143{
144 QgsAction act = action( actionId );
145
146 if ( !act.isValid() || !act.runable() )
147 return;
148
149 QgsExpressionContext actionContext( context );
150
151 if ( mLayer )
152 actionContext << QgsExpressionContextUtils::layerScope( mLayer );
153 actionContext.setFeature( feat );
154
155 QString expandedAction = QgsExpression::replaceExpressionText( act.command(), &actionContext );
156 if ( expandedAction.isEmpty() )
157 return;
158
159 QgsAction newAction( act.type(), act.name(), expandedAction, act.capture() );
160 runAction( newAction );
161}
162
164{
165 mActions.clear();
166 if ( mOnNotifyConnected && mLayer && mLayer->dataProvider() )
167 {
168 // note that there is no way of knowing if the provider is listening only because
169 // this class has hasked it to, so we do not reset the provider listening state here
170 disconnect( mLayer->dataProvider(), &QgsDataProvider::notify, this, &QgsActionManager::onNotifyRunActions );
171 mOnNotifyConnected = false;
172 }
173}
174
175QList<QgsAction> QgsActionManager::actions( const QString &actionScope ) const
176{
177 if ( actionScope.isNull() )
178 return mActions;
179 else
180 {
181 QList<QgsAction> actions;
182
183 for ( const QgsAction &action : std::as_const( mActions ) )
184 {
185 if ( action.actionScopes().contains( actionScope ) )
186 actions.append( action );
187 }
188
189 return actions;
190 }
191}
192
193void QgsActionManager::runAction( const QgsAction &action )
194{
195 switch ( action.type() )
196 {
198 {
199 QFileInfo finfo( action.command() );
200 if ( finfo.exists() && finfo.isFile() )
201 QDesktopServices::openUrl( QUrl::fromLocalFile( action.command() ) );
202 else
203 QDesktopServices::openUrl( QUrl( action.command(), QUrl::TolerantMode ) );
204 break;
205 }
209 {
211 break;
212 }
217 {
218 // The QgsRunProcess instance created by this static function
219 // deletes itself when no longer needed.
221 break;
222 }
223 }
224}
225
226QgsExpressionContext QgsActionManager::createExpressionContext() const
227{
228 QgsExpressionContext context;
231 if ( mLayer )
232 context << QgsExpressionContextUtils::layerScope( mLayer );
233
234 return context;
235}
236
237bool QgsActionManager::writeXml( QDomNode &layer_node ) const
238{
239 QDomElement aActions = layer_node.ownerDocument().createElement( QStringLiteral( "attributeactions" ) );
240 for ( QMap<QString, QUuid>::const_iterator defaultAction = mDefaultActions.constBegin(); defaultAction != mDefaultActions.constEnd(); ++ defaultAction )
241 {
242 QDomElement defaultActionElement = layer_node.ownerDocument().createElement( QStringLiteral( "defaultAction" ) );
243 defaultActionElement.setAttribute( QStringLiteral( "key" ), defaultAction.key() );
244 defaultActionElement.setAttribute( QStringLiteral( "value" ), defaultAction.value().toString() );
245 aActions.appendChild( defaultActionElement );
246 }
247
248 for ( const QgsAction &action : std::as_const( mActions ) )
249 {
250 action.writeXml( aActions );
251 }
252 layer_node.appendChild( aActions );
253
254 return true;
255}
256
257bool QgsActionManager::readXml( const QDomNode &layer_node )
258{
259 clearActions();
260
261 QDomNode aaNode = layer_node.namedItem( QStringLiteral( "attributeactions" ) );
262
263 if ( !aaNode.isNull() )
264 {
265 QDomNodeList actionsettings = aaNode.toElement().elementsByTagName( QStringLiteral( "actionsetting" ) );
266 for ( int i = 0; i < actionsettings.size(); ++i )
267 {
269 action.readXml( actionsettings.item( i ) );
270 addAction( action );
271 }
272
273 QDomNodeList defaultActionNodes = aaNode.toElement().elementsByTagName( QStringLiteral( "defaultAction" ) );
274
275 for ( int i = 0; i < defaultActionNodes.size(); ++i )
276 {
277 QDomElement defaultValueElem = defaultActionNodes.at( i ).toElement();
278 mDefaultActions.insert( defaultValueElem.attribute( QStringLiteral( "key" ) ), QUuid( defaultValueElem.attribute( QStringLiteral( "value" ) ) ) );
279 }
280 }
281 return true;
282}
283
285{
286 for ( const QgsAction &action : std::as_const( mActions ) )
287 {
288 if ( action.id() == id )
289 return action;
290 }
291
292 return QgsAction();
293}
294
295QgsAction QgsActionManager::action( const QString &id ) const
296{
297 for ( const QgsAction &action : std::as_const( mActions ) )
298 {
299 if ( action.id().toString() == id )
300 return action;
301 }
302
303 return QgsAction();
304}
305
306void QgsActionManager::setDefaultAction( const QString &actionScope, QUuid actionId )
307{
308 mDefaultActions[ actionScope ] = actionId;
309}
310
311QgsAction QgsActionManager::defaultAction( const QString &actionScope )
312{
313 return action( mDefaultActions.value( actionScope ) );
314}
AttributeActionType
Attribute action types.
Definition qgis.h:4339
@ Mac
MacOS specific.
@ 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...
void removeAction(QUuid actionId)
Remove an action by its id.
bool writeXml(QDomNode &layer_node) const
Writes the actions out in XML format.
QList< QgsAction > actions(const QString &actionScope=QString()) const
Returns a list of actions that are available in the given action scope.
void doAction(QUuid actionId, const QgsFeature &feature, int defaultValueIndex=0, const QgsExpressionContextScope &scope=QgsExpressionContextScope())
Does the given action.
void clearActions()
Removes all actions.
QUuid addAction(Qgis::AttributeActionType type, const QString &name, const QString &command, bool capture=false)
Add an action with the given name and action details.
void setDefaultAction(const QString &actionScope, QUuid actionId)
Each scope can have a default action.
QgsActionManager(QgsVectorLayer *layer)
Constructor.
QgsAction defaultAction(const QString &actionScope)
Each scope can have a default action.
bool readXml(const QDomNode &layer_node)
Reads the actions in in XML format.
QgsAction action(QUuid id) const
Gets an action by its id.
Utility class that encapsulates an action based on vector attributes.
Definition qgsaction.h:37
QString notificationMessage() const
Returns the notification message that triggers the action.
Definition qgsaction.h:150
QString name() const
The name of the action. This may be a longer description.
Definition qgsaction.h:115
QSet< QString > actionScopes() const
The action scopes define where an action will be available.
Qgis::AttributeActionType type() const
The action type.
Definition qgsaction.h:153
void readXml(const QDomNode &actionNode)
Reads an XML definition from actionNode into this object.
void run(QgsVectorLayer *layer, const QgsFeature &feature, const QgsExpressionContext &expressionContext) const
Run this action.
Definition qgsaction.cpp:78
bool runable() const
Checks if the action is runable on the current platform.
Definition qgsaction.cpp:41
bool isValid() const
Returns true if this action was a default constructed one.
Definition qgsaction.h:130
QString command() const
Returns the command that is executed by this action.
Definition qgsaction.h:144
bool capture() const
Whether to capture output for display when this action is run.
Definition qgsaction.h:156
void writeXml(QDomNode &actionsNode) const
Appends an XML definition for this action as a new child node to actionsNode.
QUuid id() const
Returns a unique id for this action.
Definition qgsaction.h:124
virtual void setListening(bool isListening)
Set whether the provider will listen to datasource notifications If set, the provider will issue noti...
void notify(const QString &msg)
Emitted when the datasource issues a notification.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
static QgsExpressionContextScope * notificationScope(const QString &message=QString())
Creates a new scope which contains variables and functions relating to provider notifications.
static QgsExpressionContextScope * projectScope(const QgsProject *project)
Creates a new scope which contains variables and functions relating to a QGIS project.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context.
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...
Definition qgsfeature.h:58
QgsFields fields
Definition qgsfeature.h:68
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
QString name
Definition qgsfield.h:62
int size() const
Returns number of items.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
static QgsProject * instance()
Returns the QgsProject singleton instance.
static QgsRunProcess * create(const QString &action, bool capture)
Represents a vector layer which manages a vector based data sets.
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39
Single variable definition for use within a QgsExpressionContextScope.