source: trunk/Documentation/PluginHowTo/appendix.tex @ 2320

Last change on this file since 2320 was 2320, checked in by Matthäus Wander, 10 years ago

HowTo:

  • removed DisplayLevel, refs #122
File size: 14.0 KB
Line 
1\chapter{CaesarSettings.cs}
2\label{app:CaesarSettings}
3
4\begin{center}
5                \includegraphics[width=5cm]{figures/task_pane.jpg}
6\end{center}
7
8\begin{lstlisting}
9using System;
10using System.ComponentModel;
11using System.Windows;
12using System.Windows.Controls;
13
14using Cryptool.PluginBase;
15
16namespace Cryptool.Caesar
17{
18    public class CaesarSettings : ISettings
19    {
20        #region Public Caesar specific interface
21
22        /// <summary>
23        /// This delegate is ued to send log messages from
24        /// the settings class to the Caesar plugin.
25        /// </summary>
26        public delegate void CaesarLogMessage(string msg, NotificationLevel loglevel);
27
28        /// <summary>
29        /// An enumeration for the different modes of handling
30        /// unknown characters.
31        /// </summary>
32        public enum UnknownSymbolHandlingMode { Ignore = 0, Remove = 1, Replace = 2 };
33
34        /// <summary>
35        /// Fires when a new status message was sent.
36        /// </summary>
37        public event CaesarLogMessage LogMessage;
38
39        public delegate void CaesarReExecute();
40
41        public event CaesarReExecute ReExecute;
42
43        /// <summary>
44        /// Retrieves or sets the current shift value (i.e. the key).
45        /// </summary>
46        [PropertySaveOrder(0)]
47        public int ShiftKey
48        {
49            get { return shiftValue; }
50            set
51            {
52                setKeyByValue(value);
53            }
54        }
55
56        /// <summary>
57        /// Retrieves the current setting of whether or not the
58        /// alphabet should be treated as case-sensitive.
59        /// </summary>
60        [PropertySaveOrder(1)]
61        public bool CaseSensitiveAlphabet
62        {
63            get
64            {
65                if (caseSensitiveAlphabet == 0)
66                {   return false;   }
67                else
68                {   return true;    }
69            }
70            set {} // this setting is readonly, but we must include
71                   // some form of set method to prevent problems.
72        }
73
74        /// <summary>
75        /// Returns true if any settings have been changed.
76        /// This value should be set externally to false, i.e.
77        /// when a project is saved.
78        /// </summary>
79        [PropertySaveOrder(3)]
80        public bool HasChanges
81        {
82            get { return hasChanges; }
83            set { hasChanges = value; }
84        }
85
86        #endregion
87
88        #region Private variables
89        private bool hasChanges;
90        private int selectedAction = 0;
91        private string upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
92        private string lowerAlphabet = "abcdefghijklmnopqrstuvwxyz";
93        private string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
94        private char shiftChar = 'C';
95        private int shiftValue = 2;
96        private UnknownSymbolHandlingMode unknownSymbolHandling = UnknownSymbolHandlingMode.Ignore;
97        private int caseSensitiveAlphabet = 0; // 0 = case-insensitve, 1 = case-sensitive
98        private bool sensitivityEnabled = true;
99        #endregion
100
101        #region Private methods
102
103        private string removeEqualChars(string value)
104        {
105            int length = value.Length;
106
107            for (int i = 0; i < length; i++)
108            {
109                for (int j = i + 1; j < length; j++)
110                {
111                    if ((value[i] == value[j]) || (!CaseSensitiveAlphabet & (char.ToUpper(value[i]) == char.ToUpper(value[j]))))
112                    {
113                        LogMessage("Removing duplicate letter: \'" + value[j] + "\' from alphabet!", NotificationLevel.Warning);
114                        value = value.Remove(j,1);
115                        j--;
116                        length--;
117                    }
118                }
119            }
120
121            return value;
122        }
123
124        /// <summary>
125        /// Set the new shiftValue and the new shiftCharacter
126        /// to offset % alphabet.Length.
127        /// </summary>
128        private void setKeyByValue(int offset)
129        {
130            HasChanges = true;
131
132            // Make sure the shift value lies within the alphabet range.
133            offset = offset % alphabet.Length;
134
135            // Set the new shiftChar.
136            shiftChar = alphabet[offset];
137
138            // Set the new shiftValue.
139            shiftValue = offset;
140
141            // Announce this to the settings pane.
142            OnPropertyChanged("ShiftValue");
143            OnPropertyChanged("ShiftChar");
144
145            // Print some info in the log.
146            LogMessage("Accepted new shift value " + offset + "! (Adjusted shift character to \'" + shiftChar + "\')", NotificationLevel.Info);
147        }
148
149        private void setKeyByCharacter(string value)
150        {
151            try
152            {
153                int offset;
154                if (this.CaseSensitiveAlphabet)
155                {
156                    offset = alphabet.IndexOf(value[0]);
157                }
158                else
159                {
160                    offset = alphabet.ToUpper().IndexOf(char.ToUpper(value[0]));
161                }
162
163                if (offset >= 0)
164                {
165                    HasChanges = true;
166                    shiftValue = offset;
167                    shiftChar = alphabet[shiftValue];
168                    LogMessage("Accepted new shift character \'" + shiftChar + "\'! (Adjusted shift value to " + shiftValue + ")", NotificationLevel.Info);
169                    OnPropertyChanged("ShiftValue");
170                    OnPropertyChanged("ShiftChar");
171                }
172                else
173                {
174                    LogMessage("Bad input \"" + value + "\"! (Character not in alphabet!) Reverting to " + shiftChar.ToString() + "!", NotificationLevel.Error);
175                }
176            }
177            catch (Exception e)
178            {
179                LogMessage("Bad input \"" + value + "\"! (" + e.Message + ") Reverting to " + shiftChar.ToString() + "!", NotificationLevel.Error);
180            }
181        }
182
183        #endregion
184
185        #region Algorithm settings properties (visible in the Settings pane)
186
187        [PropertySaveOrder(4)]
188        [ContextMenu("Action", "Select the algorithm action", 1, ContextMenuControlType.ComboBox, new int[] { 1, 2 }, "Encrypt", "Decrypt")]
189        [TaskPane("Action", "setAlgorithmActionDescription", null, 1, true, ControlType.ComboBox, new string[] { "Encrypt", "Decrypt" })]
190        public int Action
191        {
192            get
193            {
194                return this.selectedAction;
195            }
196            set
197            {
198                if(value != selectedAction)
199                {
200                        HasChanges = true;
201                        this.selectedAction = value;
202                    OnPropertyChanged("Action");
203                }
204                if(ReExecute != null)
205                {       ReExecute();    }
206            }
207        }
208
209        [PropertySaveOrder(5)]
210        [TaskPane("Key as integer", "Enter the number of letters to shift. For example, a value of 1 means that the plaintext character 'a' gets mapped to the ciphertext character 'B', 'b' to 'C', and so on.", null, 2, true, ControlType.NumericUpDown, ValidationType.RangeInteger, 0, 100)]
211        public int ShiftValue
212        {
213            get { return shiftValue; }
214            set
215            {
216                setKeyByValue(value);
217                if (ReExecute != null)
218                {       ReExecute();    }
219            }
220        }
221
222        [PropertySaveOrder(6)]
223        [TaskPaneAttribute("Key as single letter", "Enter a single letter as the key. This letter is mapped to an integer stating the position in the alphabet. The values for 'Key as integer' and 'Key as single letter' are always synchronized.", null, 3, true, ControlType.TextBox, ValidationType.RegEx, "^([A-Z]|[a-z]){1,1}")]
224        public string ShiftChar
225        {
226            get { return this.shiftChar.ToString(); }
227            set
228            {
229                setKeyByCharacter(value);
230                if (ReExecute != null)
231                        {   ReExecute();    }
232            }
233        }
234
235        [PropertySaveOrder(7)]
236        [ContextMenu("Unknown symbol handling", "What should be done with characters encountered in the input which are not in the alphabet?", 4, ContextMenuControlType.ComboBox, null, new string[] { "Ignore (leave unmodified)", "Remove", "Replace with \'?\'" })]
237        [TaskPane("Unknown symbol handling", "What should be done with characters encountered in the input which are not in the alphabet?", null, 4, true, ControlType.ComboBox, new string[] { "Ignore (leave unmodified)", "Remove", "Replace with \'?\'" })]
238        public int UnknownSymbolHandling
239        {
240            get { return (int)this.unknownSymbolHandling; }
241            set
242            {
243                if((UnknownSymbolHandlingMode)value != unknownSymbolHandling)
244                {
245                        HasChanges = true;
246                        this.unknownSymbolHandling = (UnknownSymbolHandlingMode)value;
247                    OnPropertyChanged("UnknownSymbolHandling");
248                                }
249                if (ReExecute != null)
250                {       ReExecute();    }
251            }
252        }
253
254        [SettingsFormat(0, "Normal", "Normal", "Black", "White", Orientation.Vertical)]
255        [PropertySaveOrder(9)]
256        [TaskPane("Alphabet", "This is the alphabet currently in use.", null, 6, true, ControlType.TextBox, "")]
257        public string AlphabetSymbols
258        {
259          get { return this.alphabet; }
260          set
261          {
262            string a = removeEqualChars(value);
263            if (a.Length == 0) // cannot accept empty alphabets
264            {
265              LogMessage("Ignoring empty alphabet from user! Using previous alphabet instead: \" + alphabet + "\" (" + alphabet.Length.ToString() + " Symbols)", NotificationLevel.Info);
266            }
267            else if (!alphabet.Equals(a))
268            {
269              HasChanges = true;
270              this.alphabet = a;
271              setKeyByValue(shiftValue); // reevaluate if the shiftvalue is still within the range
272              LogMessage("Accepted new alphabet from user: \"" + alphabet + "\" (" + alphabet.Length.ToString() + " Symbols)", NotificationLevel.Info);
273              OnPropertyChanged("AlphabetSymbols");
274
275              if (ReExecute != null)
276              { ReExecute();    }
277            }
278          }
279        }
280
281        /// <summary>
282        /// Visible setting how to deal with alphabet case.
283        /// 0 = case-insentive, 1 = case-sensitive
284        /// </summary>
285        [PropertySaveOrder(8)]
286        [ContextMenu("Alphabet case sensitivity", "Should upper and lower case be treated as the same (so that 'a' = 'A')?", 7, ContextMenuControlType.ComboBox, null, new string[] { "Case insensitive", "Case sensitive" })]
287        [TaskPane("Alphabet case sensitivity", "Should upper and lower case be treated as the same (so that 'a' = 'A')?", null, 7, true, ControlType.ComboBox, new string[] { "Case insensitive", "Case sensitive" })]
288        public int AlphabetCase
289        {
290            get { return this.caseSensitiveAlphabet; }
291            set
292            {
293                if (value != caseSensitiveAlphabet)
294                {       HasChanges = true;      }
295                this.caseSensitiveAlphabet = value;
296                if (value == 0)
297                {
298                    if (alphabet == (upperAlphabet + lowerAlphabet))
299                    {
300                        alphabet = upperAlphabet;
301                        LogMessage("Changing alphabet to: \"" + alphabet + "\" (" + alphabet.Length.ToString() + " Symbols)", NotificationLevel.Info);
302                        OnPropertyChanged("AlphabetSymbols");
303                        // reset the key (shiftvalue/shiftChar)
304                        // to be in the range of the new alphabet.
305                        setKeyByValue(shiftValue);
306                    }
307                }
308                else
309                {
310                    if (alphabet == upperAlphabet)
311                    {
312                        alphabet = upperAlphabet + lowerAlphabet;
313                        LogMessage("Changing alphabet to: \"" + alphabet + "\" (" + alphabet.Length.ToString() + " Symbols)", NotificationLevel.Info);
314                        OnPropertyChanged("AlphabetSymbols");
315                    }
316                }
317
318                // Remove equal characters from the current alphabet.
319                string a = alphabet;
320                alphabet = removeEqualChars(alphabet);
321                if (a != alphabet)
322                {
323                    OnPropertyChanged("AlphabetSymbols");
324                    LogMessage("Changing alphabet to: \"" + alphabet + "\" (" + alphabet.Length.ToString() + " Symbols)", NotificationLevel.Info);
325                }
326                OnPropertyChanged("AlphabetCase");
327                if (ReExecute != null)
328                {       ReExecute();    }
329            }
330        }
331
332        #endregion
333
334        #region INotifyPropertyChanged Members
335
336        public event PropertyChangedEventHandler PropertyChanged;
337
338        protected void OnPropertyChanged(string name)
339        {
340          if (PropertyChanged != null)
341          {
342            PropertyChanged(this, new PropertyChangedEventArgs(name));
343          }
344        }
345
346        #endregion
347
348        #region TaskPaneAttributeChanged (Sample)
349        /// <summary>
350        /// This event is here merely as a sample.
351        /// </summary>
352        public event TaskPaneAttributeChangedHandler TaskPaneAttributeChanged;
353
354        [TaskPane("Enable/Disable sensitivity", "This setting is just a sample and shows how to enable / disable a setting.", "AttributeChangedSample", 8, false, ControlType.Button)]
355        public void EnableDisableSesitivity()
356        {
357          if (TaskPaneAttributeChanged!= null)
358          {
359            sensitivityEnabled = !sensitivityEnabled;
360            if (sensitivityEnabled)
361            {
362              TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(new TaskPaneAttribteContainer("AlphabetCase", Visibility.Visible)));
363            }
364            else
365            {
366              TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(new TaskPaneAttribteContainer("AlphabetCase", Visibility.Collapsed)));
367            }
368          }
369        }
370        #endregion TaskPaneAttributeChanged (Sample)
371    }
372}
373\end{lstlisting}
Note: See TracBrowser for help on using the repository browser.