Merge "[AT-SPI] Rework intercepting key events" into devel/master
[platform/core/uifw/dali-adaptor.git] / dali / internal / accessibility / bridge / bridge-base.h
1 #ifndef DALI_INTERNAL_ACCESSIBILITY_BRIDGE_BASE_H
2 #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_BASE_H
3
4 /*
5  * Copyright (c) 2021 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  */
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/actors/layer.h>
23 #include <dali/public-api/dali-adaptor-version.h>
24 #include <dali/public-api/object/weak-handle.h>
25 #include <dali/public-api/signals/connection-tracker.h>
26 #include <memory>
27 #include <tuple>
28
29 // INTERNAL INCLUDES
30 #include <dali/devel-api/adaptor-framework/proxy-accessible.h>
31 #include <dali/devel-api/adaptor-framework/window-devel.h>
32 #include <dali/devel-api/atspi-interfaces/accessible.h>
33 #include <dali/devel-api/atspi-interfaces/application.h>
34 #include <dali/devel-api/atspi-interfaces/collection.h>
35 #include <dali/devel-api/atspi-interfaces/socket.h>
36 #include <dali/internal/accessibility/bridge/accessibility-common.h>
37
38 /**
39  * @brief The ApplicationAccessible class is to define Accessibility Application.
40  */
41 class ApplicationAccessible : public virtual Dali::Accessibility::Accessible,
42                               public virtual Dali::Accessibility::Application,
43                               public virtual Dali::Accessibility::Collection,
44                               public virtual Dali::Accessibility::Component,
45                               public virtual Dali::Accessibility::Socket
46 {
47 public:
48   Dali::Accessibility::ProxyAccessible          mParent;
49   std::vector<Dali::Accessibility::Accessible*> mChildren;
50   std::string                                   mName;
51   std::string                                   mToolkitName{"dali"};
52   bool                                          mIsEmbedded{false};
53
54   std::string GetName() const override
55   {
56     return mName;
57   }
58
59   std::string GetDescription() const override
60   {
61     return "";
62   }
63
64   Dali::Accessibility::Accessible* GetParent() override
65   {
66     return &mParent;
67   }
68
69   size_t GetChildCount() const override
70   {
71     return mChildren.size();
72   }
73
74   std::vector<Dali::Accessibility::Accessible*> GetChildren() override
75   {
76     return mChildren;
77   }
78
79   Dali::Accessibility::Accessible* GetChildAtIndex(size_t index) override
80   {
81     auto size = mChildren.size();
82     if(index >= size)
83     {
84       throw std::domain_error{"invalid index " + std::to_string(index) + " for object with " + std::to_string(size) + " children"};
85     }
86     return mChildren[index];
87   }
88
89   size_t GetIndexInParent() override
90   {
91     if(mIsEmbedded)
92     {
93       return 0u;
94     }
95
96     throw std::domain_error{"can't call GetIndexInParent on application object"};
97   }
98
99   Dali::Accessibility::Role GetRole() const override
100   {
101     return Dali::Accessibility::Role::APPLICATION;
102   }
103
104   Dali::Accessibility::States GetStates() override
105   {
106     Dali::Accessibility::States result;
107
108     for(auto* child : mChildren)
109     {
110       result = result | child->GetStates();
111     }
112
113     // The Application object should never have the SENSITIVE state
114     result[Dali::Accessibility::State::SENSITIVE] = false;
115
116     return result;
117   }
118
119   Dali::Accessibility::Attributes GetAttributes() const override
120   {
121     return {};
122   }
123
124   /**
125    * @brief Gets the Accessible object from the window.
126    *
127    * @param[in] window The window to find
128    * @return Null if mChildren is empty, otherwise the Accessible object
129    * @note Currently, the default window would be returned when mChildren is not empty.
130    */
131   Dali::Accessibility::Accessible* GetWindowAccessible(Dali::Window window)
132   {
133     if(mChildren.empty())
134     {
135       return nullptr;
136     }
137
138     Dali::Layer rootLayer = window.GetRootLayer();
139
140     // Find a child which is related to the window.
141     for(auto i = 0u; i < mChildren.size(); ++i)
142     {
143       if(rootLayer == mChildren[i]->GetInternalActor())
144       {
145         return mChildren[i];
146       }
147     }
148
149     // If can't find its children, return the default window.
150     return mChildren[0];
151   }
152
153   bool DoGesture(const Dali::Accessibility::GestureInfo& gestureInfo) override
154   {
155     return false;
156   }
157
158   std::vector<Dali::Accessibility::Relation> GetRelationSet() override
159   {
160     return {};
161   }
162
163   Dali::Actor GetInternalActor() override
164   {
165     return Dali::Actor{};
166   }
167
168   Dali::Accessibility::Address GetAddress() const override
169   {
170     return {"", "root"};
171   }
172
173   // Application
174
175   std::string GetToolkitName() const override
176   {
177     return mToolkitName;
178   }
179
180   std::string GetVersion() const override
181   {
182     return std::to_string(Dali::ADAPTOR_MAJOR_VERSION) + "." + std::to_string(Dali::ADAPTOR_MINOR_VERSION);
183   }
184
185   // Socket
186
187   Dali::Accessibility::Address Embed(Dali::Accessibility::Address plug) override
188   {
189     mIsEmbedded = true;
190     mParent.SetAddress(plug);
191
192     return GetAddress();
193   }
194
195   void Unembed(Dali::Accessibility::Address plug) override
196   {
197     if(mParent.GetAddress() == plug)
198     {
199       mIsEmbedded = false;
200       mParent.SetAddress({});
201       Dali::Accessibility::Bridge::GetCurrentBridge()->SetExtentsOffset(0, 0);
202     }
203   }
204
205   void SetOffset(std::int32_t x, std::int32_t y) override
206   {
207     if(!mIsEmbedded)
208     {
209       return;
210     }
211
212     Dali::Accessibility::Bridge::GetCurrentBridge()->SetExtentsOffset(x, y);
213   }
214
215   // Component
216
217   Dali::Rect<> GetExtents(Dali::Accessibility::CoordinateType type) const override
218   {
219     using limits = std::numeric_limits<float>;
220
221     float minX = limits::max();
222     float minY = limits::max();
223     float maxX = limits::min();
224     float maxY = limits::min();
225
226     for(Dali::Accessibility::Accessible* child : mChildren)
227     {
228       auto* component = Dali::Accessibility::Component::DownCast(child);
229       if(!component)
230       {
231         continue;
232       }
233
234       auto extents = component->GetExtents(type);
235
236       minX = std::min(minX, extents.x);
237       minY = std::min(minY, extents.y);
238       maxX = std::max(maxX, extents.x + extents.width);
239       maxY = std::max(maxY, extents.y + extents.height);
240     }
241
242     return {minX, minY, maxX - minX, maxY - minY};
243   }
244
245   Dali::Accessibility::ComponentLayer GetLayer() const override
246   {
247     return Dali::Accessibility::ComponentLayer::WINDOW;
248   }
249
250   std::int16_t GetMdiZOrder() const override
251   {
252     return 0;
253   }
254
255   bool GrabFocus() override
256   {
257     return false;
258   }
259
260   double GetAlpha() const override
261   {
262     return 0.0;
263   }
264
265   bool GrabHighlight() override
266   {
267     return false;
268   }
269
270   bool ClearHighlight() override
271   {
272     return false;
273   }
274
275   bool IsScrollable() const override
276   {
277     return false;
278   }
279 };
280
281 /**
282  * @brief Enumeration for CoalescableMessages.
283  */
284 enum class CoalescableMessages
285 {
286   BOUNDS_CHANGED, ///< Bounds changed
287   SET_OFFSET, ///< Set offset
288   POST_RENDER, ///< Post render
289 };
290
291 // Custom specialization of std::hash
292 namespace std
293 {
294 template<>
295 struct hash<std::pair<CoalescableMessages, Dali::Accessibility::Accessible*>>
296 {
297   size_t operator()(std::pair<CoalescableMessages, Dali::Accessibility::Accessible*> value) const
298   {
299     return (static_cast<size_t>(value.first) * 131) ^ reinterpret_cast<size_t>(value.second);
300   }
301 };
302 } // namespace std
303
304 /**
305  * @brief The BridgeBase class is basic class for Bridge functions.
306  */
307 class BridgeBase : public Dali::Accessibility::Bridge, public Dali::ConnectionTracker
308 {
309   std::unordered_map<std::pair<CoalescableMessages, Dali::Accessibility::Accessible*>, std::tuple<unsigned int, unsigned int, std::function<void()>>> mCoalescableMessages;
310
311   /**
312    * @brief Removes all CoalescableMessages using Tick signal.
313    *
314    * @return False if mCoalescableMessages is empty, otherwise true.
315    */
316   bool TickCoalescableMessages();
317
318 public:
319   /**
320    * @brief Adds CoalescableMessages, Accessible, and delay time to mCoalescableMessages.
321    *
322    * @param[in] kind CoalescableMessages enum value
323    * @param[in] obj Accessible object
324    * @param[in] delay The delay time
325    * @param[in] functor The function to be called // NEED TO UPDATE!
326    */
327   void AddCoalescableMessage(CoalescableMessages kind, Dali::Accessibility::Accessible* obj, float delay, std::function<void()> functor);
328
329   /**
330    * @brief Callback when the visibility of the window is changed.
331    *
332    * @param[in] window The window to be changed
333    * @param[in] visible The visibility of the window
334    */
335   void OnWindowVisibilityChanged(Dali::Window window, bool visible);
336
337   /**
338    * @brief Callback when the window focus is changed.
339    *
340    * @param[in] window The window whose focus is changed
341    * @param[in] focusIn Whether the focus is in/out
342    */
343   void OnWindowFocusChanged(Dali::Window window, bool focusIn);
344
345   /**
346    * @copydoc Dali::Accessibility::Bridge::GetBusName()
347    */
348   const std::string& GetBusName() const override;
349
350   /**
351    * @copydoc Dali::Accessibility::Bridge::AddTopLevelWindow()
352    */
353   void AddTopLevelWindow(Dali::Accessibility::Accessible* windowAccessible) override;
354
355   /**
356    * @copydoc Dali::Accessibility::Bridge::RemoveTopLevelWindow()
357    */
358   void RemoveTopLevelWindow(Dali::Accessibility::Accessible* windowAccessible) override;
359
360   /**
361    * @copydoc Dali::Accessibility::Bridge::RegisterDefaultLabel()
362    */
363   void RegisterDefaultLabel(Dali::Accessibility::Accessible* object) override;
364
365   /**
366    * @copydoc Dali::Accessibility::Bridge::UnregisterDefaultLabel()
367    */
368   void UnregisterDefaultLabel(Dali::Accessibility::Accessible* object) override;
369
370   /**
371    * @copydoc Dali::Accessibility::Bridge::GetDefaultLabel()
372    */
373   Dali::Accessibility::Accessible* GetDefaultLabel(Dali::Accessibility::Accessible* root) const override;
374
375   /**
376    * @copydoc Dali::Accessibility::Bridge::GetApplication()
377    */
378   Dali::Accessibility::Accessible* GetApplication() const override
379   {
380     return &mApplication;
381   }
382
383   /**
384    * @brief Adds function to dbus interface.
385    */
386   template<typename SELF, typename... RET, typename... ARGS>
387   void AddFunctionToInterface(
388     DBus::DBusInterfaceDescription& desc, const std::string& funcName, DBus::ValueOrError<RET...> (SELF::*funcPtr)(ARGS...))
389   {
390     if(auto self = dynamic_cast<SELF*>(this))
391       desc.addMethod<DBus::ValueOrError<RET...>(ARGS...)>(
392         funcName,
393         [=](ARGS... args) -> DBus::ValueOrError<RET...> {
394           try
395           {
396             return (self->*funcPtr)(std::move(args)...);
397           }
398           catch(std::domain_error& e)
399           {
400             return DBus::Error{e.what()};
401           }
402         });
403   }
404
405   /**
406    * @brief Adds 'Get' property to dbus interface.
407    */
408   template<typename T, typename SELF>
409   void AddGetPropertyToInterface(DBus::DBusInterfaceDescription& desc,
410                                  const std::string&              funcName,
411                                  T (SELF::*funcPtr)())
412   {
413     if(auto self = dynamic_cast<SELF*>(this))
414       desc.addProperty<T>(funcName,
415                           [=]() -> DBus::ValueOrError<T> {
416                             try
417                             {
418                               return (self->*funcPtr)();
419                             }
420                             catch(std::domain_error& e)
421                             {
422                               return DBus::Error{e.what()};
423                             }
424                           },
425                           {});
426   }
427
428   /**
429    * @brief Adds 'Set' property to dbus interface.
430    */
431   template<typename T, typename SELF>
432   void AddSetPropertyToInterface(DBus::DBusInterfaceDescription& desc,
433                                  const std::string&              funcName,
434                                  void (SELF::*funcPtr)(T))
435   {
436     if(auto self = dynamic_cast<SELF*>(this))
437       desc.addProperty<T>(funcName, {}, [=](T t) -> DBus::ValueOrError<void> {
438         try
439         {
440           (self->*funcPtr)(std::move(t));
441           return {};
442         }
443         catch(std::domain_error& e)
444         {
445           return DBus::Error{e.what()};
446         }
447       });
448   }
449
450   /**
451    * @brief Adds 'Set' and 'Get' properties to dbus interface.
452    */
453   template<typename T, typename T1, typename SELF>
454   void AddGetSetPropertyToInterface(DBus::DBusInterfaceDescription& desc,
455                                     const std::string&              funcName,
456                                     T1 (SELF::*funcPtrGet)(),
457                                     DBus::ValueOrError<void> (SELF::*funcPtrSet)(T))
458   {
459     if(auto self = dynamic_cast<SELF*>(this))
460       desc.addProperty<T>(
461         funcName,
462         [=]() -> DBus::ValueOrError<T> {
463           try
464           {
465             return (self->*funcPtrGet)();
466           }
467           catch(std::domain_error& e)
468           {
469             return DBus::Error{e.what()};
470           }
471         },
472         [=](T t) -> DBus::ValueOrError<void> {
473           try
474           {
475             (self->*funcPtrSet)(std::move(t));
476             return {};
477           }
478           catch(std::domain_error& e)
479           {
480             return DBus::Error{e.what()};
481           }
482         });
483   }
484
485   /**
486    * @brief Adds 'Get' and 'Set' properties to dbus interface.
487    */
488   template<typename T, typename T1, typename SELF>
489   void AddGetSetPropertyToInterface(DBus::DBusInterfaceDescription& desc,
490                                     const std::string&              funcName,
491                                     T1 (SELF::*funcPtrGet)(),
492                                     void (SELF::*funcPtrSet)(T))
493   {
494     if(auto self = dynamic_cast<SELF*>(this))
495       desc.addProperty<T>(
496         funcName,
497         [=]() -> DBus::ValueOrError<T> {
498           try
499           {
500             return (self->*funcPtrGet)();
501           }
502           catch(std::domain_error& e)
503           {
504             return DBus::Error{e.what()};
505           }
506         },
507         [=](T t) -> DBus::ValueOrError<void> {
508           try
509           {
510             (self->*funcPtrSet)(std::move(t));
511             return {};
512           }
513           catch(std::domain_error& e)
514           {
515             return DBus::Error{e.what()};
516           }
517         });
518   }
519
520   /**
521    * @brief Gets the string of the path excluding the specified prefix.
522    *
523    * @param path The path to get
524    * @return The string stripped of the specific prefix
525    */
526   static std::string StripPrefix(const std::string& path);
527
528   /**
529    * @brief Finds the Accessible object according to the path.
530    *
531    * @param[in] path The path for Accessible object
532    * @return The Accessible object corresponding to the path
533    */
534   Dali::Accessibility::Accessible* Find(const std::string& path) const;
535
536   /**
537    * @brief Finds the Accessible object with the given address.
538    *
539    * @param[in] ptr The unique Address of the object
540    * @return The Accessible object corresponding to the path
541    */
542   Dali::Accessibility::Accessible* Find(const Dali::Accessibility::Address& ptr) const;
543
544   /**
545    * @brief Returns the target object of the currently executed DBus method call.
546    *
547    * @return The Accessible object
548    * @note When a DBus method is called on some object, this target object (`currentObject`) is temporarily saved by the bridge,
549    * because DBus handles the invocation target separately from the method arguments.
550    * We then use the saved object inside the 'glue' method (e.g. BridgeValue::GetMinimum)
551    * to call the equivalent method on the respective C++ object (this could be ScrollBar::AccessibleImpl::GetMinimum in the example given).
552    */
553   Dali::Accessibility::Accessible* FindCurrentObject() const;
554
555   /**
556    * @brief Returns the target object of the currently executed DBus method call.
557    *
558    * This method tries to downcast the return value of FindCurrentObject() to the requested type,
559    * issuing an error reply to the DBus caller if the requested type is not implemented. Whether
560    * a given type is implemented is decided based on the return value of Accessible::GetInterfaces()
561    * for the current object.
562    *
563    * @tparam I The requested AT-SPI interface
564    * @return The Accessible object (cast to a more derived type)
565    *
566    * @see FindCurrentObject()
567    * @see Dali::Accessibility::AtspiInterface
568    * @see Dali::Accessibility::AtspiInterfaceType
569    * @see Dali::Accessibility::Accessible::GetInterfaces()
570    */
571   template<Dali::Accessibility::AtspiInterface I>
572   auto* FindCurrentObjectWithInterface() const
573   {
574     using Type = Dali::Accessibility::AtspiInterfaceType<I>;
575
576     Type* result;
577     auto* currentObject = FindCurrentObject();
578     DALI_ASSERT_DEBUG(currentObject); // FindCurrentObject() throws domain_error
579
580     if(!(result = Dali::Accessibility::Accessible::DownCast<I>(currentObject)))
581     {
582       std::stringstream s;
583
584       s << "Object " << currentObject->GetAddress().ToString();
585       s << " does not implement ";
586       s << Dali::Accessibility::Accessible::GetInterfaceName(I);
587
588       throw std::domain_error{s.str()};
589     }
590
591     return result;
592   }
593
594   /**
595    * @copydoc Dali::Accessibility::Bridge::FindByPath()
596    */
597   Dali::Accessibility::Accessible* FindByPath(const std::string& name) const override;
598
599   /**
600    * @copydoc Dali::Accessibility::Bridge::SetApplicationName()
601    */
602   void SetApplicationName(std::string name) override
603   {
604     mApplication.mName = std::move(name);
605   }
606
607   /**
608    * @copydoc Dali::Accessibility::Bridge::SetToolkitName()
609    */
610   void SetToolkitName(std::string_view toolkitName) override
611   {
612     mApplication.mToolkitName = std::string{toolkitName};
613   }
614
615 protected:
616   // We use a weak handle in order not to keep a window alive forever if someone forgets to UnregisterDefaultLabel()
617   using DefaultLabelType  = std::pair<Dali::WeakHandle<Dali::Window>, Dali::Accessibility::Accessible*>;
618   using DefaultLabelsType = std::list<DefaultLabelType>;
619
620   mutable ApplicationAccessible mApplication;
621   DefaultLabelsType             mDefaultLabels;
622   bool                          mIsScreenReaderSuppressed = false;
623
624 private:
625   /**
626    * @brief Sets an ID.
627    * @param[in] id An ID (integer value)
628    */
629   void SetId(int id);
630
631   /**
632    * @brief Gets the ID.
633    * @return The ID to be set
634    */
635   int GetId();
636
637   /**
638    * @brief Update registered events.
639    */
640   void UpdateRegisteredEvents();
641
642   using CacheElementType = std::tuple<
643     Dali::Accessibility::Address,
644     Dali::Accessibility::Address,
645     Dali::Accessibility::Address,
646     std::vector<Dali::Accessibility::Address>,
647     std::vector<std::string>,
648     std::string,
649     Dali::Accessibility::Role,
650     std::string,
651     std::array<uint32_t, 2>>;
652
653   /**
654    * @brief Gets Items  // NEED TO UPDATE!
655    *
656    * @return
657    */
658   DBus::ValueOrError<std::vector<CacheElementType>> GetItems();
659
660   /**
661    * @brief Creates CacheElement.
662    *
663    * CreateCacheElement method works for GetItems which is a part of ATSPI protocol.
664    * ATSPI client library (libatspi from at-spi2-core) depending on cacheing policy configuration uses GetItems
665    * to pre-load entire accessible tree from application to its own cache in single dbus call.
666    * Otherwise the particular nodes in a tree are cached lazily when client library tries to access them.
667    * @param item Accessible to get information
668    * @return The elements to be cached
669    */
670   CacheElementType CreateCacheElement(Dali::Accessibility::Accessible* item);
671
672   /**
673    * @brief Removes expired elements from the default label collection.
674    */
675   void CompressDefaultLabels();
676
677   /**
678    * @brief Gets the window to which this accessible belongs (or an empty handle).
679    *
680    * @param accessible The accessible
681    * @return The window
682    */
683   static Dali::WeakHandle<Dali::Window> GetWindow(Dali::Accessibility::Accessible* accessible);
684
685 protected:
686   BridgeBase();
687   virtual ~BridgeBase();
688
689   /**
690    * @copydoc Dali::Accessibility::Bridge::ForceUp()
691    */
692   ForceUpResult ForceUp() override;
693
694   /**
695    * @copydoc Dali::Accessibility::Bridge::ForceDown()
696    */
697   void ForceDown() override;
698
699   DBus::DBusServer           mDbusServer;
700   DBusWrapper::ConnectionPtr mConnectionPtr;
701   int                        mId = 0;
702   DBus::DBusClient           mRegistry;
703   bool                       IsBoundsChangedEventAllowed{false};
704 };
705
706 #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_BASE_H