-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinteractive_map_tracking.py
1518 lines (1233 loc) · 64.6 KB
/
interactive_map_tracking.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 -*-
"""
/***************************************************************************
interactive_map_tracking
A QGIS plugin
A QGIS 2.6 plugin to track camera of user , AND/OR to autocommit/refresh edit on PostGIS vector layer
-------------------
begin : 2015-02-20
git sha : $Format:%H$
copyright : (C) 2015 by Lionel Atty, IGN, SIDT
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* 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.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
from PyQt4.QtGui import QAction, QIcon
# Initialize Qt resources from file resources.py
import resources_rc
# Import the code for the dialog
from interactive_map_tracking_dialog import interactive_map_trackingDialog
import os.path
from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
from PyQt4.QtCore import QObject, SIGNAL, QUrl
from PyQt4.QtGui import QAction, QIcon, QTabWidget
from PyQt4.QtWebKit import QWebSettings, QWebView
from qgis.gui import QgsMessageBar
from qgis.core import *
import qgis_layer_tools
import qgis_mapcanvas_tools
import qgis_log_tools
import imt_tools
#
# for beta test purposes
#
from PyQt4.QtCore import QTimer
import Queue
from collections import namedtuple
import time
import threading
def CONVERT_S_TO_MS(s):
return s*1000
# with Qt resources files
# gui_doc_about = ":/plugins/interactive_map_tracking/gui_doc/About.htm"
# gui_doc_user_doc = ":/plugins/interactive_map_tracking/gui_doc/Simplified_User_Guide.htm"
# with absolute (os) path
class interactive_map_tracking:
"""QGIS Plugin Implementation."""
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
"""
import time
from PyQt4.QtNetwork import QNetworkProxy
current_time = time.time()
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.normcase(os.path.dirname(__file__))
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'interactive_map_tracking_{}.qm'.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)
# Create the dialog (after translation) and keep reference
self.dlg = interactive_map_trackingDialog()
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Interactive Map Tracking')
# TODO: We are going to let the user set this up in a future iteration
self.toolbar = self.iface.addToolBar(u'interactive_map_tracking')
self.toolbar.setObjectName(u'interactive_map_tracking')
# self.selections = []
self.qsettings_prefix_name = "imt/"
self.bSignalForLayerModifiedConnected = False
self.bSignalForLayerChangedConnected = False
self.bSignalForExtentsChangedConnected = False
# self.idCameraPositionLayerInBox = 0
self.currentLayerForTrackingPosition = None
self.bSignalForProjectReadConnected = True
QObject.connect(self.iface, SIGNAL("projectRead()"), self.qgisInterfaceProjectRead)
# MUTEX
self.bUseV2Functionnalities = self.dlg.enableUseMutexForTP.isChecked()
# url: https://docs.python.org/2/library/collections.html#collections.namedtuple
# Definition : namedtuples 'type'
self.TP_NAMEDTUPLE_LET = namedtuple('TP_NAMEDTUPLE_LET', ['layer', 'extent', 'w_time'])
self.TP_NAMEDTUPLE_ET = namedtuple('TP_NAMEDTUPLE_ET', ['extent', 'w_time'])
# LIFO Queue to save (in real time) requests for tracking position
self.tp_queue_rt_ntuples_let = Queue.LifoQueue()
# self.tp_rt_ntuples_let = self.TP_NAMEDTUPLE_LET(None, None, current_time)
self.tp_dict_key_l_values_et = {}
self.tp_list_fets = []
self.tp_dict_key_l_values_listfeatures = {}
self.tp_dict_layers_to_commit = {}
#
self.qtimer_tracking_position_rtt_to_memory = QTimer()
self.qtimer_tracking_position_rtt_to_memory.timeout.connect(self.tracking_position_qtimer_rttp_to_memory)
self.qtimer_tracking_position_memory_to_geom = QTimer()
self.qtimer_tracking_position_memory_to_geom.timeout.connect(self.tracking_position_qtimer_memory_to_geom)
self.qtimer_tracking_position_geom_to_layer = QTimer()
self.qtimer_tracking_position_geom_to_layer.timeout.connect(self.tracking_position_qtimer_geom_to_layer)
self.qtimer_tracking_position_layers_to_commit = QTimer()
self.qtimer_tracking_position_layers_to_commit.timeout.connect(self.tracking_position_qtimer_layers_to_commit)
# OPTIONS: timing reactions
#
self.tp_timers = imt_tools.TpTimer()
# TODO : add this options timing on GUI
# in S
tp_threshold_time_for_realtime_tracking_position = 0.125 # i.e. 8hz => (max) 8 tracking positions record per second
# in MS
tp_threshold_time_for_tp_to_mem = 250 # add to reference timing: realtime_tracking_position
tp_threshold_time_for_construct_geom = 50 # add to reference timing: tp_to_mem
tp_threshold_time_for_sending_geom_to_layer = 100 # add to reference timing: construct_geom
tp_threshold_time_for_sending_layer_to_dp = 100 # add to reference timing: sending_geom_to_layer
#
self.tp_timers.set_delay("tp_threshold_time_for_realtime_tracking_position",
tp_threshold_time_for_realtime_tracking_position)
self.tp_timers.set_delay("tp_threshold_time_for_tp_to_mem", tp_threshold_time_for_tp_to_mem)
self.tp_timers.set_delay("tp_threshold_time_for_construct_geom", tp_threshold_time_for_construct_geom)
self.tp_timers.set_delay("tp_threshold_time_for_sending_geom_to_layer",
tp_threshold_time_for_sending_geom_to_layer)
self.tp_timers.set_delay("tp_threshold_time_for_sending_layer_to_dp", tp_threshold_time_for_sending_layer_to_dp)
# in S
delay_time_still_moving = 0.750 # delta time used to decide if the user still moving on the map
self.tp_timers.set_delay("delay_time_still_moving", delay_time_still_moving)
# for timing
self.tp_time_last_rttp_to_mem = current_time
self.tp_time_last_construct_geom = current_time
self.tp_time_last_send_geom_to_layer = current_time
self.tp_time_last_send_layer_to_dp = current_time
self.tp_queue_qgis_event_to_mem = []
"""
Delay on manager of trackposition requests
can be interesting to evaluate/benchmark the impact on this value
"""
self.qtimer_tracking_position_delay = self.tp_timers.get_delay(
"p_threshold_time_for_realtime_tracking_position") # in ms
# user-id:
# from user id OS
os_username = imt_tools.get_os_username()
# try to use IP to identify the user
user_ip = imt_tools.get_lan_ip()
#
self.tp_user_name = os_username + " (" + user_ip + ")"
# default value for threshold scale
self.threshold = 0
self.tp_id_user_id = 0
self.tp_id_w_time = 0
self.values = []
self.bRefreshMapFromAutoSave = False
self.TP_NAMEDTUPLE_WEBVIEW = namedtuple(
'TP_NAMEDTUPLE_WEBVIEW',
['state', 'width', 'height', 'online_url', 'offline_url']
)
# very dirty @FIXME @TODO : here is the proper way to do it (from within the class `self.plugin_dir`)
self.qgis_plugins_directory = self.plugin_dir
self.webview_offline_about = os.path.join(self.qgis_plugins_directory , "gui_doc","About.htm" )
self.webview_offline_user_doc = os.path.join(self.qgis_plugins_directory , "gui_doc", "Simplified_User_Guide.htm" )
self.webview_online_about = "https://github.com/Remi-C/interactive_map_tracking/wiki/[User]-About"
self.webview_online_user_doc = "https://github.com/Remi-C/interactive_map_tracking/wiki/[User]-User-Guide"
self.webview_dict = {}
# url : http://qt-project.org/doc/qt-4.8/qurl.html
self.webview_default_tuple = self.TP_NAMEDTUPLE_WEBVIEW('init', 0, 0, QUrl(""), QUrl(""))
self.webview_dict[self.dlg.webView_userdoc] = self.TP_NAMEDTUPLE_WEBVIEW(
'init',
0, 0,
QUrl(self.webview_online_user_doc),
QUrl(self.webview_offline_user_doc)
)
self.webview_dict[self.dlg.webView_about] = self.TP_NAMEDTUPLE_WEBVIEW(
'init',
0, 0,
QUrl(self.webview_online_about),
QUrl(self.webview_offline_about)
)
self.webview_current = None
self.webview_margin = 60
#getting proxy
s = QSettings() #getting proxy from qgis options settings
proxyEnabled = s.value("proxy/proxyEnabled", "")
proxyType = s.value("proxy/proxyType", "" )
proxyHost = s.value("proxy/proxyHost", "" )
proxyPort = s.value("proxy/proxyPort", "" )
proxyUser = s.value("proxy/proxyUser", "" )
proxyPassword = s.value("proxy/proxyPassword", "" )
if proxyEnabled == "true": # test if there are proxy settings
proxy = QNetworkProxy()
if proxyType == "DefaultProxy":
proxy.setType(QNetworkProxy.DefaultProxy)
elif proxyType == "Socks5Proxy":
proxy.setType(QNetworkProxy.Socks5Proxy)
elif proxyType == "HttpProxy":
proxy.setType(QNetworkProxy.HttpProxy)
elif proxyType == "HttpCachingProxy":
proxy.setType(QNetworkProxy.HttpCachingProxy)
elif proxyType == "FtpCachingProxy":
proxy.setType(QNetworkProxy.FtpCachingProxy)
proxy.setHostName(proxyHost)
proxy.setPort(int(proxyPort))
proxy.setUser(proxyUser)
proxy.setPassword(proxyPassword)
QNetworkProxy.setApplicationProxy(proxy)
self.dict_tabs_size = {}
self.tp_last_extent_saved = QgsRectangle()
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""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
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('interactive_map_tracking', message)
def add_action(
self,
icon_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
"""
icon = QIcon(icon_path)
action = QAction(icon, 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.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
qgis_log_tools.logMessageINFO("Launch 'InitGui(...)' ...")
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/interactive_map_tracking/icon.png'
# icon_path = ':/plugins/interactive_map_tracking/icon_svg.png'
self.add_action(
icon_path,
text=self.tr(u'Tools for Interactive Map Tracking'),
callback=self.run,
parent=self.iface.mainWindow())
#
self.init_plugin()
# Connections
# activate/desactivate plugin
self.dlg.enablePlugin.clicked.connect(self.enabled_plugin)
# activate/desactivate autosave
self.dlg.enableAutoSave.clicked.connect(self.enabled_autosave)
# activate/desactive tracking position
self.dlg.enableTrackPosition.clicked.connect(self.enabled_trackposition)
# box for tracking layers
self.dlg.refreshLayersListForTrackPosition.clicked.connect(self.refreshComboBoxLayers)
QObject.connect(self.dlg.trackingPositionLayerCombo, SIGNAL("currentIndexChanged ( const QString & )"),
self.currentIndexChangedTPLCB)
QObject.connect(self.dlg.IMT_Window_Tabs, SIGNAL("currentChanged (int)"), self.QTabWidget_CurrentChanged)
# Dev Debug
self.dlg.enableLogging.clicked.connect(self.enableLogging)
self.dlg.enableUseMutexForTP.clicked.connect(self.enableUseMutexForTP)
# hide the window plugin
# don't change the state (options) of the plugin
self.dlg.buttonHide.clicked.connect(self.hide_plugin)
#
self.refreshComboBoxLayers()
self.thresholdChanged()
#
#QgsMessageLog.logMessage("enableLogging()")
self.enableLogging()
self.enableUseMutexForTP()
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&Interactive Map Tracking'),
action)
self.iface.removeToolBarIcon(action)
def onResizeEvent(self, event):
# url: http://openclassrooms.com/forum/sujet/dimensionnement-automatique-d-une-qtabwidget
QTabWidget.resizeEvent(self.dlg.IMT_Window_Tabs, event)
# url: http://qt-project.org/doc/qt-4.8/qresizeevent.html
self.dict_tabs_size[self.dlg.IMT_Window_Tabs.currentIndex()] = event.size()
def run(self):
"""Run method that performs all the real work"""
#
# set the icon IMT ^^
icon_path = ':/plugins/interactive_map_tracking/icon.png'
self.dlg.setWindowIcon(QIcon(icon_path))
# set the tab at init
self.dlg.IMT_Window_Tabs.setCurrentIndex(0)
# url: http://qt-project.org/doc/qt-4.8/qtabwidget.html#resizeEvent
self.dlg.IMT_Window_Tabs.resizeEvent = self.onResizeEvent
# show the dialog
self.dlg.show()
#
self.enabled_plugin()
# Run the dialog event loop
self.dlg.exec_()
def init_plugin(self):
""" Init the plugin
- Set defaults values in QSetting # note : some value are already setted !
- Setup the GUI
"""
qgis_log_tools.logMessageINFO("Launch 'init_plugin(...)' ...")
s = QSettings()
# retrieve default states from Qt Creator GUI design
self.update_setting(s, "enabledPlugin", self.dlg.enablePlugin)
self.update_setting(s, "enabledAutoSave", self.dlg.enableAutoSave)
self.update_setting(s, "enabledTrackPosition", self.dlg.enableTrackPosition)
self.update_setting(s, "enabledLogging", self.dlg.enableLogging)
self.update_setting(s, "enableV2", self.dlg.enableUseMutexForTP)
self.thresholdChanged()
s.setValue(self.qsettings_prefix_name + "threshold", str(self.threshold))
if s.value(self.qsettings_prefix_name + "enabledPlugin", "") == "true":
self.update_checkbox(s, "enableAutoSave", self.dlg.enableAutoSave)
self.update_checkbox(s, "enableTrackPosition", self.dlg.enableTrackPosition)
self.update_checkbox(s, "enableLogging", self.dlg.enableLogging)
self.update_checkbox(s, "enableV2", self.dlg.enableUseMutexForTP)
#
self.dlg.thresholdLabel.setEnabled(True)
self.dlg.threshold_extent.setEnabled(True)
QObject.connect(self.dlg.threshold_extent, SIGNAL("returnPressed ()"), self.thresholdChanged)
self.thresholdChanged()
else:
#
self.dlg.enableAutoSave.setDisabled(True)
self.dlg.enableTrackPosition.setDisabled(True)
self.dlg.enableLogging.setDisabled(True)
self.dlg.enableUseMutexForTP.setDisabled(True)
self.dlg.thresholdLabel.setDisabled(True)
self.dlg.threshold_extent.setDisabled(True)
#
QObject.disconnect(self.dlg.threshold_extent, SIGNAL("returnPressed ()"), self.thresholdChanged)
QObject.disconnect(self.dlg.webView_about, SIGNAL("loadFinished (bool)"), self.webview_loadFinished)
QObject.disconnect(self.dlg.webView_userdoc, SIGNAL("loadFinished (bool)"), self.webview_loadFinished)
def update_setting(self, _settings, _name_in_setting, _checkbox):
"""
:param _settings:
:param _name_in_setting:
:param _checkbox:
"""
if _checkbox.isChecked():
_settings.setValue(self.qsettings_prefix_name + _name_in_setting, "true")
else:
_settings.setValue(self.qsettings_prefix_name + _name_in_setting, "false")
def update_checkbox(self, _settings, _name_in_setting, _checkbox):
""" According to values stores in QSetting, update the state of a checkbox
:param _settings: (local) Setting from Qt
:type _settings: QSettings
:param _name_in_setting: setting's name for the _checkbox in QSettings
:type _name_in_setting: QString
:param _checkbox: CheckBox to update state
:type _checkbox: QCheckBox
"""
if _settings.value(self.qsettings_prefix_name + _name_in_setting, "") == "true":
_checkbox.setDisabled(False)
_checkbox.setChecked(True)
else:
_checkbox.setChecked(False)
_checkbox.setDisabled(True)
def disconnectSignaleForLayerCrsChanged(self, layer):
""" Disconnect the signal: 'layerCrsChanged' of the layer given
:param layer:
:return:
"""
if None != layer and self.bSignalForLayerModifiedConnected:
QObject.disconnect(layer, SIGNAL("layerCrsChanged()"), self.currentLayerCrsChanged)
self.bSignalForLayerCrsChangedConnected = False
#
qgis_log_tools.logMessageINFO("Disconnect SIGNAL on layer: " + layer.name())
def disconnectSignalForLayerModified(self, layer):
""" Disconnect the signal: 'Layer Modified' of the layer given
:param layer: QGIS Layer
:type layer: QgsMapLayer
"""
if None != layer and self.bSignalForLayerModifiedConnected:
QObject.disconnect(layer, SIGNAL("layerModified()"), self.currentLayerModified)
self.bSignalForLayerModifiedConnected = False
#
qgis_log_tools.logMessageINFO("Disconnect SIGNAL on layer: " + layer.name())
def disconnectSignalForLayerChanged(self):
""" Disconnect the signal: 'Current Layer Changed' of the QGIS Interface"""
#
if self.bSignalForLayerChangedConnected:
QObject.disconnect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"),
self.qgisInterfaceCurrentLayerChanged)
self.bSignalForLayerChangedConnected = False
#
qgis_log_tools.logMessageINFO("Disconnect SIGNAL on QGISInterface")
def disconnectSignalForExtentsChanged(self):
""" Disconnect the signal: 'Canvas Extents Changed' of the QGIS MapCanvas """
#
if self.bSignalForExtentsChangedConnected:
self.iface.mapCanvas().extentsChanged.disconnect(self.canvasExtentsChanged)
self.bSignalForExtentsChangedConnected = False
#
qgis_log_tools.logMessageINFO("Disconnect SIGNAL on QGISMapCanvas")
def connectSignaleForLayerCrsChanged(self, layer):
""" Disconnect the signal: 'layerCrsChanged' of the layer given
:param layer:
:return:
"""
if None != layer and not self.bSignalForLayerCrsChangedConnected:
QObject.connect(layer, SIGNAL("layerCrsChanged()"), self.currentLayerCrsChanged)
self.bSignalForLayerCrsChangedConnected = False
#
qgis_log_tools.logMessageINFO("Connect SIGNAL on layer: " + layer.name())
def connectSignalForLayerModified(self, layer):
""" Connect the signal: "Layer Modified" to the layer given
:param layer: QGIS layer
:type layer: QgsMapLayer
"""
if None != layer and not self.bSignalForLayerModifiedConnected:
QObject.connect(layer, SIGNAL("layerModified()"), self.currentLayerModified)
self.bSignalForLayerModifiedConnected = True
#
qgis_log_tools.logMessageINFO("Connect SIGNAL on layer: " + layer.name())
def connectSignalForLayerChanged(self):
""" Connect the signal: 'Layer Changed' to the layer given """
#
if not self.bSignalForLayerChangedConnected:
QObject.connect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"),
self.qgisInterfaceCurrentLayerChanged)
self.bSignalForLayerChangedConnected = True
#
qgis_log_tools.logMessageINFO("Connect SIGNAL on QGISInterface")
def connectSignalForExtentsChanged(self):
""" Connect the signal: 'Extent Changed' to the QGIS MapCanvas """
#
if not self.bSignalForExtentsChangedConnected:
self.iface.mapCanvas().extentsChanged.connect(self.canvasExtentsChanged)
self.bSignalForExtentsChangedConnected = True
#
qgis_log_tools.logMessageINFO("Connect SIGNAL on QGISMapCanvas")
def disconnectSignals(self, layer):
""" Disconnect alls signals (of current layer & QGIS MapCanvas, Interface) """
#
qgis_log_tools.logMessageINFO("Disconnect all SIGNALS ...")
#
self.disconnectSignalForLayerModified(layer)
self.disconnectSignalForLayerChanged()
self.disconnectSignalForExtentsChanged()
self.disconnectSignaleForLayerCrsChanged()
#
QObject.disconnect(self.dlg.webView_about, SIGNAL("loadFinished (bool)"), self.webview_loadFinished)
QObject.disconnect(self.dlg.webView_userdoc, SIGNAL("loadFinished (bool)"), self.webview_loadFinished)
def qgisInterfaceCurrentLayerChanged(self, layer):
""" Action when the signal: 'Current Layer Changed' from QGIS MapCanvas is emitted&captured
:param layer: QGIS layer -> current layer using by Interactive_Map_Tracking plugin
:type layer: QgsMapLayer
"""
# on deconnecte le layer courant
if None != self.currentLayer:
self.disconnectSignalForLayerModified(self.currentLayer)
# Filtre sur les layers a "surveiller"
if not qgis_layer_tools.filter_layer_for_imt(layer):
layer = None
if None != layer:
self.currentLayer = layer
#
if self.dlg.enablePlugin.isChecked():
if self.dlg.enableAutoSave.isChecked():
qgis_layer_tools.commitChangesAndRefresh(self.currentLayer, self.iface, QSettings())
self.connectSignalForLayerModified(self.currentLayer)
qgis_log_tools.logMessageINFO("Change Layer: layer.name=" + layer.name())
else:
qgis_log_tools.logMessageINFO("No layer selected (for ITP)")
def qgisInterfaceProjectRead(self):
""" Action when the signal: 'Project Read' from QGIS Inteface is emitted&captured """
pass
def currentLayerModified(self):
""" Action when the signal: 'Layer Modified' from QGIS Layer (current) is emitted&captured
We connect a new signal: 'RenderComplete' to perform operation after the QGIS rendering (deferred strategy)
"""
#
if None != self.currentLayer:
if None != self.iface.mapCanvas():
QObject.connect(self.iface.mapCanvas(), SIGNAL("renderComplete(QPainter*)"),
self.currentLayerModifiedAndRenderComplete)
qgis_log_tools.logMessageINFO("Detect modification on layer:" + self.currentLayer.name())
def currentLayerModifiedAndRenderComplete(self):
""" Action when the signal: 'Render Complete' from QGIS Layer (current) is emitted&captured (after emitted&captured signal: 'Layer Modified') """
#
QObject.disconnect(self.iface.mapCanvas(), SIGNAL("renderComplete(QPainter*)"),
self.currentLayerModifiedAndRenderComplete)
#
# qgis_layer_tools.bRefreshMapFromAutoSave = True
qgis_layer_tools.commitChangesAndRefresh(self.currentLayer, self.iface, QSettings())
def canvasExtentsChanged(self):
""" Action when the signal: 'Extent Changed' from QGIS MapCanvas is emitted&captured
We connect a new signal: 'RenderComplete' to perform operation after the QGIS rendering (deferred strategy)
"""
if self.bUseV2Functionnalities:
# filter on our dummy refreshMap using little zoom on mapcanvas (=> canvasExtentChanged was emitted)
# if self.bRefreshMapFromAutoSave:
# self.bRefreshMapFromAutoSave = False
# else:
self.update_track_position_with_qtimers()
else:
QObject.connect(self.iface.mapCanvas(), SIGNAL("renderComplete(QPainter*)"),
self.canvasExtentsChangedAndRenderComplete)
def canvasExtentsChangedAndRenderComplete(self):
""" Action when the signal: 'Render Complete' from QGIS MapCanvas is emitted&captured (after a emitted&captured signal: 'Extent Changed')
"""
#
QObject.disconnect(self.iface.mapCanvas(), SIGNAL("renderComplete(QPainter*)"),
self.canvasExtentsChangedAndRenderComplete)
if self.bUseV2Functionnalities:
self.update_track_position_with_qtimers()
else:
self.update_track_position()
def filter_layer_for_tracking_position(layer):
# set Attributes for Layer in DB
# On récupère automatiquement le nombre de champs qui compose les features présentes dans ce layer
# How to get field names in pyqgis 2.0
# url: http://gis.stackexchange.com/questions/76364/how-to-get-field-names-in-pyqgis-2-0
dataProvider = layer.dataProvider()
# Return a map of indexes with field names for this layer.
# url: http://qgis.org/api/classQgsVectorDataProvider.html#a53f4e62cb05889ecf9897fc6a015c296
fields = dataProvider.fields()
# get fields name from the layer
field_names = [field.name() for field in fields]
# find index for field 'user-id'
id_user_id_field = imt_tools.find_index_field_by_name(field_names, "user_id")
if id_user_id_field == -1:
qgis_log_tools.logMessageWARNING(
"No \"user_id\"::text field attributes found in layer: " + layer.name())
return -1
# find index for field 'writing_time'
id_w_time_field = imt_tools.find_index_field_by_name(field_names, "w_time")
if id_w_time_field == -1:
qgis_log_tools.logMessageWARNING(
"No \"w_time\"::text attributes found in layer: " + layer.name())
return -1
return [id_user_id_field, id_w_time_field]
def currentIndexChangedTPLCB(self, layer_name):
"""
:param layer_name:
:return:
"""
qgis_log_tools.logMessageINFO("Launch 'currentIndexChangedTPLCB(self, layer_name=" + layer_name + ")' ...")
# layer_name == "" when when we clear the combobox (for example)
if layer_name == "":
return
layer_for_tp = imt_tools.find_layer_in_qgis_legend_interface(self.iface, layer_name)
self.currentLayerForTrackingPosition = layer_for_tp # set the layer for tracking position (plugin)
list_id_fields = qgis_layer_tools.filter_layer_trackingposition_required_fields(layer_for_tp)
self.tp_id_user_id = list_id_fields[0]
self.tp_id_w_time = list_id_fields[1]
dataProvider = layer_for_tp.dataProvider()
# Return a map of indexes with field names for this layer.
# url: http://qgis.org/api/classQgsVectorDataProvider.html#a53f4e62cb05889ecf9897fc6a015c296
fields = dataProvider.fields()
# set the fields
# reset all fields in None
self.values = [None for i in range(fields.count())]
# set user_id field (suppose constant for a layer (in QGIS session))
self.values[self.tp_id_user_id] = self.tp_user_name
def refreshComboBoxLayers(self):
""" Action when the Combo Box attached to refreshing layers for tracking position is clicked """
#
qgis_log_tools.logMessageINFO("Launch 'refreshComboBoxLayers(...)' ...")
self.dlg.trackingPositionLayerCombo.clear()
idComboBoxIndex = -1
idComboBoxForDefaultSearchLayer = -1
# search a default layer ('camera_position') if no layer was selected before
# else we search the same layer (if it present)
if self.currentLayerForTrackingPosition is None:
defaultSearchLayer = "camera_position"
else:
defaultSearchLayer = self.currentLayerForTrackingPosition.name()
# dictionnary to link id on combobox and objects QGIS layer
dict_key_comboboxindex_value_layer = {}
#
layers = QgsMapLayerRegistry.instance().mapLayers().values()
for layer in layers:
# filter on layers to add in combobox
if qgis_layer_tools.filter_layer_for_trackingposition(layer):
idComboBoxIndex = self.dlg.trackingPositionLayerCombo.count()
dict_key_comboboxindex_value_layer[idComboBoxIndex] = layer
self.dlg.trackingPositionLayerCombo.addItem(layer.name(), layer)
# default search layer
if layer.name() == defaultSearchLayer:
idComboBoxForDefaultSearchLayer = idComboBoxIndex
#
qgis_log_tools.logMessageINFO(
defaultSearchLayer + " layer found - id in combobox: " +
str(idComboBoxForDefaultSearchLayer)
)
# update GUI
if idComboBoxForDefaultSearchLayer != -1:
self.dlg.trackingPositionLayerCombo.setCurrentIndex(idComboBoxForDefaultSearchLayer)
idComboBoxIndex = idComboBoxForDefaultSearchLayer
if idComboBoxIndex != -1:
try:
self.currentLayerForTrackingPosition = dict_key_comboboxindex_value_layer[idComboBoxIndex]
qgis_log_tools.logMessageINFO("Set the layer to: " + self.currentLayerForTrackingPosition.name())
except:
qgis_log_tools.logMessageINFO("!!! ERROR for selecting layer !!!")
def enabled_autosave(self):
""" Action when the checkbox 'Enable Auto-Save and Refresh' is clicked """
#
qgis_log_tools.logMessageINFO("Launch 'enable_autosave(...)' ...")
resultCommit = False
# filtre sur les layers
if qgis_layer_tools.filter_layer_for_imt(self.iface.activeLayer()):
self.currentLayer = self.iface.activeLayer()
else:
self.currentLayer = None
#
if self.dlg.enableAutoSave.isChecked():
#
resultCommit = qgis_layer_tools.commitChangesAndRefresh(self.currentLayer, self.iface, QSettings())
#
self.connectSignalForLayerModified(self.currentLayer)
else:
self.disconnectSignalForLayerModified(self.currentLayer)
#
return resultCommit
def stop_threads(self):
if self.qtimer_tracking_position_rtt_to_memory.isActive():
self.qtimer_tracking_position_rtt_to_memory.stop()
if self.qtimer_tracking_position_memory_to_geom.isActive():
self.qtimer_tracking_position_memory_to_geom.stop()
if self.qtimer_tracking_position_geom_to_layer.isActive():
self.qtimer_tracking_position_geom_to_layer.stop()
if self.qtimer_tracking_position_layers_to_commit.isActive():
self.qtimer_tracking_position_layers_to_commit.stop()
def enabled_trackposition(self):
""" Action when the checkbox 'Enable Tracking Position' is clicked """
#
qgis_log_tools.logMessageINFO("Launch 'enable_trackposition(...)' ...")
if self.dlg.enableTrackPosition.isChecked():
#
self.refreshComboBoxLayers()
#
self.connectSignalForExtentsChanged()
else:
self.disconnectSignalForExtentsChanged()
self.stop_threads()
def enableLogging(self):
""" Action when the checkbox 'Enable LOGging' is clicked """
#
qgis_log_tools.setLogging(self.dlg.enableLogging.isChecked())
def enableUseMutexForTP(self):
""" Action when the checkbox 'Use Mutex (for TrackingPosition) [BETA]' is clicked
Beta test for:
- using Mutex to protect commitChange operation in multi-threads context (signals strategy)
- using queuing requests from TrackPosition (we try to amortize the cost and effects on QGIS GUI)
"""
self.bUseV2Functionnalities = self.dlg.enableUseMutexForTP.isChecked()
if not(self.dlg.enableUseMutexForTP.isChecked() and self.dlg.enableTrackPosition.isChecked()):
self.stop_threads()
def enabled_plugin(self):
""" Action when the checkbox 'Enable SteetGen3 Plugin' is clicked
Activate/desactivate all options/capabilities of IMT plugin: AutoSave&Refresh, TrackPosition
"""
qgis_log_tools.logMessageINFO("Launch 'enabled_plugin(...)' ...")
#force the plugin to be in front
self.dlg.raise_()
resultCommit = False
# filtre sur les layers a prendre en compte
if qgis_layer_tools.filter_layer_postgis(self.iface.activeLayer()):
self.currentLayer = self.iface.activeLayer()
else:
self.currentLayer = None
if self.dlg.enablePlugin.isChecked():
#
self.dlg.enableAutoSave.setEnabled(True)
self.dlg.enableTrackPosition.setEnabled(True)
self.dlg.enableLogging.setEnabled(True)
self.dlg.thresholdLabel.setEnabled(True)
self.dlg.threshold_extent.setEnabled(True)
QObject.connect(self.dlg.threshold_extent, SIGNAL("editingFinished ()"), self.thresholdChanged)
self.dlg.enableUseMutexForTP.setEnabled(True)
#
self.connectSignalForLayerChanged()
if self.dlg.enableAutoSave.isChecked():
self.connectSignalForLayerModified(self.currentLayer)
resultCommit = qgis_layer_tools.commitChangesAndRefresh(self.currentLayer, self.iface, QSettings())
if self.dlg.enableTrackPosition.isChecked():
self.refreshComboBoxLayers()
self.connectSignalForExtentsChanged()
else:
self.dlg.enableAutoSave.setDisabled(True)
self.dlg.enableTrackPosition.setDisabled(True)
self.dlg.enableLogging.setDisabled(True)
self.dlg.thresholdLabel.setDisabled(True)
self.dlg.threshold_extent.setDisabled(True)
QObject.disconnect(self.dlg.threshold_extent, SIGNAL("returnPressed ()"), self.thresholdChanged)
self.dlg.enableUseMutexForTP.setDisabled(True)
#
self.disconnectSignalForLayerChanged()
if self.dlg.enableAutoSave.isChecked():
self.disconnectSignalForLayerModified(self.currentLayer)
if self.dlg.enableTrackPosition.isChecked():
self.disconnectSignalForExtentsChanged()
self.stop_threads()
return resultCommit
def update_setting(self, _s, _name_in_setting, _checkbox):
""" Update the value store in settings (Qt settings) according to checkbox (Qt) status
:param _s: Qt Settings
:type _s: QSettings
:param _name_in_setting: Name of the setting in QSetting
:type _name_in_setting: QString
:param _checkbox: CheckBox link to this setting
:type _checkbox: QCheckBox
"""
if _checkbox.isChecked():
_s.setValue(self.qsettings_prefix_name + _name_in_setting, "true")
else:
_s.setValue(self.qsettings_prefix_name + _name_in_setting, "false")
def update_settings(self, _s):
""" Update all settings
:param _s: Qt Settings
:type _s: QSettings
"""
dlg = self.dlg
# Update (Qt) settings according to the GUI IMT plugin
self.update_setting(_s, "enabledPlugin", dlg.enablePlugin)
self.update_setting(_s, "enablesAutoSave", dlg.enableAutoSave)
self.update_setting(_s, "enablesTrackPosition", dlg.enableTrackPosition)
def hide_plugin(self):
""" Hide the plugin.
Don't change the state of the plugin
"""
# @FIXME there is a mistake here, this function is also called before init. Because QSettings is a singleton, variable are inited before end of init !
self.update_settings(QSettings())
self.dlg.hide()
def thresholdChanged(self):
"""
QT Line edit changed, we get/interpret the new value (if valid)
Format for threshold scale : 'a'[int]:'b'[int]
We just used 'b' for scale => threshold_scale = 'b'
"""
validFormat = True
try:
threshold_string = self.dlg.threshold_extent.text()
self.threshold = int(threshold_string)
except ValueError:
try:
a, b = threshold_string.split(":")
try:
int(a) # just to verify the type of 'a'
self.threshold = int(b) # only use 'b' to change the threshold scale value
except Exception:
validFormat = False # problem with 'a'
except Exception:
validFormat = False # problem with 'b'
# Input format problem!
if validFormat == False:
qgis_log_tools.logMessageWARNING("Invalid input for scale! Scale format input : [int]:[int] or just [int]")
# just for visualisation purpose
self.dlg.threshold_extent.setText("1:" + str(self.threshold))
def update_size_dlg_from_frame(self, dlg, frame, margin_width=60):
"""
:param dlg:
:param frame:
:param margin_width:
:return:
"""
width = frame.contentsSize().width()
height = frame.contentsSize().height()
#
width += margin_width
#