Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Parameters/3.3/OptionalConstrainedValueParameter.cs @ 3339

Last change on this file since 3339 was 3317, checked in by swagner, 15 years ago

Implemented ReadOnlyView property for items (#969).

File size: 6.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using HeuristicLab.Collections;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27
28namespace HeuristicLab.Parameters {
29  /// <summary>
30  /// A parameter whose value has to be chosen from a set of valid values or is null.
31  /// </summary>
32  [Item("OptionalConstrainedValueParameter<T>", "A parameter whose value has to be chosen from a set of valid values or is null.")]
33  [StorableClass]
34  public class OptionalConstrainedValueParameter<T> : Parameter, IValueParameter<T> where T : class, IItem {
35    [Storable]
36    private ItemSet<T> validValues;
37    public ItemSet<T> ValidValues {
38      get { return validValues; }
39    }
40
41    [Storable]
42    private T value;
43    public virtual T Value {
44      get { return this.value; }
45      set {
46        if (value != this.value) {
47          if ((value != null) && !validValues.Contains(value)) throw new ArgumentException("Invalid value.");
48          if (this.value != null) this.value.ToStringChanged -= new EventHandler(Value_ToStringChanged);
49          this.value = value;
50          if (this.value != null) this.value.ToStringChanged += new EventHandler(Value_ToStringChanged);
51          OnValueChanged();
52        }
53      }
54    }
55
56    IItem IValueParameter.Value {
57      get { return Value; }
58      set {
59        T val = value as T;
60        if ((value != null) && (val == null))
61          throw new InvalidOperationException(
62            string.Format("Type mismatch. Value is not a \"{0}\".",
63                          typeof(T).GetPrettyName())
64          );
65        Value = val;
66      }
67    }
68
69    public OptionalConstrainedValueParameter()
70      : base("Anonymous", typeof(T)) {
71      this.validValues = new ItemSet<T>();
72      Initialize();
73    }
74    public OptionalConstrainedValueParameter(string name)
75      : base(name, typeof(T)) {
76      this.validValues = new ItemSet<T>();
77      Initialize();
78    }
79    public OptionalConstrainedValueParameter(string name, ItemSet<T> validValues)
80      : base(name, typeof(T)) {
81      this.validValues = validValues;
82      Initialize();
83    }
84    public OptionalConstrainedValueParameter(string name, ItemSet<T> validValues, T value)
85      : base(name, typeof(T)) {
86      this.validValues = validValues;
87      this.value = value;
88      Initialize();
89    }
90    public OptionalConstrainedValueParameter(string name, string description)
91      : base(name, description, typeof(T)) {
92      this.validValues = new ItemSet<T>();
93      Initialize();
94    }
95    public OptionalConstrainedValueParameter(string name, string description, ItemSet<T> validValues)
96      : base(name, description, typeof(T)) {
97      this.validValues = validValues;
98      Initialize();
99    }
100    public OptionalConstrainedValueParameter(string name, string description, ItemSet<T> validValues, T value)
101      : base(name, description, typeof(T)) {
102      this.validValues = validValues;
103      this.value = value;
104      Initialize();
105    }
106    [StorableConstructor]
107    protected OptionalConstrainedValueParameter(bool deserializing) : base(deserializing) { }
108
109    [StorableHook(HookType.AfterDeserialization)]
110    private void Initialize() {
111      RegisterValidValuesEvents();
112      if (value != null) value.ToStringChanged += new EventHandler(Value_ToStringChanged);
113    }
114
115    public override IDeepCloneable Clone(Cloner cloner) {
116      OptionalConstrainedValueParameter<T> clone = (OptionalConstrainedValueParameter<T>)base.Clone(cloner);
117      clone.validValues = (ItemSet<T>)cloner.Clone(validValues);
118      clone.value = (T)cloner.Clone(value);
119      clone.Initialize();
120      return clone;
121    }
122
123    public override string ToString() {
124      return string.Format("{0}: {1} ({2})", Name, Value != null ? Value.ToString() : "null", DataType.GetPrettyName());
125    }
126
127    protected override IItem GetActualValue() {
128      return Value;
129    }
130    protected override void SetActualValue(IItem value) {
131      ((IValueParameter)this).Value = value;
132    }
133
134    public event EventHandler ValueChanged;
135    protected virtual void OnValueChanged() {
136      if (ValueChanged != null)
137        ValueChanged(this, EventArgs.Empty);
138      OnToStringChanged();
139    }
140
141    private void RegisterValidValuesEvents() {
142      if (validValues != null) {
143        validValues.ItemsAdded += new CollectionItemsChangedEventHandler<T>(validValues_ItemsAdded);
144        validValues.ItemsRemoved += new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsRemoved);
145        validValues.CollectionReset += new CollectionItemsChangedEventHandler<T>(ValidValues_CollectionReset);
146      }
147    }
148
149    private void DeregisterValidValuesEvents() {
150      if (validValues != null) {
151        validValues.ItemsAdded -= new CollectionItemsChangedEventHandler<T>(validValues_ItemsAdded);
152        validValues.ItemsRemoved -= new CollectionItemsChangedEventHandler<T>(ValidValues_ItemsRemoved);
153        validValues.CollectionReset -= new CollectionItemsChangedEventHandler<T>(ValidValues_CollectionReset);
154      }
155    }
156
157    protected virtual void validValues_ItemsAdded(object sender, CollectionItemsChangedEventArgs<T> e) { }
158    protected virtual void ValidValues_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<T> e) {
159      if ((Value != null) && !validValues.Contains(Value)) Value = null;
160    }
161    protected virtual void ValidValues_CollectionReset(object sender, CollectionItemsChangedEventArgs<T> e) {
162      if ((Value != null) && !validValues.Contains(Value)) Value = null;
163    }
164    protected virtual void Value_ToStringChanged(object sender, EventArgs e) {
165      OnToStringChanged();
166    }
167  }
168}
Note: See TracBrowser for help on using the repository browser.