Merge "[AT-SPI] Rework Accessible::GetInterfaces()" into devel/master
[platform/core/uifw/dali-adaptor.git] / dali / internal / accessibility / bridge / bridge-base.cpp
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/accessibility/bridge/bridge-base.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/common/stage.h>
23 #include <atomic>
24 #include <cstdlib>
25 #include <memory>
26
27 // INTERNAL INCLUDES
28 #include <dali/public-api/adaptor-framework/timer.h>
29
30 using namespace Dali::Accessibility;
31
32 static Dali::Timer tickTimer;
33
34 BridgeBase::BridgeBase()
35 {
36 }
37
38 BridgeBase::~BridgeBase()
39 {
40   mApplication.mChildren.clear();
41   mApplication.mWindows.clear();
42 }
43
44 void BridgeBase::AddFilteredEvent(FilteredEvents kind, Dali::Accessibility::Accessible* obj, float delay, std::function<void()> functor)
45 {
46   if(delay < 0)
47   {
48     delay = 0;
49   }
50
51   auto it = mFilteredEvents.insert({{kind, obj}, {static_cast<unsigned int>(delay * 10), {}}});
52   if(it.second)
53   {
54     functor();
55   }
56   else
57   {
58     it.first->second.second = std::move(functor);
59   }
60
61   if(!tickTimer)
62   {
63     tickTimer = Dali::Timer::New(100);
64     tickTimer.TickSignal().Connect(this, &BridgeBase::TickFilteredEvents);
65   }
66 }
67
68 bool BridgeBase::TickFilteredEvents()
69 {
70   for(auto it = mFilteredEvents.begin(); it != mFilteredEvents.end();)
71   {
72     if(it->second.first)
73     {
74       --it->second.first;
75     }
76     else
77     {
78       if(it->second.second)
79       {
80         it->second.second();
81         it->second.second = {};
82       }
83       else
84       {
85         it = mFilteredEvents.erase(it);
86         continue;
87       }
88     }
89     ++it;
90   }
91   return !mFilteredEvents.empty();
92 }
93
94 void BridgeBase::UpdateRegisteredEvents()
95 {
96   using ReturnType = std::vector<std::tuple<std::string, std::string>>;
97   mRegistry.method<DBus::ValueOrError<ReturnType>()>("GetRegisteredEvents").asyncCall([this](DBus::ValueOrError<ReturnType> msg) {
98     if(!msg)
99     {
100       LOG() << "Get registered events failed";
101       return;
102     }
103
104     IsBoundsChangedEventAllowed = false;
105
106     ReturnType values = std::get<ReturnType>(msg.getValues());
107     for(long unsigned int i = 0; i < values.size(); i++)
108     {
109       if(!std::get<1>(values[i]).compare("Object:BoundsChanged"))
110       {
111         IsBoundsChangedEventAllowed = true;
112       }
113     }
114   });
115 }
116
117 BridgeBase::ForceUpResult BridgeBase::ForceUp()
118 {
119   //TODO: checking mBusName is enough? or a new variable to check bridge state?
120   if(Bridge::ForceUp() == ForceUpResult::ALREADY_UP && !GetBusName().empty())
121   {
122     return ForceUpResult::ALREADY_UP;
123   }
124   auto proxy = DBus::DBusClient{dbusLocators::atspi::BUS, dbusLocators::atspi::OBJ_PATH, dbusLocators::atspi::BUS_INTERFACE, DBus::ConnectionType::SESSION};
125   auto addr  = proxy.method<std::string()>(dbusLocators::atspi::GET_ADDRESS).call();
126
127   if(!addr)
128   {
129     DALI_LOG_ERROR("failed at call '%s': %s\n", dbusLocators::atspi::GET_ADDRESS, addr.getError().message.c_str());
130     return ForceUpResult::FAILED;
131   }
132
133   mConnectionPtr  = DBusWrapper::Installed()->eldbus_address_connection_get_impl(std::get<0>(addr));
134   mData->mBusName = DBus::getConnectionName(mConnectionPtr);
135   mDbusServer     = {mConnectionPtr};
136
137   {
138     DBus::DBusInterfaceDescription desc{Accessible::GetInterfaceName(AtspiInterface::CACHE)};
139     AddFunctionToInterface(desc, "GetItems", &BridgeBase::GetItems);
140     mDbusServer.addInterface(AtspiDbusPathCache, desc);
141   }
142   {
143     DBus::DBusInterfaceDescription desc{Accessible::GetInterfaceName(AtspiInterface::APPLICATION)};
144     AddGetSetPropertyToInterface(desc, "Id", &BridgeBase::GetId, &BridgeBase::SetId);
145     mDbusServer.addInterface(AtspiPath, desc);
146   }
147
148   mRegistry = {AtspiDbusNameRegistry, AtspiDbusPathRegistry, Accessible::GetInterfaceName(AtspiInterface::REGISTRY), mConnectionPtr};
149
150   UpdateRegisteredEvents();
151
152   mRegistry.addSignal<void(void)>("EventListenerRegistered", [this](void) {
153     UpdateRegisteredEvents();
154   });
155
156   mRegistry.addSignal<void(void)>("EventListenerDeregistered", [this](void) {
157     UpdateRegisteredEvents();
158   });
159
160   return ForceUpResult::JUST_STARTED;
161 }
162
163 void BridgeBase::ForceDown()
164 {
165   Bridge::ForceDown();
166   mRegistry      = {};
167   mDbusServer    = {};
168   mConnectionPtr = {};
169 }
170
171 const std::string& BridgeBase::GetBusName() const
172 {
173   static std::string empty;
174   return mData ? mData->mBusName : empty;
175 }
176
177 Accessible* BridgeBase::FindByPath(const std::string& name) const
178 {
179   try
180   {
181     return Find(name);
182   }
183   catch(std::domain_error&)
184   {
185     return nullptr;
186   }
187 }
188
189 void BridgeBase::OnWindowVisibilityChanged(Dali::Window window, bool visible)
190 {
191   if(visible)
192   {
193     // TODO : Should we check 'out of screen' here? -> Then, we need an actor of this change.
194     Dali::Accessibility::Bridge::GetCurrentBridge()->WindowShown(window); // Called when Window is shown.
195   }
196   else
197   {
198     Dali::Accessibility::Bridge::GetCurrentBridge()->WindowHidden(window); // Called when Window is hidden and iconified.
199   }
200 }
201
202 void BridgeBase::OnWindowFocusChanged(Dali::Window window, bool focusIn)
203 {
204   if(focusIn)
205   {
206     Dali::Accessibility::Bridge::GetCurrentBridge()->WindowFocused(window); // Called when Window is focused.
207   }
208   else
209   {
210     Dali::Accessibility::Bridge::GetCurrentBridge()->WindowUnfocused(window); // Called when Window is out of focus.
211   }
212 }
213
214 void BridgeBase::AddTopLevelWindow(Accessible* windowAccessible)
215 {
216   if(windowAccessible->GetInternalActor() == nullptr)
217   {
218     return;
219   }
220
221   // Prevent adding the default window twice.
222   if(!mApplication.mChildren.empty() &&
223      mApplication.mChildren[0]->GetInternalActor() == windowAccessible->GetInternalActor())
224   {
225     return;
226   }
227
228   // Adds Window to a list of Windows.
229   mApplication.mChildren.push_back(windowAccessible);
230   SetIsOnRootLevel(windowAccessible);
231
232   RegisterDefaultLabel(windowAccessible);
233
234   Dali::Window window = Dali::DevelWindow::Get(windowAccessible->GetInternalActor());
235   if(window)
236   {
237     mApplication.mWindows.push_back(window);
238     Dali::DevelWindow::VisibilityChangedSignal(window).Connect(this, &BridgeBase::OnWindowVisibilityChanged);
239     window.FocusChangeSignal().Connect(this, &BridgeBase::OnWindowFocusChanged);
240   }
241 }
242
243 void BridgeBase::RemoveTopLevelWindow(Accessible* windowAccessible)
244 {
245   for(auto i = 0u; i < mApplication.mWindows.size(); ++i)
246   {
247     if(windowAccessible->GetInternalActor() == mApplication.mWindows[i].GetRootLayer())
248     {
249       Dali::DevelWindow::VisibilityChangedSignal(mApplication.mWindows[i]).Disconnect(this, &BridgeBase::OnWindowVisibilityChanged);
250       mApplication.mWindows[i].FocusChangeSignal().Disconnect(this, &BridgeBase::OnWindowFocusChanged);
251       mApplication.mWindows.erase(mApplication.mWindows.begin() + i);
252       break;
253     }
254   }
255
256   UnregisterDefaultLabel(windowAccessible);
257
258   for(auto i = 0u; i < mApplication.mChildren.size(); ++i)
259   {
260     if(mApplication.mChildren[i] == windowAccessible)
261     {
262       mApplication.mChildren.erase(mApplication.mChildren.begin() + i);
263       break;
264     }
265   }
266 }
267
268 void BridgeBase::RegisterDefaultLabel(Accessible* object)
269 {
270   if(std::find(mDefaultLabels.begin(), mDefaultLabels.end(), object) == mDefaultLabels.end())
271   {
272     mDefaultLabels.push_back(object);
273   }
274 }
275
276 void BridgeBase::UnregisterDefaultLabel(Accessible* object)
277 {
278   auto it = std::find(mDefaultLabels.begin(), mDefaultLabels.end(), object);
279   if(it != mDefaultLabels.end())
280   {
281     mDefaultLabels.erase(it);
282   }
283 }
284
285 std::string BridgeBase::StripPrefix(const std::string& path)
286 {
287   auto size = strlen(AtspiPath);
288   return path.substr(size + 1);
289 }
290
291 Accessible* BridgeBase::Find(const std::string& path) const
292 {
293   if(path == "root")
294   {
295     return &mApplication;
296   }
297
298   void*              accessible;
299   std::istringstream tmp{path};
300   if(!(tmp >> accessible))
301   {
302     throw std::domain_error{"invalid path '" + path + "'"};
303   }
304
305   auto it = mData->mKnownObjects.find(static_cast<Accessible*>(accessible));
306   if(it == mData->mKnownObjects.end() || (*it)->IsHidden())
307   {
308     throw std::domain_error{"unknown object '" + path + "'"};
309   }
310
311   return static_cast<Accessible*>(accessible);
312 }
313
314 Accessible* BridgeBase::Find(const Address& ptr) const
315 {
316   assert(ptr.GetBus() == mData->mBusName);
317   return Find(ptr.GetPath());
318 }
319
320 Accessible* BridgeBase::FindCurrentObject() const
321 {
322   auto path = DBus::DBusServer::getCurrentObjectPath();
323   auto size = strlen(AtspiPath);
324   if(path.size() <= size)
325   {
326     throw std::domain_error{"invalid path '" + path + "'"};
327   }
328   if(path.substr(0, size) != AtspiPath)
329   {
330     throw std::domain_error{"invalid path '" + path + "'"};
331   }
332   if(path[size] != '/')
333   {
334     throw std::domain_error{"invalid path '" + path + "'"};
335   }
336   return Find(StripPrefix(path));
337 }
338
339 void BridgeBase::SetId(int id)
340 {
341   this->mId = id;
342 }
343
344 int BridgeBase::GetId()
345 {
346   return this->mId;
347 }
348
349 auto BridgeBase::GetItems() -> DBus::ValueOrError<std::vector<CacheElementType>>
350 {
351   auto root = &mApplication;
352
353   std::vector<CacheElementType> res;
354
355   std::function<void(Accessible*)> proc =
356     [&](Accessible* item) {
357       res.emplace_back(std::move(CreateCacheElement(root)));
358       for(auto i = 0u; i < item->GetChildCount(); ++i)
359       {
360         proc(item->GetChildAtIndex(i));
361       }
362     };
363
364   return res;
365 }
366
367 auto BridgeBase::CreateCacheElement(Accessible* item) -> CacheElementType
368 {
369   if(!item)
370   {
371     return {};
372   }
373
374   auto root   = &mApplication;
375   auto parent = item->GetParent();
376
377   std::vector<Address> children;
378   for(auto i = 0u; i < item->GetChildCount(); ++i)
379   {
380     children.emplace_back(item->GetChildAtIndex(i)->GetAddress());
381   }
382
383   return std::make_tuple(
384     item->GetAddress(),
385     root->GetAddress(),
386     parent ? parent->GetAddress() : Address{},
387     children,
388     item->GetInterfacesAsStrings(),
389     item->GetName(),
390     item->GetRole(),
391     item->GetDescription(),
392     item->GetStates().GetRawData());
393 }