-
Notifications
You must be signed in to change notification settings - Fork 476
Expand file tree
/
Copy pathUIItem.cs
More file actions
451 lines (390 loc) · 14.8 KB
/
UIItem.cs
File metadata and controls
451 lines (390 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
using System;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using Castle.Core.Logging;
using TestStack.White.AutomationElementSearch;
using TestStack.White.Configuration;
using TestStack.White.Factory;
using TestStack.White.InputDevices;
using TestStack.White.Recording;
using TestStack.White.UIA;
using TestStack.White.UIItemEvents;
using TestStack.White.UIItems.Actions;
using TestStack.White.UIItems.Finders;
using TestStack.White.UIItems.Scrolling;
using TestStack.White.UIItems.WindowItems;
using TestStack.White.WindowsAPI;
using Action = TestStack.White.UIItems.Actions.Action;
using Point = System.Windows.Point;
using System.Windows.Forms;
namespace TestStack.White.UIItems
{
//TODO Make this class smaller
//TODO ToolStrip and Similar kind of support
public class UIItem : IUIItem
{
protected readonly AutomationElement automationElement;
protected ActionListener actionListener;
internal static readonly Mouse mouse = Mouse.Instance;
protected readonly PrimaryUIItemFactory factory;
internal readonly Keyboard keyboard = Keyboard.Instance;
protected IScrollBars scrollBars;
private AutomationEventHandler handler;
protected readonly ILogger Logger = CoreAppXmlConfiguration.Instance.LoggerFactory.Create(typeof(UIItem));
protected UIItem()
{
}
public UIItem(AutomationElement automationElement, ActionListener actionListener)
{
if (null == automationElement) throw new NullReferenceException();
this.automationElement = automationElement;
this.actionListener = actionListener;
factory = new PrimaryUIItemFactory(new AutomationElementFinder(automationElement));
}
/// <summary>
/// Should be used only if white doesn't support the feature you are looking for.
/// Knowledge of UIAutomation would be required. It would better idea to also raise an issue if you are using it.
/// </summary>
public virtual AutomationElement AutomationElement
{
get { return automationElement; }
}
protected virtual object Property(AutomationProperty automationProperty)
{
return automationElement.GetCurrentPropertyValue(automationProperty);
}
public virtual bool Enabled
{
get { return automationElement.Current.IsEnabled; }
}
public virtual WindowsFramework Framework
{
get { return WindowsFrameworkExtensions.FromFrameworkId(automationElement.Current.FrameworkId); }
}
public virtual Point Location
{
get { return automationElement.Current.BoundingRectangle.TopLeft; }
}
protected virtual void ActionPerformed()
{
actionListener.ActionPerformed(Action.WindowMessage);
}
public virtual Rect Bounds
{
get { return automationElement.Current.BoundingRectangle; }
}
public virtual string Name
{
get
{
try
{
return automationElement.Current.Name;
}
catch (InvalidOperationException)
{
return automationElement.Current.Name;
}
}
}
public virtual Point ClickablePoint
{
get { return (Point)Property(AutomationElement.ClickablePointProperty); }
}
public virtual string AccessKey
{
get { return automationElement.Current.AccessKey; }
}
public virtual bool ValueOfEquals(AutomationProperty property, object compareTo)
{
return Property(property).Equals(compareTo);
}
protected virtual T Pattern<T>()
{
var fieldInfo = typeof(T).GetField("Pattern", BindingFlags.Static | BindingFlags.Public);
var pattern = (AutomationPattern)fieldInfo.GetValue(null);
object patternObject;
if (automationElement.TryGetCurrentPattern(pattern, out patternObject))
{
return (T)patternObject;
}
return (T)(object)null;
}
protected virtual BasePattern Pattern(AutomationPattern pattern)
{
return Pattern(AutomationElement, pattern);
}
internal static BasePattern Pattern(AutomationElement automationElement, AutomationPattern pattern)
{
object patternObject;
if (automationElement.TryGetCurrentPattern(pattern, out patternObject))
{
return (BasePattern)patternObject;
}
return null;
}
public virtual void RightClickAt(Point point)
{
actionListener.ActionPerforming(this);
mouse.RightClick(point, actionListener);
}
public virtual void RightClick()
{
RightClickOnCenter();
}
private void RightClickOnCenter()
{
RightClickAt(Bounds.Center());
}
public virtual void Focus()
{
actionListener.ActionPerforming(this);
try
{
automationElement.SetFocus();
ActionPerformed();
}
catch
{
Logger.Debug("Could not set focus on " + AutomationElement.Display());
}
}
public virtual void Visit(WindowControlVisitor windowControlVisitor)
{
windowControlVisitor.Accept(this);
}
public virtual string Id
{
get { return automationElement.Current.AutomationId; }
}
public virtual bool Visible
{
get { return !automationElement.Current.IsOffscreen; }
}
/// <summary>
/// Provides the Error on this UIItem. This would return Error object when this item has ErrorProvider displayed next to it.
/// </summary>
/// <param name="window"></param>
/// <returns></returns>
public virtual string ErrorProviderMessage(Window window)
{
AutomationElement element =
AutomationElement.FromPoint(automationElement.Current.BoundingRectangle.ImmediateExteriorEast());
if (element == null) return null;
Rect errorProviderBounds = element.Current.BoundingRectangle;
if (automationElement.Current.BoundingRectangle.Right != errorProviderBounds.Left) return null;
mouse.Location = errorProviderBounds.Center();
actionListener.ActionPerformed(Action.WindowMessage);
return window.ToolTip.Text;
}
public virtual bool NameMatches(string text)
{
return Name.Equals(text);
}
public virtual string PrimaryIdentification
{
get { return automationElement.Current.FrameworkId.Equals(WindowsFramework.Win32.FrameworkId()) ? Name : Id; }
}
public virtual ActionListener ActionListener
{
get { return actionListener; }
}
/// <summary>
/// Performs mouse click at the center of this item
/// </summary>
public virtual void Click()
{
actionListener.ActionPerforming(this);
PerformIfValid(PerformClick);
}
private void PerformIfValid(System.Action action)
{
var startTime = DateTime.Now;
var busyTimeout = CoreAppXmlConfiguration.Instance.BusyTimeout / 1000;
while (DateTime.Now.Subtract(startTime).TotalSeconds < busyTimeout)
{
if (Enabled && !IsOffScreen)
{
action();
return;
}
Thread.Sleep(500);
}
string message = null;
if (!Enabled)
message = "element not enabled";
else if (IsOffScreen)
message = "element is offscreen";
throw new AutomationException(string.Format("Cannot perform action on {0}, {1}", this, message), Debug.Details(AutomationElement));
}
void PerformClick()
{
if (!Enabled) Logger.WarnFormat("Clicked on disabled item: {0}", ToString());
var bounds = Bounds;
if (bounds.IsEmpty)
{
throw new WhiteException(string.Format("Failed to click on {0}, bounds empty", ToString()));
}
mouse.Click(bounds.Center(), actionListener);
}
/// <summary>
/// Performs mouse double click at the center of this item
/// </summary>
public virtual void DoubleClick()
{
actionListener.ActionPerforming(this);
PerformIfValid(() => mouse.DoubleClick(Bounds.Center(), actionListener));
}
/// <summary>
/// Performs mouse wheel at the center of this item
/// </summary>
public virtual void MouseWheel(int delta)
{
actionListener.ActionPerforming(this);
PerformIfValid(() => mouse.Wheel(Bounds.Center(), delta, actionListener));
}
/// <summary>
/// Perform keyboard action on this UIItem
/// </summary>
/// <param name="key"></param>
public virtual void KeyIn(KeyboardInput.SpecialKeys key)
{
actionListener.ActionPerforming(this);
keyboard.PressSpecialKey(key, actionListener);
}
public override bool Equals(object obj)
{
if (this == obj) return true;
var uiItem = obj as UIItem;
if (uiItem == null) return false;
return Equals(automationElement, uiItem.AutomationElement);
}
public override int GetHashCode()
{
return automationElement.GetHashCode();
}
public override string ToString()
{
return string.Format("{0}. {1}", GetType().Name, automationElement.Display());
}
public virtual IScrollBars ScrollBars
{
get { return scrollBars ?? (scrollBars = ScrollerFactory.CreateBars(automationElement, actionListener)); }
}
protected virtual void HookClickEvent(UIItemEventListener eventListener)
{
handler = delegate { eventListener.EventOccured(new UIItemClickEvent(this)); };
Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, automationElement, TreeScope.Element,
handler);
}
protected virtual void UnHookClickEvent()
{
Automation.RemoveAutomationEventHandler(InvokePattern.InvokedEvent, automationElement, handler);
}
public virtual bool IsOffScreen
{
get { return automationElement.Current.IsOffscreen; }
}
public virtual bool IsFocussed
{
get { return automationElement.Current.HasKeyboardFocus; }
}
public virtual Color BorderColor
{
get { return VisibleImage.GetPixel(0, 0); }
}
public virtual Bitmap VisibleImage
{
get
{
var displayedItem = new DisplayedItem(new IntPtr(automationElement.Current.NativeWindowHandle));
using (System.Drawing.Image image = displayedItem.GetVisibleImage())
return new Bitmap(image);
}
}
public virtual string HelpText { get { return automationElement.Current.HelpText; } }
/// <summary>
/// Internal to white and intended to be used for white recording
/// </summary>
public virtual void UnHookEvents()
{
}
/// <summary>
/// Internal to white and intended to be used for white recording
/// </summary>
/// <param name="eventListener"></param>
public virtual void HookEvents(UIItemEventListener eventListener)
{
}
public virtual void SetValue(object value)
{
}
public virtual void ActionPerforming(UIItem uiItem)
{
}
public virtual void ActionPerformed(Action action)
{
actionListener.ActionPerformed(action);
}
public virtual void LogStructure()
{
Logger.Info(Debug.Details(AutomationElement));
}
/// <summary>
/// Uses the Raw View provided by UIAutomation to find elements within this UIItem. RawView sometimes contains extra AutomationElements. This is internal to
/// white although made public. Should be used only if the standard approaches dont work. Also if you end up using it please raise an issue
/// so that it can be fixed.
/// Please understand that calling this method on any UIItem which has a lot of child AutomationElements might result in very bad performance.
/// </summary>
/// <param name="searchCriteria"></param>
/// <returns>null or found AutomationElement</returns>
public virtual AutomationElement GetElement(SearchCriteria searchCriteria)
{
return
new AutomationElementFinder(automationElement).FindDescendantRaw(
searchCriteria.AutomationSearchCondition);
}
public virtual void Enter(string value)
{
var pattern = Pattern(ValuePattern.Pattern) as ValuePattern;
if (pattern != null) pattern.SetValue(string.Empty);
if (string.IsNullOrEmpty(value)) return;
actionListener.ActionPerformed(Action.WindowMessage);
EnterData(value);
}
protected virtual void EnterData(string value)
{
var lines = value.Replace("\r\n", "\n").Split('\n');
keyboard.Send(lines[0], actionListener);
foreach (var line in lines.Skip(1))
{
keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RETURN);
keyboard.Send(line, actionListener);
}
}
internal virtual UIItemContainer AsContainer()
{
return new UIItemContainer(AutomationElement, ActionListener);
}
public virtual void RaiseClickEvent()
{
var invokePattern = (InvokePattern)Pattern(InvokePattern.Pattern);
if (invokePattern != null) invokePattern.Invoke();
}
/// <summary>
/// Highlight UIItem with red frame
/// </summary>
public virtual void DrawHighlight()
{
Rect rectangle = AutomationElement.Current.BoundingRectangle;
if (rectangle != Rect.Empty)
{
new Drawing.FrameRectangle(rectangle).Highlight();
}
}
}
}