-
Notifications
You must be signed in to change notification settings - Fork 0
/
easysearch_plugin.py
200 lines (159 loc) · 7.25 KB
/
easysearch_plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# -*- coding: utf-8 -*-
#/***************************************************************************
# Easy Search
#
# Easy search features base on predefined layer and attribute
#
# -------------------
# begin : 2014-03-03
# copyright : (C) 2014 by Camptocamp SA
# email : info@camptocamp.com
# ***************************************************************************/
#
#/***************************************************************************
# * *
# * 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 os.path
import unicodedata
from PyQt4.QtCore import QSettings, QObject, QTranslator, QCoreApplication, qVersion
from PyQt4.QtGui import QAction, QIcon, QLineEdit
from qgis.core import QgsProject, QgsMapLayerRegistry, QgsFeatureRequest, QgsFeature
from qgis.gui import QgsMessageBar
from easysearch.ui import resources_rc
from easysearch.widgets.settings_dialog import SettingsDialog
def remove_accents(data):
# http://www.unicode.org/reports/tr44/#GC_Values_Table
return ''.join(x for x in unicodedata.normalize('NFKD', data) if unicodedata.category(x)[0] in ('L', 'N', 'P', 'Zs')).lower()
class EasySearch(QObject):
name = ""
pluginName = 'EasySearch'
actions = {}
toolbar = None
searchText = None
layer = None
def __init__(self, iface):
"""Constructor for the plugin.
:param iface: A QGisAppInterface instance we use to access QGIS via.
:type iface: QgsAppInterface
"""
super(EasySearch, self).__init__()
# 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', 'easysearch_{}.qm'.format(locale))
if os.path.exists(localePath):
self.translator = QTranslator()
self.translator.load(localePath)
if qVersion() > '4.3.3':
QCoreApplication.installTranslator(self.translator)
self.name = self.tr(u"Easy Search")
def initGui(self):
self.actions['showSettings'] = QAction(
QIcon(":/plugins/easysearch/flaticon/gears2.svg"),
self.tr(u"&Settings"),
self.iface.mainWindow())
self.actions['showSettings'].triggered.connect(self.showSettings)
self.iface.addPluginToMenu(u"&{}".format(self.name), self.actions['showSettings'])
self.toolbar_init()
self.iface.projectRead.connect(self.searchText_placeholderTextUpdate)
self.iface.newProjectCreated.connect(self.searchText_placeholderTextUpdate)
def unload(self):
self.iface.removePluginMenu(u"&{}".format(self.name), self.actions['showSettings'])
if self.toolbar:
self.toolbar.deleteLater()
self.toolbar = None
self.iface.projectRead.disconnect(self.searchText_placeholderTextUpdate)
self.iface.newProjectCreated.disconnect(self.searchText_placeholderTextUpdate)
def toolbar_init(self):
"""setup the plugin toolbar."""
self.toolbar = self.iface.addToolBar(self.name)
self.toolbar.setObjectName('mEasySearchToolBar')
self.searchText = QLineEdit(self.toolbar)
self.searchText_placeholderTextUpdate()
self.searchText.returnPressed.connect(self.search)
self.actions['searchText'] = self.toolbar.addWidget(self.searchText)
self.actions['searchText'].setVisible(True);
self.actions['searchButton'] = QAction(
QIcon(":/plugins/easysearch/flaticon/magnifier13.svg"),
self.tr("Search"),
self.toolbar)
self.actions['searchButton'].triggered.connect(self.search)
self.toolbar.addAction(self.actions['searchButton'])
self.toolbar.setVisible(True)
def searchText_placeholderTextUpdate(self):
project = QgsProject.instance()
placeHolder, ok = project.readEntry(self.pluginName, 'placeHolder')
self.searchText.setPlaceholderText(placeHolder)
def search(self):
project = QgsProject.instance()
layerId, ok = project.readEntry(self.pluginName, 'layerId')
fieldName, ok = project.readEntry(self.pluginName, 'fieldName')
pattern = self.searchText.text()
self.layer = QgsMapLayerRegistry.instance().mapLayer(layerId)
if self.layer is None:
self.iface.messageBar().pushMessage(self.name,
self.tr("Choose a layer first in settings dialog."),
QgsMessageBar.WARNING, 3)
self.showSettings()
return
if fieldName == "":
self.iface.messageBar().pushMessage(self.name,
self.tr("Choose a field first in settings dialog."),
QgsMessageBar.WARNING, 3)
self.showSettings()
return
fields = self.layer.dataProvider().fields()
fieldIndex = fields.indexFromName(fieldName)
# create feature request
featReq = QgsFeatureRequest()
featReq.setFlags(QgsFeatureRequest.NoGeometry)
featReq.setSubsetOfAttributes([fieldIndex])
iterator = self.layer.getFeatures(featReq)
# process search
f = QgsFeature()
results = []
self.continueSearch = True
while iterator.nextFeature(f) and self.continueSearch:
if self.evaluate(f[fieldName], pattern):
results.append(f.id())
QCoreApplication.processEvents()
# process results
if self.continueSearch:
msg = self.tr("{} features found").format(len(results))
legend = self.iface.legendInterface()
if (not legend.isLayerVisible(self.layer)):
msg += self.tr(' - The layer named {} is not visible').format(self.layer.name())
self.iface.messageBar().pushMessage(self.name,
msg,
QgsMessageBar.INFO, 2)
self.processResults(results)
def evaluate(self, v1, v2):
try:
remove_accents(unicode(v1)).index(remove_accents(v2))
return True
except ValueError:
return False
def processResults(self, results):
if self.layer is None:
return
self.layer.setSelectedFeatures(results)
if len(results) == 0:
return
canvas = self.iface.mapCanvas()
rect = canvas.mapRenderer().layerExtentToOutputExtent(self.layer, self.layer.boundingBoxOfSelected())
if rect is not None:
rect.scale(1.5)
canvas.setExtent(rect)
canvas.refresh()
def showSettings(self):
dlg = SettingsDialog()
dlg.exec_()
self.searchText_placeholderTextUpdate()