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