2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 #include <dali/devel-api/common/stage.h>
22 #include <dali/integration-api/debug.h>
23 #include <dali/public-api/actors/layer.h>
25 #include <unordered_map>
28 #include <dali/devel-api/adaptor-framework/environment-variable.h>
29 #include <dali/devel-api/adaptor-framework/window-devel.h>
30 #include <dali/internal/accessibility/bridge/accessibility-common.h>
31 #include <dali/internal/accessibility/bridge/bridge-accessible.h>
32 #include <dali/internal/accessibility/bridge/bridge-action.h>
33 #include <dali/internal/accessibility/bridge/bridge-collection.h>
34 #include <dali/internal/accessibility/bridge/bridge-component.h>
35 #include <dali/internal/accessibility/bridge/bridge-editable-text.h>
36 #include <dali/internal/accessibility/bridge/bridge-hypertext.h>
37 #include <dali/internal/accessibility/bridge/bridge-hyperlink.h>
38 #include <dali/internal/accessibility/bridge/bridge-object.h>
39 #include <dali/internal/accessibility/bridge/bridge-selection.h>
40 #include <dali/internal/accessibility/bridge/bridge-socket.h>
41 #include <dali/internal/accessibility/bridge/bridge-text.h>
42 #include <dali/internal/accessibility/bridge/bridge-value.h>
43 #include <dali/internal/accessibility/bridge/bridge-application.h>
44 #include <dali/internal/accessibility/bridge/dummy/dummy-atspi.h>
45 #include <dali/internal/adaptor/common/adaptor-impl.h>
46 #include <dali/internal/system/common/environment-variables.h>
48 using namespace Dali::Accessibility;
50 namespace // unnamed namespace
53 const int RETRY_INTERVAL = 1000;
55 } // unnamed namespace
58 * @brief The BridgeImpl class is to implement some Bridge functions.
60 class BridgeImpl : public virtual BridgeBase,
61 public BridgeAccessible,
63 public BridgeComponent,
64 public BridgeCollection,
68 public BridgeEditableText,
69 public BridgeSelection,
70 public BridgeApplication,
71 public BridgeHypertext,
72 public BridgeHyperlink,
75 DBus::DBusClient mAccessibilityStatusClient;
76 DBus::DBusClient mRegistryClient;
77 DBus::DBusClient mDirectReadingClient;
78 bool mIsScreenReaderEnabled = false;
79 bool mIsEnabled = false;
80 std::unordered_map<int32_t, std::function<void(std::string)>> mDirectReadingCallbacks;
81 Dali::Actor mHighlightedActor;
82 std::function<void(Dali::Actor)> mHighlightClearAction;
83 Dali::CallbackBase* mIdleCallback = NULL;
84 Dali::Timer mInitializeTimer;
85 Dali::Timer mReadIsEnabledTimer;
86 Dali::Timer mReadScreenReaderEnabledTimer;
87 Dali::Timer mForceUpTimer;
88 std::string mPreferredBusName;
96 * @copydoc Dali::Accessibility::Bridge::Emit()
98 Consumed Emit(KeyEventType type, unsigned int keyCode, const std::string& keyName, unsigned int timeStamp, bool isText) override
105 unsigned int keyType = 0;
109 case KeyEventType::KEY_PRESSED:
114 case KeyEventType::KEY_RELEASED:
129 * @copydoc Dali::Accessibility::Bridge::Pause()
131 void Pause() override
138 mDirectReadingClient.method<DBus::ValueOrError<void>(bool)>("PauseResume").asyncCall([](DBus::ValueOrError<void> msg) {
141 LOG() << "Direct reading command failed (" << msg.getError().message << ")\n";
148 * @copydoc Dali::Accessibility::Bridge::Resume()
150 void Resume() override
157 mDirectReadingClient.method<DBus::ValueOrError<void>(bool)>("PauseResume").asyncCall([](DBus::ValueOrError<void> msg) {
160 LOG() << "Direct reading command failed (" << msg.getError().message << ")\n";
167 * @copydoc Dali::Accessibility::Bridge::StopReading()
169 void StopReading(bool alsoNonDiscardable) override
176 mDirectReadingClient.method<DBus::ValueOrError<void>(bool)>("StopReading").asyncCall([](DBus::ValueOrError<void> msg) {
179 LOG() << "Direct reading command failed (" << msg.getError().message << ")\n";
186 * @copydoc Dali::Accessibility::Bridge::Say()
188 void Say(const std::string& text, bool discardable, std::function<void(std::string)> callback) override
195 mDirectReadingClient.method<DBus::ValueOrError<std::string, bool, int32_t>(std::string, bool)>("ReadCommand").asyncCall([=](DBus::ValueOrError<std::string, bool, int32_t> msg) {
198 LOG() << "Direct reading command failed (" << msg.getError().message << ")\n";
202 mDirectReadingCallbacks.emplace(std::get<2>(msg), callback);
210 * @copydoc Dali::Accessibility::Bridge::ForceDown()
212 void ForceDown() override
216 if(mData->mCurrentlyHighlightedActor && mData->mHighlightActor)
218 mData->mCurrentlyHighlightedActor.Remove(mData->mHighlightActor);
220 mData->mCurrentlyHighlightedActor = {};
221 mData->mHighlightActor = {};
223 mDisabledSignal.Emit();
224 UnembedSocket(mApplication.GetAddress(), {AtspiDbusNameRegistry, "root"});
225 ReleaseBusName(mPreferredBusName);
228 mHighlightedActor = {};
229 mHighlightClearAction = {};
230 BridgeAccessible::ForceDown();
231 mRegistryClient = {};
232 mDirectReadingClient = {};
233 mDirectReadingCallbacks.clear();
234 mApplication.mChildren.clear();
242 mInitializeTimer.Stop();
243 mInitializeTimer.Reset();
246 if(mReadIsEnabledTimer)
248 mReadIsEnabledTimer.Stop();
249 mReadIsEnabledTimer.Reset();
252 if(mReadScreenReaderEnabledTimer)
254 mReadScreenReaderEnabledTimer.Stop();
255 mReadScreenReaderEnabledTimer.Reset();
260 mForceUpTimer.Stop();
261 mForceUpTimer.Reset();
266 * @copydoc Dali::Accessibility::Bridge::Terminate()
268 void Terminate() override
272 // The ~Window() after this point cannot emit DESTROY, because Bridge is not available. So emit DESTROY here.
273 for(auto windowAccessible : mApplication.mChildren)
275 BridgeObject::Emit(windowAccessible, WindowEvent::DESTROY);
277 mData->mCurrentlyHighlightedActor = {};
278 mData->mHighlightActor = {};
281 if((NULL != mIdleCallback) && Dali::Adaptor::IsAvailable())
283 Dali::Adaptor::Get().RemoveIdle(mIdleCallback);
285 mAccessibilityStatusClient = {};
290 bool ForceUpTimerCallback()
292 if(ForceUp() != ForceUpResult::FAILED)
300 * @copydoc Dali::Accessibility::Bridge::ForceUp()
302 ForceUpResult ForceUp() override
304 auto forceUpResult = BridgeAccessible::ForceUp();
305 if(forceUpResult == ForceUpResult::ALREADY_UP)
307 return forceUpResult;
309 else if(forceUpResult == ForceUpResult::FAILED)
313 mForceUpTimer = Dali::Timer::New(RETRY_INTERVAL);
314 mForceUpTimer.TickSignal().Connect(this, &BridgeImpl::ForceUpTimerCallback);
315 mForceUpTimer.Start();
317 return forceUpResult;
320 BridgeObject::RegisterInterfaces();
321 BridgeAccessible::RegisterInterfaces();
322 BridgeComponent::RegisterInterfaces();
323 BridgeCollection::RegisterInterfaces();
324 BridgeAction::RegisterInterfaces();
325 BridgeValue::RegisterInterfaces();
326 BridgeText::RegisterInterfaces();
327 BridgeEditableText::RegisterInterfaces();
328 BridgeSelection::RegisterInterfaces();
329 BridgeApplication::RegisterInterfaces();
330 BridgeHypertext::RegisterInterfaces();
331 BridgeHyperlink::RegisterInterfaces();
332 BridgeSocket::RegisterInterfaces();
334 RegisterOnBridge(&mApplication);
336 mRegistryClient = {AtspiDbusNameRegistry, AtspiDbusPathDec, Accessible::GetInterfaceName(AtspiInterface::DEVICE_EVENT_CONTROLLER), mConnectionPtr};
337 mDirectReadingClient = DBus::DBusClient{DirectReadingDBusName, DirectReadingDBusPath, DirectReadingDBusInterface, mConnectionPtr};
339 mDirectReadingClient.addSignal<void(int32_t, std::string)>("ReadingStateChanged", [=](int32_t id, std::string readingState) {
340 auto it = mDirectReadingCallbacks.find(id);
341 if(it != mDirectReadingCallbacks.end())
343 it->second(readingState);
344 if(readingState != "ReadingPaused" && readingState != "ReadingResumed" && readingState != "ReadingStarted")
346 mDirectReadingCallbacks.erase(it);
351 RequestBusName(mPreferredBusName);
353 auto parentAddress = EmbedSocket(mApplication.GetAddress(), {AtspiDbusNameRegistry, "root"});
354 mApplication.mParent.SetAddress(std::move(parentAddress));
355 mEnabledSignal.Emit();
357 return ForceUpResult::JUST_STARTED;
361 * @brief Sends a signal to dbus that the window is shown.
363 * @param[in] window The window to be shown
364 * @see Accessible::EmitShowing() and BridgeObject::EmitStateChanged()
366 void EmitShown(Dali::Window window)
368 auto windowAccessible = mApplication.GetWindowAccessible(window);
371 windowAccessible->EmitShowing(true);
376 * @brief Sends a signal to dbus that the window is hidden.
378 * @param[in] window The window to be hidden
379 * @see Accessible::EmitShowing() and BridgeObject::EmitStateChanged()
381 void EmitHidden(Dali::Window window)
383 auto windowAccessible = mApplication.GetWindowAccessible(window);
386 windowAccessible->EmitShowing(false);
391 * @brief Sends a signal to dbus that the window is activated.
393 * @param[in] window The window to be activated
394 * @see BridgeObject::Emit()
396 void EmitActivate(Dali::Window window)
398 auto windowAccessible = mApplication.GetWindowAccessible(window);
401 windowAccessible->Emit(WindowEvent::ACTIVATE, 0);
406 * @brief Sends a signal to dbus that the window is deactivated.
408 * @param[in] window The window to be deactivated
409 * @see BridgeObject::Emit()
411 void EmitDeactivate(Dali::Window window)
413 auto windowAccessible = mApplication.GetWindowAccessible(window);
416 windowAccessible->Emit(WindowEvent::DEACTIVATE, 0);
421 * @copydoc Dali::Accessibility::Bridge::WindowShown()
423 void WindowShown(Dali::Window window) override
432 * @copydoc Dali::Accessibility::Bridge::WindowHidden()
434 void WindowHidden(Dali::Window window) override
443 * @copydoc Dali::Accessibility::Bridge::WindowFocused()
445 void WindowFocused(Dali::Window window) override
449 EmitActivate(window);
454 * @copydoc Dali::Accessibility::Bridge::WindowUnfocused()
456 void WindowUnfocused(Dali::Window window) override
460 EmitDeactivate(window);
465 * @copydoc Dali::Accessibility::Bridge::SuppressScreenReader()
467 void SuppressScreenReader(bool suppress) override
469 if(mIsScreenReaderSuppressed == suppress)
473 mIsScreenReaderSuppressed = suppress;
474 ReadScreenReaderEnabledProperty();
479 if((!mIsScreenReaderSuppressed && mIsScreenReaderEnabled) || mIsEnabled)
489 bool ReadIsEnabledTimerCallback()
491 ReadIsEnabledProperty();
495 void ReadIsEnabledProperty()
497 mAccessibilityStatusClient.property<bool>("IsEnabled").asyncGet([this](DBus::ValueOrError<bool> msg) {
500 DALI_LOG_ERROR("Get IsEnabled property error: %s\n", msg.getError().message.c_str());
501 if(msg.getError().errorType == DBus::ErrorType::INVALID_REPLY)
503 if(!mReadIsEnabledTimer)
505 mReadIsEnabledTimer = Dali::Timer::New(RETRY_INTERVAL);
506 mReadIsEnabledTimer.TickSignal().Connect(this, &BridgeImpl::ReadIsEnabledTimerCallback);
508 mReadIsEnabledTimer.Start();
513 if(mReadIsEnabledTimer)
515 mReadIsEnabledTimer.Stop();
516 mReadIsEnabledTimer.Reset();
519 mIsEnabled = std::get<0>(msg);
524 void ListenIsEnabledProperty()
526 mAccessibilityStatusClient.addPropertyChangedEvent<bool>("IsEnabled", [this](bool res) {
532 bool ReadScreenReaderEnabledTimerCallback()
534 ReadScreenReaderEnabledProperty();
538 void ReadScreenReaderEnabledProperty()
540 // can be true because of SuppressScreenReader before init
541 if (!mAccessibilityStatusClient)
546 mAccessibilityStatusClient.property<bool>("ScreenReaderEnabled").asyncGet([this](DBus::ValueOrError<bool> msg) {
549 DALI_LOG_ERROR("Get ScreenReaderEnabled property error: %s\n", msg.getError().message.c_str());
550 if(msg.getError().errorType == DBus::ErrorType::INVALID_REPLY)
552 if(!mReadScreenReaderEnabledTimer)
554 mReadScreenReaderEnabledTimer = Dali::Timer::New(RETRY_INTERVAL);
555 mReadScreenReaderEnabledTimer.TickSignal().Connect(this, &BridgeImpl::ReadScreenReaderEnabledTimerCallback);
557 mReadScreenReaderEnabledTimer.Start();
562 if(mReadScreenReaderEnabledTimer)
564 mReadScreenReaderEnabledTimer.Stop();
565 mReadScreenReaderEnabledTimer.Reset();
568 mIsScreenReaderEnabled = std::get<0>(msg);
573 void EmitScreenReaderEnabledSignal()
575 if (mIsScreenReaderEnabled)
577 mScreenReaderEnabledSignal.Emit();
581 mScreenReaderDisabledSignal.Emit();
585 void ListenScreenReaderEnabledProperty()
587 mAccessibilityStatusClient.addPropertyChangedEvent<bool>("ScreenReaderEnabled", [this](bool res) {
588 mIsScreenReaderEnabled = res;
589 EmitScreenReaderEnabledSignal();
594 void ReadAndListenProperties()
596 ReadIsEnabledProperty();
597 ListenIsEnabledProperty();
599 ReadScreenReaderEnabledProperty();
600 ListenScreenReaderEnabledProperty();
603 bool InitializeAccessibilityStatusClient()
605 mAccessibilityStatusClient = DBus::DBusClient{A11yDbusName, A11yDbusPath, A11yDbusStatusInterface, DBus::ConnectionType::SESSION};
607 if (!mAccessibilityStatusClient)
609 DALI_LOG_ERROR("Accessibility Status DbusClient is not ready\n");
616 bool InitializeTimerCallback()
618 if ( InitializeAccessibilityStatusClient() )
620 ReadAndListenProperties();
628 if ( InitializeAccessibilityStatusClient() )
630 ReadAndListenProperties();
631 mIdleCallback = NULL;
635 if(!mInitializeTimer)
637 mInitializeTimer = Dali::Timer::New(RETRY_INTERVAL);
638 mInitializeTimer.TickSignal().Connect(this, &BridgeImpl::InitializeTimerCallback);
640 mInitializeTimer.Start();
642 mIdleCallback = NULL;
647 * @copydoc Dali::Accessibility::Bridge::Initialize()
649 void Initialize() override
651 if ( InitializeAccessibilityStatusClient() )
653 ReadAndListenProperties();
657 // Initialize failed. Try it again on Idle
658 if( Dali::Adaptor::IsAvailable() )
660 Dali::Adaptor& adaptor = Dali::Adaptor::Get();
661 if( NULL == mIdleCallback )
663 mIdleCallback = MakeCallback( this, &BridgeImpl::OnIdleSignal );
664 adaptor.AddIdle( mIdleCallback, true );
670 * @copydoc Dali::Accessibility::Bridge::GetScreenReaderEnabled()
672 bool GetScreenReaderEnabled() override
674 return mIsScreenReaderEnabled;
678 * @copydoc Dali::Accessibility::Bridge::IsEnabled()
680 bool IsEnabled() override
685 Address EmbedSocket(const Address& plug, const Address& socket) override
687 auto client = CreateSocketClient(socket);
688 auto reply = client.method<Address(Address)>("Embed").call(plug);
692 DALI_LOG_ERROR("Failed to embed socket %s: %s", socket.ToString().c_str(), reply.getError().message.c_str());
696 return std::get<0>(reply.getValues());
699 void EmbedAtkSocket(const Address& plug, const Address& socket) override
701 auto client = CreateSocketClient(socket);
703 client.method<void(std::string)>("Embedded").call(ATSPI_PREFIX_PATH + plug.GetPath());
706 void UnembedSocket(const Address& plug, const Address& socket) override
708 auto client = CreateSocketClient(socket);
710 client.method<void(Address)>("Unembed").call(plug);
713 void SetSocketOffset(ProxyAccessible* socket, std::int32_t x, std::int32_t y) override
715 AddCoalescableMessage(CoalescableMessages::SET_OFFSET, socket, 1.0f, [=]() {
716 auto client = CreateSocketClient(socket->GetAddress());
718 client.method<void(std::int32_t, std::int32_t)>("SetOffset").asyncCall([](DBus::ValueOrError<void>) {}, x, y);
722 void SetExtentsOffset(std::int32_t x, std::int32_t y) override
726 mData->mExtentsOffset = {x, y};
730 void SetPreferredBusName(std::string_view preferredBusName) override
732 if(preferredBusName == mPreferredBusName)
737 std::string oldPreferredBusName = std::move(mPreferredBusName);
738 mPreferredBusName = std::string{preferredBusName};
742 ReleaseBusName(oldPreferredBusName);
743 RequestBusName(mPreferredBusName);
745 // else: request/release will be handled by ForceUp/ForceDown, respectively
749 DBus::DBusClient CreateSocketClient(const Address& socket)
751 return {socket.GetBus(), ATSPI_PREFIX_PATH + socket.GetPath(), Accessible::GetInterfaceName(AtspiInterface::SOCKET), mConnectionPtr};
754 void RequestBusName(const std::string& busName)
761 DBus::requestBusName(mConnectionPtr, busName);
764 void ReleaseBusName(const std::string& busName)
771 DBus::releaseBusName(mConnectionPtr, busName);
775 namespace // unnamed namespace
778 bool INITIALIZED_BRIDGE = false;
781 * @brief Creates BridgeImpl instance.
783 * @return The BridgeImpl instance
784 * @note This method is to check environment variable first. If ATSPI is disable using env, it returns dummy bridge instance.
786 std::shared_ptr<Bridge> CreateBridge()
788 INITIALIZED_BRIDGE = true;
792 /* check environment variable first */
793 const char* envAtspiDisabled = Dali::EnvironmentVariable::GetEnvironmentVariable(DALI_ENV_DISABLE_ATSPI);
794 if(envAtspiDisabled && std::atoi(envAtspiDisabled) != 0)
796 return Dali::Accessibility::DummyBridge::GetInstance();
799 return std::make_shared<BridgeImpl>();
801 catch(const std::exception&)
803 DALI_LOG_ERROR("Failed to initialize AT-SPI bridge");
804 return Dali::Accessibility::DummyBridge::GetInstance();
808 } // unnamed namespace
810 // Dali::Accessibility::Bridge class implementation
812 std::shared_ptr<Bridge> Bridge::GetCurrentBridge()
814 static std::shared_ptr<Bridge> bridge;
820 else if(mAutoInitState == AutoInitState::ENABLED)
822 bridge = CreateBridge();
824 /* check environment variable for suppressing screen-reader */
825 const char* envSuppressScreenReader = Dali::EnvironmentVariable::GetEnvironmentVariable(DALI_ENV_SUPPRESS_SCREEN_READER);
826 if(envSuppressScreenReader && std::atoi(envSuppressScreenReader) != 0)
828 bridge->SuppressScreenReader(true);
834 return Dali::Accessibility::DummyBridge::GetInstance();
837 void Bridge::DisableAutoInit()
839 if(INITIALIZED_BRIDGE)
841 DALI_LOG_ERROR("Bridge::DisableAutoInit() called after bridge auto-initialization");
844 mAutoInitState = AutoInitState::DISABLED;
847 void Bridge::EnableAutoInit()
849 mAutoInitState = AutoInitState::ENABLED;
851 if(INITIALIZED_BRIDGE)
856 auto rootLayer = Dali::Stage::GetCurrent().GetRootLayer(); // A root layer of the default window.
857 auto window = Dali::DevelWindow::Get(rootLayer);
858 auto applicationName = Dali::Internal::Adaptor::Adaptor::GetApplicationPackageName();
860 auto accessible = Accessibility::Accessible::Get(rootLayer);
862 auto bridge = Bridge::GetCurrentBridge();
863 bridge->AddTopLevelWindow(accessible);
864 bridge->SetApplicationName(applicationName);
865 bridge->Initialize();
867 if(window && window.IsVisible())
869 bridge->WindowShown(window);
873 std::string Bridge::MakeBusNameForWidget(std::string_view widgetInstanceId)
875 // The bus name should consist of dot-separated alphanumeric elements, e.g. "com.example.BusName123".
876 // Allowed characters in each element: "[A-Z][a-z][0-9]_", but no element may start with a digit.
878 static const char prefix[] = "com.samsung.dali.widget_";
879 static const char underscore = '_';
881 std::stringstream tmp;
885 for(char ch : widgetInstanceId)
887 tmp << (std::isalnum(ch) ? ch : underscore);