[AT-SPI] Add compression for STATE_CHANGED event
[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   STATE_CHANGED_BEGIN = 500, ///< State changed (begin of reserved range)
290   STATE_CHANGED_END   = 599, ///< State changed (end of reserved range)
291   // <- any enum value declared here will have the value 600
292 };
293
294 // Custom specialization of std::hash
295 namespace std
296 {
297 template<>
298 struct hash<std::pair<CoalescableMessages, Dali::Accessibility::Accessible*>>
299 {
300   size_t operator()(std::pair<CoalescableMessages, Dali::Accessibility::Accessible*> value) const
301   {
302     return (static_cast<size_t>(value.first) * 131) ^ reinterpret_cast<size_t>(value.second);
303   }
304 };
305 } // namespace std
306
307 /**
308  * @brief The BridgeBase class is basic class for Bridge functions.
309  */
310 class BridgeBase : public Dali::Accessibility::Bridge, public Dali::ConnectionTracker
311 {
312   std::unordered_map<std::pair<CoalescableMessages, Dali::Accessibility::Accessible*>, std::tuple<unsigned int, unsigned int, std::function<void()>>> mCoalescableMessages;
313
314   /**
315    * @brief Removes all CoalescableMessages using Tick signal.
316    *
317    * @return False if mCoalescableMessages is empty, otherwise true.
318    */
319   bool TickCoalescableMessages();
320
321 public:
322   /**
323    * @brief Adds CoalescableMessages, Accessible, and delay time to mCoalescableMessages.
324    *
325    * @param[in] kind CoalescableMessages enum value
326    * @param[in] obj Accessible object
327    * @param[in] delay The delay time
328    * @param[in] functor The function to be called // NEED TO UPDATE!
329    */
330   void AddCoalescableMessage(CoalescableMessages kind, Dali::Accessibility::Accessible* obj, float delay, std::function<void()> functor);
331
332   /**
333    * @brief Callback when the visibility of the window is changed.
334    *
335    * @param[in] window The window to be changed
336    * @param[in] visible The visibility of the window
337    */
338   void OnWindowVisibilityChanged(Dali::Window window, bool visible);
339
340   /**
341    * @brief Callback when the window focus is changed.
342    *
343    * @param[in] window The window whose focus is changed
344    * @param[in] focusIn Whether the focus is in/out
345    */
346   void OnWindowFocusChanged(Dali::Window window, bool focusIn);
347
348   /**
349    * @copydoc Dali::Accessibility::Bridge::GetBusName()
350    */
351   const std::string& GetBusName() const override;
352
353   /**
354    * @copydoc Dali::Accessibility::Bridge::AddTopLevelWindow()
355    */
356   void AddTopLevelWindow(Dali::Accessibility::Accessible* windowAccessible) override;
357
358   /**
359    * @copydoc Dali::Accessibility::Bridge::RemoveTopLevelWindow()
360    */
361   void RemoveTopLevelWindow(Dali::Accessibility::Accessible* windowAccessible) override;
362
363   /**
364    * @copydoc Dali::Accessibility::Bridge::RegisterDefaultLabel()
365    */
366   void RegisterDefaultLabel(Dali::Accessibility::Accessible* object) override;
367
368   /**
369    * @copydoc Dali::Accessibility::Bridge::UnregisterDefaultLabel()
370    */
371   void UnregisterDefaultLabel(Dali::Accessibility::Accessible* object) override;
372
373   /**
374    * @copydoc Dali::Accessibility::Bridge::GetDefaultLabel()
375    */
376   Dali::Accessibility::Accessible* GetDefaultLabel(Dali::Accessibility::Accessible* root) const override;
377
378   /**
379    * @copydoc Dali::Accessibility::Bridge::GetApplication()
380    */
381   Dali::Accessibility::Accessible* GetApplication() const override
382   {
383     return &mApplication;
384   }
385
386   /**
387    * @brief Adds function to dbus interface.
388    */
389   template<typename SELF, typename... RET, typename... ARGS>
390   void AddFunctionToInterface(
391     DBus::DBusInterfaceDescription& desc, const std::string& funcName, DBus::ValueOrError<RET...> (SELF::*funcPtr)(ARGS...))
392   {
393     if(auto self = dynamic_cast<SELF*>(this))
394       desc.addMethod<DBus::ValueOrError<RET...>(ARGS...)>(
395         funcName,
396         [=](ARGS... args) -> DBus::ValueOrError<RET...> {
397           try
398           {
399             return (self->*funcPtr)(std::move(args)...);
400           }
401           catch(std::domain_error& e)
402           {
403             return DBus::Error{e.what()};
404           }
405         });
406   }
407
408   /**
409    * @brief Adds 'Get' property to dbus interface.
410    */
411   template<typename T, typename SELF>
412   void AddGetPropertyToInterface(DBus::DBusInterfaceDescription& desc,
413                                  const std::string&              funcName,
414                                  T (SELF::*funcPtr)())
415   {
416     if(auto self = dynamic_cast<SELF*>(this))
417       desc.addProperty<T>(funcName,
418                           [=]() -> DBus::ValueOrError<T> {
419                             try
420                             {
421                               return (self->*funcPtr)();
422                             }
423                             catch(std::domain_error& e)
424                             {
425                               return DBus::Error{e.what()};
426                             }
427                           },
428                           {});
429   }
430
431   /**
432    * @brief Adds 'Set' property to dbus interface.
433    */
434   template<typename T, typename SELF>
435   void AddSetPropertyToInterface(DBus::DBusInterfaceDescription& desc,
436                                  const std::string&              funcName,
437                                  void (SELF::*funcPtr)(T))
438   {
439     if(auto self = dynamic_cast<SELF*>(this))
440       desc.addProperty<T>(funcName, {}, [=](T t) -> DBus::ValueOrError<void> {
441         try
442         {
443           (self->*funcPtr)(std::move(t));
444           return {};
445         }
446         catch(std::domain_error& e)
447         {
448           return DBus::Error{e.what()};
449         }
450       });
451   }
452
453   /**
454    * @brief Adds 'Set' and 'Get' properties to dbus interface.
455    */
456   template<typename T, typename T1, typename SELF>
457   void AddGetSetPropertyToInterface(DBus::DBusInterfaceDescription& desc,
458                                     const std::string&              funcName,
459                                     T1 (SELF::*funcPtrGet)(),
460                                     DBus::ValueOrError<void> (SELF::*funcPtrSet)(T))
461   {
462     if(auto self = dynamic_cast<SELF*>(this))
463       desc.addProperty<T>(
464         funcName,
465         [=]() -> DBus::ValueOrError<T> {
466           try
467           {
468             return (self->*funcPtrGet)();
469           }
470           catch(std::domain_error& e)
471           {
472             return DBus::Error{e.what()};
473           }
474         },
475         [=](T t) -> DBus::ValueOrError<void> {
476           try
477           {
478             (self->*funcPtrSet)(std::move(t));
479             return {};
480           }
481           catch(std::domain_error& e)
482           {
483             return DBus::Error{e.what()};
484           }
485         });
486   }
487
488   /**
489    * @brief Adds 'Get' and 'Set' properties to dbus interface.
490    */
491   template<typename T, typename T1, typename SELF>
492   void AddGetSetPropertyToInterface(DBus::DBusInterfaceDescription& desc,
493                                     const std::string&              funcName,
494                                     T1 (SELF::*funcPtrGet)(),
495                                     void (SELF::*funcPtrSet)(T))
496   {
497     if(auto self = dynamic_cast<SELF*>(this))
498       desc.addProperty<T>(
499         funcName,
500         [=]() -> DBus::ValueOrError<T> {
501           try
502           {
503             return (self->*funcPtrGet)();
504           }
505           catch(std::domain_error& e)
506           {
507             return DBus::Error{e.what()};
508           }
509         },
510         [=](T t) -> DBus::ValueOrError<void> {
511           try
512           {
513             (self->*funcPtrSet)(std::move(t));
514             return {};
515           }
516           catch(std::domain_error& e)
517           {
518             return DBus::Error{e.what()};
519           }
520         });
521   }
522
523   /**
524    * @brief Gets the string of the path excluding the specified prefix.
525    *
526    * @param path The path to get
527    * @return The string stripped of the specific prefix
528    */
529   static std::string StripPrefix(const std::string& path);
530
531   /**
532    * @brief Finds the Accessible object according to the path.
533    *
534    * @param[in] path The path for Accessible object
535    * @return The Accessible object corresponding to the path
536    */
537   Dali::Accessibility::Accessible* Find(const std::string& path) const;
538
539   /**
540    * @brief Finds the Accessible object with the given address.
541    *
542    * @param[in] ptr The unique Address of the object
543    * @return The Accessible object corresponding to the path
544    */
545   Dali::Accessibility::Accessible* Find(const Dali::Accessibility::Address& ptr) const;
546
547   /**
548    * @brief Returns the target object of the currently executed DBus method call.
549    *
550    * @return The Accessible object
551    * @note When a DBus method is called on some object, this target object (`currentObject`) is temporarily saved by the bridge,
552    * because DBus handles the invocation target separately from the method arguments.
553    * We then use the saved object inside the 'glue' method (e.g. BridgeValue::GetMinimum)
554    * to call the equivalent method on the respective C++ object (this could be ScrollBar::AccessibleImpl::GetMinimum in the example given).
555    */
556   Dali::Accessibility::Accessible* FindCurrentObject() const;
557
558   /**
559    * @brief Returns the target object of the currently executed DBus method call.
560    *
561    * This method tries to downcast the return value of FindCurrentObject() to the requested type,
562    * issuing an error reply to the DBus caller if the requested type is not implemented. Whether
563    * a given type is implemented is decided based on the return value of Accessible::GetInterfaces()
564    * for the current object.
565    *
566    * @tparam I The requested AT-SPI interface
567    * @return The Accessible object (cast to a more derived type)
568    *
569    * @see FindCurrentObject()
570    * @see Dali::Accessibility::AtspiInterface
571    * @see Dali::Accessibility::AtspiInterfaceType
572    * @see Dali::Accessibility::Accessible::GetInterfaces()
573    */
574   template<Dali::Accessibility::AtspiInterface I>
575   auto* FindCurrentObjectWithInterface() const
576   {
577     using Type = Dali::Accessibility::AtspiInterfaceType<I>;
578
579     Type* result;
580     auto* currentObject = FindCurrentObject();
581     DALI_ASSERT_DEBUG(currentObject); // FindCurrentObject() throws domain_error
582
583     if(!(result = Dali::Accessibility::Accessible::DownCast<I>(currentObject)))
584     {
585       std::stringstream s;
586
587       s << "Object " << currentObject->GetAddress().ToString();
588       s << " does not implement ";
589       s << Dali::Accessibility::Accessible::GetInterfaceName(I);
590
591       throw std::domain_error{s.str()};
592     }
593
594     return result;
595   }
596
597   /**
598    * @copydoc Dali::Accessibility::Bridge::FindByPath()
599    */
600   Dali::Accessibility::Accessible* FindByPath(const std::string& name) const override;
601
602   /**
603    * @copydoc Dali::Accessibility::Bridge::SetApplicationName()
604    */
605   void SetApplicationName(std::string name) override
606   {
607     mApplication.mName = std::move(name);
608   }
609
610   /**
611    * @copydoc Dali::Accessibility::Bridge::SetToolkitName()
612    */
613   void SetToolkitName(std::string_view toolkitName) override
614   {
615     mApplication.mToolkitName = std::string{toolkitName};
616   }
617
618 protected:
619   // We use a weak handle in order not to keep a window alive forever if someone forgets to UnregisterDefaultLabel()
620   using DefaultLabelType  = std::pair<Dali::WeakHandle<Dali::Window>, Dali::Accessibility::Accessible*>;
621   using DefaultLabelsType = std::list<DefaultLabelType>;
622
623   mutable ApplicationAccessible mApplication;
624   DefaultLabelsType             mDefaultLabels;
625   bool                          mIsScreenReaderSuppressed = false;
626
627 private:
628   /**
629    * @brief Sets an ID.
630    * @param[in] id An ID (integer value)
631    */
632   void SetId(int id);
633
634   /**
635    * @brief Gets the ID.
636    * @return The ID to be set
637    */
638   int GetId();
639
640   /**
641    * @brief Update registered events.
642    */
643   void UpdateRegisteredEvents();
644
645   using CacheElementType = std::tuple<
646     Dali::Accessibility::Address,
647     Dali::Accessibility::Address,
648     Dali::Accessibility::Address,
649     std::vector<Dali::Accessibility::Address>,
650     std::vector<std::string>,
651     std::string,
652     Dali::Accessibility::Role,
653     std::string,
654     std::array<uint32_t, 2>>;
655
656   /**
657    * @brief Gets Items  // NEED TO UPDATE!
658    *
659    * @return
660    */
661   DBus::ValueOrError<std::vector<CacheElementType>> GetItems();
662
663   /**
664    * @brief Creates CacheElement.
665    *
666    * CreateCacheElement method works for GetItems which is a part of ATSPI protocol.
667    * ATSPI client library (libatspi from at-spi2-core) depending on cacheing policy configuration uses GetItems
668    * to pre-load entire accessible tree from application to its own cache in single dbus call.
669    * Otherwise the particular nodes in a tree are cached lazily when client library tries to access them.
670    * @param item Accessible to get information
671    * @return The elements to be cached
672    */
673   CacheElementType CreateCacheElement(Dali::Accessibility::Accessible* item);
674
675   /**
676    * @brief Removes expired elements from the default label collection.
677    */
678   void CompressDefaultLabels();
679
680   /**
681    * @brief Gets the window to which this accessible belongs (or an empty handle).
682    *
683    * @param accessible The accessible
684    * @return The window
685    */
686   static Dali::WeakHandle<Dali::Window> GetWindow(Dali::Accessibility::Accessible* accessible);
687
688 protected:
689   BridgeBase();
690   virtual ~BridgeBase();
691
692   /**
693    * @copydoc Dali::Accessibility::Bridge::ForceUp()
694    */
695   ForceUpResult ForceUp() override;
696
697   /**
698    * @copydoc Dali::Accessibility::Bridge::ForceDown()
699    */
700   void ForceDown() override;
701
702   DBus::DBusServer           mDbusServer;
703   DBusWrapper::ConnectionPtr mConnectionPtr;
704   int                        mId = 0;
705   DBus::DBusClient           mRegistry;
706   bool                       IsBoundsChangedEventAllowed{false};
707 };
708
709 #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_BASE_H