-
-
Notifications
You must be signed in to change notification settings - Fork 579
/
Copy pathWindowsSelector.cs
612 lines (580 loc) · 30.3 KB
/
WindowsSelector.cs
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
using FlaUI.Core;
using FlaUI.Core.AutomationElements;
using FlaUI.Core.AutomationElements.Infrastructure;
using OpenRPA.Interfaces;
using OpenRPA.Interfaces.Selector;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenRPA.Windows
{
public class WindowsSelector : Selector
{
UIElement element { get; set; }
private WindowsSelector() { }
public WindowsSelector(string json) : base(json) { }
public WindowsSelector(AutomationElement element, WindowsSelector anchor, bool doEnum)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
Log.Selector(string.Format("windowsselector::begin {0:mm\\:ss\\.fff}", sw.Elapsed));
AutomationElement root = null;
var pathToRoot = new List<AutomationElement>();
while (element != null)
{
// Break on circular relationship(should not happen?)
if (pathToRoot.Contains(element)) { break; }
try
{
if (element.Parent != null) pathToRoot.Add(element);
if (element.Parent == null) root = element;
}
catch (Exception)
{
root = element;
}
try
{
//element = _treeWalker.GetParent(element);
element = element.Parent;
}
catch (Exception ex)
{
Log.Error(ex.ToString());
return;
}
}
Log.Selector(string.Format("windowsselector::create pathToRoot::end {0:mm\\:ss\\.fff}", sw.Elapsed));
AutomationElement win = null;
for (var i = 0; i < pathToRoot.Count; i++)
{
var _item = pathToRoot[i];
FlaUI.Core.Definitions.ControlType ct;
if (_item.Properties.ControlType.TryGetValue(out ct))
{
if (ct == FlaUI.Core.Definitions.ControlType.Window) win = _item;
}
}
if (win != null && PluginConfig.remove_fisrt_window)
{
var indexof = pathToRoot.IndexOf(win) + 1;
pathToRoot.RemoveRange(indexof, pathToRoot.Count - indexof);
}
pathToRoot.Reverse();
if (anchor != null)
{
bool SearchDescendants = anchor.First().SearchDescendants();
if (SearchDescendants)
{
var a = anchor.Last();
var idx = -1;
for (var i = 0; i < pathToRoot.Count(); i++)
{
if (WindowsSelectorItem.Match(a, pathToRoot[i]))
{
idx = i;
// break;
}
}
pathToRoot.RemoveRange(0, idx);
}
else
{
var anchorlist = anchor.Where(x => x.Enabled && x.Selector == null).ToList();
for (var i = 0; i < anchorlist.Count(); i++)
{
if (WindowsSelectorItem.Match(anchorlist[i], pathToRoot[0]))
//if (((WindowsSelectorItem)anchorlist[i]).Match(pathToRoot[0]))
{
pathToRoot.Remove(pathToRoot[0]);
}
else
{
Log.Selector("Element does not match the anchor path");
return;
}
}
}
}
WindowsSelectorItem item;
if (PluginConfig.traverse_selector_both_ways)
{
Log.Selector(string.Format("windowsselector::create traverse_selector_both_ways::begin {0:mm\\:ss\\.fff}", sw.Elapsed));
var temppathToRoot = new List<AutomationElement>();
var newpathToRoot = new List<AutomationElement>();
foreach (var e in pathToRoot) temppathToRoot.Add(e);
Log.Selector(string.Format("windowsselector::traverse back to element from root::begin {0:mm\\:ss\\.fff}", sw.Elapsed));
using (var automation = AutomationUtil.getAutomation())
{
bool isDesktop = true;
AutomationElement parent = null;
if (anchor != null) { parent = temppathToRoot[0].Parent; isDesktop = false; }
else { parent = automation.GetDesktop(); }
int count = temppathToRoot.Count;
while (temppathToRoot.Count > 0)
{
count--;
var i = temppathToRoot.First();
temppathToRoot.Remove(i);
item = new WindowsSelectorItem(i, false, null);
if (parent != null)
{
var m = item.matches(root, count, parent, 2, isDesktop, false);
if (m.Length > 0)
{
newpathToRoot.Add(i);
parent = i;
isDesktop = false;
}
if (m.Length == 0 && Config.local.log_selector)
{
//var message = "needed to find " + Environment.NewLine + item.ToString() + Environment.NewLine + "but found only: " + Environment.NewLine;
//var children = parent.FindAllChildren();
//foreach (var c in children)
//{
// try
// {
// message += new UIElement(c).ToString() + Environment.NewLine;
// }
// catch (Exception)
// {
// }
//}
//Log.Debug(message);
}
}
}
}
if (newpathToRoot.Count != pathToRoot.Count)
{
Log.Information("Selector had " + pathToRoot.Count + " items to root, but traversing children only matched " + newpathToRoot.Count);
pathToRoot = newpathToRoot;
}
Log.Selector(string.Format("windowsselector::create traverse_selector_both_ways::end {0:mm\\:ss\\.fff}", sw.Elapsed));
}
if (pathToRoot.Count == 0)
{
Log.Error("Element has not parent, or is same as annchor");
return;
}
AutomationElement baseElement = pathToRoot.First();
WindowsSelectorItem rootselectoritem = new WindowsSelectorItem(baseElement, true, null);
if (PluginConfig.search_descendants && PluginConfig.create_short_selector)
{
Log.Selector(string.Format("windowsselector::begin create short selector using 1 item {0:mm\\:ss\\.fff}", sw.Elapsed));
bool testSelector = false;
using (var automation = AutomationUtil.getAutomation())
{
var subparent = pathToRoot[0];
var subparentui = new UIElement(subparent);
UIElement[] subparents = { subparentui };
item = new WindowsSelectorItem(pathToRoot.Last(), false, rootselectoritem);
bool worked = true;
if (testSelector)
{
Log.Selector(string.Format("windowsselector::begin test short selector using 1 item {0:mm\\:ss\\.fff}", sw.Elapsed));
var subelements2 = GetElementsWithuiSelectorItem(2, automation, item, subparents, 2, true, true).ToList();
Log.Selector(string.Format("windowsselector::begin test found " + subelements2.Count + " {0:mm\\:ss\\.fff}", sw.Elapsed));
worked = subelements2.Count == 1;
}
if (worked)
{
if (anchor == null)
{
item = new WindowsSelectorItem(baseElement, true, rootselectoritem);
item.Enabled = true;
Items.Add(item);
item = new WindowsSelectorItem(baseElement, false, rootselectoritem);
item.Enabled = true;
Items.Add(item);
}
item = new WindowsSelectorItem(pathToRoot.Last(), false, rootselectoritem);
item.Enabled = true;
Items.Add(item);
Log.Selector(string.Format("windowsselector::end {0:mm\\:ss\\.fff}", sw.Elapsed));
OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Count"));
OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset));
return;
}
}
}
element = pathToRoot.Last();
Clear();
Log.Selector(string.Format("windowsselector::remove anchor if needed::end {0:mm\\:ss\\.fff}", sw.Elapsed));
if (anchor == null)
{
Log.Selector(string.Format("windowsselector::create root element::begin {0:mm\\:ss\\.fff}", sw.Elapsed));
item = new WindowsSelectorItem(baseElement, true, rootselectoritem);
item.Enabled = true;
//item.canDisable = false;
Items.Add(item);
Log.Selector(string.Format("windowsselector::create root element::end {0:mm\\:ss\\.fff}", sw.Elapsed));
}
bool isStartmenu = false;
for (var i = 0; i < pathToRoot.Count(); i++)
{
Log.Selector(string.Format("windowsselector::search_descendants::loop element " + i + ":begin {0:mm\\:ss\\.fff}", sw.Elapsed));
var o = pathToRoot[i];
int IndexInParent = -1;
if (o.Parent != null && i > 0)
{
var c = o.Parent.FindAllChildren();
for (var x = 0; x < c.Count(); x++)
{
if (o.Equals(c[x])) IndexInParent = x;
}
}
item = new WindowsSelectorItem(o, false, rootselectoritem, IndexInParent);
var _IndexInParent = item.Properties.Where(x => x.Name == "IndexInParent").FirstOrDefault();
if (_IndexInParent != null) _IndexInParent.Enabled = false;
if (i == 0 || i == (pathToRoot.Count() - 1)) item.canDisable = false;
foreach (var p in item.Properties)
{
int idx = p.Value.IndexOf(".");
if (p.Name == "ClassName" && idx > -1)
{
var FrameworkId = item.Properties.Where(x => x.Name == "FrameworkId").FirstOrDefault();
//if (FrameworkId!=null && (FrameworkId.Value == "XAML" || FrameworkId.Value == "WinForm") && _IndexInParent != null)
//{
// item.Properties.ForEach(x => x.Enabled = false);
// _IndexInParent.Enabled = true;
// p.Enabled = true;
//}
int idx2 = p.Value.IndexOf(".", idx + 1);
// if (idx2 > idx) p.Value = p.Value.Substring(0, idx2 + 1) + "*";
if (idx2 > idx && item.Properties.Count > 1)
{
p.Enabled = false;
}
}
//if (p.Name == "ClassName" && p.Value.StartsWith("WindowsForms10")) p.Value = "WindowsForms10*";
if (p.Name == "ClassName" && p.Value.ToLower() == "shelldll_defview")
{
item.Enabled = false;
}
if (p.Name == "ClassName" && (p.Value.ToLower() == "dv2vontrolhost" || p.Value.ToLower() == "desktopprogramsmfu"))
{
isStartmenu = true;
}
//if (p.Name == "ClassName" && p.Value == "#32770")
//{
// item.Enabled = false;
//}
if (p.Name == "ControlType" && p.Value == "ListItem" && isStartmenu)
{
p.Enabled = false;
}
}
var hassyslistview32 = item.Properties.Where(p => p.Name == "ClassName" && p.Value.ToLower() == "syslistview32").ToList();
if (hassyslistview32.Count > 0)
{
var hasControlType = item.Properties.Where(p => p.Name == "ControlType").ToList();
if (hasControlType.Count > 0) { hasControlType[0].Enabled = false; }
}
if (doEnum) item.EnumNeededProperties(o, o.Parent);
Items.Add(item);
Log.Selector(string.Format("windowsselector::search_descendants::loop element " + i + ":end {0:mm\\:ss\\.fff}", sw.Elapsed));
}
pathToRoot.Reverse();
Log.Selector(string.Format("windowsselector::end {0:mm\\:ss\\.fff}", sw.Elapsed));
OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Count"));
OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset));
}
public override IElement[] GetElements(IElement fromElement = null, int maxresults = 1)
{
return WindowsSelector.GetElementsWithuiSelector(this, fromElement, maxresults, null);
}
public static UIElement[] GetElementsWithuiSelectorItem(int ident, AutomationBase automation, WindowsSelectorItem sel, UIElement[] parents, int maxresults, bool LastItem, bool search_descendants)
{
var _current = new List<UIElement>();
var cond = sel.GetConditionsWithoutStar();
foreach (var _ele in parents)
{
if (PluginConfig.enable_cache && cond.ChildCount > 0)
{
var cache = WindowsSelectorItem.GetFromCache(_ele.RawElement as AutomationElement, ident, cond.ToString());
if (cache != null)
{
Log.Debug("GetElementsWithuiSelector: found in AppWindowCache " + cond.ToString());
foreach (var elementNode in cache)
{
if (WindowsSelectorItem.Match(sel, elementNode)) _current.Add(new UIElement(elementNode));
}
}
}
if (!string.IsNullOrEmpty(sel.processname()))
{
if (!string.IsNullOrEmpty(sel.processname()) && (sel.processname().ToLower() != "startmenuexperiencehost" && sel.processname().ToLower() != "explorer"))
{
var me = System.Diagnostics.Process.GetCurrentProcess();
var ps = System.Diagnostics.Process.GetProcessesByName(sel.processname()).Where(_p => _p.SessionId == me.SessionId).ToArray();
if (ps.Length == 0)
{
Log.Selector(string.Format("GetElementsWithuiSelector::Process " + sel.processname() + " not found, end with 0 results"));
return new UIElement[] { };
}
var psids = ps.Select(x => x.Id).ToArray();
var condition = new FlaUI.Core.Conditions.ConditionFactory(automation.PropertyLibrary);
var ors = new List<FlaUI.Core.Conditions.ConditionBase>();
foreach (var p in ps)
{
ors.Add(condition.ByProcessId(p.Id));
}
var con = new FlaUI.Core.Conditions.OrCondition(ors);
if (PluginConfig.enable_cache && con.ChildCount > 0)
{
var cache = WindowsSelectorItem.GetFromCache(_ele.RawElement as AutomationElement, ident, con.ToString());
if (cache != null)
{
Log.Debug("GetElementsWithuiSelector: found in AppWindowCache " + con.ToString());
foreach (var elementNode in cache)
{
if (WindowsSelectorItem.Match(sel, elementNode)) _current.Add(new UIElement(elementNode));
}
}
}
if (_current.Count == 0)
{
Log.Debug(string.Format("GetElementsWithuiSelector::Searchin for all " + con.ToString()));
// var ___treeWalker = automation.TreeWalkerFactory.GetCustomTreeWalker(con);
var ___treeWalker = automation.TreeWalkerFactory.GetControlViewWalker();
int retries = 0;
AutomationElement win = null;
bool hasError = false;
do
{
hasError = false;
try
{
win = ___treeWalker.GetFirstChild(_ele.RawElement as AutomationElement);
}
catch (Exception ex)
{
Log.Debug(ex.ToString());
retries++;
hasError = true;
// throw;
}
} while (hasError && retries < 10);
while (win != null)
{
bool addit = false;
if (win.Properties.ProcessId.IsSupported && psids.Contains(win.Properties.ProcessId))
{
addit = true;
}
if (addit)
{
var uiele = new UIElement(win);
Log.Debug("GetElementsWithuiSelector::Adding element " + uiele.ToString());
_current.Add(uiele);
if (win.Patterns.Window.TryGetPattern(out var winPattern))
{
if (winPattern.WindowVisualState.Value == FlaUI.Core.Definitions.WindowVisualState.Minimized)
{
IntPtr handle = win.Properties.NativeWindowHandle.Value;
winPattern.SetWindowVisualState(FlaUI.Core.Definitions.WindowVisualState.Normal);
}
}
if (PluginConfig.allow_multiple_hits_mid_selector || ident == 0) // do all
{
win = ___treeWalker.GetNextSibling(win);
}
else
{
win = null;
}
}
else
{
win = ___treeWalker.GetNextSibling(win);
}
}
if (_current.Count > 0 && PluginConfig.enable_cache && con.ChildCount > 0)
{
var elements = _current.Select(x => x.RawElement).Cast<AutomationElement>().ToArray();
WindowsSelectorItem.AddToCache(_ele.RawElement as AutomationElement, ident, con.ToString(), elements);
}
}
}
return _current.ToArray();
}
if (_current.Count == 0 && string.IsNullOrEmpty(sel.Selector))
{
Log.Debug("GetElementsWithuiSelector::Searchin for " + cond.ToString());
ITreeWalker _treeWalker = default(ITreeWalker);
if (search_descendants)
{
var hasStar = sel.Properties.Where(x => x.Enabled == true && (x.Value != null && x.Value.Contains("*"))).ToArray();
_treeWalker = automation.TreeWalkerFactory.GetCustomTreeWalker(cond);
}
else
{
_treeWalker = automation.TreeWalkerFactory.GetControlViewWalker();
}
int retries = 0;
AutomationElement ele = null;
bool hasError = false;
do
{
hasError = false;
try
{
ele = _treeWalker.GetFirstChild(_ele.RawElement as AutomationElement);
}
catch (Exception ex)
{
Log.Debug(ex.ToString());
retries++;
hasError = true;
// throw;
}
} while (hasError && retries < 10);
if (ele != null)
{
do
{
// Log.Debug(string.Format("GetElementsWithuiSelector::Match element {0:mm\\:ss\\.fff}", sw.Elapsed));
if (WindowsSelectorItem.Match(sel, ele))
{
var uiele = new UIElement(ele);
Log.Debug("GetElementsWithuiSelector::Adding element " + uiele.ToString());
_current.Add(uiele);
}
bool getmore = false;
if (LastItem)
{
if (_current.Count < maxresults) getmore = true;
}
else
{
if (_current.Count == 0)
{
getmore = true;
}
else if (PluginConfig.allow_multiple_hits_mid_selector)
{
getmore = true;
}
}
if (getmore) ele = _treeWalker.GetNextSibling(ele);
if (!getmore) ele = null;
} while (ele != null);
}
if (_current.Count > 0 && PluginConfig.enable_cache && cond.ChildCount > 0)
{
var elements = _current.Select(x => x.RawElement).Cast<AutomationElement>().ToArray();
WindowsSelectorItem.AddToCache(_ele.RawElement as AutomationElement, ident, cond.ToString(), elements);
}
}
}
return _current.ToArray();
}
public static UIElement[] GetElementsWithuiSelector(WindowsSelector selector, IElement fromElement, int maxresults, WindowsCacheExtension ext)
{
TimeSpan timeout = TimeSpan.FromMilliseconds(5000);
timeout = TimeSpan.FromMilliseconds(20000);
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
Log.Selector(string.Format("GetElementsWithuiSelector::begin {0:mm\\:ss\\.fff}", sw.Elapsed));
UIElement _fromElement = fromElement as UIElement;
// var selectors = selector.Where(x => x.Enabled == true && x.Selector == null).ToList();
var selectors = selector.ToList();
AutomationElement startfrom = null;
if (_fromElement != null) startfrom = _fromElement.RawElement as AutomationElement;
var _current = new List<UIElement>();
// var automation = AutomationUtil.getAutomation();
AutomationBase automation = null;
if (ext != null) automation = ext.automation;
if (automation == null) automation = AutomationUtil.getAutomation();
UIElement[] result = null;
// AutomationElement ele = null;
bool search_descendants = selectors[0].SearchDescendants();
if (startfrom == null) startfrom = automation.GetDesktop();
_current.Add(new UIElement(startfrom));
for (var i = 0; i < selectors.Count; i++)
{
var _sel = selectors[i];
var sel = new WindowsSelectorItem(_sel);
var current = _current.ToArray();
_current.Clear();
// if(i == 1 && current.Length == 1 && current.First().ControlType == sel.ControlType)
if (i == 1)
{
foreach (var e in current)
{
if (WindowsSelectorItem.Match(sel, e.RawElement as AutomationElement))
{
_current.Add(e);
}
}
if (_current.Count > 0) continue;
//_current = GetElementsWithuiSelectorItem(automation, sel, current, maxresults, i == (selectors.Count - 1)).ToList();
//if(_current.Count == 0) _current = current.ToList();
//_current = current.ToList();
}
_current = GetElementsWithuiSelectorItem(i, automation, sel, current, maxresults, i == (selectors.Count - 1), search_descendants).ToList();
if (i == 0 && _current.Count == 0)
{
_current = current.ToList();
}
else if (i > 0 && _current.Count == 0 && current.Length > 0 && (PluginConfig.try_mouse_over_search || selector.mouse_over_search()))
{
for (var z = 0; z < current.Length; z++)
{
current[z].Focus();
var x = current[z].Rectangle.X + 5; var y = current[z].Rectangle.Y + 5;
var screen = automation.FromPoint(new System.Drawing.Point(x, y));
Log.Selector("mouse point lookup at " + x + "," + y + " for " + sel.ToString());
var screenel = screen.Parent;
while (screenel != null)
{
var uiscreenel = new UIElement(screenel);
if (WindowsSelectorItem.Match(sel, screenel))
{
_current.Clear();
_current.Add(new UIElement(screenel));
Log.Selector("Mouse lookup found " + uiscreenel.ToString());
break;
}
else { screenel = screenel.Parent; }
// only allow direct parents, or search for match in all child elements found ? ( like searching for a button inside a pane )
//else
//{
// Log.Output("Lookup in " + uiscreenel.ToString());
// _current = GetElementsWithuiSelectorItem(i, automation, sel, new UIElement[] { uiscreenel }, maxresults, i == (selectors.Count - 1), search_descendants).ToList();
// if (_current.Count != 0) break;
// screenel = screenel.Parent;
//}
}
if (_current.Count > 0) break;
}
}
}
Log.Debug(string.Format("GetElementsWithuiSelector::completed with " + _current.Count + " results {0:mm\\:ss\\.fff}", sw.Elapsed));
if (_current.Count > 0)
{
result = _current.ToArray();
if (result.Count() > maxresults)
{
Console.WriteLine("found " + result.Count() + " but only needed " + maxresults);
result = result.Take(maxresults).ToArray();
}
return result;
}
if (result == null)
{
Log.Selector(string.Format("GetElementsWithuiSelector::ended with 0 results after {0:mm\\:ss\\.fff}", sw.Elapsed));
return new UIElement[] { };
}
if (result.Count() > maxresults) result = result.Take(maxresults).ToArray();
Log.Selector(string.Format("GetElementsWithuiSelector::ended with " + result.Length + " results after {0:mm\\:ss\\.fff}", sw.Elapsed));
return result;
}
}
}