From d43bfadcd8ebcff759401abcf494cbeedaecfea7 Mon Sep 17 00:00:00 2001 From: Michal Buzik Date: Thu, 15 Oct 2026 12:03:13 +0200 Subject: [PATCH] feat(ui): add bulk parameter editing for component configurations - Introduced `BulkComponentParametersDlg` to support simultaneous parameter updates for selected components. - Added context menu in `ComponentsManagerDlg` with bulk edit and copy column options. - Updated resource strings for localization of bulk editing actions and tooltips. - Enhanced UI controls to handle mixed values, validation, and conditional updates efficiently. - Included new providers (iPerl and WaterMeter) for bulk parameter management. --- TBF/Resources/Strings.Designer.cs | 11 + TBF/Resources/Strings.cs.resx | 10 + TBF/Resources/Strings.resx | 10 + TBF/Resources/Strings.sk.resx | 10 + TBF/TBF.csproj | 6 + .../BulkComponentParametersDlg.Designer.cs | 166 ++++++++ .../Components/BulkComponentParametersDlg.cs | 373 ++++++++++++++++++ .../ComponentsManagerDlg.Designer.cs | 4 +- .../Bench/Components/ComponentsManagerDlg.cs | 221 ++++++++++- TBFTests/TBFTests.csproj | 1 + .../BulkComponentParametersDlgTests.cs | 87 ++++ 11 files changed, 892 insertions(+), 7 deletions(-) create mode 100644 TBF/UI/Bench/Components/BulkComponentParametersDlg.Designer.cs create mode 100644 TBF/UI/Bench/Components/BulkComponentParametersDlg.cs create mode 100644 TBFTests/UI/Bench/Components/BulkComponentParametersDlgTests.cs diff --git a/TBF/Resources/Strings.Designer.cs b/TBF/Resources/Strings.Designer.cs index f8c3472f7..4ffdcba07 100644 --- a/TBF/Resources/Strings.Designer.cs +++ b/TBF/Resources/Strings.Designer.cs @@ -7393,5 +7393,16 @@ namespace TBF.Resources { get { return ResourceManager.GetString("ReaderPhysicalMuxTooltip", resourceCulture); } } + internal static string BulkEditTitle { get { return ResourceManager.GetString("BulkEditTitle", resourceCulture); } } + internal static string BulkEditSelected { get { return ResourceManager.GetString("BulkEditSelected", resourceCulture); } } + internal static string BulkEditHelp { get { return ResourceManager.GetString("BulkEditHelp", resourceCulture); } } + internal static string BulkEditMixedValue { get { return ResourceManager.GetString("BulkEditMixedValue", resourceCulture); } } + internal static string BulkEditApply { get { return ResourceManager.GetString("BulkEditApply", resourceCulture); } } + internal static string BulkEditSelectedMenu { get { return ResourceManager.GetString("BulkEditSelectedMenu", resourceCulture); } } + internal static string BulkEditCopyBelow { get { return ResourceManager.GetString("BulkEditCopyBelow", resourceCulture); } } + internal static string BulkEditInvalidValue { get { return ResourceManager.GetString("BulkEditInvalidValue", resourceCulture); } } + internal static string BulkEditInvalidValueSimple { get { return ResourceManager.GetString("BulkEditInvalidValueSimple", resourceCulture); } } + internal static string BulkEditUniqueName { get { return ResourceManager.GetString("BulkEditUniqueName", resourceCulture); } } + } } diff --git a/TBF/Resources/Strings.cs.resx b/TBF/Resources/Strings.cs.resx index c7508de22..5069598f2 100644 --- a/TBF/Resources/Strings.cs.resx +++ b/TBF/Resources/Strings.cs.resx @@ -1935,5 +1935,15 @@ Běžící worker vlastní COM port až do ukončení. Další automatické čte RFID / NFC data Příkaz Odeslat příkaz + Změnit označené komponenty ({0}) + Označené komponenty: {0} + Pouze změněné hodnoty se zkopírují do všech označených komponent. Šedá hodnota se mezi komponentami liší a nezmění se, dokud nezadáte novou hodnotu. + (různé hodnoty) + Použít + Změnit označené komponenty... + Zkopírovat tuto hodnotu do následujících komponent + Komponenta '{0}', parametr '{1}': {2} + Hodnota není platná. + Názvy komponent jsou jedinečné a při hromadné úpravě je nelze měnit. diff --git a/TBF/Resources/Strings.resx b/TBF/Resources/Strings.resx index 138a4e5d8..1d983d986 100644 --- a/TBF/Resources/Strings.resx +++ b/TBF/Resources/Strings.resx @@ -2667,5 +2667,15 @@ An outstanding worker keeps ownership of its COM port until it exits. Another au RFID / NFC data Command Send command + Change selected components ({0}) + Selected components: {0} + Only values you change are copied to all selected components. A grey value differs between components and is not changed until you enter a new value. + (multiple values) + Apply + Change selected components... + Copy this value to following components + Component '{0}', parameter '{1}': {2} + The value is not valid. + Component names are unique and cannot be changed in bulk edit. diff --git a/TBF/Resources/Strings.sk.resx b/TBF/Resources/Strings.sk.resx index f2d8e38a8..594eef5a5 100644 --- a/TBF/Resources/Strings.sk.resx +++ b/TBF/Resources/Strings.sk.resx @@ -423,5 +423,15 @@ Bežiaci worker vlastní COM port až do ukončenia. Ďalšie automatické čít RFID / NFC dáta Príkaz Odoslať príkaz + Zmeniť označené komponenty ({0}) + Označené komponenty: {0} + Iba zmenené hodnoty sa skopírujú do všetkých označených komponentov. Sivá hodnota sa medzi komponentmi líši a nezmení sa, kým nezadáte novú hodnotu. + (rôzne hodnoty) + Použiť + Zmeniť označené komponenty... + Skopírovať túto hodnotu do nasledujúcich komponentov + Komponent '{0}', parameter '{1}': {2} + Hodnota nie je platná. + Názvy komponentov sú jedinečné a pri hromadnej úprave sa nedajú meniť. diff --git a/TBF/TBF.csproj b/TBF/TBF.csproj index 0c27164cf..4a9d765dd 100644 --- a/TBF/TBF.csproj +++ b/TBF/TBF.csproj @@ -2982,6 +2982,12 @@ ComponentParametersDlg.cs + + Form + + + BulkComponentParametersDlg.cs + Form diff --git a/TBF/UI/Bench/Components/BulkComponentParametersDlg.Designer.cs b/TBF/UI/Bench/Components/BulkComponentParametersDlg.Designer.cs new file mode 100644 index 000000000..17240ef74 --- /dev/null +++ b/TBF/UI/Bench/Components/BulkComponentParametersDlg.Designer.cs @@ -0,0 +1,166 @@ +namespace TBF.UI.Bench.Components +{ + partial class BulkComponentParametersDlg + { + private System.ComponentModel.IContainer components = null; + private System.Windows.Forms.Label selectionLabel; + private System.Windows.Forms.Label informationLabel; + private System.Windows.Forms.Label modeLabel; + private System.Windows.Forms.ComboBox modeComboBox; + private System.Windows.Forms.Label loggingLabel; + private System.Windows.Forms.ComboBox loggingComboBox; + private System.Windows.Forms.DataGridView parametersGrid; + private System.Windows.Forms.DataGridViewTextBoxColumn parameterColumn; + private System.Windows.Forms.DataGridViewTextBoxColumn valueColumn; + private System.Windows.Forms.Button applyButton; + private System.Windows.Forms.Button cancelButton; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) components.Dispose(); + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.selectionLabel = new System.Windows.Forms.Label(); + this.informationLabel = new System.Windows.Forms.Label(); + this.modeLabel = new System.Windows.Forms.Label(); + this.modeComboBox = new System.Windows.Forms.ComboBox(); + this.loggingLabel = new System.Windows.Forms.Label(); + this.loggingComboBox = new System.Windows.Forms.ComboBox(); + this.parametersGrid = new System.Windows.Forms.DataGridView(); + this.parameterColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.valueColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.applyButton = new System.Windows.Forms.Button(); + this.cancelButton = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.parametersGrid)).BeginInit(); + this.SuspendLayout(); + // + // selectionLabel + // + this.selectionLabel.AutoSize = true; + this.selectionLabel.Location = new System.Drawing.Point(12, 12); + this.selectionLabel.Name = "selectionLabel"; + this.selectionLabel.Size = new System.Drawing.Size(35, 13); + this.selectionLabel.TabIndex = 0; + // + // informationLabel + // + this.informationLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); + this.informationLabel.Location = new System.Drawing.Point(12, 35); + this.informationLabel.Name = "informationLabel"; + this.informationLabel.Size = new System.Drawing.Size(560, 32); + this.informationLabel.TabIndex = 1; + // + // modeLabel + // + this.modeLabel.AutoSize = true; + this.modeLabel.Location = new System.Drawing.Point(12, 78); + this.modeLabel.Name = "modeLabel"; + this.modeLabel.Size = new System.Drawing.Size(35, 13); + this.modeLabel.TabIndex = 2; + // + // modeComboBox + // + this.modeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.modeComboBox.FormattingEnabled = true; + this.modeComboBox.Location = new System.Drawing.Point(90, 75); + this.modeComboBox.Name = "modeComboBox"; + this.modeComboBox.Size = new System.Drawing.Size(190, 21); + this.modeComboBox.TabIndex = 3; + // + // loggingLabel + // + this.loggingLabel.AutoSize = true; + this.loggingLabel.Location = new System.Drawing.Point(300, 78); + this.loggingLabel.Name = "loggingLabel"; + this.loggingLabel.Size = new System.Drawing.Size(45, 13); + this.loggingLabel.TabIndex = 4; + // + // loggingComboBox + // + this.loggingComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.loggingComboBox.FormattingEnabled = true; + this.loggingComboBox.Location = new System.Drawing.Point(365, 75); + this.loggingComboBox.Name = "loggingComboBox"; + this.loggingComboBox.Size = new System.Drawing.Size(190, 21); + this.loggingComboBox.TabIndex = 5; + // + // parametersGrid + // + this.parametersGrid.AllowUserToAddRows = false; + this.parametersGrid.AllowUserToDeleteRows = false; + this.parametersGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); + this.parametersGrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + this.parametersGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.parametersGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.parameterColumn, this.valueColumn }); + this.parametersGrid.Location = new System.Drawing.Point(12, 110); + this.parametersGrid.MultiSelect = false; + this.parametersGrid.Name = "parametersGrid"; + this.parametersGrid.RowHeadersVisible = false; + this.parametersGrid.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect; + this.parametersGrid.Size = new System.Drawing.Size(560, 274); + this.parametersGrid.TabIndex = 6; + this.parametersGrid.CellBeginEdit += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.parametersGrid_CellBeginEdit); + this.parametersGrid.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.parametersGrid_CellValueChanged); + // + // parameterColumn + // + this.parameterColumn.FillWeight = 52F; + this.parameterColumn.HeaderText = "Parameter"; + this.parameterColumn.Name = "parameterColumn"; + this.parameterColumn.ReadOnly = true; + // + // valueColumn + // + this.valueColumn.FillWeight = 48F; + this.valueColumn.HeaderText = "Value"; + this.valueColumn.Name = "valueColumn"; + // + // applyButton + // + this.applyButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.applyButton.Location = new System.Drawing.Point(416, 399); + this.applyButton.Name = "applyButton"; + this.applyButton.Size = new System.Drawing.Size(75, 23); + this.applyButton.TabIndex = 7; + this.applyButton.UseVisualStyleBackColor = true; + this.applyButton.Click += new System.EventHandler(this.applyButton_Click); + // + // cancelButton + // + this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.cancelButton.Location = new System.Drawing.Point(497, 399); + this.cancelButton.Name = "cancelButton"; + this.cancelButton.Size = new System.Drawing.Size(75, 23); + this.cancelButton.TabIndex = 8; + this.cancelButton.UseVisualStyleBackColor = true; + // + // BulkComponentParametersDlg + // + this.AcceptButton = this.applyButton; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.cancelButton; + this.ClientSize = new System.Drawing.Size(584, 434); + this.Controls.Add(this.cancelButton); + this.Controls.Add(this.applyButton); + this.Controls.Add(this.parametersGrid); + this.Controls.Add(this.loggingComboBox); + this.Controls.Add(this.loggingLabel); + this.Controls.Add(this.modeComboBox); + this.Controls.Add(this.modeLabel); + this.Controls.Add(this.informationLabel); + this.Controls.Add(this.selectionLabel); + this.MinimizeBox = false; + this.Name = "BulkComponentParametersDlg"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Change selected components"; + ((System.ComponentModel.ISupportInitialize)(this.parametersGrid)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + } + } +} diff --git a/TBF/UI/Bench/Components/BulkComponentParametersDlg.cs b/TBF/UI/Bench/Components/BulkComponentParametersDlg.cs new file mode 100644 index 000000000..add080b00 --- /dev/null +++ b/TBF/UI/Bench/Components/BulkComponentParametersDlg.cs @@ -0,0 +1,373 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using Common; +using TBF.Resources; +using TBF.Rig.Generic; +using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead; +using TBF.Rig.WaterMeters.WaterMeter; +using SchematicDrawing; + +namespace TBF.UI.Bench.Components +{ + /// + /// Designer-backed editor for a compatible selection of components. It deliberately + /// writes only rows touched by the operator; a mixed value is never copied implicitly. + /// + public partial class BulkComponentParametersDlg : Form + { + private const string MixedMarker = "\u2014"; + private readonly IList configurations; + private readonly IList providers; + private readonly HashSet changedParameters = new HashSet(); + private bool loading; + private bool clearingMixedValue; + private string mixedText; + + public CfgUpdateFlags Flags { get; private set; } + + public static bool CanEdit(IList configs) + { + IList ignored; + return TryGetProviders(configs, out ignored); + } + + public BulkComponentParametersDlg(IList configs) + { + if (configs == null || configs.Count < 2) throw new ArgumentException("At least two component configurations are required.", nameof(configs)); + IList compatibleProviders; + if (!TryGetProviders(configs, out compatibleProviders)) throw new ArgumentException("The selected components do not expose a compatible configuration.", nameof(configs)); + + configurations = configs; + providers = compatibleProviders; + InitializeComponent(); + Localize(); + Populate(); + } + + private void Localize() + { + Text = string.Format(Strings.BulkEditTitle, configurations.Count); + selectionLabel.Text = string.Format(Strings.BulkEditSelected, configurations.Count); + informationLabel.Text = Strings.BulkEditHelp; + modeLabel.Text = Strings.Mode; + loggingLabel.Text = Strings.Logging; + parameterColumn.HeaderText = Strings.Parameter; + valueColumn.HeaderText = Strings.Value; + applyButton.Text = Strings.BulkEditApply; + cancelButton.Text = Strings.CancelBtnText; + mixedText = Strings.BulkEditMixedValue; + } + + private void Populate() + { + loading = true; + try + { + AddDebugValues(modeComboBox, GetCommonDebugLevel()); + AddLogValues(loggingComboBox, GetCommonLogLevel()); + for (int i = 0; i < providers[0].ParamsCount(); i++) + { + string commonValue = string.Empty; + // Match the normal single-component editor: credentials never become + // visible merely because several components were selected. + bool isMixed = IsSensitiveParameter(i) || !TryGetCommonValue(i, out commonValue); + int rowIndex = parametersGrid.Rows.Add(providers[0].ParamName(i), isMixed ? mixedText : commonValue); + var row = parametersGrid.Rows[rowIndex]; + row.Tag = i; + if (isMixed) row.Cells[1].Style.ForeColor = Color.Gray; + } + } + finally { loading = false; } + } + + private void AddDebugValues(ComboBox comboBox, DebugMode? common) + { + comboBox.Items.Add(common.HasValue ? common.Value.ToDescription() : mixedText); + for (DebugMode value = 0; value < DebugMode.Count; value++) comboBox.Items.Add(value.ToDescription()); + comboBox.SelectedIndex = 0; + comboBox.ForeColor = common.HasValue ? SystemColors.ControlText : Color.Gray; + comboBox.SelectedIndexChanged += delegate { if (comboBox.SelectedIndex > 0) comboBox.ForeColor = SystemColors.ControlText; }; + } + + private void AddLogValues(ComboBox comboBox, LogLevel? common) + { + comboBox.Items.Add(common.HasValue ? common.Value.ToDescription() : mixedText); + for (LogLevel value = 0; value < LogLevel.Count; value++) comboBox.Items.Add(value.ToDescription()); + comboBox.SelectedIndex = 0; + comboBox.ForeColor = common.HasValue ? SystemColors.ControlText : Color.Gray; + comboBox.SelectedIndexChanged += delegate { if (comboBox.SelectedIndex > 0) comboBox.ForeColor = SystemColors.ControlText; }; + } + + private DebugMode? GetCommonDebugLevel() + { + DebugMode value = configurations[0].DebugLevel; + for (int i = 1; i < configurations.Count; i++) if (configurations[i].DebugLevel != value) return null; + return value; + } + + private LogLevel? GetCommonLogLevel() + { + LogLevel value = configurations[0].LogLevel; + for (int i = 1; i < configurations.Count; i++) if (configurations[i].LogLevel != value) return null; + return value; + } + + private bool TryGetCommonValue(int index, out string value) + { + value = providers[0].ToString(index); + for (int i = 1; i < providers.Count; i++) + { + if (!string.Equals(value, providers[i].ToString(index), StringComparison.Ordinal)) + { + value = null; + return false; + } + } + return true; + } + + private bool IsSensitiveParameter(int index) + { + string name = providers[0].ParamName(index).ToLowerInvariant(); + return name.Contains("password") || name.Contains("user id"); + } + + private void parametersGrid_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) + { + if (e.ColumnIndex != 1 || e.RowIndex < 0) return; + var cell = parametersGrid.Rows[e.RowIndex].Cells[e.ColumnIndex]; + if (!string.Equals(Convert.ToString(cell.Value), mixedText, StringComparison.Ordinal)) return; + clearingMixedValue = true; + try { cell.Value = string.Empty; cell.Style.ForeColor = SystemColors.ControlText; } + finally { clearingMixedValue = false; } + } + + private void parametersGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e) + { + if (loading || clearingMixedValue || e.ColumnIndex != 1 || e.RowIndex < 0) return; + changedParameters.Add((int)parametersGrid.Rows[e.RowIndex].Tag); + parametersGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = SystemColors.ControlText; + } + + private void applyButton_Click(object sender, EventArgs e) + { + string error; + if (!ValidateChanges(out error)) + { + MessageBox.Show(this, error, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + CfgUpdateFlags flags = CfgUpdateFlags.None; + foreach (int parameterIndex in changedParameters) + { + string value = GetParameterValue(parameterIndex); + foreach (IParamsProvider provider in providers) flags |= provider.UpdateParam(parameterIndex, value); + } + if (modeComboBox.SelectedIndex > 0) + { + DebugMode value = FindDebugMode(modeComboBox.Text); + foreach (IComponentCfg config in configurations) config.DebugLevel = value; + flags |= CfgUpdateFlags.RestartRqrd; + } + if (loggingComboBox.SelectedIndex > 0) + { + LogLevel value = FindLogLevel(loggingComboBox.Text); + foreach (IComponentCfg config in configurations) config.LogLevel = value; + flags |= CfgUpdateFlags.RestartRqrd; + } + + Flags = flags; + DialogResult = DialogResult.OK; + Close(); + } + + private bool ValidateChanges(out string error) + { + foreach (int parameterIndex in changedParameters) + { + string value = GetParameterValue(parameterIndex); + for (int i = 0; i < providers.Count; i++) + { + string message; + if (!providers[i].ValidateParam(parameterIndex, value, out message)) + { + error = string.Format(Strings.BulkEditInvalidValue, configurations[i].Name, providers[i].ParamName(parameterIndex), message); + return false; + } + } + } + error = null; + return true; + } + + private string GetParameterValue(int parameterIndex) + { + foreach (DataGridViewRow row in parametersGrid.Rows) + if ((int)row.Tag == parameterIndex) return Convert.ToString(row.Cells[1].Value); + return string.Empty; + } + + private static DebugMode FindDebugMode(string text) + { + for (DebugMode value = 0; value < DebugMode.Count; value++) if (value.ToDescription() == text) return value; + return DebugMode.Normal; + } + + private static LogLevel FindLogLevel(string text) + { + for (LogLevel value = 0; value < LogLevel.Count; value++) if (value.ToDescription() == text) return value; + return LogLevel.Off; + } + + private static bool TryGetProviders(IList configs, out IList compatibleProviders) + { + compatibleProviders = null; + if (configs == null || configs.Count < 2) return false; + var providers = new List(); + if (configs[0] == null) return false; + string componentType = configs[0].Factory == null ? configs[0].GetType().FullName : configs[0].Factory.ClassName; + foreach (IComponentCfg config in configs) + { + if (config == null) return false; + string type = config.Factory == null ? config.GetType().FullName : config.Factory.ClassName; + if (!string.Equals(componentType, type, StringComparison.Ordinal)) return false; + IParamsProvider provider = config as IParamsProvider; + if (provider == null) + { + var iperl = config as IperlHeadCfg; + if (iperl != null) provider = new IperlHeadBulkParamsProvider(iperl); + } + if (provider == null) + { + var waterMeter = config as WaterMeterCfg; + if (waterMeter != null) provider = new WaterMeterBulkParamsProvider(waterMeter); + } + if (provider == null) return false; + providers.Add(provider); + } + int count = providers[0].ParamsCount(); + for (int i = 1; i < providers.Count; i++) + { + if (providers[i].ParamsCount() != count) return false; + for (int p = 0; p < count; p++) if (providers[i].ParamName(p) != providers[0].ParamName(p)) return false; + } + compatibleProviders = providers; + return true; + } + + /// Adapter gives old iPerl and ASIC configurations the same safe bulk-edit contract as IParamsProvider components. + private sealed class IperlHeadBulkParamsProvider : IParamsProvider + { + private readonly IperlHeadCfg config; + private static readonly string[] names = { "Use TCP/IP", "Optical IP address", "Optical TCP/IP port", "Optical COM port", "RFID / NFC COM port", "Group 1 (mux board)", "Group 2", "Communication interface", "Head communication COM port", "Default calibration factor" }; + public IperlHeadBulkParamsProvider(IperlHeadCfg config) { this.config = config; } + public System.Xml.Serialization.XmlSerializer GetSerializer() { return config.GetSerializer(); } + public string ComponentName { get { return config.Name; } } + public int ParamsCount() { return names.Length; } + public string ParamName(int ix) { return names[ix]; } + public System.Collections.Generic.ICollection ParamValues(int ix) { return ix == 0 ? new[] { bool.FalseString, bool.TrueString } : ix == 7 ? System.Enum.GetNames(typeof(CommunicationInterface)) : null; } + public string ToString(int ix) + { + switch (ix) + { + case 0: return config.UseTcpIP.ToString(); case 1: return config.OptoIPAddress ?? string.Empty; case 2: return config.OptoTcpipPortNr.ToString(); case 3: return config.OptoComPortNr.ToString(); case 4: return config.RfidComPortNr.ToString(); + case 5: return config.MuxBoardNr.ToString(); case 6: return config.Group.ToString(); case 7: return config.CommunicationInterface.ToString(); case 8: return config.HeadCommunicationComPortNr.ToString(); case 9: return config.CalibFactorNominal.ToString(System.Globalization.CultureInfo.InvariantCulture); + default: return string.Empty; + } + } + public void InitializeAll() { } + public bool ValidateParam(int ix, string value, out string message) + { + message = Strings.BulkEditInvalidValueSimple; + int integer; ushort port; double number; bool boolean; + switch (ix) + { + case 0: if (bool.TryParse(value, out boolean)) { message = null; return true; } break; + case 1: if (!string.IsNullOrWhiteSpace(value)) { message = null; return true; } break; + case 2: if (ushort.TryParse(value, out port) && port > 0) { message = null; return true; } break; + case 3: case 4: case 8: if (int.TryParse(value, out integer) && integer >= 0) { message = null; return true; } break; + case 5: if (int.TryParse(value, out integer) && integer >= 1 && integer <= 4) { message = null; return true; } break; + case 6: if (int.TryParse(value, out integer) && integer >= 1 && integer <= 10) { message = null; return true; } break; + case 7: CommunicationInterface iface; if (Enum.TryParse(value, out iface) && Enum.IsDefined(typeof(CommunicationInterface), iface)) { message = null; return true; } break; + case 9: if (double.TryParse(value, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out number) && number > 0) { message = null; return true; } break; + } + return false; + } + public CfgUpdateFlags UpdateParam(int ix, string value) + { + switch (ix) + { + case 0: config.UseTcpIP = bool.Parse(value); break; case 1: config.OptoIPAddress = value; break; case 2: config.OptoTcpipPortNr = ushort.Parse(value); break; case 3: config.OptoComPortNr = int.Parse(value); break; case 4: config.RfidComPortNr = int.Parse(value); break; + case 5: config.MuxBoardNr = int.Parse(value); break; case 6: config.Group = int.Parse(value); break; case 7: config.CommunicationInterface = (CommunicationInterface)Enum.Parse(typeof(CommunicationInterface), value); break; case 8: config.HeadCommunicationComPortNr = int.Parse(value); break; case 9: config.CalibFactorNominal = double.Parse(value, System.Globalization.CultureInfo.InvariantCulture); break; + } + return CfgUpdateFlags.RestartRqrd; + } + public bool UpdateEmbeddedDbEntity() { return true; } + public IParamsProvider Clone() { return new IperlHeadBulkParamsProvider(config); } + } + + /// + /// Water meters do not expose IParamsProvider because their normal dialog only + /// edits the name. Position coordinates are intentionally not exposed here: + /// applying an X/Y value to a selection would collapse the bench drawing. + /// + private sealed class WaterMeterBulkParamsProvider : IParamsProvider + { + private readonly WaterMeterCfg config; + private static readonly string[] names = { "Drawing shape", "Drawing size", "Drawing orientation", "Flip drawing", "Label orientation" }; + public WaterMeterBulkParamsProvider(WaterMeterCfg config) { this.config = config; } + public System.Xml.Serialization.XmlSerializer GetSerializer() { return config.GetSerializer(); } + public string ComponentName { get { return config.Name; } } + public int ParamsCount() { return names.Length; } + public string ParamName(int ix) { return names[ix]; } + public System.Collections.Generic.ICollection ParamValues(int ix) + { + switch (ix) + { + case 0: return Enum.GetNames(typeof(Shape)); + case 1: return Enum.GetNames(typeof(Sz)); + case 2: case 4: return Enum.GetNames(typeof(Orient)); + case 3: return new[] { bool.FalseString, bool.TrueString }; + default: return null; + } + } + public string ToString(int ix) + { + switch (ix) + { + case 0: return config.Shape.ToString(); case 1: return config.Sz.ToString(); case 2: return config.Orient.ToString(); case 3: return config.Flip.ToString(); case 4: return config.LblOrient.ToString(); + default: return string.Empty; + } + } + public void InitializeAll() { } + public bool ValidateParam(int ix, string value, out string message) + { + message = Strings.BulkEditInvalidValueSimple; + bool flip; Shape shape; Sz size; Orient orientation; + bool valid = (ix == 0 && Enum.TryParse(value, out shape) && Enum.IsDefined(typeof(Shape), shape)) || + (ix == 1 && Enum.TryParse(value, out size) && Enum.IsDefined(typeof(Sz), size)) || + ((ix == 2 || ix == 4) && Enum.TryParse(value, out orientation) && Enum.IsDefined(typeof(Orient), orientation)) || + (ix == 3 && bool.TryParse(value, out flip)); + if (valid) message = null; + return valid; + } + public CfgUpdateFlags UpdateParam(int ix, string value) + { + switch (ix) + { + case 0: config.Shape = (Shape)Enum.Parse(typeof(Shape), value); break; + case 1: config.Sz = (Sz)Enum.Parse(typeof(Sz), value); break; + case 2: config.Orient = (Orient)Enum.Parse(typeof(Orient), value); break; + case 3: config.Flip = bool.Parse(value); break; + case 4: config.LblOrient = (Orient)Enum.Parse(typeof(Orient), value); break; + } + return CfgUpdateFlags.RestartRqrd; + } + public bool UpdateEmbeddedDbEntity() { return true; } + public IParamsProvider Clone() { return new WaterMeterBulkParamsProvider(config); } + } + } +} diff --git a/TBF/UI/Bench/Components/ComponentsManagerDlg.Designer.cs b/TBF/UI/Bench/Components/ComponentsManagerDlg.Designer.cs index 3d5cbb283..c6891275c 100644 --- a/TBF/UI/Bench/Components/ComponentsManagerDlg.Designer.cs +++ b/TBF/UI/Bench/Components/ComponentsManagerDlg.Designer.cs @@ -77,7 +77,7 @@ namespace TBF.UI.Bench.Components this.listViewEx.GridLines = true; this.listViewEx.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listViewEx.HideSelection = false; - this.listViewEx.MultiSelect = false; + this.listViewEx.MultiSelect = true; this.listViewEx.Name = "listViewEx"; this.listViewEx.UseCompatibleStateImageBehavior = false; this.listViewEx.View = System.Windows.Forms.View.Details; @@ -133,4 +133,4 @@ namespace TBF.UI.Bench.Components private System.Windows.Forms.SplitContainer splitContainer1; private Shared.SharedSearchForListView sharedSearchForListView1; } -} \ No newline at end of file +} diff --git a/TBF/UI/Bench/Components/ComponentsManagerDlg.cs b/TBF/UI/Bench/Components/ComponentsManagerDlg.cs index 92ec4c894..abec518ad 100644 --- a/TBF/UI/Bench/Components/ComponentsManagerDlg.cs +++ b/TBF/UI/Bench/Components/ComponentsManagerDlg.cs @@ -58,12 +58,24 @@ namespace TBF.UI.Bench.Components bool unlocked; + readonly ContextMenuStrip selectionContextMenu = new ContextMenuStrip(); + readonly ToolStripMenuItem bulkEditMenuItem = new ToolStripMenuItem(); + readonly ToolStripMenuItem copyColumnMenuItem = new ToolStripMenuItem(); + SubItemEventArgs lastRightClickedSubItem; + public ComponentsManagerDlg() { toBeDeletedEntities = new List(); InitializeComponent(); + selectionContextMenu.Items.Add(bulkEditMenuItem); + selectionContextMenu.Items.Add(new ToolStripSeparator()); + selectionContextMenu.Items.Add(copyColumnMenuItem); + bulkEditMenuItem.Click += bulkEditMenuItem_Click; + copyColumnMenuItem.Click += copyColumnMenuItem_Click; + listViewEx.MouseDown += listViewEx_MouseDown; + flags = CfgUpdateFlags.None; selectComponentTypeDlg = new SelectComponentClassDlg(); @@ -148,12 +160,60 @@ namespace TBF.UI.Bench.Components private void listViewEx_SubItemRightClicked(object sender, SubItemEventArgs e) { - if (!unlocked || ((e.SubItem != (int)Column.DebugMode) && (e.SubItem != (int)Column.Logging))) return; + lastRightClickedSubItem = e; + ShowSelectionContextMenu(); + } + private void listViewEx_MouseDown(object sender, MouseEventArgs e) + { + if (e.Button != MouseButtons.Right) return; + ListViewHitTestInfo hit = listViewEx.HitTest(e.Location); + if (hit.Item == null || hit.Item.Selected) return; + var oldSelection = new List(); + foreach (ListViewItem selected in listViewEx.SelectedItems) oldSelection.Add(selected); + foreach (ListViewItem selected in oldSelection) selected.Selected = false; + hit.Item.Selected = true; + hit.Item.Focused = true; + } + + private IList SelectedComponents() + { + var selected = new List(); + foreach (ListViewItem item in listViewEx.SelectedItems) + { + Component component = item.Tag as Component; + if (component != null) selected.Add(component); + } + return selected; + } + + private void ShowSelectionContextMenu() + { + IList selected = SelectedComponents(); + var configs = new List(); + foreach (Component component in selected) + { + IComponentCfg config = TbfComponents.CmpntCfgFromCmpntEntity(component); + if (config == null) { configs.Clear(); break; } + configs.Add(config); + } + + bulkEditMenuItem.Text = Strings.BulkEditSelectedMenu; + bulkEditMenuItem.Enabled = unlocked && BulkComponentParametersDlg.CanEdit(configs); + copyColumnMenuItem.Text = Strings.BulkEditCopyBelow; + copyColumnMenuItem.Enabled = unlocked && selected.Count == 1 && lastRightClickedSubItem != null && + (lastRightClickedSubItem.SubItem == (int)Column.DebugMode || lastRightClickedSubItem.SubItem == (int)Column.Logging); + selectionContextMenu.Show(Cursor.Position); + } + + private void copyColumnMenuItem_Click(object sender, EventArgs e) + { + SubItemEventArgs e0 = lastRightClickedSubItem; + if (e0 == null || !unlocked) return; if (DialogResult.Yes == MessageBox.Show(Strings.Do_you_want_to_copy_this_value_to_all_cells_below_this_cell, Strings.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { - int columnNr = e.SubItem; + int columnNr = e0.SubItem; string value = null; /// foreach (ListViewItem item in listViewEx.Items) @@ -162,7 +222,7 @@ namespace TBF.UI.Bench.Components { /// Modify values in subsequent items (when value != null) Component cmpnt = (Component)item.Tag; - if (e.SubItem == (int)Column.DebugMode) + if (e0.SubItem == (int)Column.DebugMode) { for (DebugMode mode = 0; mode < DebugMode.Count; mode++) { @@ -175,7 +235,7 @@ namespace TBF.UI.Bench.Components } } } - else if (e.SubItem == (int)Column.Logging) + else if (e0.SubItem == (int)Column.Logging) { for (LogLevel level = 0; level < LogLevel.Count; level++) { @@ -189,7 +249,7 @@ namespace TBF.UI.Bench.Components } } } - else if (item == e.Item) + else if (item == e0.Item) { /// Pick value to be copied from this item value = item.SubItems[columnNr].Text; @@ -198,6 +258,157 @@ namespace TBF.UI.Bench.Components } } + private void bulkEditMenuItem_Click(object sender, EventArgs e) + { + IList components = SelectedComponents(); + var configs = new List(); + foreach (Component component in components) + { + IComponentCfg config = TbfComponents.CmpntCfgFromCmpntEntity(component); + if (config == null) return; + configs.Add(config); + } + if (!BulkComponentParametersDlg.CanEdit(configs)) return; + + var iperlHeads = new List(); + foreach (IComponentCfg config in configs) + { + var head = config as Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg; + if (head == null) { iperlHeads.Clear(); break; } + iperlHeads.Add(head); + } + if (iperlHeads.Count == configs.Count) + { + EditIperlHeadsUsingOriginalDialog(components, configs, iperlHeads); + return; + } + + using (var dialog = new BulkComponentParametersDlg(configs)) + { + if (dialog.ShowDialog(this) != DialogResult.OK) return; + PersistBulkConfigs(components, configs); + flags |= dialog.Flags; + if (dialog.Flags != CfgUpdateFlags.None) sharedButtons.UnlockButtons(); + RedrawAll(); + } + } + + /// + /// Uses the normal, designer-backed iPerl/ASIC editor for a bulk selection. + /// Values differing from the first selected reader are shown grey. The event + /// tracker is important: it lets an operator deliberately apply a value which + /// happens to equal the first reader's value to every selected reader. + /// + private void EditIperlHeadsUsingOriginalDialog(IList components, IList configs, + IList heads) + { + var model = heads[0]; + var changed = new HashSet(); + IComponentCfgCtrl control = model.GetControl(cmpntEntities); + control.Config = model; + + using (var dialog = new ComponentParametersDlg(this, components[0].Id)) + { + var nameToolTip = new ToolTip(); + dialog.CmpntEntities = cmpntEntities; + dialog.ComponentCfgCtrl = control; + dialog.UnlockAfterStart = true; + dialog.Shown += delegate + { + LockBulkComponentName(control as Control, nameToolTip); + MarkIperlMixedControls(control as Control, heads, changed); + }; + dialog.FormClosed += delegate { nameToolTip.Dispose(); }; + if (dialog.ShowDialog(this) != DialogResult.OK) return; + + ApplyChangedIperlValues(model, heads, changed); + PersistBulkConfigs(components, configs); + flags |= dialog.Flags; + if (dialog.Flags != CfgUpdateFlags.None) sharedButtons.UnlockButtons(); + RedrawAll(); + } + } + + private static void PersistBulkConfigs(IList components, IList configs) + { + for (int i = 0; i < configs.Count; i++) + { + Component modified = configs[i].CreateDbEntity(); + Component original = components[i]; + original.DebugMode = modified.DebugMode; + original.LogLevel = modified.LogLevel; + original.Parameters = modified.Parameters; + } + } + + private static void MarkIperlMixedControls(Control root, + IList heads, ISet changed) + { + if (root == null) return; + MarkMixed(root, "radioButton1", !AllSame(heads, h => h.UseTcpIP), "UseTcpIP", changed); + MarkMixed(root, "radioButton2", !AllSame(heads, h => h.UseTcpIP), "UseTcpIP", changed); + MarkMixed(root, "ipAddressTextBox", !AllSame(heads, h => h.OptoIPAddress), "OptoIPAddress", changed); + MarkMixed(root, "tcpipPortTextBox", !AllSame(heads, h => h.OptoTcpipPortNr), "OptoTcpipPortNr", changed); + MarkMixed(root, "optoSerialPortTextBox", !AllSame(heads, h => h.OptoComPortNr), "OptoComPortNr", changed); + MarkMixed(root, "rfidPortNrTextBox", !AllSame(heads, h => h.RfidComPortNr), "RfidComPortNr", changed); + MarkMixed(root, "muxBoardNrTextBox", !AllSame(heads, h => h.MuxBoardNr), "MuxBoardNr", changed); + MarkMixed(root, "groupTextBox", !AllSame(heads, h => h.Group), "Group", changed); + MarkMixed(root, "comboBoxCommunicationInterface", !AllSame(heads, h => h.CommunicationInterface), "CommunicationInterface", changed); + MarkMixed(root, "headPortNrTextBox", !AllSame(heads, h => h.HeadCommunicationComPortNr), "HeadCommunicationComPortNr", changed); + MarkMixed(root, "calibFactorNominalTextBox", !AllSame(heads, h => h.CalibFactorNominal), "CalibFactorNominal", changed); + } + + private static void LockBulkComponentName(Control root, ToolTip toolTip) + { + if (root == null) return; + Control[] controls = root.Controls.Find("nameTextBox", true); + if (controls.Length != 1) return; + controls[0].Enabled = false; + controls[0].TabStop = false; + toolTip.SetToolTip(controls[0], Strings.BulkEditUniqueName); + } + + private static bool AllSame(IList heads, Func value) + { + T first = value(heads[0]); + for (int i = 1; i < heads.Count; i++) if (!EqualityComparer.Default.Equals(first, value(heads[i]))) return false; + return true; + } + + private static void MarkMixed(Control root, string controlName, bool mixed, string field, ISet changed) + { + Control[] controls = root.Controls.Find(controlName, true); + if (controls.Length != 1) return; + Control control = controls[0]; + control.ForeColor = mixed ? System.Drawing.Color.Gray : System.Drawing.SystemColors.ControlText; + EventHandler changedHandler = delegate { control.ForeColor = System.Drawing.SystemColors.ControlText; changed.Add(field); }; + var textBox = control as TextBox; + if (textBox != null) textBox.TextChanged += changedHandler; + var comboBox = control as ComboBox; + if (comboBox != null) comboBox.SelectedIndexChanged += changedHandler; + var radioButton = control as RadioButton; + if (radioButton != null) radioButton.CheckedChanged += changedHandler; + } + + private static void ApplyChangedIperlValues(Rig.TestMethods.iPerlCommunication.iPerlHead.IperlHeadCfg model, + IList heads, ISet changed) + { + foreach (var head in heads) + { + if (changed.Contains("UseTcpIP")) head.UseTcpIP = model.UseTcpIP; + if (changed.Contains("OptoIPAddress")) head.OptoIPAddress = model.OptoIPAddress; + if (changed.Contains("OptoTcpipPortNr")) head.OptoTcpipPortNr = model.OptoTcpipPortNr; + if (changed.Contains("OptoComPortNr")) head.OptoComPortNr = model.OptoComPortNr; + if (changed.Contains("RfidComPortNr")) head.RfidComPortNr = model.RfidComPortNr; + if (changed.Contains("MuxBoardNr")) head.MuxBoardNr = model.MuxBoardNr; + if (changed.Contains("Group")) head.Group = model.Group; + if (changed.Contains("CommunicationInterface")) head.CommunicationInterface = model.CommunicationInterface; + if (changed.Contains("HeadCommunicationComPortNr")) head.HeadCommunicationComPortNr = model.HeadCommunicationComPortNr; + if (changed.Contains("CalibFactorNominal")) head.CalibFactorNominal = model.CalibFactorNominal; + } + } + + void listViewEx_SubItemEndEditing(object sender, SubItemEndEditingEventArgs e) { Component cmpnt = (Component)e.Item.Tag; diff --git a/TBFTests/TBFTests.csproj b/TBFTests/TBFTests.csproj index b441d14d2..fc9abb2e3 100644 --- a/TBFTests/TBFTests.csproj +++ b/TBFTests/TBFTests.csproj @@ -120,6 +120,7 @@ + diff --git a/TBFTests/UI/Bench/Components/BulkComponentParametersDlgTests.cs b/TBFTests/UI/Bench/Components/BulkComponentParametersDlgTests.cs new file mode 100644 index 000000000..8c514bed8 --- /dev/null +++ b/TBFTests/UI/Bench/Components/BulkComponentParametersDlgTests.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading; +using System.Windows.Forms; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TBF.Rig.Generic; +using TBF.Rig.RegisterReaders.AsicReader; +using TBF.Rig.WaterMeters.WaterMeter; +using TBF.UI.Bench.Components; + +namespace TBFTests.UI.Bench.Components +{ + [TestClass] + public class BulkComponentParametersDlgTests + { + private static void Sta(Action action) + { + Exception error = null; + var thread = new Thread(() => { try { action(); } catch (Exception ex) { error = ex; } }); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + if (error != null) throw new AssertFailedException(error.ToString()); + } + + [TestMethod] + public void AsicBulkEditor_MixedCalibrationIsNotCopiedUntilOperatorChangesIt() + { + Sta(() => + { + var first = new AsicReaderCfg(null) { CalibFactorNominal = 4096D }; + var second = new AsicReaderCfg(null) { CalibFactorNominal = 5000D }; + var configs = new List { first, second }; + Assert.IsTrue(BulkComponentParametersDlg.CanEdit(configs)); + + using (var dialog = new BulkComponentParametersDlg(configs)) + { + var grid = (DataGridView)typeof(BulkComponentParametersDlg) + .GetField("parametersGrid", BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(dialog); + DataGridViewRow calibration = null; + foreach (DataGridViewRow row in grid.Rows) + if (Convert.ToString(row.Cells[0].Value) == "Default calibration factor") { calibration = row; break; } + Assert.IsNotNull(calibration); + Assert.AreNotEqual("4096", Convert.ToString(calibration.Cells[1].Value)); + + calibration.Cells[1].Value = "6000"; + var apply = (Button)typeof(BulkComponentParametersDlg) + .GetField("applyButton", BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(dialog); + apply.PerformClick(); + } + + Assert.AreEqual(6000D, first.CalibFactorNominal); + Assert.AreEqual(6000D, second.CalibFactorNominal); + }); + } + + [TestMethod] + public void BulkEditor_AcceptingWithoutTouchedFieldsKeepsMixedValues() + { + Sta(() => + { + var first = new AsicReaderCfg(null) { CalibFactorNominal = 4096D }; + var second = new AsicReaderCfg(null) { CalibFactorNominal = 5000D }; + using (var dialog = new BulkComponentParametersDlg(new List { first, second })) + { + var apply = (Button)typeof(BulkComponentParametersDlg) + .GetField("applyButton", BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(dialog); + apply.PerformClick(); + } + Assert.AreEqual(4096D, first.CalibFactorNominal); + Assert.AreEqual(5000D, second.CalibFactorNominal); + }); + } + + [TestMethod] + public void WaterMeterSelection_IsEligibleForSafeBulkEditing() + { + var first = new WaterMeterCfg(null); + var second = new WaterMeterCfg(null); + Assert.IsTrue(BulkComponentParametersDlg.CanEdit(new List { first, second })); + } + } +}