EAR: Actions now support multiple iterations.
2 using System.Collections.Generic;
3 using System.ComponentModel;
5 using System.Diagnostics;
9 using System.Threading.Tasks;
10 using System.Windows.Forms;
11 using SharpLib.Display;
13 using System.Reflection;
14 using Microsoft.VisualBasic.CompilerServices;
16 using CodeProject.Dialog;
19 namespace SharpDisplayManager
22 /// Object edit dialog form.
24 public partial class FormEditObject<T> : Form where T: SharpLib.Ear.Object
26 public T Object = null;
28 public FormEditObject()
30 InitializeComponent();
36 /// <param name="sender"></param>
37 /// <param name="e"></param>
38 private void FormEditAction_Load(object sender, EventArgs e)
40 // Populate registered object types
41 IEnumerable < Type > types = Reflection.GetConcreteClassesDerivedFrom<T>();
42 foreach (Type type in types)
44 ItemObjectType item = new ItemObjectType(type);
45 iComboBoxObjectType.Items.Add(item);
50 // Creating new issue, select our first item
51 iComboBoxObjectType.SelectedIndex = 0;
55 // Editing existing object
56 // Look up our item in our object type combobox
57 foreach (ItemObjectType item in iComboBoxObjectType.Items)
59 if (item.Type == Object.GetType())
61 iComboBoxObjectType.SelectedItem = item;
71 /// <param name="sender"></param>
72 /// <param name="e"></param>
73 private void buttonOk_Click(object sender, EventArgs e)
75 FetchPropertiesValue(Object);
76 if (!Object.IsValid())
78 // Tell closing event to cancel
79 DialogResult = DialogResult.None;
87 /// <param name="sender"></param>
88 /// <param name="e"></param>
89 private void FormEditObject_FormClosing(object sender, FormClosingEventArgs e)
91 //Check if we need to cancel the closing of our form.
92 e.Cancel = DialogResult == DialogResult.None;
97 Object.CurrentState = SharpLib.Ear.Object.State.Rest;
98 Object.PropertyChanged -= PropertyChangedEventHandlerThreadSafe;
105 /// <param name="sender"></param>
106 /// <param name="e"></param>
107 private void comboBoxActionType_SelectedIndexChanged(object sender, EventArgs e)
109 //Instantiate an action corresponding to our type
110 Type objectType = ((ItemObjectType) iComboBoxObjectType.SelectedItem).Type;
111 //Create another type of action only if needed
112 if (Object == null || Object.GetType() != objectType)
116 // Make sure we exit edit mode and unhook from events
117 Object.CurrentState = SharpLib.Ear.Object.State.Rest;
118 Object.PropertyChanged -= PropertyChangedEventHandlerThreadSafe;
121 Object = (T)Activator.CreateInstance(objectType);
124 //Create input fields
130 /// Get properties values from our generated input fields
132 private void FetchPropertiesValue(T aObject)
135 //For each of our properties
136 foreach (PropertyInfo pi in aObject.GetType().GetProperties())
138 //Get our property attribute
139 AttributeObjectProperty[] attributes = ((AttributeObjectProperty[]) pi.GetCustomAttributes(typeof(AttributeObjectProperty), true));
140 if (attributes.Length != 1)
142 //No attribute, skip this property then.
145 AttributeObjectProperty attribute = attributes[0];
147 //Check that we support this type of property
148 if (!IsPropertyTypeSupported(pi))
153 //Now fetch our property value
154 GetPropertyValueFromControl(iTableLayoutPanel.Controls[ctrlIndex+1], pi, aObject); //+1 otherwise we get the label
156 ctrlIndex+=2; //Jump over the label too
161 /// Extend this function to support reading new types of properties.
163 /// <param name="aObject"></param>
164 private void GetPropertyValueFromControl(Control aControl, PropertyInfo aInfo, T aObject)
166 if (aInfo.PropertyType == typeof(int))
168 NumericUpDown ctrl=(NumericUpDown)aControl;
169 aInfo.SetValue(aObject,(int)ctrl.Value);
171 else if (aInfo.PropertyType.IsEnum)
173 // Instantiate our enum
174 object enumValue= Activator.CreateInstance(aInfo.PropertyType);
175 // Parse our enum from combo box
176 enumValue = Enum.Parse(aInfo.PropertyType,((ComboBox)aControl).SelectedItem.ToString());
177 //enumValue = ((ComboBox)aControl).SelectedValue;
179 aInfo.SetValue(aObject, enumValue);
181 else if (aInfo.PropertyType == typeof(bool))
183 CheckBox ctrl = (CheckBox)aControl;
184 aInfo.SetValue(aObject, ctrl.Checked);
186 else if (aInfo.PropertyType == typeof(string))
188 TextBox ctrl = (TextBox)aControl;
189 aInfo.SetValue(aObject, ctrl.Text);
191 else if (aInfo.PropertyType == typeof(PropertyFile))
193 Button ctrl = (Button)aControl;
194 PropertyFile value = new PropertyFile {FullPath=ctrl.Text};
195 aInfo.SetValue(aObject, value);
197 else if (aInfo.PropertyType == typeof(PropertyComboBox))
199 ComboBox ctrl = (ComboBox)aControl;
200 string currentItem = ctrl.SelectedItem.ToString();
201 PropertyComboBox value = (PropertyComboBox)aInfo.GetValue(aObject);
202 value.CurrentItem = currentItem;
203 //Not strictly needed but makes sure the set method is called
204 aInfo.SetValue(aObject, value);
206 else if (aInfo.PropertyType == typeof(PropertyButton))
208 Button ctrl = (Button)aControl;
209 PropertyButton value = new PropertyButton { Text = ctrl.Text };
210 aInfo.SetValue(aObject, value);
213 //TODO: add support for other types here
218 /// Create a control for the given property.
220 /// <param name="aInfo"></param>
221 /// <param name="aAttribute"></param>
222 /// <param name="aObject"></param>
223 /// <returns></returns>
224 private Control CreateControlForProperty(PropertyInfo aInfo, AttributeObjectProperty aAttribute, T aObject)
226 if (aInfo.PropertyType == typeof(int))
228 //Integer properties are using numeric editor
229 NumericUpDown ctrl = new NumericUpDown();
230 ctrl.AutoSize = true;
231 ctrl.Minimum = Int32.Parse(aAttribute.Minimum);
232 ctrl.Maximum = Int32.Parse(aAttribute.Maximum);
233 ctrl.Increment = Int32.Parse(aAttribute.Increment);
234 ctrl.Value = (int)aInfo.GetValue(aObject);
235 // Hook-in change notification after setting the value
236 ctrl.ValueChanged += ControlValueChanged;
239 else if (aInfo.PropertyType.IsEnum)
241 //Enum properties are using combo box
242 ComboBox ctrl = new ComboBox();
243 ctrl.AutoSize = true;
245 ctrl.DropDownStyle = ComboBoxStyle.DropDownList;
246 //Data source is fine but it gives us duplicate entries for duplicated enum values
247 //ctrl.DataSource = Enum.GetValues(aInfo.PropertyType);
249 //Therefore we need to explicitly create our items
250 Size cbSize = new Size(0, 0);
251 foreach (string name in aInfo.PropertyType.GetEnumNames())
253 ctrl.Items.Add(name.ToString());
254 Graphics g = this.CreateGraphics();
255 //Since combobox autosize would not work we need to get measure text ourselves
256 SizeF size = g.MeasureString(name.ToString(), ctrl.Font);
257 cbSize.Width = Math.Max(cbSize.Width, (int)size.Width);
258 cbSize.Height = Math.Max(cbSize.Height, (int)size.Height);
261 //Make sure our combobox is large enough
262 ctrl.MinimumSize = cbSize;
264 // Instantiate our enum
265 object enumValue = Activator.CreateInstance(aInfo.PropertyType);
266 enumValue = aInfo.GetValue(aObject);
267 //Set the current item
268 ctrl.SelectedItem = enumValue.ToString();
269 // Hook-in change notification after setting the value
270 ctrl.SelectedIndexChanged += ControlValueChanged;
274 else if (aInfo.PropertyType == typeof(bool))
276 CheckBox ctrl = new CheckBox();
277 ctrl.AutoSize = true;
278 ctrl.Text = aAttribute.Description;
279 ctrl.Checked = (bool)aInfo.GetValue(aObject);
280 // Hook-in change notification after setting the value
281 ctrl.CheckedChanged += ControlValueChanged;
284 else if (aInfo.PropertyType == typeof(string))
286 TextBox ctrl = new TextBox();
287 ctrl.AutoSize = true;
288 ctrl.Text = (string)aInfo.GetValue(aObject);
289 // Hook-in change notification after setting the value
290 ctrl.TextChanged += ControlValueChanged;
293 else if (aInfo.PropertyType == typeof(PropertyFile))
295 // We have a file property
296 // Create a button that will trigger the open file dialog to select our file.
297 Button ctrl = new Button();
298 ctrl.AutoSize = true;
299 ctrl.Text = ((PropertyFile)aInfo.GetValue(aObject)).FullPath;
300 // Add lambda expression to Click event
301 ctrl.Click += (sender, e) =>
303 // Create open file dialog
304 OpenFileDialog ofd = new OpenFileDialog();
305 ofd.RestoreDirectory = true;
306 // Use file filter specified by our property
307 ofd.Filter = aAttribute.Filter;
309 if (DlgBox.ShowDialog(ofd) == DialogResult.OK)
311 // Fetch selected file name
312 ctrl.Text = ofd.FileName;
316 // Hook-in change notification after setting the value
317 ctrl.TextChanged += ControlValueChanged;
320 else if (aInfo.PropertyType == typeof(PropertyComboBox))
323 ComboBox ctrl = new ComboBox();
324 ctrl.AutoSize = true;
326 ctrl.DropDownStyle = ComboBoxStyle.DropDownList;
327 //Data source is such a pain to set the current item
328 //ctrl.DataSource = ((PropertyComboBox)aInfo.GetValue(aObject)).Items;
330 PropertyComboBox pcb = ((PropertyComboBox)aInfo.GetValue(aObject));
331 foreach (string item in pcb.Items)
333 ctrl.Items.Add(item);
336 ctrl.SelectedItem = ((PropertyComboBox)aInfo.GetValue(aObject)).CurrentItem;
340 else if (aInfo.PropertyType == typeof(PropertyButton))
342 // We have a button property
343 // Create a button that will trigger the custom action.
344 Button ctrl = new Button();
345 ctrl.AutoSize = true;
346 ctrl.Text = ((PropertyButton)aInfo.GetValue(aObject)).Text;
347 // Hook in click event
348 ctrl.Click += ((PropertyButton)aInfo.GetValue(aObject)).ClickEventHandler;
349 // Hook-in change notification after setting the value
350 ctrl.TextChanged += ControlValueChanged;
354 //TODO: add support for other control type here
359 /// Don't forget to extend that one and adding types
361 /// <returns></returns>
362 private bool IsPropertyTypeSupported(PropertyInfo aInfo)
364 if (aInfo.PropertyType == typeof(int))
368 else if (aInfo.PropertyType.IsEnum)
372 else if (aInfo.PropertyType == typeof(bool))
376 else if (aInfo.PropertyType == typeof(string))
380 else if (aInfo.PropertyType == typeof(PropertyFile))
384 else if (aInfo.PropertyType == typeof(PropertyComboBox))
388 else if (aInfo.PropertyType == typeof(PropertyButton))
393 //TODO: add support for other type here
399 /// Update our table layout.
400 /// Will instantiated every field control as defined by our object.
402 /// <param name="aLayout"></param>
403 private void UpdateControls()
407 //Debug.Print("UpdateTableLayoutPanel")
408 //First clean our current panel
409 iTableLayoutPanel.Controls.Clear();
410 iTableLayoutPanel.RowStyles.Clear();
411 iTableLayoutPanel.ColumnStyles.Clear();
412 iTableLayoutPanel.RowCount = 0;
414 //We always want two columns: one for label and one for the field
415 iTableLayoutPanel.ColumnCount = 2;
416 iTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
417 iTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
426 UpdateStaticControls();
428 //IEnumerable<PropertyInfo> properties = aObject.GetType().GetProperties().Where(
429 // prop => Attribute.IsDefined(prop, typeof(AttributeObjectProperty)));
431 //TODO: Do this whenever a field changes
432 iLabelBrief.Text = Object.Brief();
435 foreach (PropertyInfo pi in Object.GetType().GetProperties())
437 AttributeObjectProperty[] attributes = ((AttributeObjectProperty[])pi.GetCustomAttributes(typeof(AttributeObjectProperty), true));
438 if (attributes.Length != 1)
443 AttributeObjectProperty attribute = attributes[0];
445 //Before anything we need to check if that kind of property is supported by our UI
447 Control ctrl = CreateControlForProperty(pi, attribute, Object);
450 //Property type not supported
455 iTableLayoutPanel.RowCount++;
456 iTableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
458 Label label = new Label();
459 label.AutoSize = true;
460 label.Dock = DockStyle.Fill;
461 label.TextAlign = ContentAlignment.MiddleCenter;
462 label.Text = attribute.Name;
463 toolTip.SetToolTip(label, attribute.Description);
464 iTableLayoutPanel.Controls.Add(label, 0, iTableLayoutPanel.RowCount-1);
466 //Add our editor to our form
467 iTableLayoutPanel.Controls.Add(ctrl, 1, iTableLayoutPanel.RowCount - 1);
468 //Add tooltip to editor too
469 toolTip.SetToolTip(ctrl, attribute.Description);
473 //Entrer object edit mode
474 Object.CurrentState = SharpLib.Ear.Object.State.Edit;
475 Object.PropertyChanged += PropertyChangedEventHandlerThreadSafe;
481 /// <param name="sender"></param>
482 /// <param name="e"></param>
483 void PropertyChangedEventHandlerThreadSafe(object sender, PropertyChangedEventArgs e)
485 if (this.InvokeRequired)
487 //Not in the proper thread, invoke ourselves
488 PropertyChangedEventHandler d = new PropertyChangedEventHandler(PropertyChangedEventHandlerThreadSafe);
489 this.Invoke(d, new object[] { sender, e });
493 // We could test the name of the property that has changed as follow
494 // It's currently not needed though
495 //if (e.PropertyName == "Brief")
497 // Our object has changed behind our back.
498 // That's currently only the case for HID events that are listening for inputs.
499 if (Object is EventHid)
501 //HID can't do full control updates for some reason
502 //We are getting spammed with HID events after a few clicks
503 //We need to investigate, HID bug?
504 UpdateStaticControls();
513 private void buttonTest_Click(object sender, EventArgs e)
515 FetchPropertiesValue(Object);
517 //If our object has a test method with no parameters just run it then
518 MethodInfo info = Object.GetType().GetMethod("Test");
519 if ( info != null && info.GetParameters().Length==0)
521 info.Invoke(Object,null);
530 /// <param name="sender"></param>
531 /// <param name="e"></param>
532 private void ControlValueChanged(object sender, EventArgs e)
540 private void UpdateObject()
542 // Update our object with the content of our controls
543 FetchPropertiesValue(Object);
545 UpdateStaticControls();
553 private void UpdateStaticControls()
555 // Update OK and test button status
556 iButtonOk.Enabled = Object.IsValid();
557 iButtonTest.Enabled = iButtonOk.Enabled;
559 // Update brief title
560 iLabelBrief.Text = Object.Brief();
562 // Update object description
563 iLabelDescription.Text = Object.AttributeDescription;
569 /// <param name="sender"></param>
570 /// <param name="e"></param>
571 private void iComboBoxObjectType_KeyPress(object sender, KeyPressEventArgs e)
573 //Special case for HID events
574 if (Object is EventHid)
576 //Disable handling of key input as we are using key input for changing our event
581 private void iComboBoxObjectType_Enter(object sender, EventArgs e)
583 //Only edit HID event when our type combo box has the focus
584 // TODO: That's an ugly workaround, fix that somehow. Maybe by only doing HID scan when a button property has the focus
585 if (Object is EventHid)
587 Object.CurrentState = SharpLib.Ear.Object.State.Edit;
591 private void iComboBoxObjectType_Leave(object sender, EventArgs e)
593 //Only edit HID event when our type combo box has the focus
594 // TODO: That's an ugly workaround, fix that somehow. Maybe by only doing HID scan when a button property has the focus
595 if (Object is EventHid)
597 Object.CurrentState = SharpLib.Ear.Object.State.Rest;