Skip to content

Commit

Permalink
Startup - expressions (#132)
Browse files Browse the repository at this point in the history
* Startup - expressions

* Fixing

* updating

* Polishing

* Update metadata.txt
  • Loading branch information
havatv authored May 16, 2020
1 parent 8e7cd46 commit c8f88d8
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 2 deletions.
3 changes: 2 additions & 1 deletion metadata.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ author=Akbar Gumbira, Håvard Tveite
qgisMinimumVersion=3.0
description=Download shared collections
about=Search for published collections and install them for use with QGIS. Symbology (SVG, images, styles), Processing scripts, Processing models and R scripts are supported. There are several options for repositories: Github, Bitbucket, local file system and HTTP(S).
version=0.14.1
version=0.15.0
tracker=https://github.com/QGIS-Contribution/QGIS-ResourceSharing/issues
repository=https://github.com/QGIS-Contribution/QGIS-ResourceSharing.git

Expand All @@ -17,6 +17,7 @@ experimental=False
deprecated=False
icon=resources/icon.png
changelog=
0.15.0 - Support expressions (#130). Switch to Python pathlib.
0.14.1 - Also support QGIS 3.4 (avoid install of style labelsettings and textformatting for v. < 3.10 - #127)
- Try another way to avoid [WinError 5] on Microsoft Windows (#103)
0.14.0 - Style import improvements (fix colorramp support, add support for label settings and text formats, clean up Style Manager tags) (#113, #114, #116, #118)
Expand Down
7 changes: 7 additions & 0 deletions resource_sharing/collection_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ def get_html(self, collection_id):
if config.COLLECTIONS[collection_id]['models'] > 1:
html = html + 's'
resource_types = resource_types + 1
if 'expressions' in config.COLLECTIONS[collection_id].keys():
if resource_types > 0:
html = html + ', '
html = html + str(config.COLLECTIONS[collection_id]['expressions']) + ' Expression (JSON) file'
if config.COLLECTIONS[collection_id]['expressions'] > 1:
html = html + 's'
resource_types = resource_types + 1
if 'processing' in config.COLLECTIONS[collection_id].keys():
if resource_types > 0:
html = html + ', '
Expand Down
1 change: 1 addition & 0 deletions resource_sharing/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
'preview': ['preview/image1.png', 'preview/image2.png']
# Additional entries (for resource statistics):
'models': count of models in the collection,
'expressions': count of expression files in the collection,
'processing': count of processing scripts in the collection,
'rscripts': count of R scripts in the collection,
'style': count of layer styles (QML) in the collection,
Expand Down
5 changes: 5 additions & 0 deletions resource_sharing/gui/resource_sharing_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,11 @@ def install_finished(self):
message = message + '\n<li> ' + str(number) + ' model'
if number > 1:
message = message + 's'
if 'expressions' in config.COLLECTIONS[self._selected_collection_id].keys():
number = config.COLLECTIONS[self._selected_collection_id]['expressions']
message = message + '\n<li> ' + str(config.COLLECTIONS[self._selected_collection_id]['expressions']) + ' expression file'
if number > 1:
message = message + 's'
if 'processing' in config.COLLECTIONS[self._selected_collection_id].keys():
number = config.COLLECTIONS[self._selected_collection_id]['processing']
message = message + '\n<li> ' + str(number) + ' processing script'
Expand Down
2 changes: 1 addition & 1 deletion resource_sharing/repository_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ def edit_directory(
collection['status'] = COLLECTION_INSTALLED_STATUS
# Keep the collection statistics
for key in installed_collection.keys():
if key in ['models', 'processing', 'rscripts', 'style', 'svg', 'symbol']:
if key in ['models', 'processing', 'rscripts', 'style', 'svg', 'symbol', 'expressions']:
collection[key] = installed_collection[key]

else:
Expand Down
1 change: 1 addition & 0 deletions resource_sharing/resource_handler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
from .style_handler import StyleResourceHandler
from .r_handler import RScriptHandler
from .model_handler import ModelHandler
from .expression_handler import ExpressionHandler
129 changes: 129 additions & 0 deletions resource_sharing/resource_handler/expression_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# coding=utf-8
from pathlib import Path
import json
import logging

from qgis.core import QgsSettings
try:
from qgis.core import Qgis
except ImportError:
from qgis.core import QGis as Qgis

from resource_sharing.resource_handler.base import BaseResourceHandler
from resource_sharing.utilities import (user_expressions_group, repo_settings_group, qgis_version)

hasExprBuilder = False
#try:
# from qgis.core import QgsExpressions

try:
from qgis.gui import QgsExpressionBuilderWidget
except:
hasExprBuilder = False
else:
hasExprBuilder = True

LOGGER = logging.getLogger('QGIS Resource Sharing')
EXPRESSIONS = 'expressions'

class ExpressionHandler(BaseResourceHandler):
"""Concrete class of the Expression handler."""
IS_DISABLED = False

def __init__(self, collection_id):
"""Constructor of the base class."""
BaseResourceHandler.__init__(self, collection_id)
# Initialize with the QGIS settings????

@classmethod
def dir_name(self):
return EXPRESSIONS

def install(self):
"""Add the expressions from this collection to QGIS settings.
"""
LOGGER.info("Installing expressions")
#return
# Skip installation if the directory does not exist
if not Path(self.resource_dir).exists():
return

# Uninstall first (in case it is a reinstall)
#self.uninstall()

# Get all the expressions in the collection
json_files = []
valid = 0
for item in Path(self.resource_dir).glob('*'):
if item.suffix.lower().endswith("json"):
file_path = Path(self.resource_dir, item)
json_files.append(file_path)
# If there are no json files, there is nothing to do
if len(json_files) == 0:
return
settings = QgsSettings()
settings.beginGroup(user_expressions_group())
for json_file in json_files:
namePrefix = json_file.stem + '_'
LOGGER.info("Installing expressions from " + str(json_file))

with open(json_file, 'rb') as expr_file:
expr_json = expr_file.read()
jsontext = json.loads(expr_json)

#QgsExpressionBuilderWidget loadExpressionsFromJson

expressions = jsontext['expressions']
for expr in expressions:
expr_name = namePrefix + expr['name']
LOGGER.info("Expr. name: " + expr_name)
expr_value =expr['expression']
LOGGER.info("Expr. expression: " + expr_value)
expr_help = expr['description']
LOGGER.info("Expr. description: " + expr_help)

settings.setValue(expr_name + '/expression', expr_value)
settings.setValue(expr_name + '/helpText', expr_help)
aftervalue = settings.value(expr_name + '/expression', '', type=unicode).strip()
LOGGER.info("after - expr: " + aftervalue)
valid += 1
settings.endGroup()
if valid >= 0:
self.collection[EXPRESSIONS] = valid

def uninstall(self):
"""Remove the expressions in this collection from QGIS settings.
"""

# Remove from settings
LOGGER.info("Removing expressions")
# Skip removal if the directory does not exist
if not Path(self.resource_dir).exists():
return
# Get all the expressions in the collection
json_files = []
for item in Path(self.resource_dir).glob('*'):
if item.suffix.lower().endswith("json"):
file_path = Path(self.resource_dir, item)
json_files.append(file_path)
# If there are no json files, there is nothing to do
if len(json_files) == 0:
return
settings = QgsSettings()
settings.beginGroup(user_expressions_group())
for json_file in json_files:
namePrefix = json_file.stem + '_'
LOGGER.info("Removing expressions from " + str(json_file))
with open(json_file, 'rb') as expr_file:
expr_json = expr_file.read()
jsontext = json.loads(expr_json)
expressions = jsontext['expressions']
for expr in expressions:
expr_name = namePrefix + expr['name']
LOGGER.info("Expr. name: " + expr_name)
if settings.contains(expr_name + '/expression'):
LOGGER.info("Exists - removing")
settings.remove(expr_name)
settings.endGroup()
# Remove files - nothing to remove

5 changes: 5 additions & 0 deletions resource_sharing/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ def ui_path(*args):
return path


def user_expressions_group():
"""Get the user expressions group."""
return '/expressions/user'


def repo_settings_group():
"""Get the settings group for Resource Sharing Dialog."""
return '/ResourceSharing/repository'
Expand Down

0 comments on commit c8f88d8

Please sign in to comment.