forked from isogeo/isogeo-plugin-qgis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
isogeo.py
1930 lines (1809 loc) · 87.7 KB
/
isogeo.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Isogeo
A QGIS plugin
Isogeo search engine within QGIS
-------------------
begin : 2016-07-22
git sha : $Format:%H$
copyright : (C) 2016 by Isogeo, Theo Sinatti, GeoJulien
email : projects+qgis@isogeo.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. *
* *
***************************************************************************/
"""
# Standard library
import os.path
import json
import base64
import urllib
import logging
from logging.handlers import RotatingFileHandler
import platform # about operating systems
from collections import OrderedDict
from functools import partial
# PyQT
from qgis.PyQt.QtCore import (QByteArray, QCoreApplication, QSettings,
Qt, QTranslator, QUrl, qVersion)
from qgis.PyQt.QtGui import (QAction, QIcon, QMessageBox, QStandardItemModel,
QStandardItem, QProgressBar)
from qgis.PyQt.QtNetwork import QNetworkAccessManager, QNetworkRequest
# PyQGIS
import db_manager.db_plugins.postgis.connector as con
from qgis.utils import iface, plugin_times, QGis
from qgis.core import (QgsAuthManager, QgsAuthMethodConfig,
QgsCoordinateReferenceSystem, QgsCoordinateTransform,
QgsDataSourceURI,
QgsMapLayerRegistry, QgsMessageLog,
QgsNetworkAccessManager,
QgsPoint, QgsRectangle, QgsRasterLayer, QgsVectorLayer)
# Initialize Qt resources from file resources.py
# import resources
# UI classes
from ui.isogeo_dockwidget import IsogeoDockWidget # main widget
from ui.auth.dlg_authentication import IsogeoAuthentication
from ui.credits.dlg_credits import IsogeoCredits
from ui.metadata.dlg_md_details import IsogeoMdDetails
from ui.quicksearch.dlg_quicksearch_new import QuicksearchNew
from ui.quicksearch.dlg_quicksearch_rename import QuicksearchRename
# Custom modules
from modules.api import IsogeoApiManager
from modules.metadata_display import MetadataDisplayer
from modules.results import ResultsManager
from modules.tools import Tools
from modules.url_builder import UrlBuilder
# ############################################################################
# ########## Globals ###############
# ##################################
# useful submodules and shortcuts
qgis_auth_mng = QgsAuthManager.instance()
custom_tools = Tools()
isogeo_api_mng = IsogeoApiManager()
msgBar = iface.messageBar()
network_mng = QNetworkAccessManager()
qsettings = QSettings()
srv_url_bld = UrlBuilder()
# LOG FILE ##
logger = logging.getLogger("IsogeoQgisPlugin")
logging.captureWarnings(True)
# logger.setLevel(logging.INFO) # all errors will be get
logger.setLevel(logging.DEBUG) # switch on it only for dev works
log_form = logging.Formatter("%(asctime)s || %(levelname)s "
"|| %(module)s - %(lineno)d ||"
"%(funcName)s || %(message)s")
logfile = RotatingFileHandler(os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"log_isogeo_plugin.log"),
"a", 5000000, 1)
# logfile.setLevel(logging.INFO)
logfile.setLevel(logging.DEBUG) # switch on it only for dev works
logfile.setFormatter(log_form)
logger.addHandler(logfile)
# icons
ico_bolt = QIcon(':/plugins/Isogeo/resources/bolt.svg')
ico_keyw = QIcon(':/plugins/Isogeo/resources/tag.svg')
ico_line = QIcon(':/plugins/Isogeo/resources/line.png')
ico_none = QIcon(':/plugins/Isogeo/resources/none.svg')
ico_poly = QIcon(':/plugins/Isogeo/resources/polygon.png')
ico_poin = QIcon(':/plugins/Isogeo/resources/point.png')
# ############################################################################
# ########## Classes ###############
# ##################################
class Isogeo:
"""QGIS Plugin Implementation."""
logger.info('\n\n\t========== Isogeo Search Engine for QGIS ==========')
logger.info('OS: {0}'.format(platform.platform()))
try:
logger.info('QGIS Version: {0}'.format(QGis.QGIS_VERSION))
except UnicodeEncodeError:
qgis_version = QGis.QGIS_VERSION.decode("latin1")
logger.info('QGIS Version: {0}'.format(qgis_version))
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# 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]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'isogeo_search_engine_{}.qm'.format(locale))
logger.info('Language applied: {0}'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
if qVersion() > '4.3.3':
QCoreApplication.installTranslator(self.translator)
else:
pass
else:
pass
if locale == "fr":
self.lang = "fr"
else:
self.lang = "en"
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Isogeo')
self.toolbar = self.iface.addToolBar(u'Isogeo')
self.toolbar.setObjectName(u'Isogeo')
self.pluginIsActive = False
self.dockwidget = None
# network manager included within QGIS
self.manager = QgsNetworkAccessManager.instance()
# self.manager = QNetworkAccessManager()
self.md_display = MetadataDisplayer(IsogeoMdDetails())
# UI submodules
self.auth_prompt_form = IsogeoAuthentication()
self.quicksearch_new_dialog = QuicksearchNew()
self.quicksearch_rename_dialog = QuicksearchRename()
self.credits_dialog = IsogeoCredits()
self.md_display = MetadataDisplayer(IsogeoMdDetails())
self.results_mng = ResultsManager(self)
# start variables
self.savedSearch = "first"
self.requestStatusClear = True
self.loopCount = 0
self.hardReset = False
self.showResult = False
self.showDetails = False
self.store = False
self.settingsRequest = False
self.PostGISdict = srv_url_bld.build_postgis_dict(qsettings)
# self.currentUrl = "https://v1.api.isogeo.com/resources/search?
# _limit=10&_include=links&_lang={0}".format(self.lang)
self.old_text = ""
self.page_index = 1
basepath = os.path.dirname(os.path.realpath(__file__))
self.json_path = basepath + '/user_settings/saved_searches.json'
# noinspection PyMethodMayBeStatic
def tr(self, message, context="Isogeo"):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:context: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate(context, message)
def add_action(self, ico_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
ico = QIcon(ico_path)
action = QAction(ico, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToWebMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
ico_path = ':/plugins/Isogeo/icon.png'
self.add_action(
ico_path,
text=self.tr(u'Search within Isogeo catalogs'),
callback=self.run,
parent=self.iface.mainWindow())
# --------------------------------------------------------------------------
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed."""
# disconnects
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
self.dockwidget = None
self.pluginIsActive = False
# try:
# reloadPlugin("isogeo_search_engine")
# except TypeError:
# pass
# try:
# reloadPlugin("isogeo_search_engine_dev")
# except TypeError:
# pass
def unload(self):
"""Remove the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginWebMenu(
self.tr(u'&Isogeo'), action)
try:
self.iface.mainWindow().statusBar().removeWidget(self.bar)
except Exception as e:
logger.error(e)
pass
self.iface.removeToolBarIcon(action)
self.dockwidget = None
logger.handlers = []
# remove the toolbar
del self.toolbar
# --------------------------------------------------------------------------
def user_authentication(self):
"""Test the validity of the user id and secret.
This is the first major function the plugin calls when executed. It
retrieves the id and secret from the config file. If they are set to
their default value, it asks for them.
If not, it tries to send a request.
"""
self.user_id = qsettings.value("isogeo-plugin/user-auth/id", 0)
self.user_secret = qsettings.value("isogeo-plugin/user-auth/secret", 0)
if self.user_id != 0 and self.user_secret != 0:
logging.info("User_authentication function is trying "
"to get a token from the id/secret")
self.ask_for_token(self.user_id, self.user_secret)
else:
logging.info("No id/secret. User authentication function "
"is showing the auth window.")
self.auth_prompt_form.show()
def write_ids_and_test(self):
"""Store the id & secret and launch the test function.
Called when the authentification window is closed,
it stores the values in the file, then call the
user_authentification function to test them.
"""
logging.info("Authentication window accepted. Writing"
" id/secret in QSettings.")
app_id = self.auth_prompt_form.ent_app_id.text()
app_secret = self.auth_prompt_form.ent_app_secret.text()
user_editor = self.auth_prompt_form.chb_isogeo_editor.isChecked()
# old name maintained for compatibility reasons
qsettings.setValue("isogeo-plugin/user-auth/id", app_id)
qsettings.setValue("isogeo-plugin/user-auth/secret", app_secret)
# new name to anticipate on future migration
qsettings.setValue("isogeo/api_auth/id", app_id)
qsettings.setValue("isogeo/api_auth/secret", app_secret)
qsettings.setValue("isogeo/user/editor", int(user_editor))
# anticipating on QGIS Auth Management
if qgis_auth_mng.authenticationDbPath():
logger.info("TRACKING - AUTH: new QGIS system already initialized")
auth_isogeo_id = qsettings.value("isogeo/app_auth/qgis_auth_id")
# already initialised => we are inside a QGIS app.
if (qgis_auth_mng.masterPasswordIsSet() and
auth_isogeo_id in qgis_auth_mng.availableAuthMethodConfigs()):
logger.info("TRACKING - AUTH: master password has been set"
" and Isogeo auth config already exists."
" Let's update it if needed.")
# get existing Isogeo auth id
auth_isogeo = qgis_auth_mng.availableAuthMethodConfigs()\
.get(auth_isogeo_id)
# update values from form
auth_isogeo.setConfig("username", app_id)
auth_isogeo.setConfig("password", app_secret)
# check if method parameters are correctly set and store it
if auth_isogeo.isValid():
qgis_auth_mng.updateAuthenticationConfig(auth_isogeo)
else:
logger.error("AUTH - Fail to create and store configuration")
elif (qgis_auth_mng.masterPasswordIsSet() and
auth_isogeo_id not in qgis_auth_mng.availableAuthMethodConfigs()):
logger.info("TRACKING - AUTH: master password has been set"
" and Isogeo auth config doesn't exist yet")
auth_isogeo_cfg = QgsAuthMethodConfig()
auth_isogeo_cfg.setName("Isogeo")
auth_isogeo_cfg.setMethod("Basic")
auth_isogeo_cfg.setUri("https://v1.api.isogeo.com/about")
auth_isogeo_cfg.setConfig("username", app_id)
auth_isogeo_cfg.setConfig("password", app_secret)
# check if method parameters are correctly set and store it
if auth_isogeo_cfg.isValid():
qgis_auth_mng.storeAuthenticationConfig(auth_isogeo_cfg)
qsettings.setValue("isogeo/app_auth/qgis_auth_id",
auth_isogeo_cfg.id())
else:
logger.error("AUTH - Fail to create and store configuration")
else:
logger.debug("TRACKING - AUTH: master password is not set")
pass
else:
pass
# launch authentication
self.user_authentication()
def ask_for_token(self, c_id, c_secret):
"""Ask a token from Isogeo API authentification page.
This send a POST request to Isogeo API with the user id and secret in
its header. The API should return an access token
"""
headervalue = "Basic " + base64.b64encode(c_id + ":" + c_secret)
data = urllib.urlencode({"grant_type": "client_credentials"})
databyte = QByteArray()
databyte.append(data)
url = QUrl('https://id.api.isogeo.com/oauth/token')
request = QNetworkRequest(url)
request.setRawHeader("Authorization", headervalue)
if self.requestStatusClear is True:
self.requestStatusClear = False
token_reply = self.manager.post(request, databyte)
token_reply.finished.connect(
partial(self.handle_token, answer=token_reply))
QgsMessageLog.logMessage("Authentication succeeded", "Isogeo")
def handle_token(self, answer):
"""Handle the API answer when asked for a token.
This handles the API answer. If it has sent an access token, it calls
the initialization function. If not, it raises an error, and ask
for new IDs
"""
logging.info("Asked a token and got a reply from the API.")
bytarray = answer.readAll()
content = str(bytarray)
try:
parsed_content = json.loads(content)
except ValueError as e:
if "No JSON object could be decoded" in e:
msgBar.pushMessage(self.tr("Request to Isogeo failed: please check your Internet connection."),
duration=10,
level=msgBar.WARNING)
logger.error("Internet connection failed")
self.pluginIsActive = False
# try:
# reloadPlugin("isogeo_search_engine")
# except TypeError:
# pass
# try:
# reloadPlugin("isogeo_search_engine_dev")
# except TypeError:
# pass
else:
pass
return
if 'access_token' in parsed_content:
logging.info("The API reply is an access token : "
"the request worked as expected.")
# TO DO : Appeler la fonction d'initialisation
self.token = "Bearer " + parsed_content.get('access_token')
if self.savedSearch == "first":
self.requestStatusClear = True
self.set_widget_status()
else:
self.requestStatusClear = True
self.send_request_to_isogeo_api(self.token)
# TO DO : Distinguer plusieurs cas d'erreur
elif 'error' in parsed_content:
logging.error("The API reply is an error. Id and secret must be "
"invalid. Asking for them again.")
QMessageBox.information(
iface.mainWindow(), self.tr("Error"), parsed_content['error'])
self.requestStatusClear = True
# displaying auth form
self.auth_prompt_form.ent_app_id.setText(self.user_id)
self.auth_prompt_form.ent_app_secret.setText(self.user_secret)
self.auth_prompt_form.show()
else:
self.requestStatusClear = True
logging.error("The API reply has an unexpected form : "
"{0}".format(parsed_content))
QMessageBox.information(
iface.mainWindow(), self.tr("Error"), self.tr("Unknown error"))
def send_request_to_isogeo_api(self, token, limit=10):
"""Send a content url to the Isogeo API.
This takes the currentUrl variable and send a request to this url,
using the token variable.
"""
myurl = QUrl(self.currentUrl)
request = QNetworkRequest(myurl)
request.setRawHeader("Authorization", token)
if self.requestStatusClear is True:
self.requestStatusClear = False
api_reply = self.manager.get(request)
api_reply.finished.connect(
partial(self.handle_api_reply, answer=api_reply))
else:
pass
def handle_api_reply(self, answer):
"""Handle the different possible Isogeo API answer.
This is called when the answer from the API is finished. If it's
content, it calls update_fields(). If it isn't, it means the token has
expired, and it calls ask_for_token()
"""
logging.info("Request sent to API and reply received.")
bytarray = answer.readAll()
content = str(bytarray)
if answer.error() == 0 and content != "":
logging.info("Reply is a result json.")
if self.showDetails is False and self.settingsRequest is False:
self.loopCount = 0
parsed_content = json.loads(content)
self.requestStatusClear = True
self.update_fields(parsed_content)
del parsed_content
elif self.showDetails is True:
self.showDetails = False
self.loopCount = 0
parsed_content = json.loads(content)
self.requestStatusClear = True
self.md_display.show_complete_md(parsed_content)
del parsed_content
elif self.settingsRequest is True:
self.settingsRequest = False
self.loopCount = 0
parsed_content = json.loads(content)
self.requestStatusClear = True
self.write_shares_info(parsed_content)
del parsed_content
elif answer.error() == 204:
logging.info("Token expired. Renewing it.")
self.loopCount = 0
self.requestStatusClear = True
self.ask_for_token(self.user_id, self.user_secret)
elif content == "":
logging.info("Empty reply. Weither no catalog is shared with the "
"plugin, or there is a problem (2 requests sent "
"together)")
if self.loopCount < 3:
self.loopCount += 1
answer.abort()
del answer
self.requestStatusClear = True
self.ask_for_token(self.user_id, self.user_secret)
else:
self.requestStatusClear = True
msgBar.pushMessage(
self.tr("The script is looping. Make sure you shared a "
"catalog with the plugin. If so, please report "
"this on the bug tracker."))
else:
self.requestStatusClear = True
QMessageBox.information(iface.mainWindow(),
self.tr("Error"),
self.tr("You are facing an unknown error. "
"Code: ") +
str(answer.error()) +
"\nPlease report tis on the bug tracker.")
# method end
return
def update_fields(self, result):
"""Update the fields content.
This takes an API answer and update the fields accordingly. It also
calls show_results in the end. This may change, so results would be
shown only when a specific button is pressed.
"""
# logs
logger.info("Update_fields function called on the API reply. reset = "
"{0}".format(self.hardReset))
QgsMessageLog.logMessage("Query sent & received: {}"
.format(result.get("query")),
"Isogeo")
# parsing
tags = isogeo_api_mng.get_tags(result.get("tags"))
self.old_text = self.dockwidget.txt_input.text()
# Getting the index of selected items in each combobox
params = self.save_params()
# Show how many results there are
self.results_count = result.get('total')
self.dockwidget.btn_show.setText(
str(self.results_count) + self.tr(" results"))
# Setting the number of rows in the result table
self.nb_page = str(custom_tools.results_pages_counter(self.results_count))
self.dockwidget.lbl_page.setText(
"page " + str(self.page_index) + self.tr(' on ') + self.nb_page)
# ALIASES FOR FREQUENTLY CALLED WIDGETS
cbb_contact = self.dockwidget.cbb_contact # contact
cbb_format = self.dockwidget.cbb_format # formats
cbb_geofilter = self.dockwidget.cbb_geofilter # geographic
cbb_geo_op = self.dockwidget.cbb_geo_op # geometric operator
cbb_inspire = self.dockwidget.cbb_inspire # INSPIRE themes
cbb_license = self.dockwidget.cbb_license # license
cbb_ob = self.dockwidget.cbb_ob # sort parameter
cbb_od = self.dockwidget.cbb_od # sort direction
cbb_owner = self.dockwidget.cbb_owner # owners
cbb_quicksearch = self.dockwidget.cbb_quicksearch # quick searches
cbb_srs = self.dockwidget.cbb_srs # coordinate systems
cbb_type = self.dockwidget.cbb_type # metadata type
tbl_result = self.dockwidget.tbl_result # results table
txt_input = self.dockwidget.txt_input # search terms
# RESET WiDGETS
cbb_contact.clear()
cbb_format.clear()
cbb_geofilter.clear()
cbb_inspire.clear()
cbb_license.clear()
cbb_owner.clear()
cbb_srs.clear()
cbb_type.clear()
tbl_result.clearContents()
tbl_result.setRowCount(0)
# Filling the quick search combobox (also the one in settings tab)
with open(self.json_path) as data_file:
saved_searches = json.load(data_file)
search_list = saved_searches.keys()
search_list.pop(search_list.index('_default'))
if '_current' in search_list:
search_list.pop(search_list.index('_current'))
cbb_quicksearch.clear()
self.dockwidget.cbb_modify_sr.clear()
# cbb_quicksearch.addItem(icon, self.tr('Quick Search'))
cbb_quicksearch.addItem(ico_bolt, "")
for i in search_list:
cbb_quicksearch.addItem(i, i)
self.dockwidget.cbb_modify_sr.addItem(i, i)
width = cbb_quicksearch.view().sizeHintForColumn(0) + 5
cbb_quicksearch.view().setMinimumWidth(width)
# Initiating the "nothing selected" and "None" items in each combobox
cbb_inspire.addItem(" - ")
cbb_inspire.addItem(ico_none,
self.tr("None"),
"has-no:keyword:inspire-theme")
cbb_owner.addItem(" - ")
cbb_format.addItem(" - ")
cbb_format.addItem(ico_none, self.tr("None"), "has-no:format")
cbb_srs.addItem(" - ")
cbb_srs.addItem(ico_none, self.tr("None"), "has-no:coordinate-system")
cbb_geofilter.addItem(" - ")
cbb_type.addItem(self.tr("All types"))
cbb_contact.addItem(" - ")
cbb_contact.addItem(ico_none, self.tr("None"), "has-no:contact")
cbb_license.addItem(" - ")
cbb_license.addItem(ico_none, self.tr("None"), "has-no:license")
# Initializing the cbb that dont't need to be updated
if self.savedSearch == "_default" or self.hardReset is True:
tbl_result.horizontalHeader().setResizeMode(1)
tbl_result.horizontalHeader().setResizeMode(1, 0)
tbl_result.horizontalHeader().setResizeMode(2, 0)
tbl_result.horizontalHeader().resizeSection(1, 80)
tbl_result.horizontalHeader().resizeSection(2, 50)
tbl_result.verticalHeader().setResizeMode(3)
# Geographical operator cbb
dict_operation = OrderedDict([(self.tr(
'Intersects'), "intersects"),
(self.tr('within'), "within"),
(self.tr('contains'), "contains")])
for key in dict_operation.keys():
cbb_geo_op.addItem(key, dict_operation.get(key))
# Order by cbb
dict_ob = OrderedDict([(self.tr("Relevance"), "relevance"),
(self.tr("Alphabetical order"), "title"),
(self.tr("Data modified"), "modified"),
(self.tr("Data created"), "created"),
(self.tr("Metadata modified"), "_modified"),
(self.tr("Metadata created"), "_created")]
)
for key in dict_ob.keys():
cbb_ob.addItem(key, dict_ob.get(key))
# Order direction cbb
dict_od = OrderedDict([(self.tr("Descending"), "desc"),
(self.tr("Ascendant"), "asc")]
)
for key in dict_od.keys():
cbb_od.addItem(key, dict_od.get(key))
# Filling comboboxes
# Owners
md_owners = tags.get("owners")
for i in sorted(md_owners):
cbb_owner.addItem(i, md_owners.get(i))
# INSPIRE themes
inspire = tags.get("inspire")
for i in sorted(inspire):
cbb_inspire.addItem(i, inspire.get(i))
width = cbb_inspire.view().sizeHintForColumn(0) + 5
cbb_inspire.view().setMinimumWidth(width)
# Formats
formats = tags.get("formats")
for i in sorted(formats):
cbb_format.addItem(i, formats.get(i))
# Coordinate system
srs = tags.get("srs")
for i in sorted(srs):
cbb_srs.addItem(i, srs.get(i))
# Contacts
contacts = tags.get("contacts")
for i in sorted(contacts):
cbb_contact.addItem(i, contacts.get(i))
# Licenses
licenses = tags.get("licenses")
for i in sorted(licenses):
cbb_license.addItem(i, licenses.get(i))
# Resource type
md_types = tags.get("types")
for i in sorted(md_types):
cbb_type.addItem(i, md_types.get(i))
# Geographical filter
cbb_geofilter.addItem(self.tr("Map canvas"), "mapcanvas")
layers = QgsMapLayerRegistry.instance().mapLayers().values()
for layer in layers:
if layer.type() == 0:
if layer.geometryType() == 2:
cbb_geofilter.addItem(ico_poly, layer.name(), layer)
elif layer.geometryType() == 1:
cbb_geofilter.addItem(ico_line, layer.name(), layer)
elif layer.geometryType() == 0:
cbb_geofilter.addItem(ico_poin, layer.name(), layer)
# Putting all the comboboxes selected index to their previous
# location. Necessary as all comboboxes items have been removed and
# put back in place. We do not want each combobox to go back to their
# default selected item
if self.hardReset is False:
if self.savedSearch is False:
# Owners
previous_index = cbb_owner.findData(params.get('owner'))
cbb_owner.setCurrentIndex(previous_index)
# Inspire keywords
previous_index = cbb_inspire.findData(params.get('inspire'))
cbb_inspire.setCurrentIndex(previous_index)
# Data type
previous_index = cbb_type.findData(params.get('datatype'))
cbb_type.setCurrentIndex(previous_index)
# Data format
previous_index = cbb_format.findData(params.get('format'))
cbb_format.setCurrentIndex(previous_index)
# Coordinate system
previous_index = cbb_srs.findData(params.get('srs'))
cbb_srs.setCurrentIndex(previous_index)
# Contact
previous_index = cbb_contact.findData(params.get('contact'))
cbb_contact.setCurrentIndex(previous_index)
# License
previous_index = cbb_license.findData(params.get('license'))
cbb_license.setCurrentIndex(previous_index)
# Sorting order
cbb_ob.setCurrentIndex(cbb_ob.findData(params.get('ob')))
# Sorting direction
cbb_od.setCurrentIndex(cbb_od.findData(params.get('od')))
# Quick searches
previous_index = cbb_quicksearch.findData(params.get('favorite'))
cbb_quicksearch.setCurrentIndex(previous_index)
# Operator for geographical filter
previous_index = cbb_geo_op.findData(params.get('operation'))
cbb_geo_op.setCurrentIndex(previous_index)
# Geographical filter
if params.get('geofilter') == "mapcanvas":
previous_index = cbb_geofilter.findData("mapcanvas")
cbb_geofilter.setCurrentIndex(previous_index)
else:
prev_index = cbb_geofilter.findText(params['geofilter'])
cbb_geofilter.setCurrentIndex(prev_index)
# Filling the keywords special combobox (items checkable)
# In the case where it isn't a saved research. So we have to
# check the items that were previously checked
model = QStandardItemModel(5, 1) # 5 rows, 1 col
# Creating the "None" option, always on top.
none_item = QStandardItem(self.tr('None'))
none_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
none_item.setData("has-no:keyword", 32)
if none_item.data(32) in params.get('keys'):
none_item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(1, none_item)
else:
none_item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.insertRow(1, none_item)
# Filling the combobox with all the normal items
i = 2
keywords = tags.get('keywords')
selected_kwd = []
for j in sorted(keywords):
item = QStandardItem(j)
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setData(keywords.get(j), 32)
# As all items have been destroyed and generated again, we
# have to set the checkstate (checked/unchecked) according
# to what the user had chosen.
if item.data(32) in params.get('keys'):
item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(0, item)
selected_kwd.append(j)
else:
item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.setItem(i, 0, item)
i += 1
# Creating the first item, that is just a banner for
# the combobox.
first_item = QStandardItem(self.tr('---- Keywords ----'))
first_item.setIcon(ico_keyw)
first_item.setSelectable(False)
model.insertRow(0, first_item)
model.itemChanged.connect(self.search)
self.dockwidget.cbb_keywords.setModel(model)
self.dockwidget.cbb_keywords.setToolTip(self.tr("Selected keywords:")
+ "\n"
+ "\n ".join(selected_kwd))
# When it is a saved research, we have to look in the json, and
# check the items accordingly (quite close to the previous case)
else:
# Opening the json and getting the keywords
with open(self.json_path) as data_file:
saved_searches = json.load(data_file)
search_params = saved_searches.get(self.savedSearch)
keywords_list = []
for a in search_params.keys():
if a.startswith("keyword"):
keywords_list.append(search_params.get(a))
model = QStandardItemModel(5, 1) # 5 rows, 1 col
# None item, on top of the cbb
none_item = QStandardItem(self.tr('None'))
none_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
none_item.setData("has-no:keyword", 32)
if none_item.data(32) in keywords_list:
none_item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(1, none_item)
else:
none_item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.insertRow(1, none_item)
# Filling with the standard items
i = 2
keywords = tags.get('keywords')
selected_kwd = []
for j in sorted(keywords):
item = QStandardItem(j)
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setData(keywords.get(j), 32)
# As all items have been destroyed and generated again, we
# have to set the checkstate (checked/unchecked) according
# to what the user had chosen.
if a[0] in keywords_list:
item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(0, item)
selected_kwd.append(a[1])
else:
item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.setItem(i, 0, item)
i += 1
# Banner item
first_item = QStandardItem(u"---- {} ----"
.format(self.tr('Keywords')))
first_item.setIcon(ico_keyw)
first_item.setSelectable(False)
model.insertRow(0, first_item)
model.itemChanged.connect(self.search)
self.dockwidget.cbb_keywords.setModel(model)
self.dockwidget.cbb_keywords.setToolTip(self.tr("Selected keywords:")
+ "\n"
+ "\n ".join(selected_kwd))
# Putting widgets to their previous states according
# to the json content
# Line edit content
txt_input.setText(search_params.get('text'))
# Owners
saved_index = cbb_owner.findData(search_params.get('owner'))
cbb_owner.setCurrentIndex(saved_index)
# Inspire keywords
value = search_params.get('inspire')
saved_index = cbb_inspire.findData(value)
cbb_inspire.setCurrentIndex(saved_index)
# Formats
saved_index = cbb_format.findData(search_params.get('format'))
cbb_format.setCurrentIndex(saved_index)
# Coordinate systems
saved_index = cbb_srs.findData(search_params.get('srs'))
cbb_srs.setCurrentIndex(saved_index)
# Contact
saved_index = cbb_contact.findData(search_params.get('contact'))
cbb_contact.setCurrentIndex(saved_index)
# License
saved_index = cbb_license.findData(search_params.get('license'))
cbb_license.setCurrentIndex(saved_index)
# Geographical filter
value = search_params.get('geofilter')
saved_index = cbb_geofilter.findData(value)
cbb_geofilter.setCurrentIndex(saved_index)
# Operator for the geographical filter
value = search_params.get('operation')
saved_index = cbb_geo_op.findData(value)
cbb_geo_op.setCurrentIndex(saved_index)
# Data type
saved_index = cbb_type.findData(search_params.get('datatype'))
cbb_type.setCurrentIndex(saved_index)
# Sorting order
saved_index = cbb_ob.findData(search_params.get('ob'))
cbb_ob.setCurrentIndex(saved_index)
# Sorting direction
saved_index = cbb_od.findData(search_params.get('od'))
cbb_od.setCurrentIndex(saved_index)
# Quick searches
if self.savedSearch != "_default":
saved_index = cbb_quicksearch.findData(self.savedSearch)
cbb_quicksearch.setCurrentIndex(saved_index)
self.savedSearch = False
# In case of a hard reset, we don't have to worry about widgets
# previous state as they are to be reset
else:
model = QStandardItemModel(5, 1) # 5 rows, 1 col
# None item
none_item = QStandardItem(self.tr('None'))
none_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
none_item.setData("has-no:keyword", 32)
if none_item.data(32) in params['keys']:
none_item.setData(Qt.Checked, Qt.CheckStateRole)
model.insertRow(1, none_item)
else:
none_item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.insertRow(1, none_item)
# Standard items
i = 2
keywords = tags.get('keywords')
for j in sorted(keywords):
item = QStandardItem(j)
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setData(keywords.get(j), 32)
# As all items have been destroyed and generated again, we have
# to set the checkstate (checked/unchecked) according to what
# the user had chosen
item.setData(Qt.Unchecked, Qt.CheckStateRole)
model.setItem(i, 0, item)
i += 1
# Banner item
first_item = QStandardItem(u"---- {} ----"
.format(self.tr('Keywords')))
first_item.setIcon(ico_keyw)
first_item.setSelectable(False)
model.insertRow(0, first_item)
model.itemChanged.connect(self.search)
self.dockwidget.cbb_keywords.setModel(model)
self.dockwidget.cbb_keywords.setToolTip(self.tr("No keyword selected"))
# Coloring the Show result button
self.dockwidget.btn_show.setStyleSheet(
"QPushButton "
"{background-color: rgb(255, 144, 0); color: white}")
# Show result, if we want them to be shown (button 'show result', 'next
# page' or 'previous page' pressed)
if self.showResult is True:
self.dockwidget.btn_next.setEnabled(True)
self.dockwidget.btn_previous.setEnabled(True)
cbb_ob.setEnabled(True)
cbb_od.setEnabled(True)
self.dockwidget.btn_show.setStyleSheet("")
# self.dockwidget.btn_show.setToolTip(self.tr("Display results"))
self.results_mng.show_results(result,
self.dockwidget.tbl_result,
progress_bar=self.bar)
self.write_search_params('_current', search_kind="Current")
self.store = True
# Re enable all user input fields now the search function is
# finished.
self.switch_widgets_on_and_off()
if self.results_count == 0:
self.dockwidget.btn_show.setEnabled(False)
# hard reset
self.hardReset = False
self.showResult = False
def add_loading_bar(self):
"""Display a "loading" bar."""
self.bar = QProgressBar()
self.bar.setRange(0, 0)
self.bar.setFixedWidth(120)
iface.mainWindow().statusBar().insertPermanentWidget(0, self.bar)
def add_layer(self, layer_info):
"""Add a layer to QGIS map canvas.
Take layer index, search the required information to add it in
the temporary dictionnary constructed in the show_results function.
It then adds it.
"""
logger.info("add_layer method called.")
if layer_info[0] == "index":
combobox = self.dockwidget.tbl_result.cellWidget(layer_info[1], 3)
layer_info = combobox.itemData(combobox.currentIndex())
elif layer_info[0] == "info":
layer_info = layer_info[1]
else:
pass
if type(layer_info) == list: