diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8bd721b --- /dev/null +++ b/Makefile @@ -0,0 +1,119 @@ +#/*************************************************************************** +# RealCentroid +# +# Create point shape from polygon centroids +# ------------------- +# begin : 2013-10-27 +# copyright : (C) 2013 by Zoltan Siki +# email : siki at agt.bme.hu +# ***************************************************************************/ +# +#/*************************************************************************** +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU General Public License as published by * +# * the Free Software Foundation; either version 2 of the License, or * +# * (at your option) any later version. * +# * * +# ***************************************************************************/ + +# CONFIGURATION +PLUGIN_UPLOAD = $(CURDIR)/plugin_upload.py + +QGISDIR=.qgis2 + +# Makefile for a PyQGIS plugin + +# translation +SOURCES = realcentroid.py ui_realcentroid.py __init__.py realcentroiddialog.py util.py +#TRANSLATIONS = i18n/realcentroid_en.ts +TRANSLATIONS = + +# global + +PLUGINNAME = realcentroid + +PY_FILES = realcentroid.py realcentroiddialog.py __init__.py + +EXTRAS = icon.png metadata.txt + +UI_FILES = ui_realcentroid.py + +RESOURCE_FILES = resources_rc.py + +HELP = help/build/html + +default: compile + +compile: $(UI_FILES) $(RESOURCE_FILES) + +%_rc.py : %.qrc + pyrcc4 -o $*_rc.py $< + +%.py : %.ui + pyuic4 -o $@ $< + +%.qm : %.ts + lrelease $< + +# The deploy target only works on unix like operating system where +# the Python plugin directory is located at: +# $HOME/$(QGISDIR)/python/plugins +deploy: compile doc transcompile + mkdir -p $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) + cp -vf $(PY_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) + cp -vf $(UI_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) + cp -vf $(RESOURCE_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) + cp -vf $(EXTRAS) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) + cp -vfr i18n $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) + cp -vfr $(HELP) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)/help + +# The dclean target removes compiled python files from plugin directory +# also delets any .svn entry +dclean: + find $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) -iname "*.pyc" -delete + find $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) -iname ".svn" -prune -exec rm -Rf {} \; + +# The derase deletes deployed plugin +derase: + rm -Rf $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) + +# The zip target deploys the plugin and creates a zip file with the deployed +# content. You can then upload the zip file on http://plugins.qgis.org +zip: deploy dclean + rm -f $(PLUGINNAME).zip + cd $(HOME)/$(QGISDIR)/python/plugins; zip -9r $(CURDIR)/$(PLUGINNAME).zip $(PLUGINNAME) + +# Create a zip package of the plugin named $(PLUGINNAME).zip. +# This requires use of git (your plugin development directory must be a +# git repository). +# To use, pass a valid commit or tag as follows: +# make package VERSION=Version_0.3.2 +package: compile + rm -f $(PLUGINNAME).zip + git archive --prefix=$(PLUGINNAME)/ -o $(PLUGINNAME).zip $(VERSION) + echo "Created package: $(PLUGINNAME).zip" + +upload: zip + $(PLUGIN_UPLOAD) $(PLUGINNAME).zip + +# transup +# update .ts translation files +transup: + pylupdate4 Makefile + +# transcompile +# compile translation files into .qm binary format +transcompile: $(TRANSLATIONS:.ts=.qm) + +# transclean +# deletes all .qm files +transclean: + rm -f i18n/*.qm + +clean: + rm $(UI_FILES) $(RESOURCE_FILES) + +# build documentation with sphinx +doc: + cd help; make html diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..87ca864 --- /dev/null +++ b/__init__.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +""" +/*************************************************************************** + RealCentroid + A QGIS plugin + Create point shape from polygon centroids + ------------------- + begin : 2013-10-27 + copyright : (C) 2013 by Zoltan Siki + email : siki at agt.bme.hu + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + This script initializes the plugin, making it known to QGIS. +""" + +def classFactory(iface): + # load RealCentroid class from file RealCentroid + from realcentroid import RealCentroid + return RealCentroid(iface) diff --git a/help/Makefile b/help/Makefile new file mode 100644 index 0000000..ebb0236 --- /dev/null +++ b/help/Makefile @@ -0,0 +1,130 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/templateclass.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/templateclass.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/templateclass" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/templateclass" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + make -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/help/make.bat b/help/make.bat new file mode 100644 index 0000000..90dc191 --- /dev/null +++ b/help/make.bat @@ -0,0 +1,155 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. changes to make an overview over all changed/added/deprecated items + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\templateclass.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\templateclass.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +:end diff --git a/help/realcentroids_03.html b/help/realcentroids_03.html new file mode 100644 index 0000000..47a9c08 --- /dev/null +++ b/help/realcentroids_03.html @@ -0,0 +1,82 @@ + + + + + + + + + + + + + +

Real +Centroids V0.3 +

+

+RealCentroids +plugin creates a point shape file with internal points of a polygon +shape, similar to PostGIS ST_PointOnSurface. The point will be inside +the polygon in all cases. Not only the points are created but the +attributes are also copied from the polygon to the internal points . +A single point is generated for multipart geometry too.

+

Installation

+

Use the plugin manager or unzip the downloaded realcentroids.zip +into your plugins directory, e.g. ~/.qgis2/python/plugins/.

+

Usage

+

Enable the plugin in the Plugins/Manage and +Install Plugins ... dialog. Open the polygon layer you want to +create centroids. Start the plugin clicking on the icon in the +plugins toolbar or select it from the plugins menu. The following +dialog appears

+


In +the Polygon layer list you can select one from the loaded +polygon layers. If the active layer is a polygon layer then it will +be selected in the list. Select a new shapefile clicking on the +Browse button, . If you select an existing shapefile, you get +a warning weather to overwrite that shape. If you check Add to map +canvas the point shape with the internal points is added to the +current project. The attributes of the polygons are also copied to +the target point shape file. If Polygon layer or Output +point on surface layer is empty, a warning will be displayed.

+

Why do we need such plugin? There is a Polygon +centroids option in the Vector/Geometry Tools menu. This +will create centroids at the weight point of the vertexes of the +polygon. So it can be outside the polygon in a concave or multipart +case. Realcentroid will place the point always inside the polygon. +See figures below to compare the results of the two methods.

+


Centroids +(weight points) created by Vector/Geometry Tools/Polygon centroids

+


Points +on surface generated by RealCentroids plugin

+

Algorithm used

+

For each polygons the weight point is generated first. If the +weight point is outside, the intersection of the horizontal line +through the weight point and the polygon is generated. The midpoint +of the longest line segment from the intersection result will be +used. See the figure below.

+


Internal +point generation

+



+

+

Thanks to Seal Phone and Jukka Rahkonen giving advice to improve +the plugin.

+
+

2

+
+ + \ No newline at end of file diff --git a/help/realcentroids_03.odt b/help/realcentroids_03.odt new file mode 100644 index 0000000..231cb19 Binary files /dev/null and b/help/realcentroids_03.odt differ diff --git a/help/realcentroids_03_html_5d03d490.png b/help/realcentroids_03_html_5d03d490.png new file mode 100644 index 0000000..2c841cd Binary files /dev/null and b/help/realcentroids_03_html_5d03d490.png differ diff --git a/help/realcentroids_03_html_6728e816.png b/help/realcentroids_03_html_6728e816.png new file mode 100644 index 0000000..0b1bbd2 Binary files /dev/null and b/help/realcentroids_03_html_6728e816.png differ diff --git a/help/realcentroids_03_html_7ca905b9.jpg b/help/realcentroids_03_html_7ca905b9.jpg new file mode 100644 index 0000000..1e36e20 Binary files /dev/null and b/help/realcentroids_03_html_7ca905b9.jpg differ diff --git a/help/realcentroids_03_html_b7839b6.png b/help/realcentroids_03_html_b7839b6.png new file mode 100644 index 0000000..ae352ac Binary files /dev/null and b/help/realcentroids_03_html_b7839b6.png differ diff --git a/help/realcentroids_03_html_m6a4362cc.png b/help/realcentroids_03_html_m6a4362cc.png new file mode 100644 index 0000000..75f5622 Binary files /dev/null and b/help/realcentroids_03_html_m6a4362cc.png differ diff --git a/help/source/conf.py b/help/source/conf.py new file mode 100644 index 0000000..008f8c0 --- /dev/null +++ b/help/source/conf.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- +# +# realcentroid documentation build configuration file, created by +# sphinx-quickstart on Sun Feb 12 17:11:03 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'realcentroid' +copyright = u'2013, Zoltan Siki' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.1' +# The full version, including alpha/beta/rc tags. +release = '0.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'templateclassdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +# The paper size ('letter' or 'a4'). +#latex_paper_size = 'letter' + +# The font size ('10pt', '11pt' or '12pt'). +#latex_font_size = '10pt' + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'realcentroid.tex', u'realcentroid Documentation', + u'Zoltan Siki', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Additional stuff for the LaTeX preamble. +#latex_preamble = '' + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'templateclass', u'realcentroid Documentation', + [u'Zoltan Siki'], 1) +] diff --git a/help/source/index.rst b/help/source/index.rst new file mode 100644 index 0000000..9caf759 --- /dev/null +++ b/help/source/index.rst @@ -0,0 +1,20 @@ +.. realcentroid documentation master file, created by + sphinx-quickstart on Sun Feb 12 17:11:03 2012. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to realcentroid's documentation! +============================================ + +Contents: + +.. toctree:: + :maxdepth: 2 + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..75f5622 Binary files /dev/null and b/icon.png differ diff --git a/metadata.txt b/metadata.txt new file mode 100644 index 0000000..2c12d33 --- /dev/null +++ b/metadata.txt @@ -0,0 +1,38 @@ +# This file contains metadata for your plugin. Beginning +# with version 1.8 this is the preferred way to supply information about a +# plugin. The current method of embedding metadata in __init__.py will +# be supported until version 2.0 + +# This file should be included when you package your plugin. + +# Mandatory items: + + +[general] +name=realcentroid +qgisMinimumVersion=2.0 +description=This plugin creates a point shape file with internal points of a polygon shape, similiar to the ST_PointOnSurface function of PostGIS. The point will be inside the polygon all cases. Not only the geometries are created but the attributes are also copied from the polygon to the internal point. +version=0.3 +author=Zoltan Siki +email=siki@agt.bme.hu + +# end of mandatory metadata + +# Optional items: + +# Uncomment the following line and add your changelog entries: +# changelog= + +# tags are comma separated with spaces allowed +tags=point on surface,centroid,polygon,shapefile + +homepage=http://www.agt.bme.hu/gis/qgis/realcentroid +tracker=http://hub.qgis.org/projects/realcentroids +repository=http://hub.qgis.org/projects/realcentroids +icon=icon.png +# experimental flag +experimental=False + +# deprecated flag (applies to the whole plugin, not just a single version +deprecated=False + diff --git a/plugin_upload.py b/plugin_upload.py new file mode 100755 index 0000000..4d2d384 --- /dev/null +++ b/plugin_upload.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# This script uploads a plugin package on the server +# +# Author: A. Pasotti, V. Picavet + +import xmlrpclib, sys, os +import getpass +from optparse import OptionParser + +# Configuration +PROTOCOL='http' +SERVER='plugins.qgis.org' +PORT='80' +ENDPOINT='/plugins/RPC2/' +VERBOSE=False + +def main(options, args): + address = "%s://%s:%s@%s:%s%s" % (PROTOCOL, options.username, options.password, + options.server, options.port, ENDPOINT) + print "Connecting to: %s" % hidepassword(address) + + server = xmlrpclib.ServerProxy(address, verbose=VERBOSE) + + try: + plugin_id, version_id = server.plugin.upload(xmlrpclib.Binary(open(args[0]).read())) + print "Plugin ID: %s" % plugin_id + print "Version ID: %s" % version_id + except xmlrpclib.ProtocolError, err: + print "A protocol error occurred" + print "URL: %s" % hidepassword(err.url, 0) + print "HTTP/HTTPS headers: %s" % err.headers + print "Error code: %d" % err.errcode + print "Error message: %s" % err.errmsg + except xmlrpclib.Fault, err: + print "A fault occurred" + print "Fault code: %d" % err.faultCode + print "Fault string: %s" % err.faultString + +def hidepassword(url, start = 6): + """Returns the http url with password part replaced with '*'.""" + passdeb = url.find(':', start) + 1 + passend = url.find('@') + return "%s%s%s" % (url[:passdeb], '*' * (passend - passdeb), url[passend:]) + + +if __name__ == "__main__": + parser = OptionParser(usage="%prog [options] plugin.zip") + parser.add_option("-w", "--password", dest="password", + help="Password for plugin site", metavar="******") + parser.add_option("-u", "--username", dest="username", + help="Username of plugin site", metavar="user") + parser.add_option("-p", "--port", dest="port", + help="Server port to connect to", metavar="80") + parser.add_option("-s", "--server", dest="server", + help="Specify server name", metavar="plugins.qgis.org") + (options, args) = parser.parse_args() + if len(args) != 1: + print "Please specify zip file.\n" + parser.print_help() + sys.exit(1) + if not options.server: + options.server = SERVER + if not options.port: + options.port = PORT + if not options.username: + # interactive mode + username = getpass.getuser() + print "Please enter user name [%s] :"%username, + res = raw_input() + if res != "": + options.username = res + else: + options.username = username + if not options.password: + # interactive mode + options.password = getpass.getpass() + main(options, args) + diff --git a/realcentroid.py b/realcentroid.py new file mode 100644 index 0000000..d0beabd --- /dev/null +++ b/realcentroid.py @@ -0,0 +1,123 @@ +# i*- coding: utf-8 -*- +""" +/*************************************************************************** + RealCentroid + A QGIS plugin + Create point shape from polygon centroids + ------------------- + begin : 2013-10-27 + copyright : (C) 2013 by Zoltan Siki + email : siki at agt.bme.hu + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +""" +# Import the PyQt and QGIS libraries +from PyQt4.QtCore import * +from PyQt4.QtGui import * +from qgis.core import * +# Initialize Qt resources from file resources.py +import resources_rc +# Import the code for the dialog +from realcentroiddialog import RealCentroidDialog +import os.path +import util +from math import sqrt +#import pdb + +class RealCentroid: + + def __init__(self, iface): + # Save reference to the QGIS interface + self.iface = iface + # initialize plugin directory + self.plugin_dir = os.path.dirname(__file__) + # initialize locale + locale = QSettings().value("locale/userLocale")[0:2] + localePath = os.path.join(self.plugin_dir, 'i18n', 'realcentroid_{}.qm'.format(locale)) + + if os.path.exists(localePath): + self.translator = QTranslator() + self.translator.load(localePath) + + if qVersion() > '4.3.3': + QCoreApplication.installTranslator(self.translator) + + # Create the dialog (after translation) and keep reference + self.dlg = RealCentroidDialog() + + def initGui(self): + # Create action that will start plugin configuration + self.action = QAction( + QIcon(":/plugins/realcentroid/icon.png"), + u"Real centroids", self.iface.mainWindow()) + # connect the action to the run method + self.action.triggered.connect(self.run) + + # Add toolbar button and menu item + self.iface.addToolBarIcon(self.action) + self.iface.addPluginToMenu(u"&realcnetroid", self.action) + + def unload(self): + # Remove the plugin menu item and icon + self.iface.removePluginMenu(u"&realcnetroid", self.action) + self.iface.removeToolBarIcon(self.action) + + # create centroids shape file + def centroids(self): + vlayer = util.getMapLayerByName(self.dlg.ui.layerBox.currentText()) + vprovider = vlayer.dataProvider() + writer = QgsVectorFileWriter(self.dlg.shapefileName, self.dlg.encoding, vprovider.fields(), QGis.WKBPoint, vprovider.crs()) + inFeat = QgsFeature() + outFeat = QgsFeature() + fit = vprovider.getFeatures() + while fit.nextFeature(inFeat): + #nElement += 1 + inGeom = inFeat.geometry() + atMap = inFeat.attributes() + outGeom = inGeom.centroid() + if not inGeom.contains(outGeom): + # weight point outside the polygon + # find intersection of horizontal line through the weight pont + rect = inGeom.boundingBox() + horiz = QgsGeometry.fromPolyline([QgsPoint(rect.xMinimum(), outGeom.asPoint()[1]), QgsPoint(rect.xMaximum(), outGeom.asPoint()[1])]); + line = horiz.intersection(inGeom) + if line.isMultipart(): + # find longest intersection + mline = line.asMultiPolyline() + l = 0 + for i in range(len(mline)): + d = sqrt((mline[i][0][0] - mline[i][1][0])**2 + (mline[i][0][1] - mline[i][1][1])**2) + if d > l: + l = d + xMid = (mline[i][0][0] + mline[i][1][0]) / 2.0 + yMid = (mline[i][0][1] + mline[i][1][1]) / 2.0 + else: + xMid = (line.vertexAt(0).x() + line.vertexAt(1).x()) / 2.0 + yMid = (line.vertexAt(0).y() + line.vertexAt(1).y()) / 2.0 + outGeom = QgsGeometry.fromPoint(QgsPoint(xMid, yMid)) + outFeat.setAttributes(atMap) + outFeat.setGeometry(outGeom) + writer.addFeature(outFeat) + del writer + # add centroid shape to canvas + if self.dlg.ui.addBox.checkState() == Qt.Checked: + if not util.addShape(self.dlg.shapefileName): + QMessageBox.warning(self, "RealCentroid", "Error loading shapefile:\n" + self.dlg.shapefileName) + + # run method that performs all the real work + def run(self): + # show the dialog + self.dlg.show() + # Run the dialog event loop + result = self.dlg.exec_() + # See if OK was pressed + if result == 1 and len(self.dlg.ui.layerBox.currentText()) and len(self.dlg.ui.pointEdit.text()): + self.centroids() diff --git a/realcentroiddialog.py b/realcentroiddialog.py new file mode 100644 index 0000000..2642e63 --- /dev/null +++ b/realcentroiddialog.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +""" +/*************************************************************************** + RealCentroidDialog + A QGIS plugin + Create point shape from polygon centroids + ------------------- + begin : 2013-10-27 + copyright : (C) 2013 by Zoltan Siki + email : siki at agt.bme.hu + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +""" + +from PyQt4 import QtCore, QtGui +from ui_realcentroid import Ui_RealCentroid +from qgis.core import * +from qgis.utils import * +import util + +# create the dialog for real centroids +class RealCentroidDialog(QtGui.QDialog): + def __init__(self): + QtGui.QDialog.__init__(self) + # Set up the user interface from Designer. + self.ui = Ui_RealCentroid() + self.ui.setupUi(self) + # add action to browse button + QtCore.QObject.connect(self.ui.browseButton, QtCore.SIGNAL("clicked()"), self.browse) + QtCore.QObject.connect(self.ui.okButton, QtCore.SIGNAL("clicked()"), self.ok) + QtCore.QObject.connect(self.ui.cancelButton, QtCore.SIGNAL("clicked()"), self.reject) + + def showEvent(self, event): + # remove previous entries from layer list + self.ui.layerBox.clear() + # remove previous shape path + self.ui.pointEdit.clear() + # add polygon layers to list + names = util.getLayerNames([QGis.Polygon]) + self.ui.layerBox.addItems(names) + if iface.activeLayer(): + # set active item in list to the active layer + i = 0 + for name in names: + l = util.getMapLayerByName(name) + if l == iface.activeLayer(): + self.ui.layerBox.setCurrentIndex(i) + break + i += 1 + + def browse(self): + self.ui.pointEdit.clear() # clear output file field + # open file dialog + (self.shapefileName, self.encoding) = util.saveDialog(self) + if self.shapefileName is None or self.encoding is None: + return + self.ui.pointEdit.setText(self.shapefileName) # fill output file field + + def ok(self): + if len(self.ui.layerBox.currentText()) == 0: + QtGui.QMessageBox.information(self, "Realcentroid", "No polygon layer selected") + return + if len(self.ui.pointEdit.text()) == 0: + QtGui.QMessageBox.information(self, "Realcentroid", "No point layer given") + return + self.accept() diff --git a/resources.qrc b/resources.qrc new file mode 100644 index 0000000..783ebea --- /dev/null +++ b/resources.qrc @@ -0,0 +1,5 @@ + + + icon.png + + diff --git a/resources_rc.py b/resources_rc.py new file mode 100644 index 0000000..5655b78 --- /dev/null +++ b/resources_rc.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- + +# Resource object code +# +# Created by: The Resource Compiler for PyQt (Qt v4.7.4) +# +# WARNING! All changes made in this file will be lost! + +from PyQt4 import QtCore + +qt_resource_data = "\ +\x00\x00\x01\xbb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ +\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\ +\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\ +\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\ +\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xdd\x0a\x1b\ +\x14\x2f\x21\xea\x86\x4e\xf1\x00\x00\x01\x3b\x49\x44\x41\x54\x48\ +\xc7\xb5\x54\x3d\x4e\xc3\x30\x18\x7d\x76\x0d\x03\x54\xc4\x9c\x81\ +\x99\x54\x62\x43\x42\x22\x0c\x4c\x59\xb8\x41\x16\x2e\xc0\x49\x38\ +\x43\x6f\xd0\x25\x13\x12\x2a\x12\x52\xe6\xa6\x33\x67\xa8\x13\xe8\ +\x00\x38\xf9\x18\xda\x48\xc6\x52\x7e\xdc\xba\x6f\xfc\xfc\x7d\xef\ +\x3d\xbf\x4f\x36\x23\xa2\xbb\x1f\xf5\x76\xa1\xcb\x2c\xa9\x75\x71\ +\x53\xad\x97\xd8\x15\xa3\xd3\x4b\x70\x11\xbc\x8b\xb3\xeb\xe9\xb1\ +\xbc\xfd\x60\xdf\xab\xf9\xe3\xef\xea\xe5\x99\xa8\x1a\xef\x43\x6c\ +\x0a\x30\x36\xfa\x3a\x3a\xbf\x7f\xe2\xba\xcc\x12\x5f\xc4\x00\x50\ +\xad\x97\x20\xaa\xc6\xba\xcc\x12\xbe\x6f\x14\x6d\xa8\xf5\xe7\x15\ +\x3f\x04\xf1\x86\xb3\x3e\xe1\x4d\x41\x86\x29\x64\x98\x7a\x15\x10\ +\x66\x41\xe5\xf1\x3f\x01\x95\xc7\x9d\x04\x4d\x6f\x5b\x9f\xb0\x0b\ +\x66\x63\xdf\x70\x9f\x21\xd1\xe5\xcc\x1e\xb4\x5d\x37\x44\x6d\x86\ +\xb8\xef\x65\x9a\x42\xde\xc9\x4d\x78\x27\x37\xe3\xe2\x43\x07\xcc\ +\xec\x4d\x82\x2e\x08\x97\x0c\x5d\xdf\x81\xd8\x75\x59\xde\x33\x0f\ +\x7a\x9c\xdb\x71\x71\x57\xe2\xc0\x21\x1a\x6e\x3f\x98\xb6\x5c\x8b\ +\xad\xa3\xc2\x21\x1a\xa6\xf2\x98\x5c\xff\x8c\xa1\xfd\xa2\x6b\x71\ +\x7d\x22\xce\x1f\xd7\x10\x91\x81\x37\x2b\x05\x80\x19\x80\x07\xfb\ +\x84\x68\x93\x16\x63\xcc\x95\xb4\xc1\x2b\x53\x79\x3c\x01\x30\x07\ +\x20\x7d\xfe\x5f\x00\x22\x2e\xc3\x74\x01\x20\xda\xde\xc0\x07\x66\ +\x00\x22\x19\xa6\x8b\x3f\x55\x01\xae\x2f\xb0\x18\x1a\x14\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +" + +qt_resource_name = "\ +\x00\x07\ +\x07\x3b\xe0\xb3\ +\x00\x70\ +\x00\x6c\x00\x75\x00\x67\x00\x69\x00\x6e\x00\x73\ +\x00\x0c\ +\x07\x4c\x90\xd4\ +\x00\x72\ +\x00\x65\x00\x61\x00\x6c\x00\x63\x00\x65\x00\x6e\x00\x74\x00\x72\x00\x6f\x00\x69\x00\x64\ +\x00\x08\ +\x0a\x61\x5a\xa7\ +\x00\x69\ +\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ +" + +qt_resource_struct = "\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\ +\x00\x00\x00\x14\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ +\x00\x00\x00\x32\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\ +" + +def qInitResources(): + QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) + +def qCleanupResources(): + QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) + +qInitResources() diff --git a/ui_realcentroid.py b/ui_realcentroid.py new file mode 100644 index 0000000..58290dc --- /dev/null +++ b/ui_realcentroid.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'ui_realcentroid.ui' +# +# Created: Fri May 9 21:12:44 2014 +# by: PyQt4 UI code generator 4.8.6 +# +# WARNING! All changes made in this file will be lost! + +from PyQt4 import QtCore, QtGui + +try: + _fromUtf8 = QtCore.QString.fromUtf8 +except AttributeError: + _fromUtf8 = lambda s: s + +class Ui_RealCentroid(object): + def setupUi(self, RealCentroid): + RealCentroid.setObjectName(_fromUtf8("RealCentroid")) + RealCentroid.resize(389, 198) + RealCentroid.setWindowTitle(QtGui.QApplication.translate("RealCentroid", "RealCentroid", None, QtGui.QApplication.UnicodeUTF8)) + RealCentroid.setModal(True) + self.label = QtGui.QLabel(RealCentroid) + self.label.setGeometry(QtCore.QRect(10, 10, 111, 21)) + self.label.setText(QtGui.QApplication.translate("RealCentroid", "Polygon layer", None, QtGui.QApplication.UnicodeUTF8)) + self.label.setObjectName(_fromUtf8("label")) + self.layerBox = QtGui.QComboBox(RealCentroid) + self.layerBox.setGeometry(QtCore.QRect(10, 30, 371, 31)) + self.layerBox.setObjectName(_fromUtf8("layerBox")) + self.label_2 = QtGui.QLabel(RealCentroid) + self.label_2.setGeometry(QtCore.QRect(10, 70, 201, 21)) + self.label_2.setText(QtGui.QApplication.translate("RealCentroid", "Output point on surface layer", None, QtGui.QApplication.UnicodeUTF8)) + self.label_2.setObjectName(_fromUtf8("label_2")) + self.pointEdit = QtGui.QLineEdit(RealCentroid) + self.pointEdit.setEnabled(False) + self.pointEdit.setGeometry(QtCore.QRect(10, 90, 291, 31)) + self.pointEdit.setObjectName(_fromUtf8("pointEdit")) + self.browseButton = QtGui.QPushButton(RealCentroid) + self.browseButton.setGeometry(QtCore.QRect(310, 90, 71, 31)) + self.browseButton.setText(QtGui.QApplication.translate("RealCentroid", "Browse", None, QtGui.QApplication.UnicodeUTF8)) + self.browseButton.setObjectName(_fromUtf8("browseButton")) + self.addBox = QtGui.QCheckBox(RealCentroid) + self.addBox.setGeometry(QtCore.QRect(10, 130, 361, 26)) + self.addBox.setText(QtGui.QApplication.translate("RealCentroid", "Add to map canvas", None, QtGui.QApplication.UnicodeUTF8)) + self.addBox.setObjectName(_fromUtf8("addBox")) + self.cancelButton = QtGui.QPushButton(RealCentroid) + self.cancelButton.setGeometry(QtCore.QRect(310, 160, 71, 31)) + self.cancelButton.setText(QtGui.QApplication.translate("RealCentroid", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) + self.cancelButton.setObjectName(_fromUtf8("cancelButton")) + self.okButton = QtGui.QPushButton(RealCentroid) + self.okButton.setGeometry(QtCore.QRect(220, 160, 71, 31)) + self.okButton.setText(QtGui.QApplication.translate("RealCentroid", "Ok", None, QtGui.QApplication.UnicodeUTF8)) + self.okButton.setObjectName(_fromUtf8("okButton")) + + self.retranslateUi(RealCentroid) + QtCore.QMetaObject.connectSlotsByName(RealCentroid) + + def retranslateUi(self, RealCentroid): + pass + diff --git a/ui_realcentroid.ui b/ui_realcentroid.ui new file mode 100644 index 0000000..3fdd22f --- /dev/null +++ b/ui_realcentroid.ui @@ -0,0 +1,123 @@ + + + RealCentroid + + + + 0 + 0 + 389 + 198 + + + + RealCentroid + + + true + + + + + 10 + 10 + 111 + 21 + + + + Polygon layer + + + + + + 10 + 30 + 371 + 31 + + + + + + + 10 + 70 + 201 + 21 + + + + Output point on surface layer + + + + + false + + + + 10 + 90 + 291 + 31 + + + + + + + 310 + 90 + 71 + 31 + + + + Browse + + + + + + 10 + 130 + 361 + 26 + + + + Add to map canvas + + + + + + 310 + 160 + 71 + 31 + + + + Cancel + + + + + + 220 + 160 + 71 + 31 + + + + Ok + + + + + + diff --git a/util.py b/util.py new file mode 100644 index 0000000..ab903e5 --- /dev/null +++ b/util.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- + +from PyQt4.QtCore import * +from PyQt4.QtGui import * + +from qgis.core import * +from qgis.gui import QgsEncodingFileDialog +import locale + +# Return list of names of layers in QgsMapLayerRegistry +# vTypes - list of layer types allowed (e.g. QGis.Point, QGis.Line, QGis.Polygon or "all" or "raster") +# return sorted list of layer names +def getLayerNames(vTypes): + layermap = QgsMapLayerRegistry.instance().mapLayers() + layerlist = [] + if vTypes == "all": + for name, layer in layermap.iteritems(): + layerlist.append(unicode(layer.name())) + else: + for name, layer in layermap.iteritems(): + if layer.type() == QgsMapLayer.VectorLayer: + if layer.geometryType() in vTypes: + layerlist.append(unicode(layer.name())) + elif layer.type() == QgsMapLayer.RasterLayer: + if "raster" in vTypes: + layerlist.append(unicode(layer.name())) + return sorted(layerlist, cmp=locale.strcoll) + +# Generate a save file dialog with a dropdown box for choosing encoding style +def saveDialog(parent, filtering="Shapefiles (*.shp)"): + settings = QSettings() + dirName = settings.value("/UI/lastShapefileDir") + encode = settings.value("/UI/encoding") + fileDialog = QgsEncodingFileDialog(parent, "Output shape file", dirName, filtering, encode) + fileDialog.setDefaultSuffix("shp") + fileDialog.setFileMode(QFileDialog.AnyFile) + fileDialog.setAcceptMode(QFileDialog.AcceptSave) + fileDialog.setConfirmOverwrite(True) + if not fileDialog.exec_() == QDialog.Accepted: + return None, None + files = fileDialog.selectedFiles() + settings.setValue("/UI/lastShapefileDir", QFileInfo(unicode(files[0])).absolutePath()) + return (unicode(files[0]), unicode(fileDialog.encoding())) + +# Return QgsMapLayer from a layer name (as string) +def getMapLayerByName(myName): + layermap = QgsMapLayerRegistry.instance().mapLayers() + for name, layer in layermap.iteritems(): + if layer.name() == myName: + if layer.isValid(): + return layer + else: + return None + return None + +# add shape to canvas +def addShape(shapefile_path): + file_info = QFileInfo(shapefile_path) + if file_info.exists(): + layer_name = file_info.completeBaseName() + else: + return False + vlayer_new = QgsVectorLayer(shapefile_path,layer_name, "ogr") + if vlayer_new.isValid(): + QgsMapLayerRegistry.instance().addMapLayer(vlayer_new) + return True + else: + return False