summaryrefslogtreecommitdiff
path: root/dali/internal/accessibility/bridge/bridge-accessible.cpp
blob: 31443ffa1ea96033adbf4415c0aff8996a13d32b (plain)
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
/*
 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// CLASS HEADER
#include <dali/internal/accessibility/bridge/bridge-accessible.h>

// EXTERNAL INCLUDES
#include <dali/public-api/math/math-utils.h>

#include <algorithm>
#include <iostream>

// INTERNAL INCLUDES
#include <dali/devel-api/atspi-interfaces/accessible.h>
#include <dali/devel-api/atspi-interfaces/component.h>
#include <dali/devel-api/atspi-interfaces/selection.h>
#include <dali/devel-api/atspi-interfaces/text.h>
#include <dali/devel-api/atspi-interfaces/value.h>

//comment out 2 lines below to get more logs
#undef LOG
#define LOG() _LoggerEmpty()

using namespace Dali::Accessibility;

#define GET_NAVIGABLE_AT_POINT_MAX_RECURSION_DEPTH 10000

namespace
{
bool SortVertically(Component* lhs, Component* rhs)
{
  auto leftRect  = lhs->GetExtents(CoordinateType::WINDOW);
  auto rightRect = rhs->GetExtents(CoordinateType::WINDOW);

  return leftRect.y < rightRect.y;
}

bool SortHorizontally(Component* lhs, Component* rhs)
{
  auto leftRect  = lhs->GetExtents(CoordinateType::WINDOW);
  auto rightRect = rhs->GetExtents(CoordinateType::WINDOW);

  return leftRect.x < rightRect.x;
}

std::vector<std::vector<Component*>> SplitLines(const std::vector<Component*>& children)
{
  // Find first with non-zero area
  auto first = std::find_if(children.begin(), children.end(), [](Component* child) -> bool {
    auto extents = child->GetExtents(CoordinateType::WINDOW);
    return !Dali::EqualsZero(extents.height) && !Dali::EqualsZero(extents.width);
  });

  if(first == children.end())
  {
    return {};
  }

  std::vector<std::vector<Component*>> lines(1);
  Dali::Rect<>                         lineRect = (*first)->GetExtents(CoordinateType::WINDOW);
  Dali::Rect<>                         rect;

  // Split into lines
  for(auto it = first; it != children.end(); ++it)
  {
    auto child = *it;

    rect = child->GetExtents(CoordinateType::WINDOW);
    if(Dali::EqualsZero(rect.height) || Dali::EqualsZero(rect.width))
    {
      // Zero area, ignore
      continue;
    }

    if(lineRect.y + (0.5 * lineRect.height) >= rect.y + (0.5 * rect.height))
    {
      // Same line
      lines.back().push_back(child);
    }
    else
    {
      // Start a new line
      lineRect = rect;
      lines.emplace_back();
      lines.back().push_back(child);
    }
  }

  return lines;
}

static bool AcceptObjectCheckRelations(Component* obj)
{
  auto relations = obj->GetRelationSet();

  for(const auto& it : relations)
  {
    if(it.mRelationType == RelationType::CONTROLLED_BY)
    {
      return false;
    }
  }
  return true;
}

static Component* GetScrollableParent(Accessible* obj)
{
  while(obj)
  {
    obj       = obj->GetParent();
    auto comp = dynamic_cast<Component*>(obj);
    if(comp && comp->IsScrollable())
    {
      return comp;
    }
  }
  return nullptr;
}

static bool IsObjectItem(Component* obj)
{
  if(!obj)
  {
    return false;
  }
  auto role = obj->GetRole();
  return role == Role::LIST_ITEM || role == Role::MENU_ITEM;
}

static bool IsObjectCollapsed(Component* obj)
{
  if(!obj)
  {
    return false;
  }
  const auto states = obj->GetStates();
  return states[State::EXPANDABLE] && !states[State::EXPANDED];
}

static bool IsObjectZeroSize(Component* obj)
{
  if(!obj)
  {
    return false;
  }
  auto extents = obj->GetExtents(CoordinateType::WINDOW);
  return Dali::EqualsZero(extents.height) || Dali::EqualsZero(extents.width);
}

static bool IsObjectAcceptable(Component* obj)
{
  if(!obj)
  {
    return false;
  }

  const auto states = obj->GetStates();
  if(!states[State::VISIBLE])
  {
    return false;
  }
  if(!AcceptObjectCheckRelations(obj))
  {
    return false;
  }
  if(!states[State::HIGHLIGHTABLE])
  {
    return false;
  }

  if(GetScrollableParent(obj) != nullptr)
  {
    auto parent = dynamic_cast<Component*>(obj->GetParent());

    if(parent)
    {
      return !IsObjectItem(obj) || !IsObjectCollapsed(parent);
    }
  }
  else
  {
    if(IsObjectZeroSize(obj))
    {
      return false;
    }
    if(!states[State::SHOWING])
    {
      return false;
    }
  }
  return true;
}

static bool IsObjectAcceptable(Accessible* obj)
{
  auto component = dynamic_cast<Component*>(obj);
  return IsObjectAcceptable(component);
}

static int32_t GetItemCountOfContainer(Accessible* obj, Dali::Accessibility::Role containerRole, Dali::Accessibility::Role itemRole, bool isDirectChild)
{
  int32_t itemCount = 0;
  if(obj && (!isDirectChild || obj->GetRole() == containerRole))
  {
    for(auto i = 0u; i < static_cast<size_t>(obj->GetChildCount()); ++i)
    {
      auto child = obj->GetChildAtIndex(i);
      if(child && child->GetRole() == itemRole)
      {
        itemCount++;
      }
    }
  }
  return itemCount;
}

static int32_t GetItemCountOfFirstDescendantContainer(Accessible* obj, Dali::Accessibility::Role containerRole, Dali::Accessibility::Role itemRole, bool isDirectChild)
{
  int32_t itemCount = 0;
  itemCount         = GetItemCountOfContainer(obj, containerRole, itemRole, isDirectChild);
  if(itemCount > 0 || !obj)
  {
    return itemCount;
  }

  for(auto i = 0u; i < static_cast<size_t>(obj->GetChildCount()); ++i)
  {
    auto child = obj->GetChildAtIndex(i);
    itemCount  = GetItemCountOfFirstDescendantContainer(child, containerRole, itemRole, isDirectChild);
    if(itemCount > 0)
    {
      return itemCount;
    }
  }
  return itemCount;
}

static std::string GetComponentInfo(Component* obj)
{
  if(!obj)
  {
    return "nullptr";
  }

  std::ostringstream object;
  auto               extent = obj->GetExtents(CoordinateType::SCREEN);
  object << "name: " << obj->GetName() << " extent: (" << extent.x << ", "
         << extent.y << "), [" << extent.width << ", " << extent.height << "]";
  return object.str();
}

static std::string MakeIndent(unsigned int maxRecursionDepth)
{
  return std::string(GET_NAVIGABLE_AT_POINT_MAX_RECURSION_DEPTH - maxRecursionDepth, ' ');
}

static bool IsRoleAcceptableWhenNavigatingNextPrev(Accessible* obj)
{
  if(!obj)
  {
    return false;
  }
  auto role = obj->GetRole();
  return role != Role::POPUP_MENU && role != Role::DIALOG;
}

static Accessible* FindNonDefunctChild(const std::vector<Component*>& children, unsigned int currentIndex, unsigned char forward)
{
  unsigned int childrenCount = children.size();
  for(; currentIndex < childrenCount; forward ? ++currentIndex : --currentIndex)
  {
    Accessible* object = children[currentIndex];
    if(object && !object->GetStates()[State::DEFUNCT])
    {
      return object;
    }
  }
  return nullptr;
}

// The auxiliary method for Depth-First Search (DFS) algorithm to find non defunct child directionally
static Accessible* FindNonDefunctChildWithDepthFirstSearch(Accessible* node, const std::vector<Component*>& children, unsigned char forward)
{
  if(!node)
  {
    return nullptr;
  }

  auto childrenCount = children.size();
  if(childrenCount > 0)
  {
    const bool isShowing = GetScrollableParent(node) == nullptr ? node->GetStates()[State::SHOWING] : true;
    if(isShowing)
    {
      return FindNonDefunctChild(children, forward ? 0 : childrenCount - 1, forward);
    }
  }
  return nullptr;
}

static bool CheckChainEndWithAttribute(Accessible* obj, unsigned char forward)
{
  if(!obj)
  {
    return false;
  }

  auto attrs = obj->GetAttributes();
  for(auto& attr : attrs)
  {
    if(attr.first == "relation_chain_end")
    {
      if((attr.second == "prev,end" && forward == 0) || (attr.second == "next,end" && forward == 1) || attr.second == "prev,next,end")
      {
        return true;
      }
    }
  }
  return false;
}

static std::vector<Component*> GetScrollableParents(Accessible* accessible)
{
  std::vector<Component*> scrollableParents;

  while(accessible)
  {
    accessible     = accessible->GetParent();
    auto component = dynamic_cast<Component*>(accessible);
    if(component && component->IsScrollable())
    {
      scrollableParents.push_back(component);
    }
  }
  return scrollableParents;
}

static std::vector<Component*> GetNonDuplicatedScrollableParents(Accessible* child, Accessible* start)
{
  auto scrollableParentsOfChild = GetScrollableParents(child);
  auto scrollableParentsOfStart = GetScrollableParents(start);

  // find the first different scrollable parent by comparing from top to bottom.
  // since it can not be the same after that, there is no need to compare.
  while(!scrollableParentsOfChild.empty() && !scrollableParentsOfStart.empty() && scrollableParentsOfChild.back() == scrollableParentsOfStart.back())
  {
    scrollableParentsOfChild.pop_back();
    scrollableParentsOfStart.pop_back();
  }

  return scrollableParentsOfChild;
}

} // anonymous namespace

BridgeAccessible::BridgeAccessible()
{
}

void BridgeAccessible::RegisterInterfaces()
{
  DBus::DBusInterfaceDescription desc{Accessible::GetInterfaceName(AtspiInterface::ACCESSIBLE)};
  AddGetPropertyToInterface(desc, "ChildCount", &BridgeAccessible::GetChildCount);
  AddGetPropertyToInterface(desc, "Name", &BridgeAccessible::GetName);
  AddGetPropertyToInterface(desc, "Description", &BridgeAccessible::GetDescription);
  AddGetPropertyToInterface(desc, "Parent", &BridgeAccessible::GetParent);
  AddFunctionToInterface(desc, "GetRole", &BridgeAccessible::GetRole);
  AddFunctionToInterface(desc, "GetRoleName", &BridgeAccessible::GetRoleName);
  AddFunctionToInterface(desc, "GetLocalizedRoleName", &BridgeAccessible::GetLocalizedRoleName);
  AddFunctionToInterface(desc, "GetState", &BridgeAccessible::GetStates);
  AddFunctionToInterface(desc, "GetAttributes", &BridgeAccessible::GetAttributes);
  AddFunctionToInterface(desc, "GetInterfaces", &BridgeAccessible::GetInterfacesAsStrings);
  AddFunctionToInterface(desc, "GetChildAtIndex", &BridgeAccessible::GetChildAtIndex);
  AddFunctionToInterface(desc, "GetChildren", &BridgeAccessible::GetChildren);
  AddFunctionToInterface(desc, "GetIndexInParent", &BridgeAccessible::GetIndexInParent);
  AddFunctionToInterface(desc, "GetNavigableAtPoint", &BridgeAccessible::GetNavigableAtPoint);
  AddFunctionToInterface(desc, "GetNeighbor", &BridgeAccessible::GetNeighbor);
  AddFunctionToInterface(desc, "GetDefaultLabelInfo", &BridgeAccessible::GetDefaultLabelInfo);
  AddFunctionToInterface(desc, "DoGesture", &BridgeAccessible::DoGesture);
  AddFunctionToInterface(desc, "GetReadingMaterial", &BridgeAccessible::GetReadingMaterial);
  AddFunctionToInterface(desc, "GetRelationSet", &BridgeAccessible::GetRelationSet);
  mDbusServer.addInterface("/", desc, true);
}

Accessible* BridgeAccessible::FindSelf() const
{
  return FindCurrentObject();
}

Component* BridgeAccessible::GetObjectInRelation(Accessible* obj, RelationType relationType)
{
  if(!obj)
  {
    return nullptr;
  }

  for(auto& relation : obj->GetRelationSet())
  {
    if(relation.mRelationType == relationType)
    {
      for(auto& target : relation.mTargets)
      {
        auto component = dynamic_cast<Component*>(target);
        if(component)
        {
          return component;
        }
      }
    }
  }
  return nullptr;
}

Component* BridgeAccessible::CalculateNavigableAccessibleAtPoint(Accessible* root, Point point, CoordinateType type, unsigned int maxRecursionDepth)
{
  if(!root || maxRecursionDepth == 0)
  {
    return nullptr;
  }

  auto rootComponent = dynamic_cast<Component*>(root);
  LOG() << "CalculateNavigableAccessibleAtPoint: checking: " << MakeIndent(maxRecursionDepth) << GetComponentInfo(rootComponent);

  if(rootComponent && !rootComponent->IsAccessibleContainingPoint(point, type))
  {
    return nullptr;
  }

  auto children = root->GetChildren();
  for(auto childIt = children.rbegin(); childIt != children.rend(); childIt++)
  {
    //check recursively all children first
    auto result = CalculateNavigableAccessibleAtPoint(*childIt, point, type, maxRecursionDepth - 1);
    if(result)
    {
      return result;
    }
  }

  if(rootComponent)
  {
    //Found a candidate, all its children are already checked
    auto controledBy = GetObjectInRelation(rootComponent, RelationType::CONTROLLED_BY);
    if(!controledBy)
    {
      controledBy = rootComponent;
    }

    if(controledBy->IsProxy() || IsObjectAcceptable(controledBy))
    {
      LOG() << "CalculateNavigableAccessibleAtPoint: found:    " << MakeIndent(maxRecursionDepth) << GetComponentInfo(rootComponent);
      return controledBy;
    }
  }
  return nullptr;
}

BridgeAccessible::ReadingMaterialType BridgeAccessible::GetReadingMaterial()
{
  auto self                     = FindSelf();
  auto findObjectByRelationType = [this, &self](RelationType relationType) {
    auto relations = self->GetRelationSet();
    auto relation  = std::find_if(relations.begin(),
                                 relations.end(),
                                 [relationType](const Dali::Accessibility::Relation& relation) -> bool {
                                   return relation.mRelationType == relationType;
                                 });
    return relations.end() != relation && !relation->mTargets.empty() ? relation->mTargets.back() : nullptr;
  };

  auto        labellingObject = findObjectByRelationType(RelationType::LABELLED_BY);
  std::string labeledByName   = labellingObject ? labellingObject->GetName() : "";

  auto describedByObject = findObjectByRelationType(RelationType::DESCRIBED_BY);

  double currentValue     = 0.0;
  double minimumIncrement = 0.0;
  double maximumValue     = 0.0;
  double minimumValue     = 0.0;
  auto*  valueInterface   = Value::DownCast(self);
  if(valueInterface)
  {
    currentValue     = valueInterface->GetCurrent();
    minimumIncrement = valueInterface->GetMinimumIncrement();
    maximumValue     = valueInterface->GetMaximum();
    minimumValue     = valueInterface->GetMinimum();
  }

  int32_t firstSelectedChildIndex = -1;
  int32_t selectedChildCount      = 0;
  auto*   selfSelectionInterface  = Selection::DownCast(self);
  if(selfSelectionInterface)
  {
    selectedChildCount      = selfSelectionInterface->GetSelectedChildrenCount();
    auto firstSelectedChild = selfSelectionInterface->GetSelectedChild(0);
    if(firstSelectedChild)
    {
      firstSelectedChildIndex = firstSelectedChild->GetIndexInParent();
    }
  }

  auto childCount       = static_cast<int32_t>(self->GetChildCount());
  bool hasCheckBoxChild = false;
  for(auto i = 0u; i < static_cast<size_t>(childCount); ++i)
  {
    auto child = self->GetChildAtIndex(i);
    if(child->GetRole() == Role::CHECK_BOX)
    {
      hasCheckBoxChild = true;
      break;
    }
  }

  auto    atspiRole         = self->GetRole();
  int32_t listChildrenCount = 0;
  if(atspiRole == Role::DIALOG)
  {
    listChildrenCount = GetItemCountOfFirstDescendantContainer(self, Role::LIST, Role::LIST_ITEM, true);
  }
  else if(atspiRole == Role::POPUP_MENU)
  {
    listChildrenCount = GetItemCountOfFirstDescendantContainer(self, Role::POPUP_MENU, Role::MENU_ITEM, false);
  }

  auto*       textInterface         = Text::DownCast(self);
  std::string nameFromTextInterface = "";
  if(textInterface)
  {
    nameFromTextInterface = textInterface->GetText(0, textInterface->GetCharacterCount());
  }

  auto attributes        = self->GetAttributes();
  auto name              = self->GetName();
  auto role              = static_cast<uint32_t>(atspiRole);
  auto states            = self->GetStates();
  auto localizedRoleName = self->GetLocalizedRoleName();
  auto description       = self->GetDescription();
  auto indexInParent     = static_cast<int32_t>(self->GetIndexInParent());

  auto  parent                   = self->GetParent();
  auto  parentRole               = static_cast<uint32_t>(parent ? parent->GetRole() : Role{});
  auto  parentChildCount         = parent ? static_cast<int32_t>(parent->GetChildCount()) : 0;
  auto  parentStateSet           = parent ? parent->GetStates() : States{};
  bool  isSelectedInParent       = false;
  auto* parentSelectionInterface = Selection::DownCast(parent);
  if(parentSelectionInterface)
  {
    isSelectedInParent = parentSelectionInterface->IsChildSelected(indexInParent);
  }

  return {
    attributes,
    name,
    labeledByName,
    nameFromTextInterface,
    role,
    states,
    localizedRoleName,
    childCount,
    currentValue,
    minimumIncrement,
    maximumValue,
    minimumValue,
    description,
    indexInParent,
    isSelectedInParent,
    hasCheckBoxChild,
    listChildrenCount,
    firstSelectedChildIndex,
    parent,
    parentStateSet,
    parentChildCount,
    parentRole,
    selectedChildCount,
    describedByObject};
}

DBus::ValueOrError<bool> BridgeAccessible::DoGesture(Dali::Accessibility::Gesture type, int32_t startPositionX, int32_t startPositionY, int32_t endPositionX, int32_t endPositionY, Dali::Accessibility::GestureState state, uint32_t eventTime)
{
  // Please be aware of sending GestureInfo point in the different order with parameters
  return FindSelf()->DoGesture(Dali::Accessibility::GestureInfo{type, startPositionX, endPositionX, startPositionY, endPositionY, state, eventTime});
}

DBus::ValueOrError<Accessible*, uint8_t, Accessible*> BridgeAccessible::GetNavigableAtPoint(int32_t x, int32_t y, uint32_t coordinateType)
{
  Accessible* deputy     = nullptr;
  auto        accessible = FindSelf();
  auto        cType      = static_cast<CoordinateType>(coordinateType);

  x -= mData->mExtentsOffset.first;
  y -= mData->mExtentsOffset.second;

  LOG() << "GetNavigableAtPoint: " << x << ", " << y << " type: " << coordinateType;
  auto component = CalculateNavigableAccessibleAtPoint(accessible, {x, y}, cType, GET_NAVIGABLE_AT_POINT_MAX_RECURSION_DEPTH);
  bool recurse   = false;
  if(component)
  {
    recurse = component->IsProxy();
  }
  //TODO: add deputy
  return {component, recurse, deputy};
}

Accessible* BridgeAccessible::GetCurrentlyHighlighted()
{
  //TODO: add currently highlighted object
  return nullptr;
}

std::vector<Component*> BridgeAccessible::GetValidChildren(const std::vector<Accessible*>& children, Accessible* start)
{
  if(children.empty())
  {
    return {};
  }

  std::vector<Component*> vec;

  Dali::Rect<> scrollableParentExtents;
  auto         nonDuplicatedScrollableParents = GetNonDuplicatedScrollableParents(children.front(), start);
  if(!nonDuplicatedScrollableParents.empty())
  {
    scrollableParentExtents = nonDuplicatedScrollableParents.front()->GetExtents(CoordinateType::WINDOW);
  }

  for(auto child : children)
  {
    auto* component = dynamic_cast<Component*>(child);
    if(component)
    {
      if(nonDuplicatedScrollableParents.empty() || scrollableParentExtents.Intersects(component->GetExtents(CoordinateType::WINDOW)))
      {
        vec.push_back(component);
      }
    }
  }

  return vec;
}

void BridgeAccessible::SortChildrenFromTopLeft(std::vector<Dali::Accessibility::Component*>& children)
{
  if(children.empty())
  {
    return;
  }

  std::vector<Component*> sortedChildren;

  std::sort(children.begin(), children.end(), &SortVertically);

  for(auto& line : SplitLines(children))
  {
    std::sort(line.begin(), line.end(), &SortHorizontally);
    sortedChildren.insert(sortedChildren.end(), line.begin(), line.end());
  }

  children = sortedChildren;
}

template<class T>
struct CycleDetection
{
  CycleDetection(const T value)
  : mKey(value),
    mCurrentSearchSize(1),
    mCounter(1)
  {
  }

  bool Check(const T value)
  {
    if(mKey == value)
    {
      return true;
    }

    if(--mCounter == 0)
    {
      mCurrentSearchSize <<= 1;
      if(mCurrentSearchSize == 0)
      {
        return true; // UNDEFINED BEHAVIOR
      }
      mCounter = mCurrentSearchSize;
      mKey     = value;
    }
    return false;
  }

  T            mKey;
  unsigned int mCurrentSearchSize;
  unsigned int mCounter;
};

Accessible* BridgeAccessible::GetNextNonDefunctSibling(Accessible* obj, Accessible* start, unsigned char forward)
{
  if(!obj)
  {
    return nullptr;
  }

  auto parent = obj->GetParent();
  if(!parent)
  {
    return nullptr;
  }
  else if(parent->IsProxy())
  {
    return parent;
  }

  auto children = GetValidChildren(parent->GetChildren(), start);
  SortChildrenFromTopLeft(children);

  unsigned int childrenCount = children.size();
  if(childrenCount == 0)
  {
    return nullptr;
  }

  unsigned int current = 0;
  for(; current < childrenCount && children[current] != obj; ++current)
  {
  }

  if(current >= childrenCount)
  {
    return nullptr;
  }

  forward ? ++current : --current;
  auto ret = FindNonDefunctChild(children, current, forward);
  return ret;
}

Accessible* BridgeAccessible::FindNonDefunctSibling(bool& areAllChildrenVisited, Accessible* node, Accessible* start, Accessible* root, unsigned char forward)
{
  while(true)
  {
    Accessible* sibling = GetNextNonDefunctSibling(node, start, forward);
    if(sibling)
    {
      node                  = sibling;
      areAllChildrenVisited = false; // Note that this is passed by non-const reference, so it is the caller that can determine whether this search exhausted all children.
      break;
    }
    // walk up...
    node = node->GetParent();
    if(node == nullptr || node == root)
    {
      return nullptr;
    }

    // in backward traversing stop the walk up on parent
    if(!forward)
    {
      break;
    }
  }

  return node;
}

Accessible* BridgeAccessible::CalculateNeighbor(Accessible* root, Accessible* start, unsigned char forward, BridgeAccessible::NeighborSearchMode searchMode)
{
  if(start && CheckChainEndWithAttribute(start, forward))
  {
    return start;
  }
  if(root && root->GetStates()[State::DEFUNCT])
  {
    return NULL;
  }
  if(start && start->GetStates()[State::DEFUNCT])
  {
    start   = NULL;
    forward = 1;
  }

  if(searchMode == BridgeAccessible::NeighborSearchMode::RECURSE_TO_OUTSIDE)
  {
    searchMode = BridgeAccessible::NeighborSearchMode::CONTINUE_AFTER_FAILED_RECURSION;
  }

  Accessible* node = start ? start : root;
  if(!node)
  {
    return nullptr;
  }

  // initialization of all-children-visited flag for start node - we assume
  // that when we begin at start node and we navigate backward, then all children
  // are visited, so navigation will ignore start's children and go to
  // previous sibling available.
  // Regarding condtion (start != root):
  // The last object can be found only if areAllChildrenVisited is false.
  // The start is same with root, when looking for the last object.
  bool areAllChildrenVisited = (start != root) && (searchMode != BridgeAccessible::NeighborSearchMode::RECURSE_FROM_ROOT && !forward);

  // true, if starting element should be ignored. this is only used in rare case of
  // recursive search failing to find an object.
  // consider tree, where element A on bus BUS_A has child B on bus BUS_B. when going "next" from
  // element A algorithm has to descend into BUS_B and search element B and its children. this is done
  // by returning to our caller object B with special flag set (meaning - continue the search from B on bus BUS_B).
  // if next object will be found there (on BUS_B), then search ends. but if not, then our caller will find it out
  // and will call us again with object A and flag searchMode set to NEIGHBOR_SEARCH_MODE_CONTINUE_AFTER_FAILED_RECURSING.
  // this flag means, that object A was already checked previously and we should skip it and its children.
  bool forceNext = (searchMode == BridgeAccessible::NeighborSearchMode::CONTINUE_AFTER_FAILED_RECURSION);

  CycleDetection<Accessible*> cycleDetection(node);
  while(node)
  {
    if(node->GetStates()[State::DEFUNCT])
    {
      return nullptr;
    }

    // always accept proxy object from different world
    if(!forceNext && node->IsProxy())
    {
      return node;
    }

    auto children = GetValidChildren(node->GetChildren(), start);
    SortChildrenFromTopLeft(children);

    // do accept:
    // 1. not start node
    // 2. parent after all children in backward traversing
    // 3. Nodes with roles: ATSPI_ROLE_PAGE_TAB, ATSPI_ROLE_POPUP_MENU and ATSPI_ROLE_DIALOG, only when looking for first or last element.
    //    Objects with those roles shouldnt be reachable, when navigating next / prev.
    bool areAllChildrenVisitedOrMovingForward = (children.size() == 0 || forward || areAllChildrenVisited);

    if(!forceNext && node != start && areAllChildrenVisitedOrMovingForward && IsObjectAcceptable(node))
    {
      if(start == NULL || IsRoleAcceptableWhenNavigatingNextPrev(node))
      {
        return node;
      }
    }

    Accessible* nextRelatedInDirection = !forceNext ? GetObjectInRelation(node, forward ? RelationType::FLOWS_TO : RelationType::FLOWS_FROM) : nullptr;
    if(nextRelatedInDirection && start && start->GetStates()[State::DEFUNCT])
    {
      nextRelatedInDirection = NULL;
    }

    unsigned char wantCycleDetection = 0;
    if(nextRelatedInDirection)
    {
      node               = nextRelatedInDirection;
      wantCycleDetection = 1;
    }
    else
    {
      auto child = !forceNext && !areAllChildrenVisited ? FindNonDefunctChildWithDepthFirstSearch(node, children, forward) : nullptr;
      if(child)
      {
        wantCycleDetection = 1;
      }
      else
      {
        if(!forceNext && node == root)
        {
          return NULL;
        }
        areAllChildrenVisited = true;
        child                 = FindNonDefunctSibling(areAllChildrenVisited, node, start, root, forward);
      }
      node = child;
    }

    forceNext = 0;
    if(wantCycleDetection && cycleDetection.Check(node))
    {
      return NULL;
    }
  }
  return NULL;
}

DBus::ValueOrError<Accessible*, uint8_t> BridgeAccessible::GetNeighbor(std::string rootPath, int32_t direction, int32_t searchMode)
{
  auto          start      = FindSelf();
  auto          root       = !rootPath.empty() ? Find(StripPrefix(rootPath)) : nullptr;
  auto          accessible = CalculateNeighbor(root, start, direction == 1, static_cast<NeighborSearchMode>(searchMode));
  unsigned char recurse    = 0;
  if(accessible)
  {
    recurse = accessible->IsProxy();
  }
  return {accessible, recurse};
}

Accessible* BridgeAccessible::GetParent()
{
  // NOTE: currently bridge supports single application root element.
  // only element set as application root might return nullptr from GetParent
  // if you want more, then you need to change setApplicationRoot to
  // add/remove ApplicationRoot and make roots a vector.
  auto parent = FindSelf()->GetParent();

  return parent;
}

DBus::ValueOrError<std::vector<Accessible*>> BridgeAccessible::GetChildren()
{
  return FindSelf()->GetChildren();
}

std::string BridgeAccessible::GetDescription()
{
  return FindSelf()->GetDescription();
}

DBus::ValueOrError<uint32_t> BridgeAccessible::GetRole()
{
  return static_cast<unsigned int>(FindSelf()->GetRole());
}

DBus::ValueOrError<std::string> BridgeAccessible::GetRoleName()
{
  return FindSelf()->GetRoleName();
}

DBus::ValueOrError<std::string> BridgeAccessible::GetLocalizedRoleName()
{
  return FindSelf()->GetLocalizedRoleName();
}

DBus::ValueOrError<int32_t> BridgeAccessible::GetIndexInParent()
{
  return FindSelf()->GetIndexInParent();
}

DBus::ValueOrError<std::array<uint32_t, 2>> BridgeAccessible::GetStates()
{
  return FindSelf()->GetStates().GetRawData();
}

DBus::ValueOrError<std::unordered_map<std::string, std::string>> BridgeAccessible::GetAttributes()
{
  std::unordered_map<std::string, std::string> attributes = FindSelf()->GetAttributes();

  if(mIsScreenReaderSuppressed)
  {
    attributes.insert({"suppress-screen-reader", "true"});
  }

  return attributes;
}

DBus::ValueOrError<std::vector<std::string>> BridgeAccessible::GetInterfacesAsStrings()
{
  return FindSelf()->GetInterfacesAsStrings();
}

int BridgeAccessible::GetChildCount()
{
  return FindSelf()->GetChildCount();
}

DBus::ValueOrError<Accessible*> BridgeAccessible::GetChildAtIndex(int index)
{
  if(index < 0)
  {
    throw std::domain_error{"negative index (" + std::to_string(index) + ")"};
  }
  return FindSelf()->GetChildAtIndex(static_cast<size_t>(index));
}

std::string BridgeAccessible::GetName()
{
  return FindSelf()->GetName();
}

DBus::ValueOrError<Accessible*, uint32_t, std::unordered_map<std::string, std::string>> BridgeAccessible::GetDefaultLabelInfo()
{
  auto* defaultLabel = GetDefaultLabel(FindSelf());
  DALI_ASSERT_DEBUG(defaultLabel);

  // By default, the text is taken from navigation context root's accessibility properties name and description.
  return {defaultLabel, static_cast<uint32_t>(defaultLabel->GetRole()), defaultLabel->GetAttributes()};
}

DBus::ValueOrError<std::vector<BridgeAccessible::Relation>> BridgeAccessible::GetRelationSet()
{
  auto                                    relations = FindSelf()->GetRelationSet();
  std::vector<BridgeAccessible::Relation> ret;

  for(auto& it : relations)
  {
    ret.emplace_back(Relation{static_cast<uint32_t>(it.mRelationType), it.mTargets});
  }

  return ret;
}