Skip to content

Commit

Permalink
Adapted to qgis3
Browse files Browse the repository at this point in the history
  • Loading branch information
volaya committed Dec 20, 2018
1 parent bd78401 commit 536ba2a
Show file tree
Hide file tree
Showing 11 changed files with 167 additions and 259 deletions.
2 changes: 0 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ env:
- secure: kwkGudPxVTnr0Tq1qivJ03+31W/uq9962m468mtSMPcKjc/mKZE3Oq1T8NGuZ2oBL4i7dFU2BciXutt8zBF/PU6Xrz4Z/HeIK7S3Vt8blLlZDKvubtb+xoEBtXgvp01ta08sNru9oknN1Orkm7XUBBiFfbkISVp3h08cDXzVNwVw/5SdsTFuyh341lOU5YLwFAk/Aj0pvAbgKBKpiFGvBhCHAPkSuPL1bc3/Aj/Wr7s2bGShWcwD0bKQDck931hEhJhZwfZJRE15VuWDo5uBRIlEqONeZ69jWcBQcApgjETFcaOWStSMUvwe+M7om8IrkQfAYh1+wvgmqF1LII22aNBwTxRzRGQm3bpL8R6iKedNh+0n3yzTDqZ1h5S14lFzfRBEFWDrfNgEUSTXfisIbXfcdtjETG0QTUpc1LZ0DuipHPD5TYjNcF582WjRLiQYgXrgPTl8CtZqbZf+8th/uZ5tFte0WPNawHtJoN3DEfsCF4KIikH1sXkY9h8enDQgaxhdT5vb5GFI2wLCD+ovDrORByozERTwzYiQY47a0vzzwKOL7dXZgB7RVHm4nWEg6P/ze/kB2q7hIvsl9SL553I6z3f9+9xr4xjesb0rKXzm5Up24FfQvLRn7BQKUWjknvBiVENWKRF8UgpgkDrgcCFLxeWqZVptEruwv92kFlY=
- secure: jJJGWt6oEgUMNT1w9qqc7HONy1KQVLGfQ/WOAOV0VdXirtPRXflUJAFUDFw98fYVJyi3cgJgM9bAg1yyvX2UXkoh4I6/KiotU+Tz55Ifj/z2oaGoHfbUI3HTjXNdErUC0lZzQ6ugLw1dUf6RRl8TBL859iENcE1/qb1/0huKM1r4ewaKMNsZGDtlUa2igXFOB+G8ZBZrs2bMyo+OiQUdsx7j9EHMgbRsd78fiYypUo8RiRtydP2fN1YEq9mrAysVsLqIuFOmDdVzTGNF6XycJStos6kUhh5HpKmrja70eIjFO4OlAOI8lwI4Iv4O38l7KUnPNLntWw0YkO6KnLCeSteShP6ZOsrohAnvU0y/EqIKIEobJUfxBthW8Zm+KguoTqjLEVy6GuR99gAl33AkzpOW8RwHLQqqWJegcfEk6hfgKlE46FuXv3rukLrG3ieNH6H9IdvVfFok6MtuEziVX5bt0p4gCLmTXicyBTGEf/skED8r3Zw7KW/svx7wEAmem1bD3l/jUpbtOaooVl4QV4N9YeOl7liZRufyFge6BG/DfokQb5Hl46MsEJLFKY5YTiTc+OK9dVK6bhojSBQLGZvleExDmJtGufsmgsDhZfrAXmBJsF1LpzPYdrcyeEkd/a4YCWyvfNPZep2yvKrYrOHVMUcP+b61ljVz/8nlK0o=
matrix:
- QGIS_VERSION_TAG=release PYTHON_EXECUTABLE=python PIP_EXECUTABLE=pip
- QGIS_VERSION_TAG=master_2 PYTHON_EXECUTABLE=python PIP_EXECUTABLE=pip
- QGIS_VERSION_TAG=master PYTHON_EXECUTABLE=python3 PIP_EXECUTABLE=pip3
matrix:
allow_failures:
Expand Down
192 changes: 51 additions & 141 deletions pavement.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@


@task
def setup():
def setup(options):
"""Install run-time dependencies"""
clean = getattr(options, 'clean', False)
ext_libs = options.plugin.ext_libs
Expand All @@ -48,23 +48,29 @@ def setup():
ext_libs.makedirs()

runtime, test = read_requirements()
os.environ['PYTHONPATH'] = ext_libs.abspath()
os.environ['PYTHONPATH']=ext_libs.abspath()
for req in runtime + test:
sh('easy_install -a -d %(ext_libs)s %(dep)s' % {
'ext_libs': ext_libs.abspath(),
'dep': req
sh('pip3 install -U -t %(ext_libs)s %(dep)s' % {
'ext_libs' : ext_libs.abspath(),
'dep' : req
})


def _install(folder, options):
@task
def install(options):
'''install plugin to qgis'''
builddocs(options)
plugin_name = options.plugin.name
src = path(__file__).dirname() / plugin_name
dst = path('~').expanduser() / folder / 'python' / 'plugins' / plugin_name
if os.name == 'nt':
dst = path('~/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins').expanduser() / plugin_name
elif sys.platform == 'darwin':
dst = path(' ~/Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins').expanduser() / plugin_name
else:
dst = path('~/.local/share/QGIS/QGIS3/profiles/default/python/plugins').expanduser() / plugin_name
print("Destination folder for plugin: " + str(dst))
src = src.abspath()
dst = dst.abspath()
if not hasattr(os, 'symlink'):
if os.name == 'nt':
dst.rmtree()
src.copytree(dst)
elif not dst.exists():
Expand All @@ -78,30 +84,20 @@ def _install(folder, options):
if not docs_link.islink():
docs.symlink(docs_link)

@task
def install(options):
_install(".qgis2", options)

@task
def installdev(options):
_install(".qgis-dev", options)

@task
def install3(options):
_install(".qgis3", options)
def read_requirements():
"""Return a list of runtime and list of test requirements"""
lines = path('requirements.txt').lines()
lines = [ l for l in [ l.strip() for l in lines] if l ]
divider = '# test requirements'

@task
def install_devtools():
"""Install development tools
"""
try:
import pip
except:
error('FATAL: Unable to import pip, please install it first!')
sys.exit(1)

pip.main(['install', '-r', 'requirements-dev.txt'])
idx = lines.index(divider)
except ValueError:
raise BuildFailure(
'Expected to find "%s" in requirements.txt' % divider)

not_comments = lambda s,e: [ l for l in lines[s:e] if l[0] != '#']
return not_comments(0, idx), not_comments(idx+1, None)

@task
@cmdopts([
Expand All @@ -118,90 +114,33 @@ def package(options):
_make_zip(zf, options)
return package_file

def _make_zip(zipFile, options):
excludes = set(options.plugin.excludes)
skips = options.plugin.skip_exclude

@task
@consume_args
def pep8(args):
"""Check code for PEP8 violations
"""
try:
import pep8
except:
error('pep8 not found! Run "paver install_devtools".')
sys.exit(1)

# Errors to ignore
ignore = ['E203', 'E121', 'E122', 'E123', 'E124', 'E125', 'E126', 'E127',
'E128', 'E402']
styleguide = pep8.StyleGuide(ignore=ignore,
exclude=['*/extlibs/*', '*/ext-src/*'],
repeat=True, max_line_length=79,
parse_argv=args)
styleguide.input_dir(options.plugin.source_dir)
info('===== PEP8 SUMMARY =====')
styleguide.options.report.print_statistics()


@task
@consume_args
def autopep8(args):
"""Format code according to PEP8
"""
try:
import autopep8
except:
error('autopep8 not found! Run "paver install_devtools".')
sys.exit(1)

if any(x not in args for x in ['-i', '--in-place']):
args.append('-i')

args.append('--ignore=E261,E265,E402,E501')
args.insert(0, 'dummy')

cmd_args = autopep8.parse_args(args)

excludes = ('ext-lib', 'ext-src')
for p in options.plugin.source_dir.walk():
if any(exclude in p for exclude in excludes):
continue

if p.fnmatch('*.py'):
autopep8.fix_file(p, options=cmd_args)


def read_requirements():
"""Return a list of runtime and list of test requirements"""
lines = path('requirements.txt').lines()
lines = [ l for l in [ l.strip() for l in lines] if l ]
divider = '# test requirements'

try:
idx = lines.index(divider)
except ValueError:
raise BuildFailure(
'Expected to find "%s" in requirements.txt' % divider)

not_comments = lambda s,e: [ l for l in lines[s:e] if l[0] != '#']
return not_comments(0, idx), not_comments(idx+1, None)


@task
@consume_args
def pylint(args):
"""Check code for errors and coding standard violations
"""
try:
from pylint import lint
except:
error('pylint not found! Run "paver install_devtools".')
sys.exit(1)
src_dir = options.plugin.source_dir
exclude = lambda p: any([path(p).fnmatch(e) for e in excludes])
def filter_excludes(root, items):
if not items:
return []
# to prevent descending into dirs, modify the list in place
for item in list(items): # copy list or iteration values change
itempath = path(os.path.relpath(root)) / item
if exclude(item) and item not in skips:
debug('Excluding %s' % itempath)
items.remove(item)
return items

if not 'rcfile' in args:
args.append('--rcfile=pylintrc')
for root, dirs, files in os.walk(src_dir):
for f in filter_excludes(root, files):
relpath = os.path.relpath(root)
zipFile.write(path(root) / f, path(relpath) / f)
filter_excludes(root, dirs)

args.append(options.plugin.source_dir)
lint.Run(args)
for root, dirs, files in os.walk(options.sphinx.builddir):
for f in files:
relpath = os.path.join(options.plugin.name, "docs", os.path.relpath(root, options.sphinx.builddir))
zipFile.write(path(root) / f, path(relpath) / f)


def create_settings_docs(options):
Expand Down Expand Up @@ -260,33 +199,4 @@ def builddocs(options):
set_theme = ""
sh("sphinx-build -a {} {} {}/html".format(set_theme,
options.sphinx.sourcedir,
options.sphinx.builddir))


def _make_zip(zipFile, options):
excludes = set(options.plugin.excludes)
skips = options.plugin.skip_exclude

src_dir = options.plugin.source_dir
exclude = lambda p: any([path(p).fnmatch(e) for e in excludes])
def filter_excludes(root, items):
if not items:
return []
# to prevent descending into dirs, modify the list in place
for item in list(items): # copy list or iteration values change
itempath = path(os.path.relpath(root)) / item
if exclude(item) and item not in skips:
debug('Excluding %s' % itempath)
items.remove(item)
return items

for root, dirs, files in os.walk(src_dir):
for f in filter_excludes(root, files):
relpath = os.path.relpath(root)
zipFile.write(path(root) / f, path(relpath) / f)
filter_excludes(root, dirs)

for root, dirs, files in os.walk(options.sphinx.builddir):
for f in files:
relpath = os.path.join(options.plugin.name, "docs", os.path.relpath(root, options.sphinx.builddir))
zipFile.write(path(root) / f, path(relpath) / f)
options.sphinx.builddir))
3 changes: 0 additions & 3 deletions requirements-dev.txt

This file was deleted.

1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
future
qgiscommons
# test requirements
6 changes: 4 additions & 2 deletions what3words/coorddialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
from qgis.PyQt.QtGui import QCursor

from qgis.core import (QgsCoordinateReferenceSystem,
QgsCoordinateTransform
QgsCoordinateTransform,
QgsProject
)
from qgis.gui import QgsVertexMarker

Expand Down Expand Up @@ -66,7 +67,7 @@ def zoomToPressed(self):
lon = float(json["geometry"]["lng"])
canvasCrs = self.canvas.mapSettings().destinationCrs()
epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326")
transform4326 = QgsCoordinateTransform(epsg4326, canvasCrs)
transform4326 = QgsCoordinateTransform(epsg4326, canvasCrs, QgsProject.instance())
center = transform4326.transform(lon, lat)
self.canvas.zoomByFactor(1, center)
self.canvas.refresh()
Expand All @@ -78,6 +79,7 @@ def zoomToPressed(self):
self.removeMarkerButton.setDisabled(False)
self.coordBox.setStyleSheet("QLineEdit{background: white}")
except Exception as e:
raise
self.coordBox.setStyleSheet("QLineEdit{background: yellow}")
finally:
QApplication.restoreOverrideCursor()
Expand Down
12 changes: 8 additions & 4 deletions what3words/maptool.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from qgis.PyQt.QtWidgets import QApplication
from qgis.PyQt.QtGui import QCursor

from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform
from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, Qgis
from qgis.gui import QgsMapTool, QgsMessageBar
from qgis.utils import iface

Expand All @@ -28,7 +28,7 @@ def __init__(self, canvas):
def toW3W(self, pt):
canvas = iface.mapCanvas()
canvasCrs = canvas.mapSettings().destinationCrs()
transform = QgsCoordinateTransform(canvasCrs, self.epsg4326)
transform = QgsCoordinateTransform(canvasCrs, self.epsg4326, QgsProject.instance())
pt4326 = transform.transform(pt.x(), pt.y())
try:
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
Expand All @@ -44,8 +44,12 @@ def canvasReleaseEvent(self, e):
pt = self.toMapCoordinates(e.pos())
w3wCoord = self.toW3W(pt)
if w3wCoord:
iface.messageBar().pushMessage("what3words", "The 3 word address: '{}' has been copied to the clipboard".format(w3wCoord), level=QgsMessageBar.INFO, duration=6)
iface.messageBar().pushMessage("what3words",
"The 3 word address: '{}' has been copied to the clipboard".format(w3wCoord),
level=Qgis.Info, duration=6)
clipboard = QApplication.clipboard()
clipboard.setText(w3wCoord)
else:
iface.messageBar().pushMessage("what3words", "Could not convert the selected point to a 3 word address", level=QgsMessageBar.WARNING, duration=3)
iface.messageBar().pushMessage("what3words",
"Could not convert the selected point to a 3 word address",
level=Qgis.Warning, duration=3)
4 changes: 2 additions & 2 deletions what3words/metadata.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ name=What3words Tools
description=Enables what3words three word addresses in QGIS
about=<p>what3words is a global grid of 57 trillion 3mx3m squares. Each square has a 3 word address that can be communicated quickly, easily and with no ambiguity. Their geocoder turns geographic coordinates into 3 word addresses and vice-versa. Our plugin lets you work with the addresses within QGIS.</p>
category=Plugins
qgisMinimumVersion=2.0
version=1.3
qgisMinimumVersion=3.0
version=3.0
roles=desktop-qgis-plugin-w3w

author=Boundless (Victor Olaya)
Expand Down
23 changes: 8 additions & 15 deletions what3words/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from qgis.PyQt.QtWidgets import QAction

from qgis.gui import QgsMessageBar
from qgis.core import QgsApplication
from qgis.core import QgsApplication, Qgis
from qgis.utils import iface

from what3words.maptool import W3WMapTool
Expand All @@ -29,12 +29,7 @@
from qgiscommons2.gui.settings import (addSettingsMenu,
removeSettingsMenu)

try:
from processing.core.Processing import Processing
from what3words.processingprovider.w3wprovider import W3WProvider
processingOk = True
except:
processingOk = False
from what3words.processingprovider.w3wprovider import W3WProvider

class W3WTools(object):

Expand All @@ -49,8 +44,8 @@ def __init__(self, iface):
pass

self.mapTool = None
if processingOk:
self.provider = W3WProvider()

self.provider = W3WProvider()

readSettings()

Expand Down Expand Up @@ -82,8 +77,7 @@ def initGui(self):
self.iface.addDockWidget(Qt.TopDockWidgetArea, self.zoomToDialog)
self.zoomToDialog.hide()

if processingOk:
Processing.addProvider(self.provider)
QgsApplication.processingRegistry().addProvider(self.provider)

try:
from lessons import addLessonsFolder, addGroup
Expand Down Expand Up @@ -112,7 +106,7 @@ def unsetTool(self, tool):
def setTool(self):
apikey = pluginSetting("apiKey")
if apikey is None or apikey == "":
self._showMessage('what3words API key is not set. Please set it and try again.', QgsMessageBar.WARNING)
self._showMessage('what3words API key is not set. Please set it and try again.', Qgis.Warning)
return
if self.mapTool is None:
self.mapTool = W3WMapTool(self.iface.mapCanvas())
Expand All @@ -131,8 +125,7 @@ def unload(self):

self.iface.removeDockWidget(self.zoomToDialog)

if processingOk:
Processing.removeProvider(self.provider)
QgsApplication.processingRegistry().addProvider(self.provider)

try:
from what3words.tests import testerplugin
Expand All @@ -148,6 +141,6 @@ def unload(self):
except:
pass

def _showMessage(self, message, level=QgsMessageBar.INFO):
def _showMessage(self, message, level=Qgis.Info):
iface.messageBar().pushMessage(
message, level, iface.messageTimeout())
Loading

0 comments on commit 536ba2a

Please sign in to comment.