using System.Linq; using HeuristicLab.Collections; using HeuristicLab.Core; using HeuristicLab.Core.Views; using HeuristicLab.MainForm; namespace HeuristicLab.Problems.ProgramSynthesis { [View("ERC Options")] [Content(typeof(ErcOptions), true)] public partial class ErcOptionsView : NamedItemView { private const string PERCENTAGE_FORMAT = "0%"; private CheckedItemCollection ercItems; public ErcOptionsView() { InitializeComponent(); possibilityTextBox.Validating += PossibilityTextBoxValidating; possibilityTextBox.KeyDown += PossibilityTextBoxKeyDown; } private void PossibilityTextBoxKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == System.Windows.Forms.Keys.Enter) { Validate(); } } private void PossibilityTextBoxValidating(object sender, System.ComponentModel.CancelEventArgs e) { var text = possibilityTextBox.Text.Trim(); if (text.EndsWith("%")) { text = text.Substring(0, text.Length - 1); } double value; if (double.TryParse(text, out value)) { if (value > 1) value /= 100.0; possibilityTextBox.Text = value.ToString(PERCENTAGE_FORMAT); } else { possibilityTextBox.Text = "0%"; e.Cancel = true; } Content.ErcProbability = value; } public new ErcOptions Content { get { return (ErcOptions)base.Content; } set { ClearOldContent(); base.Content = value; } } protected override void OnReadOnlyChanged() { base.OnReadOnlyChanged(); possibilityTextBox.ReadOnly = ReadOnly; } protected override void OnContentChanged() { if (Content == null) return; nameTextBox.Text = Content.Name; possibilityTextBox.Text = Content.ErcProbability.ToString(PERCENTAGE_FORMAT); var ercOptions = typeof(ErcOptions) .GetProperties() .Where(p => typeof(IErcItem).IsAssignableFrom(p.PropertyType)) .Select(p => (IErcItem)p.GetValue(Content)) .ToArray(); ercItems = new CheckedItemCollection(ercOptions); ercItems.ForEach(item => { item.EnabledChanged += OptionEnabledChanged; ercItems.SetItemCheckedState(item, item.IsEnabled); }); ercItems.CheckedItemsChanged += ErcItemsCheckedItemsChanged; ErcOptionListView.Content = new ReadOnlyCheckedItemCollection(ercItems); } private void ClearOldContent() { if (ercItems != null) { ercItems.ForEach(item => item.EnabledChanged -= OptionEnabledChanged); ercItems.CheckedItemsChanged -= ErcItemsCheckedItemsChanged; ercItems = null; } } private void ErcItemsCheckedItemsChanged(object sender, Collections.CollectionItemsChangedEventArgs e) { foreach (var item in e.Items) item.IsEnabled = ercItems.ItemChecked(item); } private void OptionEnabledChanged(object sender, bool state) { var item = (IErcItem)sender; // avoid unnecessary state change events if (ercItems.ItemChecked(item) != state) ercItems.SetItemCheckedState(item, state); } } }