Migration Roadmap: AutoParamWidget for IO Widgets
Migration Roadmap: Replacing Boilerplate IO Widgets with AutoParamWidget
Problem Statement
The DataImport_Widget (68 files, ~25 format-specific sub-widgets) and DataExport_Widget (28 files, ~9 format-specific sub-widgets) contain extensive boilerplate UI code. Each format/data-type combination has:
- A hand-written
.uiXML file defining QSpinBoxes, QComboBoxes, QCheckBoxes, etc. - A hand-written
.hpp/.cppclass that manually reads widget values and constructs either an Options struct or anlohmann::jsonconfig object. - Manual signal wiring between parent container widgets and child format widgets.
Meanwhile, the project already has:
- ParameterSchema (
src/ParameterSchema/): Compile-time schema extraction from reflect-cpp structs. - AutoParamWidget (
src/WhiskerToolbox/AutoParamWidget/): Generates a complete Qt form from aParameterSchema, with JSON serialization/deserialization. - Existing IO Options structs that already use reflect-cpp (e.g.,
CSVPointLoaderOptions,BinaryAnalogLoaderOptions). - SaverInfo with a
ParameterSchema schemafield that is already populated at registration time but never consumed by the export UI.
This roadmap describes how to systematically replace hand-written format widgets with AutoParamWidget, making the UI self-updating when new formats or options are added.
Current Architecture
┌──────────────────────────────────────────────────────────┐
│ DataImport_Widget (top-level) │
│ ├── DataImportTypeRegistry (factory map) │
│ ├── PointImport_Widget (container) │
│ │ └── CSVPointImport_Widget (hand-written .ui) │
│ ├── AnalogImport_Widget (container) │
│ │ ├── CSVAnalogImport_Widget (hand-written .ui) │
│ │ └── BinaryAnalogImport_Widget (hand-written .ui) │
│ ├── LineImport_Widget (container) │
│ │ ├── CSVLineImport_Widget (hand-written .ui) │
│ │ ├── BinaryLineImport_Widget (hand-written .ui) │
│ │ ├── HDF5LineImport_Widget (hand-written .ui) │
│ │ └── LMDBLineImport_Widget (hand-written .ui) │
│ ├── MaskImport_Widget (container) │
│ │ ├── HDF5MaskImport_Widget (hand-written .ui) │
│ │ └── ImageMaskImport_Widget (hand-written .ui) │
│ ├── DigitalEventImport_Widget (container) │
│ │ └── CSVDigitalEventImport_Widget (hand-written .ui)│
│ ├── DigitalIntervalImport_Widget (container) │
│ │ ├── CSVDigitalIntervalImport_Widget │
│ │ └── BinaryDigitalIntervalImport_Widget │
│ └── TensorImport_Widget (container) │
│ └── (Numpy sub-widget) │
└──────────────────────────────────────────────────────────┘
Key asymmetry: Savers already have SaverInfo with ParameterSchema populated via extractParameterSchema<T>(). Loaders have no equivalent LoaderInfo struct.
Target Architecture
┌──────────────────────────────────────────────────────────┐
│ DataImport_Widget (top-level) │
│ ├── Queries LoaderRegistry for LoaderInfo │
│ ├── Data type combo → filters LoaderInfos by type │
│ ├── Format combo → populated from LoaderInfos │
│ └── AutoParamWidget → setSchema(selected_loader.schema) │
│ ├── File path field (from Options struct) │
│ ├── Format-specific fields (auto-generated) │
│ └── [Load] button → toJson() → registry.tryLoad() │
│ │
│ DataExport_Widget (top-level) │
│ ├── Queries LoaderRegistry.getSupportedSaveFormats() │
│ ├── Data type combo → filters SaverInfos │
│ ├── Format combo → populated from SaverInfos │
│ └── AutoParamWidget → setSchema(selected_saver.schema) │
│ ├── Filename/directory fields (auto-generated) │
│ ├── Format-specific fields (auto-generated) │
│ └── [Save] button → toJson() → registry.trySave() │
└──────────────────────────────────────────────────────────┘
Migration Phases
Phase 0: Infrastructure — Add LoaderInfo to IO Layer
Goal: Create parity between loaders and savers so both can be discovered and auto-generate UI.
Step 0.1: Create LoaderInfo struct ✅ DONE
Created src/IO/core/LoaderInfo.hpp with format, data_type, description, supports_batch, and ParameterSchema schema fields. Added to src/IO/CMakeLists.txt.
Step 0.2: Add getLoaderInfo() to IFormatLoader ✅ DONE
Added virtual std::vector<LoaderInfo> getLoaderInfo() const { return {}; } to IFormatLoader in src/IO/core/IFormatLoader.hpp, mirroring getSaverInfo().
Step 0.3: Add LoaderInfo query methods to LoaderRegistry ✅ DONE
Added getSupportedLoadFormats() and getSupportedLoadFormats(DM_DataType) to LoaderRegistry in src/IO/core/LoaderRegistry.hpp and src/IO/core/LoaderRegistry.cpp. Added 8 test cases (59 assertions) in tests/DataManager/IO/loader_registry.test.cpp covering empty registry, stub loaders, data-type filtering, multi-loader aggregation, and batch flag preservation.
Step 0.4: Add ParameterUIHints specializations for loader options ✅ DONE
For each loader Options struct that uses rfl::Validator, add tooltips and display hints. These are optional but improve the auto-generated UI quality significantly.
Priority order (by complexity of the Options struct):
BinaryAnalogLoaderOptions— 10+ fields, prime candidateCSVAnalogLoaderOptions— 6 fieldsCSVPointLoaderOptions— 5 fieldsCSVEventLoaderOptions— 7 fieldsCSVIntervalLoaderOptions— 5 fieldsCSVLineLoaderOptions— (if exists)- Others (HDF5, Image, etc.)
Example for BinaryAnalogLoaderOptions:
template<>
struct ParameterUIHints<BinaryAnalogLoaderOptions> {
static void annotate(ParameterSchema & schema) {
if (auto * f = schema.field("header_size")) {
f->tooltip = "Number of bytes to skip at the start of the file";
}
if (auto * f = schema.field("num_channels")) {
f->tooltip = "Number of interleaved channels in the binary file";
}
if (auto * f = schema.field("binary_data_type")) {
f->tooltip = "Binary encoding of each sample";
f->allowed_values = {"int8", "int16", "uint16", "float32", "float64"};
}
if (auto * f = schema.field("use_memory_mapped")) {
f->tooltip = "Use memory-mapped I/O for large files";
}
if (auto * f = schema.field("scale_factor")) {
f->tooltip = "Multiply each sample by this value after loading";
}
if (auto * f = schema.field("offset_value")) {
f->tooltip = "Add this value to each sample after scaling";
}
}
};- Files to modify: Each
*Optionsheader insrc/IO/formats/*/(addParameterUIHintsspecialization). - Depends on: These headers already include
ParameterSchema/ParameterSchema.hppfor the saver side; reuse for loaders.
Step 0.5: Implement getLoaderInfo() in each format loader
For each IFormatLoader subclass, add getLoaderInfo() returning one LoaderInfo per supported data-type/format combination with extractParameterSchema<OptionsType>().
CSVLoader example:
std::vector<LoaderInfo> CSVLoader::getLoaderInfo() const {
using WhiskerToolbox::Transforms::V2::extractParameterSchema;
return {
{"csv", DM_DataType::Points, "CSV point data (frame, x, y)", false,
extractParameterSchema<CSVPointLoaderOptions>()},
{"csv", DM_DataType::Analog, "CSV analog time series", false,
extractParameterSchema<CSVAnalogLoaderOptions>()},
{"csv", DM_DataType::DigitalEvent, "CSV digital events", true,
extractParameterSchema<CSVEventLoaderOptions>()},
{"csv", DM_DataType::DigitalInterval, "CSV digital intervals", false,
extractParameterSchema<CSVIntervalLoaderOptions>()},
// ... etc
};
}Do this for all format loaders:
CSVLoader— largest, ~6 loader infosBinaryFormatLoader— ~3 loader infosCapnProtoFormatLoader— 1 loader infoHDF5FormatLoader— ~2 loader infosOpenCVFormatLoader— 1 loader infoNumpyFormatLoader— 1 loader info
- Files to modify: Each format loader
.hpp/.cppinsrc/IO/formats/ - Tests: Extend the Step 0.3 test to verify schema field counts match expected values for key loaders (e.g.,
BinaryAnalogLoaderOptionsshould have 10+ fields).
Phase 1: Export Widget Migration (Easier — SaverInfo Already Exists)
Goal: Replace all 9 hand-written export sub-widgets with a single AutoParamWidget-based export panel.
Step 1.1: Create GenericSaverPanel widget
Create a new widget src/WhiskerToolbox/DataExport_Widget/GenericSaverPanel.hpp/cpp:
class GenericSaverPanel : public QWidget {
Q_OBJECT
public:
explicit GenericSaverPanel(QWidget * parent = nullptr);
/// Set the saver info and rebuild the form
void setSaverInfo(SaverInfo const & info);
/// Get the current options as JSON
[[nodiscard]] std::string toJson() const;
signals:
void saveRequested(QString format, nlohmann::json config);
private:
AutoParamWidget * _param_widget = nullptr;
QPushButton * _save_button = nullptr;
QLabel * _description_label = nullptr;
SaverInfo _current_info;
};The implementation:
- When
setSaverInfo()is called, call_param_widget->setSchema(info.schema). - When the Save button is clicked, call
_param_widget->toJson(), parse tonlohmann::json, and emitsaveRequested(format, config). - Add a “Browse” button that opens a
QFileDialogfor filename/directory fields.
- Files to create:
GenericSaverPanel.hpp,GenericSaverPanel.cpp - Files to modify:
DataExport_Widget/CMakeLists.txt - Tests: Layout constraint test via
LayoutTesting— verify no zero-dimension widgets.
Step 1.2: Add file/directory browsing support to AutoParamWidget — implemented
The loader/saver Options structs have fields like filepath, filename, parent_dir, directory_path. These should get a browse button rather than a plain QLineEdit.
Implemented design: ParameterFieldDescriptor uses a PathFieldKind enum (None, FilePath, DirectoryPath) plus optional file_dialog_id. This replaces the earlier proposal of separate is_file_path / is_directory_path booleans (mutually exclusive). AutoParamWidget renders QLineEdit + Browse for non-None kinds. Fallback directories are registered at app startup via AutoParamWidget::registerDialogFallback(), keyed by file_dialog_id — not as a per-field schema hint.
Use ParameterUIHints to mark path fields:
template<>
struct ParameterUIHints<CSVPointSaverOptions> {
static void annotate(ParameterSchema & schema) {
if (auto * f = schema.field("filename")) {
f->path_field_kind = PathFieldKind::FilePath;
f->file_dialog_id = "export_csv";
f->tooltip = "Output filename";
}
if (auto * f = schema.field("parent_dir")) {
f->path_field_kind = PathFieldKind::DirectoryPath;
f->file_dialog_id = "export_dir";
f->tooltip = "Output directory";
}
}
};MainWindow wires AutoParamWidget::setFileDialogOpener() to AppFileDialog and registers fallbacks (e.g. transformv2_pipeline_open → user pipeline library). First command consumer: RunTransformsV2PipelineAtTime.pipeline_path in TriageSession. TransformsV2Properties_Widget still uses hand-written buttons (no schema).
- Files modified:
ParameterSchema.hpp,AutoParamWidget.hpp/cpp,mainwindow.cpp - Tests:
RunTransformsV2PipelineAtTime.test.cppschema hint extraction;GenericLoaderPanel/GenericSaverPanelbrowse UX still future work.
Step 1.3: Refactor DataExport_Widget to use registry-driven discovery
Replace the current stacked-widget approach with:
- Query
LoaderRegistry::getInstance().getSupportedSaveFormats()to get allSaverInfoentries. - Populate a data-type combo from the unique
data_typevalues. - When data type is selected, populate a format combo from matching
SaverInfoentries. - When format is selected, call
GenericSaverPanel::setSaverInfo(selectedInfo).
DataExport_Widget
├── QComboBox (data key selector — pick which data object to export)
├── QComboBox (format selector — populated from SaverInfos matching data type)
├── GenericSaverPanel (AutoParamWidget + Save button)
└── QLabel (status/error messages)
- Files to modify:
DataExport_Widget.hpp,DataExport_Widget.cpp,DataExport_Widget.ui - Files to delete (after migration is complete and tested): All 9 format-specific saver sub-widgets and their
.uifiles. - Tests: Integration test — verify that saving a PointData to CSV with the new widget produces the same output as the old widget.
Step 1.4: Migrate DataInspector export sections
DataInspectors (e.g., LineInspector) currently embed hand-written saver widgets. Replace these with GenericSaverPanel instances populated from SaverInfo.
For each Inspector that has export functionality:
- Remove the
#includeof the old saver widget. - Create a
GenericSaverPanel, querygetSupportedSaveFormats(data_type), and let the user pick format + configure options. - Wire the
saveRequestedsignal to the existing save logic.
- Files to modify: Each DataInspector that includes saver widgets (search for
Saver_Widgetincludes). - Tests: Manual smoke test — export from inspector, verify file correctness.
Step 1.5: Add ParameterUIHints for all saver Options structs
Many saver Options structs are plain structs without hints. Add ParameterUIHints specializations for each to improve the generated UI:
CSVPointSaverOptionsCSVAnalogSaverOptionsCSVEventSaverOptionsCSVIntervalSaverOptionsCSVMaskRLESaverOptionsCSVSingleFileLineSaverOptionsBinaryLineSaverOptionsImageMaskSaverOptions
For each, add tooltips, mark file/directory fields, set reasonable min/max for numeric fields (e.g., precision 0–15).
- Files to modify: Each Options header in
src/IO/formats/. - Tests: None required (cosmetic).
Phase 2: Import Widget Migration (Requires Phase 0)
Goal: Replace all 12+ hand-written import sub-widgets with a single AutoParamWidget-based import panel.
Step 2.1: Create GenericLoaderPanel widget
Create src/WhiskerToolbox/DataImport_Widget/GenericLoaderPanel.hpp/cpp:
class GenericLoaderPanel : public QWidget {
Q_OBJECT
public:
explicit GenericLoaderPanel(QWidget * parent = nullptr);
/// Set the loader info and rebuild the form
void setLoaderInfo(LoaderInfo const & info);
/// Get the current options as JSON
[[nodiscard]] std::string toJson() const;
signals:
void loadRequested(QString format, DM_DataType data_type, nlohmann::json config);
private:
AutoParamWidget * _param_widget = nullptr;
QPushButton * _load_button = nullptr;
QLabel * _description_label = nullptr;
LoaderInfo _current_info;
};- Files to create:
GenericLoaderPanel.hpp,GenericLoaderPanel.cpp - Files to modify:
DataImport_Widget/CMakeLists.txt
Step 2.2: Refactor DataImport_Widget to use registry-driven discovery
Replace DataImportTypeRegistry + per-type container widgets with:
- Query
LoaderRegistry::getInstance().getSupportedLoadFormats()to get allLoaderInfoentries. - Data type combo populated from unique
data_typevalues in the LoaderInfos. - Format combo populated from
LoaderInfoentries matching selected data type. GenericLoaderPanelrendered for the selected format.
DataImport_Widget
├── QLineEdit + Browse (data name for DataManager)
├── QComboBox (data type — from LoaderInfos)
├── QComboBox (format — from LoaderInfos matching type)
├── GenericLoaderPanel (AutoParamWidget + Load button)
└── QLabel (status/error messages)
- Files to modify:
DataImport_Widget.hpp,DataImport_Widget.cpp,DataImport_Widget.ui
Step 2.3: Handle special cases
Some import widgets have behavior that plain AutoParamWidget cannot handle:
Batch loading (DLC points, multi-file CSVs): The
LoaderInfo.supports_batchflag indicates this. When true, add a “Load All” button that callsloadBatch()instead ofload(). The JSON config is still generated the same way.Scaling widget (MaskImport, used for coordinate rescaling): This is orthogonal to format-specific options. Add a collapsible “Post-Import Options” section below the
GenericLoaderPanelwith aScaling_Widget. This section is shown when the data type supports scaling (Mask, Line, Point).Preview (some widgets show a data preview after file selection): This can be deferred — the old behavior was inconsistent anyway.
Multi-file vs single-file modes (CSVLineImport has radio buttons for this): Model this as a variant or an enum field in the loader Options struct (e.g.,
std::optional<std::string> load_modewithallowed_values = {"single_file", "multi_file"}). TheParameterUIHintsannotation can set this up.
For each special case, document it as a ParameterUIHints annotation or a small wrapper around GenericLoaderPanel, rather than creating a custom widget.
- Files to modify: Various loader Options structs may need new fields.
GenericLoaderPanelmay need optional slots for auxiliary widgets (scaling, preview).
Step 2.4: Migrate one data type at a time
Migrate import widgets in order from simplest to most complex. For each:
- Verify the
LoaderInfois returned by the registry with correct schema. - Verify
AutoParamWidgetrenders the schema correctly. - Verify
toJson()output matches what the loader expects. - Verify loading works end-to-end.
- Mark the old widget as deprecated (comment only — do not delete yet).
Migration order:
| Order | Data Type | Format | Old Widget | Complexity |
|---|---|---|---|---|
| 1 | Points | CSV | CSVPointImport_Widget |
Low (4 fields) |
| 2 | DigitalInterval | CSV | CSVDigitalIntervalImport_Widget |
Low (5 fields) |
| 3 | DigitalEvent | CSV | CSVDigitalEventImport_Widget |
Low (7 fields) |
| 4 | Analog | CSV | CSVAnalogImport_Widget |
Medium (6 fields) |
| 5 | Analog | Binary | BinaryAnalogImport_Widget |
High (10+ fields) |
| 6 | Lines | CSV | CSVLineImport_Widget |
Medium (has single/multi mode) |
| 7 | Lines | Binary | BinaryLineImport_Widget |
Low (1 field) |
| 8 | Lines | HDF5 | HDF5LineImport_Widget |
Low (few fields) |
| 9 | Masks | HDF5 | HDF5MaskImport_Widget |
Low-Medium |
| 10 | Masks | Image | ImageMaskImport_Widget |
Medium (6 fields) |
| 11 | Tensors | Numpy | TensorImport_Widget |
Low |
| 12 | DigitalInterval | Binary | BinaryDigitalIntervalImport_Widget |
Low |
For each migration step, the concrete actions are:
- Open the old widget’s
.cppfile and the corresponding*LoaderOptionsstruct. - Verify the Options struct has all fields the old widget exposes. If not, add missing fields.
- Add
ParameterUIHintsspecialization if not present. - Implement
getLoaderInfo()entry in the format loader (if not done in Phase 0). - Test:
auto schema = extractParameterSchema<OptionsType>(); auto w = AutoParamWidget(); w.setSchema(schema);— visually verify the form matches the old widget. - Test: Fill the form, call
toJson(), pass toregistry.tryLoad()— verify data loads correctly. - If the old widget had custom behavior (e.g., file preview, batch discovery), implement it in
GenericLoaderPanelor as aParameterUIHintsannotation.
Step 2.5: Delete old widgets and DataImportTypeRegistry
After all data types are migrated and tested:
- Remove all format-specific import sub-widgets (
.hpp,.cpp,.uifiles). - Remove all container widgets (e.g.,
PointImport_Widget,AnalogImport_Widget, etc.). - Remove
DataImportTypeRegistryandDataImportWidgetRegistration. - Update
DataImport_Widget/CMakeLists.txtto remove old sources. - Update
DataExport_Widget/CMakeLists.txtsimilarly.
- Files to delete: ~60 files in
DataImport_Widget/, ~25 files inDataExport_Widget/. - Tests: Full regression test — load and save each data type/format combination.
Phase 3: DataInspector Integration
Goal: DataInspectors that embed import/export functionality should use the new generic panels.
Step 3.1: Replace embedded saver widgets in Inspectors
Search for all Inspector files that include DataExport_Widget/ headers. Replace the embedded format-specific saver widget with a GenericSaverPanel configured from SaverInfo.
Step 3.2: Add import capability to Inspectors (optional)
If desired, Inspectors could also embed a GenericLoaderPanel for quick re-loading or format conversion. This follows the same pattern.
Phase 4: Cleanup and Documentation
Step 4.1: Remove DataImportTypeRegistry if no longer needed
If DataImport_Widget now discovers loaders entirely from LoaderRegistry, the DataImportTypeRegistry factory map is redundant.
Step 4.2: Update developer documentation
- Update
docs/developer/IO/docs to describe the newLoaderInfoand registry discovery flow. - Update widget documentation to describe the
GenericLoaderPanel/GenericSaverPanelpattern. - Update
copilot-instructions.mdto add the new libraries/widgets to the architecture section.
Step 4.3: Update user documentation
- Update
docs/user_guide/import/export articles to reflect the simplified UI.
Summary of File Impact
| Phase | Files Created | Files Modified | Files Deleted (eventual) |
|---|---|---|---|
| 0 | 1 (LoaderInfo.hpp) | ~15 (IFormatLoader, Registry, all format loaders) | 0 |
| 1 | 2 (GenericSaverPanel) | ~5 (DataExport_Widget, ParameterSchema, AutoParamWidget) | ~25 (old saver widgets) |
| 2 | 2 (GenericLoaderPanel) | ~3 (DataImport_Widget) | ~60 (old import widgets) |
| 3 | 0 | ~5 (Inspectors) | 0 |
| 4 | 0 | ~5 (docs) | ~3 (TypeRegistry) |
Key Design Decisions
filepathhandling: Loader Options structs have afilepathfield. In the auto-generated UI, this needs a browse button. UsePathFieldKind+file_dialog_idonParameterFieldDescriptorandAutoParamWidgetbrowse rows (implemented — see Step 1.2).Saver
parent_dir+filenamepattern: Many savers split the output path intoparent_dirandfilename. The auto-generated UI will show both as browseable fields. This is actually cleaner than the current approach where some widgets combine them.Batch loading: Handled by a flag on
LoaderInfo, with a secondary “Load All” button when supported. The JSON config is identical for single and batch loading.Post-import transforms (scaling, coordinate maps): These are orthogonal to format-specific options. Model them as an optional auxiliary section below the
GenericLoaderPanel, not as part of theAutoParamWidgetform.Backward compatibility: The
LoaderRegistry.tryLoad()andtrySave()methods already acceptnlohmann::jsonconfig. TheAutoParamWidget.toJson()output is compatible. No changes needed to the IO dispatch layer.Incremental migration: Each data type can be migrated independently. The old Type Registry and new Registry-driven discovery can coexist during migration. Old widgets can remain alongside new ones until fully tested.
Risk Assessment
| Risk | Mitigation |
|---|---|
| AutoParamWidget doesn’t support a field type used in an Options struct | The rfl::Validator types are already proven. Only risk is custom validators like ValidBinaryDataType — add ParameterUIHints to map these to combo boxes. |
| File browse UX is worse than hand-written | PathFieldKind + file_dialog_id on ParameterFieldDescriptor and AutoParamWidget::registerDialogFallback() (Step 1.2 — implemented for commands; IO panels pending). |
| Batch loading UI needs custom logic | Keep batch handling in GenericLoaderPanel as a flag, not in AutoParamWidget. The param widget only handles the schema. |
| Some import widgets have validation logic (e.g., “column X must be different from column Y”) | Use PostEditHook on the AutoParamWidget for cross-field validation. |
| Performance of extractParameterSchema at startup | Negligible — these are small structs. Schema extraction is already used for all savers. |