Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3.0/sources/HeuristicLab.Core/Scope.cs @ 4949

Last change on this file since 4949 was 262, checked in by swagner, 17 years ago

Merged fix of ticket #151 (r260:261) from trunk into 3.0 release branch

File size: 11.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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 System.Collections.Generic;
24using System.Text;
25using System.Xml;
26
27namespace HeuristicLab.Core {
28  public class Scope : ItemBase, IScope {
29    private IScope parent;
30
31    private string myName;
32    public string Name {
33      get { return myName; }
34    }
35
36    private IDictionary<string, IVariable> myVariables;
37    public ICollection<IVariable> Variables {
38      get { return myVariables.Values; }
39    }
40    private IDictionary<string, string> myAliases;
41    public IEnumerable<KeyValuePair<string, string>> Aliases {
42      get { return myAliases; }
43    }
44    private List<IScope> mySubScopes;
45    public IList<IScope> SubScopes {
46      get { return mySubScopes.AsReadOnly(); }
47    }
48
49    public Scope() {
50      myName = "Anonymous";
51      myVariables = new Dictionary<string, IVariable>();
52      myAliases = new Dictionary<string, string>();
53      mySubScopes = new List<IScope>();
54    }
55    public Scope(string name)
56      : this() {
57      if (name != null) myName = name;
58    }
59
60    public void SetParent(IScope scope) {
61      parent = scope;
62    }
63
64    public override IView CreateView() {
65      return new ScopeView(this);
66    }
67
68    public IVariable GetVariable(string name) {
69      IVariable variable;
70      if (myVariables.TryGetValue(name, out variable))
71        return variable;
72      else
73        return null;
74    }
75    public void AddVariable(IVariable variable) {
76      myVariables.Add(variable.Name, variable);
77      variable.NameChanging += new EventHandler<NameChangingEventArgs>(Variable_NameChanging);
78      variable.NameChanged += new EventHandler(Variable_NameChanged);
79      OnVariableAdded(variable);
80    }
81
82    public void RemoveVariable(string name) {
83      IVariable variable;
84      if (myVariables.TryGetValue(name, out variable)) {
85        variable.NameChanging -= new EventHandler<NameChangingEventArgs>(Variable_NameChanging);
86        variable.NameChanged -= new EventHandler(Variable_NameChanged);
87        myVariables.Remove(name);
88        OnVariableRemoved(variable);
89      }
90    }
91    private void Variable_NameChanging(object sender, NameChangingEventArgs e) {
92      e.Cancel = myVariables.ContainsKey(e.Name);
93    }
94    private void Variable_NameChanged(object sender, EventArgs e) {
95      IVariable variable = (IVariable)sender;
96      string oldName = null;
97      foreach (KeyValuePair<string, IVariable> element in myVariables) {
98        if (element.Value == variable)
99          oldName = element.Key;
100      }
101      myVariables.Remove(oldName);
102      myVariables.Add(variable.Name, variable);
103    }
104    public T GetVariableValue<T>(string name, bool recursiveLookup) where T : class, IItem {
105      return GetVariableValue<T>(name, recursiveLookup, true);
106    }
107    public T GetVariableValue<T>(string name, bool recursiveLookup, bool throwOnError) where T : class, IItem {
108      return (T)GetVariableValue(name, recursiveLookup, throwOnError);
109    }
110    public IItem GetVariableValue(string name, bool recursiveLookup) {
111      return GetVariableValue(name, recursiveLookup, true);
112    }
113    public IItem GetVariableValue(string name, bool recursiveLookup, bool throwOnError) {
114      IVariable variable;
115      name = TranslateName(name);
116      if (myVariables.TryGetValue(name, out variable)) {
117        return variable.Value;
118      } else {
119        if (recursiveLookup && (parent != null))
120          return parent.GetVariableValue(name, recursiveLookup, throwOnError);
121        else {
122          if (throwOnError)
123            throw new ArgumentException("Variable " + name + " not found");
124          else
125            return null;
126        }
127      }
128    }
129
130    public string TranslateName(string name) {
131      while (myAliases.ContainsKey(name))
132        name = myAliases[name];
133      if (parent != null)
134        name = parent.TranslateName(name);
135      return name;
136    }
137    public void AddAlias(string alias, string name) {
138      RemoveAlias(alias);
139      if (alias != name) {
140        myAliases.Add(alias, name);
141        OnAliasAdded(alias);
142      }
143    }
144    public void RemoveAlias(string alias) {
145      if (myAliases.ContainsKey(alias)) {
146        myAliases.Remove(alias);
147        OnAliasRemoved(alias);
148      }
149    }
150
151    public void AddSubScope(IScope scope) {
152      scope.SetParent(this);
153      mySubScopes.Add(scope);
154      OnSubScopeAdded(scope, mySubScopes.Count - 1);
155    }
156    public void RemoveSubScope(IScope scope) {
157      int index = mySubScopes.IndexOf(scope);
158      if (mySubScopes.Remove(scope)) {
159        scope.SetParent(null);
160        OnSubScopeRemoved(scope, index);
161      }
162    }
163    public void ReorderSubScopes(int[] sequence) {
164      IScope[] scopes = mySubScopes.ToArray();
165      mySubScopes.Clear();
166      for (int i = 0; i < scopes.Length; i++)
167        mySubScopes.Add(scopes[sequence[i]]);
168      OnSubScopesReordered();
169    }
170    public IScope GetScope(Guid guid) {
171      if (Guid == guid) return this;
172      else {
173        for (int i = 0; i < mySubScopes.Count; i++) {
174          IScope s = mySubScopes[i].GetScope(guid);
175          if (s != null) return s;
176        }
177      }
178      return null;
179    }
180    public IScope GetScope(string name) {
181      if (Name == name) return this;
182      else {
183        for (int i = 0; i < mySubScopes.Count; i++) {
184          IScope s = mySubScopes[i].GetScope(name);
185          if (s != null) return s;
186        }
187      }
188      return null;
189    }
190
191    public void Clear() {
192      string[] variableNames = new string[Variables.Count];
193      int i = 0;
194      foreach (IVariable variable in Variables) {
195        variableNames[i] = variable.Name;
196        i++;
197      }
198      for (int j = 0; j < variableNames.Length; j++)
199        RemoveVariable(variableNames[j]);
200
201      KeyValuePair<string, string>[] aliases = new KeyValuePair<string,string>[myAliases.Count];
202      myAliases.CopyTo(aliases, 0);
203      for (int j = 0; j < aliases.Length; j++)
204        RemoveAlias(aliases[j].Key);
205
206      while (SubScopes.Count > 0)
207        RemoveSubScope(SubScopes[0]);
208    }
209
210    public override object Clone(IDictionary<Guid, object> clonedObjects) {
211      Scope clone = (Scope)base.Clone(clonedObjects);
212      clone.myName = Name;
213
214      foreach (IVariable variable in myVariables.Values)
215        clone.AddVariable((IVariable)Auxiliary.Clone(variable, clonedObjects));
216      foreach (KeyValuePair<string, string> alias in myAliases)
217        clone.AddAlias(alias.Key, alias.Value);
218      for (int i = 0; i < SubScopes.Count; i++)
219        clone.AddSubScope((IScope)Auxiliary.Clone(SubScopes[i], clonedObjects));
220
221      return clone;
222    }
223
224    public event EventHandler<VariableEventArgs> VariableAdded;
225    protected virtual void OnVariableAdded(IVariable variable) {
226      if (VariableAdded != null)
227        VariableAdded(this, new VariableEventArgs(variable));
228    }
229    public event EventHandler<VariableEventArgs> VariableRemoved;
230    protected virtual void OnVariableRemoved(IVariable variable) {
231      if (VariableRemoved != null)
232        VariableRemoved(this, new VariableEventArgs(variable));
233    }
234    public event EventHandler<AliasEventArgs> AliasAdded;
235    protected virtual void OnAliasAdded(string alias) {
236      if (AliasAdded != null)
237        AliasAdded(this, new AliasEventArgs(alias));
238    }
239    public event EventHandler<AliasEventArgs> AliasRemoved;
240    protected virtual void OnAliasRemoved(string alias) {
241      if (AliasRemoved != null)
242        AliasRemoved(this, new AliasEventArgs(alias));
243    }
244    public event EventHandler<ScopeIndexEventArgs> SubScopeAdded;
245    protected virtual void OnSubScopeAdded(IScope scope, int index) {
246      if (SubScopeAdded != null)
247        SubScopeAdded(this, new ScopeIndexEventArgs(scope, index));
248    }
249    public event EventHandler<ScopeIndexEventArgs> SubScopeRemoved;
250    protected virtual void OnSubScopeRemoved(IScope scope, int index) {
251      if (SubScopeRemoved != null)
252        SubScopeRemoved(this, new ScopeIndexEventArgs(scope, index));
253    }
254    public event EventHandler SubScopesReordered;
255    protected virtual void OnSubScopesReordered() {
256      if (SubScopesReordered != null)
257        SubScopesReordered(this, new EventArgs());
258    }
259
260    #region Persistence Methods
261    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid,IStorable> persistedObjects) {
262      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
263      XmlAttribute nameAttribute = document.CreateAttribute("Name");
264      nameAttribute.Value = Name.ToString();
265      node.Attributes.Append(nameAttribute);
266
267      XmlNode variables = document.CreateNode(XmlNodeType.Element, "Variables", null);
268      foreach (IVariable variable in Variables)
269        variables.AppendChild(PersistenceManager.Persist(variable, document, persistedObjects));
270      node.AppendChild(variables);
271
272      XmlNode aliases = document.CreateNode(XmlNodeType.Element, "Aliases", null);
273      foreach (KeyValuePair<string, string> alias in myAliases) {
274        XmlNode aliasNode = document.CreateNode(XmlNodeType.Element, "Alias", null);
275        XmlAttribute keyAttribute = document.CreateAttribute("Alias");
276        keyAttribute.Value = alias.Key;
277        aliasNode.Attributes.Append(keyAttribute);
278        XmlAttribute valueAttribute = document.CreateAttribute("Name");
279        valueAttribute.Value = alias.Value;
280        aliasNode.Attributes.Append(valueAttribute);
281        aliases.AppendChild(aliasNode);
282      }
283      node.AppendChild(aliases);
284
285      XmlNode subScopes = document.CreateNode(XmlNodeType.Element, "SubScopes", null);
286      for (int i = 0; i < SubScopes.Count; i++)
287        subScopes.AppendChild(PersistenceManager.Persist(SubScopes[i], document, persistedObjects));
288      node.AppendChild(subScopes);
289
290      return node;
291    }
292    public override void Populate(XmlNode node, IDictionary<Guid,IStorable> restoredObjects) {
293      base.Populate(node, restoredObjects);
294      myName = node.Attributes["Name"].Value;
295
296      XmlNode variables = node.SelectSingleNode("Variables");
297      foreach (XmlNode variableNode in variables.ChildNodes) {
298        IVariable variable = (IVariable)PersistenceManager.Restore(variableNode, restoredObjects);
299        AddVariable(variable);
300      }
301
302      XmlNode aliases = node.SelectSingleNode("Aliases");
303      if (aliases != null) {
304        foreach (XmlNode aliasNode in aliases.ChildNodes)
305          AddAlias(aliasNode.Attributes["Alias"].Value, aliasNode.Attributes["Name"].Value);
306      }
307
308      XmlNode subScopes = node.SelectSingleNode("SubScopes");
309      for (int i = 0; i < subScopes.ChildNodes.Count; i++) {
310        IScope scope = (IScope)PersistenceManager.Restore(subScopes.ChildNodes[i], restoredObjects);
311        AddSubScope(scope);
312      }
313    }
314    #endregion
315  }
316}
Note: See TracBrowser for help on using the repository browser.