Repository navigation
Expand file tree
/
Copy pathfilter_mate.py
More file actions
2149 lines (1830 loc) · 102 KB
/
Copy pathfilter_mate.py
File metadata and controls
2149 lines (1830 loc) · 102 KB
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 -*-
"""
/***************************************************************************
FilterMate
A QGIS plugin
FilterMate is a Qgis plugin, an everyday companion that allows you to easily filter your vector layers
-------------------
begin : 2023-10-26
git sha : $Format:%H$
copyright : (C) 2023 by imagodata
email : imagodata+filter_mate@skiff.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. *
* *
***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, QSize, Qt, QUrl
from qgis.PyQt.QtGui import QIcon, QDesktopServices, QPixmap
try:
from qgis.PyQt.QtGui import QAction
except ImportError: # QGIS < 3.34.2 (Qt5): QAction is in QtWidgets
from qgis.PyQt.QtWidgets import QAction
from qgis.PyQt.QtWidgets import (QMessageBox, QCheckBox, QDialog,
QVBoxLayout, QHBoxLayout, QLabel, QPushButton)
import weakref
import os
import os.path
from .filter_mate_app import FilterMateApp
from .config.config import reload_config, get_config_json_path
from .infrastructure.logging import get_logger
from .infrastructure import feedback_forms
logger = get_logger(__name__)
# SQLite database of the layer properties, filter history and favorites
# (FilterMateApp.db_name), in the FilterMate folder of the QGIS profile.
LAYER_DATABASE_NAME = 'filterMate_db.sqlite'
# Persistent FID cache of FilterMate 4.x (removed in 5.0, never filled): deleted by a configuration reset
LEGACY_CACHE_DB_NAME = 'filtermate_cache.db'
def _clear_layer_database(db_path):
"""Delete the layer properties and filter history stored in ``db_path``.
The favorites (fm_favorites) and the project identities they belong to
(fm_projects) live in the same database and stay.
"""
import sqlite3
conn = sqlite3.connect(db_path)
try:
tables = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type = 'table'")}
for table in ('fm_project_layers_properties', 'fm_subset_history'):
if table in tables:
conn.execute(f"DELETE FROM {table}") # nosec B608 - fixed table names
conn.commit()
finally:
conn.close()
def _forget_module_aliases(package, tracked=None):
"""Drop the ``sys.modules`` entries of ``package`` that QGIS would leave behind on unload.
QGIS tracks what a plugin imports by the ``__name__`` of each module and
removes those names after ``unload()`` (``qgis.utils._unloadPluginModules``).
Left behind were:
- the aliases of the compatibility shims of the modules moved to
``filtermate_core`` (``filter_mate.core.domain.x`` is the module
``filter_mate.filtermate_core.domain.x``), always dropped here;
- the packages imported only as parents of a module, and the modules
loaded through ``importlib``, which QGIS never tracked: dropped when
``tracked`` (the names QGIS tracked for this plugin) is given.
After an update or a reload in the session, those names still gave the
previous code next to the fresh one (two copies of each class,
``isinstance`` and ``except`` failing across them). A module QGIS tracked is
left to QGIS, and so is a Qt resource module (``qCleanupResources``), which
QGIS cleans up only while it is still in ``sys.modules``.
Returns:
The names removed.
"""
import sys
prefix = package + '.'
removed = []
for key, module in list(sys.modules.items()):
if not key.startswith(prefix) or module is None:
continue
alias = getattr(module, '__name__', key) != key
untracked = (tracked is not None and key not in tracked
and not hasattr(module, 'qCleanupResources'))
if alias or untracked:
sys.modules.pop(key, None)
removed.append(key)
return removed
def _qgis_tracked_modules(package):
"""The module names QGIS tracked for ``package`` (``qgis.utils._plugin_modules``), None when unknown."""
try:
import qgis.utils
tracked = getattr(qgis.utils, '_plugin_modules', {}).get(package)
except Exception: # a private name of QGIS: never fail an unload on it
return None
return set(tracked) if tracked else None
class FilterMate:
"""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
"""
# Save reference to the QGIS interface
self.iface = iface
self.current_index = 0
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
# Try to load config to check for forced language setting
config_language = None
try:
import json
# The active config (QGIS profile), where the Configuration tab saves the language:
# the copy in the plugin folder never held it, so a forced language was lost on restart.
config_path = get_config_json_path()
if os.path.exists(config_path):
with open(config_path, 'r', encoding='utf-8') as f:
config_data = json.load(f)
# Support both old format (APP.DOCKWIDGET.LANGUAGE) and new format (app.ui.language)
config_language = (
config_data.get('app', {}).get('ui', {}).get('language', {}).get('value') or
config_data.get('APP', {}).get('DOCKWIDGET', {}).get('LANGUAGE', {}).get('value') or
'auto'
)
except Exception as e:
logger.warning(f"Could not load language from config: {e}")
# Determine locale: use config if not 'auto', otherwise use QGIS setting
if config_language and config_language != 'auto':
locale = config_language
else:
# Get QGIS locale setting
locale_setting = QSettings().value('locale/userLocale')
if locale_setting:
# Handle both 'fr' and 'fr_FR' formats
locale = locale_setting.split('_')[0] if '_' in locale_setting else locale_setting[0:2]
else:
locale = 'en'
logger.debug(f"Language detection: config_language={config_language}, locale_setting={QSettings().value('locale/userLocale')}, final locale={locale}")
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'FilterMate_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
self._current_locale = locale
feedback_forms.set_locale(locale)
logger.info(f"Loaded translation: {locale}")
else:
self._current_locale = None
logger.warning(f"Translation file not found: {locale_path}")
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&FilterMate')
# Note: Menu name is hardcoded. Custom menu names may be added in future.
# No iface under qgis_process (Processing only, see initProcessing).
self.toolbar = self.iface.addToolBar(u'FilterMate') if self.iface is not None else None
if self.toolbar is not None:
self.toolbar.setObjectName(u'FilterMate')
# print "** INITIALIZING FilterMate"
# v4.4: Initialize QGIS factory BEFORE creating app (required by hexagonal architecture)
# This must happen in __init__ so AppInitializer can use it
logger.debug("FilterMate.__init__: Initializing QGIS factory")
try:
from .core.ports.qgis_port import set_qgis_factory
from .adapters.qgis.factory import QGISFactory
factory = QGISFactory()
set_qgis_factory(factory)
logger.debug("FilterMate: QGIS factory initialized in __init__")
except Exception as factory_error:
logger.error(f"FilterMate: CRITICAL - Could not initialize QGIS factory: {factory_error}")
# This is critical - without factory, hexagonal services won't work
# A1 (audit 2026-04-29): Wire the IFeedback adapter so domain code
# (core/filter/result_processor.py) can push messages without
# importing iface directly. Failures here downgrade to logger-only
# output — never block the plugin from loading.
try:
from .core.ports.qgis_port import set_feedback_adapter
from .adapters.qgis.qgis_feedback_adapter import QgisMessageBarFeedback
set_feedback_adapter(QgisMessageBarFeedback())
logger.debug("FilterMate: Feedback adapter initialized in __init__")
except Exception as feedback_error:
logger.error(f"FilterMate: Could not initialize feedback adapter: {feedback_error}")
self.pluginIsActive = False
self.app = None
self._auto_activation_signals_connected = False
self._project_read_connection = None
self._new_project_connection = None
self.processing_provider = None
# 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('FilterMate', message)
def reload_translator(self, locale: str):
"""Reload the translator for a new locale without restarting the plugin.
Args:
locale: Language code (e.g. 'fr', 'en', 'de') or 'auto' to use QGIS locale.
"""
logger.info(f"reload_translator called with locale={locale}")
if locale == 'auto':
locale_setting = QSettings().value('locale/userLocale')
if locale_setting:
locale = locale_setting.split('_')[0] if '_' in locale_setting else locale_setting[0:2]
else:
locale = 'en'
logger.info(f"reload_translator: auto resolved to {locale}")
locale_path = os.path.join(self.plugin_dir, 'i18n', f'FilterMate_{locale}.qm')
# Remove old translator if present
if hasattr(self, 'translator') and self.translator:
QCoreApplication.removeTranslator(self.translator)
logger.info("reload_translator: removed old translator")
else:
logger.warning("reload_translator: no existing translator to remove")
if os.path.exists(locale_path):
self.translator = QTranslator()
loaded = self.translator.load(locale_path)
if loaded:
QCoreApplication.installTranslator(self.translator)
self._current_locale = locale
feedback_forms.set_locale(locale)
test = self.tr('Open FilterMate panel')
logger.info(f"Reloaded translation: {locale} (test: '{test}')")
else:
logger.error(f"reload_translator: QTranslator.load() returned False for {locale_path}")
else:
logger.error(f"Translation file not found: {locale_path}")
def _add_menu_actions(self):
"""The entries of Vector > FilterMate, the first one in the toolbar too."""
icon_path = os.path.join(self.plugin_dir, 'icon.png')
# Main action to open FilterMate
self._open_action = self.add_action(
icon_path,
text=self.tr(u'FilterMate'),
callback=self.run,
parent=self.iface.mainWindow(),
status_tip=self.tr(u'Open FilterMate panel'))
# The setup, asked with cards in the AGENT panel (no model): also offered there once per version
self._setup_action = self.add_action(
icon_path,
text=self.tr(u'Set up FilterMate'),
callback=self.setup_with_agent,
parent=self.iface.mainWindow(),
add_to_toolbar=False,
status_tip=self.tr(u'A few choices, then every setting before and after: no AI model needed'))
# What each section does, the sections as panels of QGIS, the buttons: told in the AGENT panel (no model)
self._tour_action = self.add_action(
icon_path,
text=self.tr(u'How FilterMate works'),
callback=self.show_how_it_works,
parent=self.iface.mainWindow(),
add_to_toolbar=False,
status_tip=self.tr(u'What each section does, the sections as panels of QGIS, where the buttons are'))
# Action to reset configuration and database
reset_icon_path = os.path.join(self.plugin_dir, 'icons', 'parameters.png')
self._reset_action = self.add_action(
reset_icon_path,
text=self.tr(u'Reset configuration and database'),
callback=self.reset_configuration,
parent=self.iface.mainWindow(),
add_to_toolbar=False,
status_tip=self.tr(u'Reset the default configuration and delete the SQLite database'))
# The forms of the feedback page of the site: the plugin only opens the page (no data sent)
self._feedback_actions = {}
for form, text in self._feedback_entries():
self._feedback_actions[form] = self.add_action(
icon_path,
text=text,
callback=lambda checked=False, f=form: feedback_forms.open_form(f, 'plugin-menu'),
parent=self.iface.mainWindow(),
add_to_toolbar=False)
def _feedback_entries(self):
"""(form, menu text) of the feedback entries of Vector > FilterMate."""
return (
('usage', self.tr(u'Give your opinion')),
('feature', self.tr(u'Suggest a feature')),
('testers', self.tr(u'Test the experimental features')),
('services', self.tr(u'Training and services')),
)
def retranslate_actions(self):
"""Retranslate menu and toolbar action texts after a language change.
Each entry is found by its own reference, never by its place in ``self.actions``: an entry added between
two others (the setup) took the words of the one after it.
"""
self.menu = self.tr(u'&FilterMate')
entries = (
('_open_action', self.tr(u'FilterMate'), self.tr(u'Open FilterMate panel')),
('_setup_action', self.tr(u'Set up FilterMate'),
self.tr(u'A few choices, then every setting before and after: no AI model needed')),
('_tour_action', self.tr(u'How FilterMate works'),
self.tr(u'What each section does, the sections as panels of QGIS, where the buttons are')),
('_reset_action', self.tr(u'Reset configuration and database'),
self.tr(u'Reset the default configuration and delete the SQLite database')),
)
for name, text, status_tip in entries:
action = getattr(self, name, None)
if action is not None:
action.setText(text)
action.setStatusTip(status_tip)
feedback_actions = getattr(self, '_feedback_actions', None)
if feedback_actions:
for form, text in self._feedback_entries():
action = feedback_actions.get(form)
if action is not None:
action.setText(text)
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.addPluginToVectorMenu(
self.menu,
action)
# retranslate_actions renames self.menu: unload removes the entries
# from the submenu they were added to.
self._vector_menu_name = self.menu
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
try:
from .infrastructure.utils import stall_watch
stall_watch.start() # its thread now, at a quiet moment: never when a layer task starts
except Exception as exc: # a diagnostic: never in the way of the plugin
logger.debug(f"Stall watch not started: {exc}")
try:
# v4.4: QGIS factory already initialized in __init__ (required by AppInitializer)
# This section kept for backward compatibility verification only
logger.debug("FilterMate.initGui: Verifying QGIS factory initialization")
try:
from .core.ports.qgis_port import get_qgis_factory
factory = get_qgis_factory()
logger.info("FilterMate: QGIS factory verified in initGui")
except Exception as verify_error:
logger.warning(f"FilterMate: QGIS factory not initialized: {verify_error}")
# Try to initialize as fallback
try:
from .core.ports.qgis_port import set_qgis_factory
from .adapters.qgis.factory import QGISFactory
factory = QGISFactory()
set_qgis_factory(factory)
logger.debug("FilterMate: QGIS factory initialized as fallback in initGui")
except Exception as fallback_error:
logger.error(f"FilterMate: Could not initialize QGIS factory: {fallback_error}")
# Install message log filter to suppress known QGIS warnings about missing form dependencies
logger.debug("FilterMate.initGui: Starting _install_message_filter")
self._install_message_filter()
# Force reload configuration from disk to get latest user changes
logger.debug("FilterMate.initGui: Starting reload_config")
reload_config()
# Auto-migrate configuration if needed
logger.debug("FilterMate.initGui: Starting _auto_migrate_config")
self._auto_migrate_config()
# Check and warn about invalid geometry filtering settings
logger.debug("FilterMate.initGui: Starting _check_geometry_validation_settings")
self._check_geometry_validation_settings()
logger.debug("FilterMate.initGui: Creating actions")
self._add_menu_actions()
# Connect signals to handle project changes and automatically reload layers
# Note: layersAdded signal is NOT connected to avoid freeze issues
logger.debug("FilterMate.initGui: Connecting auto-activation signals")
self._connect_auto_activation_signals()
# v5.0: Discover and initialize extensions (QFieldCloud, etc.)
logger.debug("FilterMate.initGui: Initializing extension system")
self._init_extensions()
# Register FilterMate algorithms in the Processing Toolbox
logger.debug("FilterMate.initGui: Registering Processing provider")
self.initProcessing()
# FilterMate 5: remove the derived-file folders of crashed QGIS
# sessions (live sessions hold a lock), off the startup path. A timer
# of the plugin, stopped in unload: a QTimer.singleShot still fired
# after an unload and imported the removed package again.
from qgis.PyQt.QtCore import QTimer
self._stale_cache_timer = QTimer()
self._stale_cache_timer.setSingleShot(True)
self._stale_cache_timer.timeout.connect(self._cleanup_stale_cache)
self._stale_cache_timer.start(30000)
from .adapters.qgis import python_dependencies
python_dependencies.activate_installed()
# 2026-11-22: local copies of web service layers (dock button, menu of the layers, project hooks).
try:
from .ui.controllers.stream_copy_actions import StreamCopyActions
self._stream_copy = StreamCopyActions(self.iface)
self._stream_copy.start()
except Exception as exc: # a feature: never in the way of the plugin
self._stream_copy = None
logger.warning(f"FilterMate: local copies of web services not available: {exc}")
logger.debug("FilterMate.initGui: Completed successfully")
except Exception as e:
import traceback
error_msg = f"Error in initGui: {str(e)}"
traceback_msg = traceback.format_exc()
logger.error(error_msg)
logger.error(f"Traceback: {traceback_msg}")
self.iface.messageBar().pushCritical(
"FilterMate",
self.tr("Initialization error: {0}").format(str(e))
)
# Re-raise to prevent partial initialization
raise
@staticmethod
def _cleanup_stale_cache():
try:
import threading
from .adapters.qgis.coverage_layers import cache as _coverage_cache
# The root is read here (config, QGIS API); the removal of possibly
# large folders runs off the main thread.
threading.Thread(target=_coverage_cache.cleanup_stale_sessions,
kwargs={'root': _coverage_cache.cache_root()},
name='FilterMate cache cleanup', daemon=True).start()
except Exception as e:
logger.debug(f"FilterMate: stale cache sessions not cleaned: {e}")
# --------------------------------------------------------------------------
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed"""
# print "** CLOSING FilterMate"
# disconnects
if self.app and self.app.dockwidget:
self.app.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.app = None
self.pluginIsActive = False
def resources_path(self, *args):
"""Get the path to our resources folder.
:param args List of path elements e.g. ['img', 'logos', 'image.png']
:type args: str
:return: Absolute path to the resources folder.
:rtype: str
"""
path = str(self.plugin_dir) + os.sep + 'images'
for item in args:
path = path + os.sep + item
return path
def _confirm_config_reset(self, reason: str, version: str) -> bool:
"""
Ask user for confirmation before resetting configuration.
Args:
reason: Reason for reset ('obsolete', 'corrupted')
version: Detected version (may be None)
Returns:
True if user confirms reset, False otherwise
"""
if reason == "obsolete":
title = self.tr("Obsolete configuration detected")
version_str = f"v{version}" if version else self.tr("unknown version")
message = self.tr(
"An obsolete configuration ({}) has been detected.\n\n"
"Do you want to reset to default settings?\n\n"
"• Yes: Reset (a backup will be created)\n"
"• No: Keep current configuration (may cause issues)"
).format(version_str)
elif reason == "corrupted":
title = self.tr("Corrupted configuration detected")
message = self.tr(
"The configuration file is corrupted and cannot be read.\n\n"
"Do you want to reset to default settings?\n\n"
"• Yes: Reset (a backup will be created if possible)\n"
"• No: Cancel (the plugin may not work correctly)"
)
else:
title = self.tr("Configuration reset")
message = self.tr(
"The configuration needs to be reset.\n\n"
"Do you want to continue?"
)
reply = QMessageBox.question(
self.iface.mainWindow(),
title,
message,
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.Yes
)
return reply == QMessageBox.StandardButton.Yes
def _auto_migrate_config(self):
"""Auto-migrate configuration to latest version if needed.
If an obsolete or corrupted configuration is detected, asks the user
for confirmation before resetting to default values.
"""
try:
from .infrastructure.config.config_migration import ConfigMigration
migrator = ConfigMigration()
# Pass the confirmation callback for reset operations
result = migrator.auto_migrate_if_needed(
confirm_reset_callback=self._confirm_config_reset
)
# Defensive: ensure result is a tuple with 2 elements
if result is None:
logger.warning("auto_migrate_if_needed returned None, using defaults")
performed, warnings = False, []
elif not isinstance(result, tuple) or len(result) != 2:
logger.warning(f"auto_migrate_if_needed returned unexpected result: {result}")
performed, warnings = False, []
else:
performed, warnings = result
# Ensure warnings is a list (defensive programming)
if warnings is None:
warnings = []
# Check if user declined reset
if any("user declined" in str(w).lower() for w in warnings):
logger.info("User declined configuration reset")
self.iface.messageBar().pushWarning(
"FilterMate",
self.tr("Configuration not reset. Some features may not work correctly.")
)
return
if performed:
logger.info("Configuration migrated to latest version")
# Determine the type of action performed
if any("missing" in str(w).lower() for w in warnings):
msg = self.tr("Configuration created with default values")
msg_type = "info"
elif any("corrupted" in str(w).lower() or "failed to load" in str(w).lower() for w in warnings):
msg = self.tr("Corrupted configuration reset. Default settings have been restored.")
msg_type = "warning"
elif any("obsolete" in str(w).lower() for w in warnings):
msg = self.tr("Obsolete configuration reset. Default settings have been restored.")
msg_type = "warning"
elif any(w.startswith("config_updated:") for w in warnings):
# v2.7.6: New settings sections were added
added_sections = []
for w in warnings:
if w.startswith("config_updated:"):
added_sections = w.replace("config_updated:", "").split(",")
break
# Build user-friendly message
section_names = {
"GEOMETRY_SIMPLIFICATION": self.tr("Geometry Simplification"),
"OPTIMIZATION_THRESHOLDS": self.tr("Optimization Thresholds")
}
friendly_names = [section_names.get(s, s) for s in added_sections]
sections_str = ", ".join(friendly_names)
msg = self.tr("Configuration updated: new settings available ({sections}). Access via Options menu.").format(sections=sections_str)
msg_type = "info"
else:
msg = self.tr("Configuration updated to latest version")
msg_type = "success"
# Display appropriate message
if msg_type == "success":
self.iface.messageBar().pushSuccess("FilterMate", msg)
elif msg_type == "warning":
self.iface.messageBar().pushWarning("FilterMate", msg)
else:
self.iface.messageBar().pushInfo("FilterMate", msg)
if warnings:
for warning in warnings:
logger.warning(f"Config migration: {warning}")
except Exception as e:
import traceback
logger.error(f"Error during config migration: {e}")
logger.error(f"Traceback: {traceback.format_exc()}")
self.iface.messageBar().pushCritical(
"FilterMate",
self.tr("Error during configuration migration: {}").format(str(e))
)
# Don't block plugin initialization if migration fails
def _install_message_filter(self):
"""Check for layers with missing ValueRelation dependencies and optionally clear warnings.
QGIS emits individual warnings for each missing layer form dependency.
This method detects affected layers, clears the message bar after a delay,
and shows a single consolidated informational message instead.
The check is triggered:
1. At plugin initialization (for already loaded projects)
2. When a project is read/loaded (via readProject signal)
"""
self._form_dependency_warning_shown = False
self._missing_dependency_layers = set()
try:
from qgis.core import QgsProject
from qgis.PyQt.QtCore import QTimer
def check_and_clear_warnings():
"""Check all layers for missing ValueRelation dependencies and clear message bar."""
if self._form_dependency_warning_shown:
return
try:
from .infrastructure.field_utils import get_value_relation_info
project = QgsProject.instance()
for layer_id, layer in project.mapLayers().items():
if not hasattr(layer, 'fields'):
continue
for field in layer.fields():
vr_info = get_value_relation_info(layer, field.name(), check_layer_availability=False)
if vr_info and not vr_info.get('layer_available', True):
ref_name = vr_info.get('layer_name', '') or 'unknown'
self._missing_dependency_layers.add(ref_name)
if self._missing_dependency_layers and not self._form_dependency_warning_shown:
self._form_dependency_warning_shown = True
# 2026-10-17: only FilterMate's own message is replaced (its item is kept).
# clearWidgets() removed every message of the bar, other plugins' and
# QGIS's included; a match on the layer names could too.
bar = self.iface.messageBar()
previous = getattr(self, '_dependency_message_item', None)
if previous is not None:
try:
bar.popWidget(previous)
except Exception: # nosec B110 - already closed by the user
pass
self._dependency_message_item = None
# Show a single consolidated info message
count = len(self._missing_dependency_layers)
layers_list = ', '.join(list(self._missing_dependency_layers)[:3])
if count > 3:
layers_list += f" (+{count - 3} more)"
text = self.tr(f"{count} referenced layer(s) not loaded ({layers_list}). Using fallback display.")
try:
from qgis.core import Qgis
item = bar.createMessage("FilterMate", text)
self._dependency_message_item = bar.pushWidget(item, Qgis.MessageLevel.Info)
except Exception: # nosec B110 - fall back on a plain message
bar.pushInfo("FilterMate", text)
logger.info(
f"FilterMate: {count} referenced layer(s) not loaded. "
f"ValueRelation fallback active: {', '.join(self._missing_dependency_layers)}"
)
except Exception as e:
logger.debug(f"FilterMate: Dependency check error (non-critical): {e}")
def on_project_read(*args):
"""Handler for project read signal - reset state and schedule check."""
# Reset state for new project
self._form_dependency_warning_shown = False
self._missing_dependency_layers = set()
# Schedule check after QGIS warnings have appeared (project load is async)
self._dependency_check_timer.start(2000)
# 2026-10-17: a timer of the plugin, stopped in unload (QTimer.singleShot
# could not be canceled: it ran on an unloaded plugin).
self._dependency_check_timer = QTimer()
self._dependency_check_timer.setSingleShot(True)
self._dependency_check_timer.timeout.connect(check_and_clear_warnings)
# Connect to project read signal for future project loads
# Store reference to avoid garbage collection and allow disconnection
self._on_project_read_handler = on_project_read
QgsProject.instance().readProject.connect(on_project_read)
# Also check now for already loaded project (e.g., plugin activated after project load)
self._dependency_check_timer.start(1500)
except Exception as e:
logger.debug(f"FilterMate: Message filter setup note: {e}")
def _check_geometry_validation_settings(self):
"""Check QGIS geometry validation settings and warn user if not disabled.
FilterMate works best when QGIS's invalid geometry filtering is disabled
(set to "Off"). When enabled, QGIS may filter out features with invalid
geometries before FilterMate can process them, leading to missing features
in exports and filters.
This method checks the current setting and offers to disable it if needed,
with an explanation of why this is recommended.
"""
try:
from qgis.core import QgsSettings
# Get current geometry validation setting
# Values: 0 = Off, 1 = QGIS validation, 2 = GEOS validation
settings = QgsSettings()
current_value = settings.value("qgis/digitizing/validate_geometries", 0, type=int)
if current_value != 0:
# Setting is not "Off" - need to warn user
validation_modes = {
1: "QGIS",
2: "GEOS"
}
current_mode = validation_modes.get(current_value, str(current_value))
title = self.tr("Geometry validation setting")
message = self.tr(
"The QGIS setting 'Invalid features filtering' is currently "
"set to '{mode}'.\n\n"
"FilterMate recommends disabling this setting (value 'Off') "
"for the following reasons:\n\n"
"• Features with invalid geometries could be "
"silently excluded from exports and filters\n"
"• FilterMate handles geometry validation internally "
"with automatic repair options\n"
"• Some legitimate data may have geometries considered "
"as 'invalid' according to strict OGC rules\n\n"
"Do you want to disable this setting now?\n\n"
"• Yes: Disable filtering (recommended for FilterMate)\n"
"• No: Keep current setting"
).format(mode=current_mode)
reply = QMessageBox.question(
self.iface.mainWindow(),
title,
message,
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.Yes
)
if reply == QMessageBox.StandardButton.Yes:
# Disable geometry validation
settings.setValue("qgis/digitizing/validate_geometries", 0)
logger.info("Geometry validation disabled by user via FilterMate startup check")
self.iface.messageBar().pushSuccess(
"FilterMate",
self.tr("Invalid geometry filtering disabled successfully.")
)
else:
# User declined - just log and show info
logger.info(f"User declined to disable geometry validation (current: {current_mode})")
self.iface.messageBar().pushWarning(
"FilterMate",
self.tr("Invalid geometry filtering not modified. "
"Some features may be excluded from exports.")
)
else:
logger.debug("Geometry validation already disabled (Off) - no action needed")
except Exception as e:
logger.warning(f"Error checking geometry validation settings: {e}")
# Don't block plugin initialization if check fails
def _init_extensions(self):
"""Discover and initialize FilterMate extensions (v5.0).
Extensions are optional modules (e.g., QFieldCloud) that add
functionality without modifying core FilterMate code.
If no extensions are found or all fail, FilterMate works normally.
"""
try:
from .extensions import get_extension_registry
registry = get_extension_registry()
discovered = registry.discover_extensions()
if discovered:
logger.info("FilterMate: Discovered %d extension(s): %s",
len(discovered), ', '.join(discovered))
# Initialize all available extensions
results = registry.initialize_all(self.iface)
for ext_id, success in results.items():
if success:
logger.info("FilterMate: Extension '%s' initialized", ext_id)
else:
logger.debug("FilterMate: Extension '%s' not available", ext_id)
# Create UI for initialized extensions
ui_results = registry.create_all_ui(self.toolbar, self.menu)
for ext_id, actions in ui_results.items():
if actions:
self.actions.extend(actions)
logger.debug("FilterMate: Extension '%s' added %d UI action(s)",
ext_id, len(actions))
else:
logger.debug("FilterMate: No extensions found")
except Exception as e:
logger.warning("FilterMate: Extension system error: %s", e)
# Extension failure must never block core FilterMate
def initProcessing(self):
"""Register the Processing provider (called by QGIS for ``qgis_process``, and by initGui).
``metadata.txt`` declares ``hasProcessingProvider=yes``: ``qgis_process``
loads the plugin without a GUI (``iface`` is None) and calls this method
only, so the FilterMate algorithms and models run from the command line.
"""
if self.processing_provider is None:
self._register_processing_provider()
def _register_processing_provider(self):
"""Register FilterMate's algorithms in the QGIS Processing Toolbox.
Best-effort: a failure here must never block core FilterMate loading.
"""
try:
from qgis.core import QgsApplication
from .processing.provider import FilterMateProcessingProvider
if QgsApplication.processingRegistry().providerById("filtermate") is not None:
logger.debug("FilterMate: Processing provider already registered")
return
self.processing_provider = FilterMateProcessingProvider()
QgsApplication.processingRegistry().addProvider(self.processing_provider)
logger.debug("FilterMate: Processing provider registered")
except Exception as e:
logger.warning("FilterMate: Could not register Processing provider: %s", e)
self.processing_provider = None
def _init_extensions_dockwidget_ui(self):
"""Inject extension UI into the FilterMate dockwidget.
Called after the dockwidget is created and shown, allowing extensions
to add buttons/widgets inside the dockwidget (e.g., in the action bar).
"""
if not self.app or not self.app.dockwidget:
return
try:
from .extensions import get_extension_registry
registry = get_extension_registry()
dw_results = registry.create_all_dockwidget_ui(self.app.dockwidget)
for ext_id, widgets_list in dw_results.items():
if widgets_list:
logger.debug(
"FilterMate: Extension '%s' added %d dockwidget widget(s)",
ext_id, len(widgets_list),
)