This page is a map of the source tree for a developer who has just cloned the repository. It describes FilterMate 5.1 (QGIS 3.22 to 4.x, Qt5 and Qt6). Paths are relative to the repository root, which is the plugin folder (filter_mate/).
Related documents: AUTOMATION.md (Processing, Python API, REST API), AGENT_MODE.md (AGENT section, MCP servers), SEGMENTATION.md (objects drawn by SAM), ../filtermate_core/README.md (host-free core), ../extensions/README.md (extension system), ../adapters/backends/README.md (backends, written for 4.1), ../CONTRIBUTING.md.
The code follows a hexagonal layout: core/ holds the logic and the ports (abstract interfaces), adapters/ implements them for QGIS and the data providers, ui/ is the presentation layer. The layering is not strict. Much of core/services/, core/tasks/ and core/geometry/ imports qgis.core; most of core/domain/ and core/ports/ does not.
| Folder | Role |
|---|---|
filtermate_core/ |
The filtering semantics free of any host (no QGIS, Qt nor GDAL): criteria, expression combination, the PostGIS and SpatiaLite SQL of the spatial filters, the geometric filter on shapely. |
core/ |
Domain objects, ports, services, the filter task and its handlers; core/agent/ for the AGENT section. |
adapters/ |
Backends (PostgreSQL, Spatialite, OGR, memory), QGIS adapters, repositories, public API; adapters/agent/ for the network and the history of AGENT. |
infrastructure/ |
Cross-cutting code: caches, database helpers, logging, DI container, constants, utilities. |
ui/ |
Controllers, managers, widgets, dialogs, styles and layout of the dock widget. |
processing/ |
Processing provider, algorithms and shipped models. |
filtermate_api/ |
FastAPI REST server, the tools of the chat (agent_tools.py) and the stdio MCP server (mcp/). |
extensions/ |
Optional modules discovered at startup (QFieldCloud, favorites sharing). |
config/ |
Default configuration and configuration helpers. |
resources/ |
Fonts and QSS style sheets. |
i18n/ |
Translation sources (.ts) and compiled files (.qm) for 34 locales. |
tests/ |
Unit tests, API tests, AST guards, headless QGIS smoke tests. |
scripts/ |
Release, screenshot, site and QGIS check scripts. Not shipped in the zip. |
Other top-level items: icons/ (button icons), website/ (static site published to GitHub Pages by .github/workflows/deploy-docs.yml), metadata.txt (plugin metadata), filter_mate_dockwidget_base.ui (Qt Designer form of the dock).
__init__.py classFactory(iface) -> FilterMate(iface)
filter_mate.py FilterMate: initGui, menu and toolbar, extensions, Processing provider, unload
filter_mate_app.py FilterMateApp: layer state, task management, dock lifecycle
filter_mate_dockwidget.py FilterMateDockWidget: the panel (AGENT, EXPLORING, FILTERING, EXPORTING, configuration)
The dock has two stacks of sections on either side of a splitter (ui/layout/dock_chrome.py): AGENT and EXPLORING
above, FILTERING, EXPORTING and CONFIGURATION below, one section open at most in each. Opening AGENT folds EXPLORING
and FILTERING; opening FILTERING opens EXPLORING and folds AGENT. The splitter share is kept in the QGIS settings.
FilterMate.initGuicalls_init_extensions()andinitProcessing().metadata.txtdeclareshasProcessingProvider=yes, soqgis_processcallsinitProcessing()alone, with noiface.FilterMate.run()createsFilterMateAppand callsFilterMateApp.run(), which creates the dock widget (delegated toAppInitializerincore/services/app_initializer.pywhen available).FilterMateAppis a large legacy class being split into services. New logic belongs incore/services/or a handler, not in these three files.- The dock widget owns the widgets. It delegates behaviour to the controllers of
ui/controllers/, wired byControllerIntegration(ui/controllers/integration.py). FilterMateApp.PROJECT_LAYERS(a dict keyed by layer id) holds the per-layer properties and filter state. The dock shares it.
domain/: dataclasses and enums.filter_expression.py,layer_info.py,filter_state.py,favorites_manager.py; v5 additionslayer_kind.py(LayerKind),cross_filter.py(CrossFilterRequest, predicate table),raster_filter_criteria.py,point_cloud_filter_criteria.py,api_requests.py(OperationReport).ports/: abstract interfaces (backend_port.py,cache_port.py,filter_executor_port.py,repository_port.py,public_api_port.py,qfieldcloud_port.py,point_cloud_port.py) and theBackendServicesfacade (backend_services.py).services/: application services.task_orchestrator.py,task_run_orchestrator.py,filter_application_service.py,history_service.py,favorites_service.py,cross_filter_service.py(v5),point_cloud_filter_service.py,app_initializer.py.tasks/:filter_task.py(FilterEngineTask, aQgsTask) and the handlers it delegates to (filtering_orchestrator.py,finished_handler.py,export_handler.py,subset_management_handler.py, ...), with sub-packagesdispatchers/,executors/,builders/,collectors/,connectors/,cache/.layer_management_task.pyandexpression_evaluation_task.pyare separate tasks.filter/:filter_orchestrator.py(per-layer backend choice and fallback),expression_builder.py,expression_combiner.py,filter_chain.py.geometry/,optimization/,strategies/,export/: buffer and CRS helpers, backend auto-selection and query analysis, multi-step filtering, layer exporters.agent/: the conversation of AGENT without QGIS, Qt nor network (provider adapters inproviders/,session.pywith its 16-turn limit,tool_catalog.json,tool_executor.py,sql_guard.pythe allowlist of filters,project_summary.pythe map context,open_data.pyandsources.py,mcp_server.pythe built-in MCP server,mcp_client.pythe remote connectors). Details in AGENT_MODE.md.
Modules that need neither QGIS, Qt nor GDAL moved to filtermate_core/ in 5.1; their former paths under core/ and infrastructure/ are compatibility shims. tests/test_filtermate_core_is_host_free.py keeps the core free of qgis, PyQt, osgeo and of the plugin's other packages.
backends/:factory.py(BackendFactory,BackendSelector), then one package per backend:postgresql/,spatialite/,ogr/,memory/. Each has abackend.py; PostgreSQL also hasmv_manager.py(materialized views) and Spatialiteindex_manager.py,temp_table_manager.py.backend_registry.py:BackendRegistryreturns the executor for a layer's provider type. It is created infilter_mate_app.pyand injected intoFilterEngineTask.qgis/: QGIS adapters (layers, expressions, signals insignals/,tasks/) andcoverage_layers/for rasters and point clouds (see below).repositories/: layer and history storage.public_api/:operations.pyandfilter_mate_public_api.py;introspection.py(fields, values, statistics, samples, identify, map state),project_control.py(zoom, selection, visibility, adding and removing layers) andprocessing_tools.py(the Processing algorithms AGENT may find, describe and run, undercore/agent/processing_policy.py) serve the chat and the MCP servers.agent/:qt_transport.py(streamed requests),bounded_http.py(every network read of the agent: no redirect, time and size capped),native_mcp.py,turn_checkpoint.pyandturn_effects.py(undo of a turn and of its steps),transcript_store.py.task_builder.py(TaskParameterBuilder),filter_result_handler.py,undo_redo_handler.py,database_manager.py,app_bridge.py(service locator used by the legacy app).
cache/ (query, geometry, WKT, Spatialite caches), database/ (connection pool, PostgreSQL and Spatialite helpers, sql_utils.py), di/ (Container, providers.py), logging/, parallel/, streaming/, state/, feedback/ (message bar helpers), utils/ (layer, thread, validation helpers), constants.py (provider names), perf_timer.py, config/config_migration.py.
controllers/:BaseControllerand one controller per area:exploring_controller.py,filtering_controller.py,exporting_controller.py,favorites_controller.py,config_controller.py,backend_controller.py,layer_sync_controller.py,coverage_mode_controller.py(v5).registry.pyholdsControllerRegistryandTabIndex.managers/: widget configuration, combobox population, config model, export dialogs.widgets/: custom widgets,json_view/(configuration tree),coverage_panels/(raster and point cloud EXPLORING panels).dialogs/,layout/(spacing and layout managers),styles/(themes, icons, QSS loading),tools/(raster pixel picker map tool).
processing/provider.py:FilterMateProcessingProvider(idfiltermate).algorithms/has the algorithm classes,models/the four shipped.model3files.filtermate_api/:server.py(FastAPI app),routers/(filters.py,layers.py,export.py,favorites.py),auth.py(API key),main_thread.py(runs QGIS calls on the Qt main thread),qgis_accessor.py(bridge to the running plugin),run_api.pyand__main__.py(standalone start). Dependencies are inrequirements-api.txt.
See the sections below.
- The user clicks Filter (
pushButton_action_filter). The button'sclickedhandler callslaunchTaskEvent(state, 'filter')infilter_mate_dockwidget.py. It first offers the task toControllerIntegration.delegate_point_cloud_task, which returns True only when the current layer is a raster or a point cloud (see the next section). - For a vector source,
launchTaskEventstores the checked target layers inPROJECT_LAYERS, splits off raster and point cloud targets (delegate_split_coverage_targets) and emitslaunchingTask('filter'). FilterMateApp.manage_taskreceives it (connected infilter_mate_app.py). It checks that the dock is ready (it retries every 500 ms, up to 10 times), deals with layers in edit mode, then callsTaskOrchestrator.dispatch_task(core/services/task_orchestrator.py). If that raises,_legacy_dispatch_taskis used instead.- The orchestrator calls back
FilterMateApp.get_task_parameters, which validates the current layer and builds the parameter dict withTaskParameterBuilder(adapters/task_builder.py): atasksection (layers to filter, expression,skip_source_filter), afilteringsection (buffer, predicates) andforced_backends. FilterMateApp._execute_filter_task(the orchestrator's filter callback) createsFilterEngineTask(description, task_name, task_parameters, backend_registry=...)(core/tasks/filter_task.py), connects the completion handlers, freezes the canvas and adds the task toQgsApplication.taskManager().- In the worker thread,
FilterEngineTask.rungoes throughTaskRunOrchestrator, thenActionDispatcher(core/tasks/dispatchers/action_dispatcher.py) routes the action (filter,unfilter,reset,export). For a filter,FilteringOrchestrator.execute_filtering(core/tasks/filtering_orchestrator.py) filters the source layer, then the target layers, in parallel (infrastructure/parallel/) or sequentially. - For each target layer,
FilterOrchestrator.orchestrate_geometric_filter(core/filter/filter_orchestrator.py) callsBackendFactory.get_backend(adapters/backends/factory.py) and builds the expression through the backend'sexpression_builder.py.postgresql/writes SQL for PostGIS,spatialite/SQL for Spatialite and GeoPackage,ogr/serves file formats without a SQL subset,memory/memory layers. A forced backend (forced_backendsin the parameters) is honoured, and a failing backend falls back to another. - The worker thread never calls
setSubsetString. It queues(layer, expression)pairs (FilterEngineTask.queue_subset_request). FilterEngineTask.finishedruns on the main thread.FinishedHandler(core/tasks/finished_handler.py) applies the queued subsets withapply_pending_subset_requests, which callssafe_set_subset_string(infrastructure/utils), then schedules one canvas refresh.taskCompletedtriggersFilterMateApp.filter_engine_task_completed, which callsFilterResultHandler.handle_task_completion(adapters/filter_result_handler.py): history push, cache clearing, auto-zoom, backend indicator, completion message. Undo and redo are handled byadapters/undo_redo_handler.pywithcore/services/history_service.py.
FilteringController.execute_filter (ui/controllers/filtering_controller.py) validates the configuration but returns False, so the path above is the one that runs. The controller still builds the FilterConfiguration and receives the task-started and task-completed callbacks.
When the current layer is a raster or a point cloud, EXPLORING shows a panel of that kind and the dock's buttons run a cross filter instead of the vector task.
ui/controllers/coverage_mode_controller.py(CoverageModeController) swaps the EXPLORING groups, owns the panels ofui/widgets/coverage_panels/(raster_exploring_panel.py,point_cloud_exploring_panel.py,histogram_widget.py) and implementshandle_taskforfilter,unfilter,reset,undo,redoandexport.ui/controllers/coverage_dock_extras.pyadds the layer card and the tool rail buttons of the layer kind;ui/tools/pixel_picker_tool.pyis the map tool.core/services/cross_filter_service.py(CrossFilterService) handles every source/target pair except vector to vector. It keeps the cross operation history per source layer so Undo, Redo and Unfilter can restore derived sources. The model is incore/domain/cross_filter.py; snapshots and history are incore/domain/filter_state.py.adapters/qgis/coverage_layers/does the QGIS work:source_jobs.py: turns the EXPLORING selection into a source geometry (VectorSourceJob,RasterSourceJob,PointCloudSourceJob).target_appliers.py: applies it to a target (VectorTargetJob,RasterTargetJob,PointCloudTargetJob). A job runsprepareon the main thread,computein the task,applyon the main thread again.cross_filter_task.py: theQgsTaskthat runs the jobs.raster_adapter.py,point_cloud_footprint.py,geometry_tools.py: raster statistics and pixel selection, footprint of selected points, geometry helpers.gdal_warp.py,pdal_cli.py,hag_task.py:gdal.Warpwrapper, thepdalexecutable, height above ground.exporters.py,favorites_bridge.py.sam_model.py,segmentation.py: the SAM 2.1 model (downloaded on request, checked against its SHA-256) run withonnxruntime, and the objects it draws.ui/controllers/segmentation_controller.pydrives the pipette;processing/algorithms/segmentation_algorithm.pyisfiltermate:segment_from_features.onnxruntimeis declared bypython_dependenciesinmetadata.txtand installed into the QGIS profile after a confirmation. See SEGMENTATION.md.
- Derived sources: a raster is clipped to a VRT, a point cloud to a COPC file. The layer keeps its id and style; its data source is swapped (
setDataSource).snapshots.pykeeps the registry of swapped layers (DerivedSourceRegistry): it writes the original source back into the saved project XML and restores every layer when the plugin unloads. - Cache:
cache.pymanages the folder of derived files,<QGIS profile>/filtermate/cache/<session>/unlessAPP.OPTIONS.CROSS_FILTER.cache_diris set.collect_garbageremoves files that no layer or undo step uses.cache_max_gbcaps the size. A lock file protects a live session from other QGIS instances. - When the source is a vector layer, raster and point cloud targets are removed from the vector task and clipped by the same source geometry after it is launched (
delegate_vector_source_coverage_task).
A layer whose data is read over the network (WFS, OGC API Features, ArcGIS Feature / Map Server, WMS / WMTS / XYZ, WCS, vector tiles, remote EPT / COPC, /vsicurl/ files, MSSQL / Oracle / HANA) follows the same paths as a local one, with three rules: no network read on the main thread, every read bounded, and no result that is wrong or partial without saying so. The plan and its history are in internal/plans/V5_STREAMING/.
- Classification.
core/domain/source_capability.py(classify, pure Python) tells from the provider key and the source string where the data lives (local file, database, web service, remote file), the filter language of the server (ServerFilter: OGC Filter, CQL2, SQLwhere, provider SQL), whether raster pixels are values or a rendered image (ValueKind), whether a count goes over the network (NetworkCost) and the longest key list sent to a service (500).adapters/qgis/source_capability_probe.pycaches it per layer (capability_for_layer,counts_cheaply,feature_count_or_none). - Keys and literals.
core/domain/stable_key.pychooses a key proven unique (declared key, thengml_id/cleabs/objectid-like fields checked in the task); a web service without one refuses a key list (a WFS is then cut by the extent of the source, see below).core/filter/pk_formatter.pyis the only formatter of key literals. - Attribute filters sent to a server.
core/filter/server_dialect.pysays whether an expression translates completely (FULL), in part (PARTIAL: AND-split, the rest evaluated locally) or not at all (NONE) for a dialect;adapters/qgis/server_filter_translation.pywalks the realQgsExpressiontree (WFS:QgsOgcUtils). Only aFULLtranslation is set as a subset.adapters/qgis/server_subset_job.pyprepares the new provider (and a rollback provider) in a task and installs it on the main thread;core/filter/server_transfer_policy.py(transfer_mode) decides per QGIS version: asynchronous from 3.32, synchronous WFS from 3.24 to 3.31, refused before (the 3.22 setter crashes). - Spatial filters and bounded copies. For a web service target,
adapters/qgis/remote_materializer.pyreads the features of the source extent only (server BBOX), evaluates the exact predicate locally and returns the keys; it also evaluates aPARTIALresidual on a bounded copy (APP.OPTIONS.REMOTE_MATERIALIZATION: 20,000 features / 90 s by default). A result cut by the limit is reported as partial, never as complete. Where the keys cannot be listed (more than 500 of them, a list longer than the address a server reads —source_capability.key_list_fits, 8,000 bytes by default,REMOTE_MATERIALIZATION.max_request_bytes—, no stable key, or a QGIS on which no service read is checked) a WFS target is cut by the extent of the source instead: its subset isintersects_bbox($geometry, geom_from_wkt('POLYGON((...))'))(source_capability.extent_subset), the one function call the WFS dialect validates (server_dialect, nodeextent) and QGIS sends as<fes:BBOX>; the outcome says it is a cut by extent (by_extent), never an exact one. A service may also refuse a list of keys far under 500 (their address is too long for it: read on a real WFS at about 100 keys): the exact filter leaves its cut by extent inadapters/qgis/extent_fallback.py, and whoever sets the filter and sees it refused sets that one instead (VectorTargetJob.apply,apply_pending_subset_requests). Not for AND NOT nor Disjoint (negations), nor for OGC API Features and ArcGIS. Where QGIS cannot report a protocol error (before 3.26, or QGIS < 3.36 under Python 3.12, #197) a service read is refused. - Exploration.
adapters/qgis/async_query.pyruns value lists, feature lists, zooms and filtered extents of a non-cheap layer in cancellableQgsTasks (submit_query, oneQuerySlotper widget, generation tokens drop stale results); expressions evaluated in a worker are checked first (remote_expression_is_safe). - Rasters. Remote COG / WCS / PostgreSQL rasters are value rasters: statistics and previews run in workers (
raster_statistics_task.py,raster_surface_task.py) on a bounded capture, and a WCS used as a source or target is copied to a GeoTIFF of the session cache, bounded to the kept zone (raster_materialization.py). WMS / WMTS / XYZ / ArcGIS MapServer layers are rendered images: colour selection on a bounded render (rendered_raster.py). A WMS, a WMTS or XYZ tiles (providerwms) are filter targets all the same: the worker captures the image over the area kept (materialize_web_map), on the finest grid a pixel budget affords (CROSS_FILTER.web_map_target_max_pixels, a level of the tiles when the service has levels:web_map_grid), then cuts it as a local raster; the outcome says it is a still image and its resolution (captured), and how many requests the service did not answer. Unfilter puts the live service back. An ArcGIS MapServer and a GDAL description of a WMS stay refused. - Vector tiles are targets only: the filter is written into the
filterExpressionof the basic renderer and labeling rules (vector_tile_filters.py,vector_tile_target.py) and restored by the snapshots. - Remote point clouds (EPT, COPC over http) are read through the PDAL readers with the useful extent (
pdal_cli.py), never as a whole. - The dock, Processing, the Python API and REST / MCP share these paths: a public API cross filter to a WFS takes the same bounded path as the dock.
adapters/public_api/operations.py implements the operations without the dock: cross_filter, cross_filter_by_geometry, filter_point_clouds, clear_filters, export_layers, apply_favorite, list_favorites, filter_state. They run synchronously on the main thread, one at a time (busy_reason), and record their changes in the cross filter history.
Three surfaces share it:
| Surface | Code |
|---|---|
Processing, qgis_process, models |
processing/ |
| Python API | adapters/public_api/filter_mate_public_api.py, returned by FilterMate.get_public_api() |
| REST API | filtermate_api/ through QGISFilterMateAccessor |
| Chat of AGENT and both MCP servers | filtermate_api/agent_tools.py (chat, built-in MCP server), filtermate_api/mcp/ (stdio, through the REST API) |
Parameters, routes and examples are in AUTOMATION.md. Add a new operation in operations.py first, then expose it on each surface.
extensions/ holds optional modules. ExtensionRegistry (extensions/registry.py) discovers every sub-package that exposes an Extension class deriving from BaseExtension (extensions/base.py), then runs check_dependencies, initialize(iface), create_ui and, on unload, teardown. FilterMate._init_extensions drives this from initGui. An extension whose dependencies are missing disables itself and FilterMate runs unchanged.
extensions/qfieldcloud/: export of filtered layers to QFieldCloud (needsqfieldcloud-sdk).extensions/favorites_sharing/: share favorites through git repositories; has its own README.
An extension declares its configuration keys in config_schema(); they appear under EXTENSIONS.<id> in config.json. The full tree and the extension guide are in ../extensions/README.md.
config/config.default.json: the reference. Each setting is{"value": ..., "description": ..., "choices"/"min"/"max": ...}; keys starting with_(_display_name,_hidden) drive the Configuration tab. Top-level sections:APP,CURRENT_PROJECT,EXTENSIONS.- At start,
config/config.py(init_env_vars) loadsconfig.jsonfrom theFilterMatefolder of the QGIS profile, creating it from the default when missing. It merges new keys, refreshes the metadata of existing keys and keeps user values (_migrate_config).ENV_VARSholds paths and the loaded data. - Other modules:
feedback_config.py(message verbosity),theme_helpers.py,config_metadata.py. See ../config/README_CONFIG.md. - The Configuration tab is a JSON tree (
ui/widgets/json_view/) managed byui/managers/config_model_manager.py. - Plugin metadata is in
metadata.txt(version, QGIS 3.22 to 4.99: QGIS 4 compatibility comes fromqgisMaximumVersion).
User strings go through tr() or QCoreApplication.translate. i18n/FilterMate.pro lists the source files and the 34 FilterMate_<locale>.ts files; the compiled .qm files are tracked in git and shipped. Update the catalogs with pylupdate5 FilterMate.pro (in i18n/), then scripts/i18n_processing_context.py and scripts/i18n_runtime_contexts.py (strings translated through helpers such as _tr('...'), self._tr('...') or dw.tr('...'), which pylupdate5 misses or files under the wrong context), translate, and compile with lrelease; tests/unit/test_i18n_runtime_contexts.py fails if the second script was skipped. FilterMate loads i18n/FilterMate_<locale>.qm with a QTranslator and can reload it when the language is changed in the Configuration tab. The zip script leaves out .ts and .pro files.
tests/unit/mirrors the plugin layout (core,adapters,infrastructure,ui,processing,extensions).tests/api/tests the REST API.tests/conftest.pymocksqgis.*so these run without QGIS.- AST guards at the top of
tests/:test_no_unscoped_qt_enums.py,test_no_qtwidgets_relocated_symbols.py,test_no_unguarded_sip_import.py,test_no_bare_disconnect_on_qgis_signals.py,test_no_clear_on_map_layer_combobox.py,test_no_layout_insert_item_temporaries.py, plustest_package_import_exports.pyandtest_backend_services_facade_calls.py. Each walks the plugin source and fails on a pattern that broke in a real QGIS. tests/qgis_headless/: scripts run inside QGIS Docker images (fixtures, engine smoke test, dock smoke test under Xvfb). They are not pytest modules. Thecheck_stream_*.pyscripts check the streaming sources against loopback HTTP fixtures (WFS, OGC API, ArcGIS, COG, MBTiles, COPC / EPT);FM_STREAM_PUBLIC=1also runs them, andcheck_stream_e2e.py, against public services..github/workflows/test.yml: flake8, then pytest on Python 3.10 and 3.12..github/workflows/qgis-headless.yml: the headless scripts onqgis/qgisimages from QGIS 3.22 to nightly.- These two workflows are turned off on GitHub since 2026-11-06: run
python -m pytest tests/ -o "addopts="and the headless scripts in Docker locally before a merge (see CONTRIBUTING.md). .github/workflows/release.yml: on av*.*.*tag, runs the tests, checks the tag againstmetadata.txt, builds the zip withscripts/prepare_plugin_zip.sh, creates the GitHub release and publishes to plugins.qgis.org..github/workflows/deploy-docs.yml: publisheswebsite/to GitHub Pages.