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 actionType = ((ItemObjectType) iComboBoxObjectType.SelectedItem).Type;
111 //Create another type of action only if needed
112 if (Object == null || Object.GetType() != actionType)
114 Object = (T)Activator.CreateInstance(actionType);
117 //Create input fields
123 /// Get properties values from our generated input fields
125 private void FetchPropertiesValue(T aObject)
128 //For each of our properties
129 foreach (PropertyInfo pi in aObject.GetType().GetProperties())
131 //Get our property attribute
132 AttributeObjectProperty[] attributes = ((AttributeObjectProperty[]) pi.GetCustomAttributes(typeof(AttributeObjectProperty), true));
133 if (attributes.Length != 1)
135 //No attribute, skip this property then.
138 AttributeObjectProperty attribute = attributes[0];
140 //Check that we support this type of property
141 if (!IsPropertyTypeSupported(pi))
146 //Now fetch our property value
147 GetPropertyValueFromControl(iTableLayoutPanel.Controls[ctrlIndex+1], pi, aObject); //+1 otherwise we get the label
149 ctrlIndex+=2; //Jump over the label too
154 /// Extend this function to support reading new types of properties.
156 /// <param name="aObject"></param>
157 private void GetPropertyValueFromControl(Control aControl, PropertyInfo aInfo, T aObject)
159 if (aInfo.PropertyType == typeof(int))
161 NumericUpDown ctrl=(NumericUpDown)aControl;
162 aInfo.SetValue(aObject,(int)ctrl.Value);
164 else if (aInfo.PropertyType.IsEnum)
166 // Instantiate our enum
167 object enumValue= Activator.CreateInstance(aInfo.PropertyType);
168 // Parse our enum from combo box
169 enumValue = Enum.Parse(aInfo.PropertyType,((ComboBox)aControl).SelectedItem.ToString());
170 //enumValue = ((ComboBox)aControl).SelectedValue;
172 aInfo.SetValue(aObject, enumValue);
174 else if (aInfo.PropertyType == typeof(bool))
176 CheckBox ctrl = (CheckBox)aControl;
177 aInfo.SetValue(aObject, ctrl.Checked);
179 else if (aInfo.PropertyType == typeof(string))
181 TextBox ctrl = (TextBox)aControl;
182 aInfo.SetValue(aObject, ctrl.Text);
184 else if (aInfo.PropertyType == typeof(PropertyFile))
186 Button ctrl = (Button)aControl;
187 PropertyFile value = new PropertyFile {FullPath=ctrl.Text};
188 aInfo.SetValue(aObject, value);
190 else if (aInfo.PropertyType == typeof(PropertyComboBox))
192 ComboBox ctrl = (ComboBox)aControl;
193 string currentItem = ctrl.SelectedItem.ToString();
194 PropertyComboBox value = (PropertyComboBox)aInfo.GetValue(aObject);
195 value.CurrentItem = currentItem;
196 //Not strictly needed but makes sure the set method is called
197 aInfo.SetValue(aObject, value);
199 else if (aInfo.PropertyType == typeof(PropertyButton))
201 Button ctrl = (Button)aControl;
202 PropertyButton value = new PropertyButton { Text = ctrl.Text };
203 aInfo.SetValue(aObject, value);
206 //TODO: add support for other types here
211 /// Create a control for the given property.
213 /// <param name="aInfo"></param>
214 /// <param name="aAttribute"></param>
215 /// <param name="aObject"></param>
216 /// <returns></returns>
217 private Control CreateControlForProperty(PropertyInfo aInfo, AttributeObjectProperty aAttribute, T aObject)
219 if (aInfo.PropertyType == typeof(int))
221 //Integer properties are using numeric editor
222 NumericUpDown ctrl = new NumericUpDown();
223 ctrl.AutoSize = true;
224 ctrl.Minimum = Int32.Parse(aAttribute.Minimum);
225 ctrl.Maximum = Int32.Parse(aAttribute.Maximum);
226 ctrl.Increment = Int32.Parse(aAttribute.Increment);
227 ctrl.Value = (int)aInfo.GetValue(aObject);
228 // Hook-in change notification after setting the value
229 ctrl.ValueChanged += ControlValueChanged;
232 else if (aInfo.PropertyType.IsEnum)
234 //Enum properties are using combo box
235 ComboBox ctrl = new ComboBox();
236 ctrl.AutoSize = true;
238 ctrl.DropDownStyle = ComboBoxStyle.DropDownList;
239 //Data source is fine but it gives us duplicate entries for duplicated enum values
240 //ctrl.DataSource = Enum.GetValues(aInfo.PropertyType);
242 //Therefore we need to explicitly create our items
243 Size cbSize = new Size(0, 0);
244 foreach (string name in aInfo.PropertyType.GetEnumNames())
246 ctrl.Items.Add(name.ToString());
247 Graphics g = this.CreateGraphics();
248 //Since combobox autosize would not work we need to get measure text ourselves
249 SizeF size = g.MeasureString(name.ToString(), ctrl.Font);
250 cbSize.Width = Math.Max(cbSize.Width, (int)size.Width);
251 cbSize.Height = Math.Max(cbSize.Height, (int)size.Height);
254 //Make sure our combobox is large enough
255 ctrl.MinimumSize = cbSize;
257 // Instantiate our enum
258 object enumValue = Activator.CreateInstance(aInfo.PropertyType);
259 enumValue = aInfo.GetValue(aObject);
260 //Set the current item
261 ctrl.SelectedItem = enumValue.ToString();
262 // Hook-in change notification after setting the value
263 ctrl.SelectedIndexChanged += ControlValueChanged;
267 else if (aInfo.PropertyType == typeof(bool))
269 CheckBox ctrl = new CheckBox();
270 ctrl.AutoSize = true;
271 ctrl.Text = aAttribute.Description;
272 ctrl.Checked = (bool)aInfo.GetValue(aObject);
273 // Hook-in change notification after setting the value
274 ctrl.CheckedChanged += ControlValueChanged;
277 else if (aInfo.PropertyType == typeof(string))
279 TextBox ctrl = new TextBox();
280 ctrl.AutoSize = true;
281 ctrl.Text = (string)aInfo.GetValue(aObject);
282 // Hook-in change notification after setting the value
283 ctrl.TextChanged += ControlValueChanged;
286 else if (aInfo.PropertyType == typeof(PropertyFile))
288 // We have a file property
289 // Create a button that will trigger the open file dialog to select our file.
290 Button ctrl = new Button();
291 ctrl.AutoSize = true;
292 ctrl.Text = ((PropertyFile)aInfo.GetValue(aObject)).FullPath;
293 // Add lambda expression to Click event
294 ctrl.Click += (sender, e) =>
296 // Create open file dialog
297 OpenFileDialog ofd = new OpenFileDialog();
298 ofd.RestoreDirectory = true;
299 // Use file filter specified by our property
300 ofd.Filter = aAttribute.Filter;
302 if (DlgBox.ShowDialog(ofd) == DialogResult.OK)
304 // Fetch selected file name
305 ctrl.Text = ofd.FileName;
309 // Hook-in change notification after setting the value
310 ctrl.TextChanged += ControlValueChanged;
313 else if (aInfo.PropertyType == typeof(PropertyComboBox))
316 ComboBox ctrl = new ComboBox();
317 ctrl.AutoSize = true;
319 ctrl.DropDownStyle = ComboBoxStyle.DropDownList;
320 //Data source is such a pain to set the current item
321 //ctrl.DataSource = ((PropertyComboBox)aInfo.GetValue(aObject)).Items;
323 PropertyComboBox pcb = ((PropertyComboBox)aInfo.GetValue(aObject));
324 foreach (string item in pcb.Items)
326 ctrl.Items.Add(item);
329 ctrl.SelectedItem = ((PropertyComboBox)aInfo.GetValue(aObject)).CurrentItem;
333 else if (aInfo.PropertyType == typeof(PropertyButton))
335 // We have a button property
336 // Create a button that will trigger the custom action.
337 Button ctrl = new Button();
338 ctrl.AutoSize = true;
339 ctrl.Text = ((PropertyButton)aInfo.GetValue(aObject)).Text;
340 // Hook in click event
341 ctrl.Click += ((PropertyButton)aInfo.GetValue(aObject)).ClickEventHandler;
342 // Hook-in change notification after setting the value
343 ctrl.TextChanged += ControlValueChanged;
347 //TODO: add support for other control type here
352 /// Don't forget to extend that one and adding types
354 /// <returns></returns>
355 private bool IsPropertyTypeSupported(PropertyInfo aInfo)
357 if (aInfo.PropertyType == typeof(int))
361 else if (aInfo.PropertyType.IsEnum)
365 else if (aInfo.PropertyType == typeof(bool))
369 else if (aInfo.PropertyType == typeof(string))
373 else if (aInfo.PropertyType == typeof(PropertyFile))
377 else if (aInfo.PropertyType == typeof(PropertyComboBox))
381 else if (aInfo.PropertyType == typeof(PropertyButton))
386 //TODO: add support for other type here
392 /// Update our table layout.
393 /// Will instantiated every field control as defined by our object.
395 /// <param name="aLayout"></param>
396 private void UpdateControls()
400 //Debug.Print("UpdateTableLayoutPanel")
401 //First clean our current panel
402 iTableLayoutPanel.Controls.Clear();
403 iTableLayoutPanel.RowStyles.Clear();
404 iTableLayoutPanel.ColumnStyles.Clear();
405 iTableLayoutPanel.RowCount = 0;
407 //We always want two columns: one for label and one for the field
408 iTableLayoutPanel.ColumnCount = 2;
409 iTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
410 iTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
419 UpdateStaticControls();
421 //IEnumerable<PropertyInfo> properties = aObject.GetType().GetProperties().Where(
422 // prop => Attribute.IsDefined(prop, typeof(AttributeObjectProperty)));
424 //TODO: Do this whenever a field changes
425 iLabelBrief.Text = Object.Brief();
428 foreach (PropertyInfo pi in Object.GetType().GetProperties())
430 AttributeObjectProperty[] attributes = ((AttributeObjectProperty[])pi.GetCustomAttributes(typeof(AttributeObjectProperty), true));
431 if (attributes.Length != 1)
436 AttributeObjectProperty attribute = attributes[0];
438 //Before anything we need to check if that kind of property is supported by our UI
440 Control ctrl = CreateControlForProperty(pi, attribute, Object);
443 //Property type not supported
448 iTableLayoutPanel.RowCount++;
449 iTableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
451 Label label = new Label();
452 label.AutoSize = true;
453 label.Dock = DockStyle.Fill;
454 label.TextAlign = ContentAlignment.MiddleCenter;
455 label.Text = attribute.Name;
456 toolTip.SetToolTip(label, attribute.Description);
457 iTableLayoutPanel.Controls.Add(label, 0, iTableLayoutPanel.RowCount-1);
459 //Add our editor to our form
460 iTableLayoutPanel.Controls.Add(ctrl, 1, iTableLayoutPanel.RowCount - 1);
461 //Add tooltip to editor too
462 toolTip.SetToolTip(ctrl, attribute.Description);
466 //Entrer object edit mode
467 Object.CurrentState = SharpLib.Ear.Object.State.Edit;
468 Object.PropertyChanged += PropertyChangedEventHandlerThreadSafe;
474 /// <param name="sender"></param>
475 /// <param name="e"></param>
476 void PropertyChangedEventHandlerThreadSafe(object sender, PropertyChangedEventArgs e)
478 if (this.InvokeRequired)
480 //Not in the proper thread, invoke ourselves
481 PropertyChangedEventHandler d = new PropertyChangedEventHandler(PropertyChangedEventHandlerThreadSafe);
482 this.Invoke(d, new object[] { sender, e });
486 // We could test the name of the property that has changed as follow
487 // It's currently not needed though
488 //if (e.PropertyName == "Brief")
490 // Our object has changed behind our back.
491 // That's currently only the case for HID events that are listening for inputs.
492 if (Object is EventHid)
494 //HID can't do full control updates for some reason
495 //We are getting spammed with HID events after a few clicks
496 //We need to investigate, HID bug?
497 UpdateStaticControls();
506 private void buttonTest_Click(object sender, EventArgs e)
508 FetchPropertiesValue(Object);
510 //If our object has a test method with no parameters just run it then
511 MethodInfo info = Object.GetType().GetMethod("Test");
512 if ( info != null && info.GetParameters().Length==0)
514 info.Invoke(Object,null);
523 /// <param name="sender"></param>
524 /// <param name="e"></param>
525 private void ControlValueChanged(object sender, EventArgs e)
533 private void UpdateObject()
535 // Update our object with the content of our controls
536 FetchPropertiesValue(Object);
538 UpdateStaticControls();
546 private void UpdateStaticControls()
548 // Update OK and test button status
549 iButtonOk.Enabled = Object.IsValid();
550 iButtonTest.Enabled = iButtonOk.Enabled;
552 // Update brief title
553 iLabelBrief.Text = Object.Brief();
555 // Update object description
556 iLabelDescription.Text = Object.Description;
562 /// <param name="sender"></param>
563 /// <param name="e"></param>
564 private void iComboBoxObjectType_KeyPress(object sender, KeyPressEventArgs e)
566 //Special case for HID events
567 if (Object is EventHid)
569 //Disable handling of key input as we are using key input for changing our event