QGIS API Documentation 3.99.0-Master (2fe06baccd8)
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
27#include "qgsaction.h"
28#include "qgsdataprovider.h"
29#include "qgsexpression.h"
31#include "qgslogger.h"
32#include "qgsproject.h"
33#include "qgsrunprocess.h"
34#include "qgsvectorlayer.h"
35
36#include <QDesktopServices>
37#include <QDomElement>
38#include <QFileInfo>
39#include <QList>
40#include <QRegularExpression>
41#include <QSettings>
42#include <QStringList>
43#include <QUrl>
44
45#include "moc_qgsactionmanager.cpp"
46
50
51QUuid QgsActionManager::addAction( Qgis::AttributeActionType type, const QString &name, const QString &command, bool capture )
52{
53 QgsAction action( type, name, command, capture );
55 return action.id();
56}
57
58QUuid QgsActionManager::addAction( Qgis::AttributeActionType type, const QString &name, const QString &command, const QString &icon, bool capture )
59{
60 QgsAction action( type, name, command, icon, capture );
62 return action.id();
63}
64
66{
67 QgsDebugMsgLevel( "add action " + action.name(), 3 );
68 mActions.append( action );
69 if ( mLayer && mLayer->dataProvider() && !action.notificationMessage().isEmpty() )
70 {
71 mLayer->dataProvider()->setListening( true );
72 if ( !mOnNotifyConnected )
73 {
74 QgsDebugMsgLevel( QStringLiteral( "connecting to notify" ), 3 );
75 connect( mLayer->dataProvider(), &QgsDataProvider::notify, this, &QgsActionManager::onNotifyRunActions );
76 mOnNotifyConnected = true;
77 }
78 }
79}
80
81void QgsActionManager::onNotifyRunActions( const QString &message )
82{
83 for ( const QgsAction &act : std::as_const( mActions ) )
84 {
85 if ( !act.notificationMessage().isEmpty() && QRegularExpression( act.notificationMessage() ).match( message ).hasMatch() )
86 {
87 if ( !act.isValid() || !act.runable() )
88 continue;
89
90 QgsExpressionContext context = createExpressionContext();
91
92 Q_ASSERT( mLayer ); // if there is no layer, then where is the notification coming from ?
93 context << QgsExpressionContextUtils::layerScope( mLayer );
95
96 QString expandedAction = QgsExpression::replaceExpressionText( act.command(), &context );
97 if ( expandedAction.isEmpty() )
98 continue;
99 runAction( QgsAction( act.type(), act.name(), expandedAction, act.capture() ) );
100 }
101 }
102}
103
104void QgsActionManager::removeAction( QUuid actionId )
105{
106 int i = 0;
107 for ( const QgsAction &action : std::as_const( mActions ) )
108 {
109 if ( action.id() == actionId )
110 {
111 mActions.removeAt( i );
112 break;
113 }
114 ++i;
115 }
116
117 if ( mOnNotifyConnected )
118 {
119 bool hasActionOnNotify = false;
120 for ( const QgsAction &action : std::as_const( mActions ) )
121 hasActionOnNotify |= !action.notificationMessage().isEmpty();
122 if ( !hasActionOnNotify && mLayer && mLayer->dataProvider() )
123 {
124 // note that there is no way of knowing if the provider is listening only because
125 // this class has hasked it to, so we do not reset the provider listening state here
126 disconnect( mLayer->dataProvider(), &QgsDataProvider::notify, this, &QgsActionManager::onNotifyRunActions );
127 mOnNotifyConnected = false;
128 }
129 }
130}
131
132void QgsActionManager::doAction( QUuid actionId, const QgsFeature &feature, int defaultValueIndex, const QgsExpressionContextScope &scope )
133{
134 QgsExpressionContext context = createExpressionContext();
135 QgsExpressionContextScope *actionScope = new QgsExpressionContextScope( scope );
136 actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_index" ), defaultValueIndex, true ) );
137 if ( defaultValueIndex >= 0 && defaultValueIndex < feature.fields().size() )
138 actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_name" ), feature.fields().at( defaultValueIndex ).name(), true ) );
139 actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_value" ), feature.attribute( defaultValueIndex ), true ) );
140 context << actionScope;
141 doAction( actionId, feature, context );
142}
143
144void QgsActionManager::doAction( QUuid actionId, const QgsFeature &feat, const QgsExpressionContext &context )
145{
146 QgsAction act = action( actionId );
147
148 if ( !act.isValid() || !act.runable() )
149 return;
150
151 QgsExpressionContext actionContext( context );
152
153 if ( mLayer )
154 actionContext << QgsExpressionContextUtils::layerScope( mLayer );
155 actionContext.setFeature( feat );
156
157 QString expandedAction = QgsExpression::replaceExpressionText( act.command(), &actionContext );
158 if ( expandedAction.isEmpty() )
159 return;
160
161 QgsAction newAction( act.type(), act.name(), expandedAction, act.capture() );
162 runAction( newAction );
163}
164
166{
167 mActions.clear();
168 if ( mOnNotifyConnected && mLayer && mLayer->dataProvider() )
169 {
170 // note that there is no way of knowing if the provider is listening only because
171 // this class has hasked it to, so we do not reset the provider listening state here
172 disconnect( mLayer->dataProvider(), &QgsDataProvider::notify, this, &QgsActionManager::onNotifyRunActions );
173 mOnNotifyConnected = false;
174 }
175}
176
177QList<QgsAction> QgsActionManager::actions( const QString &actionScope ) const
178{
179 if ( actionScope.isNull() )
180 return mActions;
181 else
182 {
183 QList<QgsAction> actions;
184
185 for ( const QgsAction &action : std::as_const( mActions ) )
186 {
187 if ( action.actionScopes().contains( actionScope ) )
188 actions.append( action );
189 }
190
191 return actions;
192 }
193}
194
195void QgsActionManager::runAction( const QgsAction &action )
196{
197 switch ( action.type() )
198 {
200 {
201 QFileInfo finfo( action.command() );
202 if ( finfo.exists() && finfo.isFile() )
203 QDesktopServices::openUrl( QUrl::fromLocalFile( action.command() ) );
204 else
205 QDesktopServices::openUrl( QUrl( action.command(), QUrl::TolerantMode ) );
206 break;
207 }
211 {
212 action.run( QgsExpressionContext() );
213 break;
214 }
219 {
220 // The QgsRunProcess instance created by this static function
221 // deletes itself when no longer needed.
222 QgsRunProcess::create( action.command(), action.capture() );
223 break;
224 }
225 }
226}
227
228QgsExpressionContext QgsActionManager::createExpressionContext() const
229{
230 QgsExpressionContext context;
233 if ( mLayer )
234 context << QgsExpressionContextUtils::layerScope( mLayer );
235
236 return context;
237}
238
239bool QgsActionManager::writeXml( QDomNode &layer_node ) const
240{
241 QDomElement aActions = layer_node.ownerDocument().createElement( QStringLiteral( "attributeactions" ) );
242 for ( QMap<QString, QUuid>::const_iterator defaultAction = mDefaultActions.constBegin(); defaultAction != mDefaultActions.constEnd(); ++ defaultAction )
243 {
244 QDomElement defaultActionElement = layer_node.ownerDocument().createElement( QStringLiteral( "defaultAction" ) );
245 defaultActionElement.setAttribute( QStringLiteral( "key" ), defaultAction.key() );
246 defaultActionElement.setAttribute( QStringLiteral( "value" ), defaultAction.value().toString() );
247 aActions.appendChild( defaultActionElement );
248 }
249
250 for ( const QgsAction &action : std::as_const( mActions ) )
251 {
252 action.writeXml( aActions );
253 }
254 layer_node.appendChild( aActions );
255
256 return true;
257}
258
259bool QgsActionManager::readXml( const QDomNode &layer_node )
260{
261 clearActions();
262
263 QDomNode aaNode = layer_node.namedItem( QStringLiteral( "attributeactions" ) );
264
265 if ( !aaNode.isNull() )
266 {
267 QDomNodeList actionsettings = aaNode.toElement().elementsByTagName( QStringLiteral( "actionsetting" ) );
268 for ( int i = 0; i < actionsettings.size(); ++i )
269 {
271 action.readXml( actionsettings.item( i ) );
272 addAction( action );
273 }
274
275 QDomNodeList defaultActionNodes = aaNode.toElement().elementsByTagName( QStringLiteral( "defaultAction" ) );
276
277 for ( int i = 0; i < defaultActionNodes.size(); ++i )
278 {
279 QDomElement defaultValueElem = defaultActionNodes.at( i ).toElement();
280 mDefaultActions.insert( defaultValueElem.attribute( QStringLiteral( "key" ) ), QUuid( defaultValueElem.attribute( QStringLiteral( "value" ) ) ) );
281 }
282 }
283 return true;
284}
285
287{
288 for ( const QgsAction &action : std::as_const( mActions ) )
289 {
290 if ( action.id() == id )
291 return action;
292 }
293
294 return QgsAction();
295}
296
297QgsAction QgsActionManager::action( const QString &id ) const
298{
299 for ( const QgsAction &action : std::as_const( mActions ) )
300 {
301 if ( action.id().toString() == id )
302 return action;
303 }
304
305 return QgsAction();
306}
307
308void QgsActionManager::setDefaultAction( const QString &actionScope, QUuid actionId )
309{
310 mDefaultActions[ actionScope ] = actionId;
311}
312
313QgsAction QgsActionManager::defaultAction( const QString &actionScope )
314{
315 return action( mDefaultActions.value( actionScope ) );
316}
AttributeActionType
Attribute action types.
Definition qgis.h:4675
@ Mac
MacOS specific.
Definition qgis.h:4678
@ OpenUrl
Open URL action.
Definition qgis.h:4681
@ Unix
Unix specific.
Definition qgis.h:4680
@ SubmitUrlMultipart
POST data to an URL using "multipart/form-data".
Definition qgis.h:4683
@ Windows
Windows specific.
Definition qgis.h:4679
@ SubmitUrlEncoded
POST data to an URL, using "application/x-www-form-urlencoded" or "application/json" if the body is v...
Definition qgis.h:4682
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.
QgsVectorLayer * layer() const
Returns the layer.
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 name() const
The name of the action. This may be a longer description.
Definition qgsaction.h:115
Qgis::AttributeActionType type() const
The action type.
Definition qgsaction.h:153
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 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:63
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 dataset.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:61
Single variable definition for use within a QgsExpressionContextScope.