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:
125 auto methodObject = mRegistryClient.method<bool(std::tuple<uint32_t, int32_t, int32_t, int32_t, int32_t, std::string, bool>)>("NotifyListenersSync");
126 auto result = methodObject.call(std::tuple<uint32_t, int32_t, int32_t, int32_t, int32_t, std::string, bool>{keyType, 0, static_cast<int32_t>(keyCode), 0, static_cast<int32_t>(timeStamp), keyName, isText ? 1 : 0});
129 LOG() << result.getError().message;
132 return std::get<0>(result) ? Consumed::YES : Consumed::NO;
136 * @copydoc Dali::Accessibility::Bridge::Pause()
138 void Pause() override
145 mDirectReadingClient.method<DBus::ValueOrError<void>(bool)>("PauseResume").asyncCall([](DBus::ValueOrError<void> msg) {
148 LOG() << "Direct reading command failed (" << msg.getError().message << ")\n";
155 * @copydoc Dali::Accessibility::Bridge::Resume()
157 void Resume() override
164 mDirectReadingClient.method<DBus::ValueOrError<void>(bool)>("PauseResume").asyncCall([](DBus::ValueOrError<void> msg) {
167 LOG() << "Direct reading command failed (" << msg.getError().message << ")\n";
174 * @copydoc Dali::Accessibility::Bridge::StopReading()
176 void StopReading(bool alsoNonDiscardable) override
183 mDirectReadingClient.method<DBus::ValueOrError<void>(bool)>("StopReading").asyncCall([](DBus::ValueOrError<void> msg) {
186 LOG() << "Direct reading command failed (" << msg.getError().message << ")\n";
193 * @copydoc Dali::Accessibility::Bridge::Say()
195 void Say(const std::string& text, bool discardable, std::function<void(std::string)> callback) override
202 mDirectReadingClient.method<DBus::ValueOrError<std::string, bool, int32_t>(std::string, bool)>("ReadCommand").asyncCall([=](DBus::ValueOrError<std::string, bool, int32_t> msg) {
205 LOG() << "Direct reading command failed (" << msg.getError().message << ")\n";
209 mDirectReadingCallbacks.emplace(std::get<2>(msg), callback);
217 * @copydoc Dali::Accessibility::Bridge::ForceDown()
219 void ForceDown() override
223 if(mData->mCurrentlyHighlightedActor && mData->mHighlightActor)
225 mData->mCurrentlyHighlightedActor.Remove(mData->mHighlightActor);
227 mData->mCurrentlyHighlightedActor = {};
228 mData->mHighlightActor = {};
230 mDisabledSignal.Emit();
231 UnembedSocket(mApplication.GetAddress(), {AtspiDbusNameRegistry, "root"});
232 ReleaseBusName(mPreferredBusName);
235 mHighlightedActor = {};
236 mHighlightClearAction = {};
237 BridgeAccessible::ForceDown();
238 mRegistryClient = {};
239 mDirectReadingClient = {};
240 mDirectReadingCallbacks.clear();
241 mApplication.mChildren.clear();
249 mInitializeTimer.Stop();
250 mInitializeTimer.Reset();
253 if(mReadIsEnabledTimer)
255 mReadIsEnabledTimer.Stop();
256 mReadIsEnabledTimer.Reset();
259 if(mReadScreenReaderEnabledTimer)
261 mReadScreenReaderEnabledTimer.Stop();
262 mReadScreenReaderEnabledTimer.Reset();
267 mForceUpTimer.Stop();
268 mForceUpTimer.Reset();
273 * @copydoc Dali::Accessibility::Bridge::Terminate()
275 void Terminate() override
279 // The ~Window() after this point cannot emit DESTROY, because Bridge is not available. So emit DESTROY here.
280 for(auto windowAccessible : mApplication.mChildren)
282 BridgeObject::Emit(windowAccessible, WindowEvent::DESTROY);
284 mData->mCurrentlyHighlightedActor = {};
285 mData->mHighlightActor = {};
288 if((NULL != mIdleCallback) && Dali::Adaptor::IsAvailable())
290 Dali::Adaptor::Get().RemoveIdle(mIdleCallback);
292 mAccessibilityStatusClient = {};
297 bool ForceUpTimerCallback()
299 if(ForceUp() != ForceUpResult::FAILED)
307 * @copydoc Dali::Accessibility::Bridge::ForceUp()
309 ForceUpResult ForceUp() override
311 auto forceUpResult = BridgeAccessible::ForceUp();
312 if(forceUpResult == ForceUpResult::ALREADY_UP)
314 return forceUpResult;
316 else if(forceUpResult == ForceUpResult::FAILED)
320 mForceUpTimer = Dali::Timer::New(RETRY_INTERVAL);
321 mForceUpTimer.TickSignal().Connect(this, &BridgeImpl::ForceUpTimerCallback);
322 mForceUpTimer.Start();
324 return forceUpResult;
327 BridgeObject::RegisterInterfaces();
328 BridgeAccessible::RegisterInterfaces();
329 BridgeComponent::RegisterInterfaces();
330 BridgeCollection::RegisterInterfaces();
331 BridgeAction::RegisterInterfaces();
332 BridgeValue::RegisterInterfaces();
333 BridgeText::RegisterInterfaces();
334 BridgeEditableText::RegisterInterfaces();
335 BridgeSelection::RegisterInterfaces();
336 BridgeApplication::RegisterInterfaces();
337 BridgeHypertext::RegisterInterfaces();
338 BridgeHyperlink::RegisterInterfaces();
339 BridgeSocket::RegisterInterfaces();
341 RegisterOnBridge(&mApplication);
343 mRegistryClient = {AtspiDbusNameRegistry, AtspiDbusPathDec, Accessible::GetInterfaceName(AtspiInterface::DEVICE_EVENT_CONTROLLER), mConnectionPtr};
344 mDirectReadingClient = DBus::DBusClient{DirectReadingDBusName, DirectReadingDBusPath, DirectReadingDBusInterface, mConnectionPtr};
346 mDirectReadingClient.addSignal<void(int32_t, std::string)>("ReadingStateChanged", [=](int32_t id, std::string readingState) {
347 auto it = mDirectReadingCallbacks.find(id);
348 if(it != mDirectReadingCallbacks.end())
350 it->second(readingState);
351 if(readingState != "ReadingPaused" && readingState != "ReadingResumed" && readingState != "ReadingStarted")
353 mDirectReadingCallbacks.erase(it);
358 RequestBusName(mPreferredBusName);
360 auto parentAddress = EmbedSocket(mApplication.GetAddress(), {AtspiDbusNameRegistry, "root"});
361 mApplication.mParent.SetAddress(std::move(parentAddress));
362 mEnabledSignal.Emit();
364 return ForceUpResult::JUST_STARTED;
368 * @brief Sends a signal to dbus that the window is shown.
370 * @param[in] window The window to be shown
371 * @see Accessible::EmitShowing() and BridgeObject::EmitStateChanged()
373 void EmitShown(Dali::Window window)
375 auto windowAccessible = mApplication.GetWindowAccessible(window);
378 windowAccessible->EmitShowing(true);
383 * @brief Sends a signal to dbus that the window is hidden.
385 * @param[in] window The window to be hidden
386 * @see Accessible::EmitShowing() and BridgeObject::EmitStateChanged()
388 void EmitHidden(Dali::Window window)
390 auto windowAccessible = mApplication.GetWindowAccessible(window);
393 windowAccessible->EmitShowing(false);
398 * @brief Sends a signal to dbus that the window is activated.
400 * @param[in] window The window to be activated
401 * @see BridgeObject::Emit()
403 void EmitActivate(Dali::Window window)
405 auto windowAccessible = mApplication.GetWindowAccessible(window);
408 windowAccessible->Emit(WindowEvent::ACTIVATE, 0);
413 * @brief Sends a signal to dbus that the window is deactivated.
415 * @param[in] window The window to be deactivated
416 * @see BridgeObject::Emit()
418 void EmitDeactivate(Dali::Window window)
420 auto windowAccessible = mApplication.GetWindowAccessible(window);
423 windowAccessible->Emit(WindowEvent::DEACTIVATE, 0);
428 * @copydoc Dali::Accessibility::Bridge::WindowShown()
430 void WindowShown(Dali::Window window) override
439 * @copydoc Dali::Accessibility::Bridge::WindowHidden()
441 void WindowHidden(Dali::Window window) override
450 * @copydoc Dali::Accessibility::Bridge::WindowFocused()
452 void WindowFocused(Dali::Window window) override
456 EmitActivate(window);
461 * @copydoc Dali::Accessibility::Bridge::WindowUnfocused()
463 void WindowUnfocused(Dali::Window window) override
467 EmitDeactivate(window);
472 * @copydoc Dali::Accessibility::Bridge::SuppressScreenReader()
474 void SuppressScreenReader(bool suppress) override
476 if(mIsScreenReaderSuppressed == suppress)
480 mIsScreenReaderSuppressed = suppress;
481 ReadScreenReaderEnabledProperty();
486 if((!mIsScreenReaderSuppressed && mIsScreenReaderEnabled) || mIsEnabled)
496 bool ReadIsEnabledTimerCallback()
498 ReadIsEnabledProperty();
502 void ReadIsEnabledProperty()
504 mAccessibilityStatusClient.property<bool>("IsEnabled").asyncGet([this](DBus::ValueOrError<bool> msg) {
507 DALI_LOG_ERROR("Get IsEnabled property error: %s\n", msg.getError().message.c_str());
508 if(msg.getError().errorType == DBus::ErrorType::INVALID_REPLY)
510 if(!mReadIsEnabledTimer)
512 mReadIsEnabledTimer = Dali::Timer::New(RETRY_INTERVAL);
513 mReadIsEnabledTimer.TickSignal().Connect(this, &BridgeImpl::ReadIsEnabledTimerCallback);
515 mReadIsEnabledTimer.Start();
520 if(mReadIsEnabledTimer)
522 mReadIsEnabledTimer.Stop();
523 mReadIsEnabledTimer.Reset();
526 mIsEnabled = std::get<0>(msg);
531 void ListenIsEnabledProperty()
533 mAccessibilityStatusClient.addPropertyChangedEvent<bool>("IsEnabled", [this](bool res) {
539 bool ReadScreenReaderEnabledTimerCallback()
541 ReadScreenReaderEnabledProperty();
545 void ReadScreenReaderEnabledProperty()
547 // can be true because of SuppressScreenReader before init
548 if (!mAccessibilityStatusClient)
553 mAccessibilityStatusClient.property<bool>("ScreenReaderEnabled").asyncGet([this](DBus::ValueOrError<bool> msg) {
556 DALI_LOG_ERROR("Get ScreenReaderEnabled property error: %s\n", msg.getError().message.c_str());
557 if(msg.getError().errorType == DBus::ErrorType::INVALID_REPLY)
559 if(!mReadScreenReaderEnabledTimer)
561 mReadScreenReaderEnabledTimer = Dali::Timer::New(RETRY_INTERVAL);
562 mReadScreenReaderEnabledTimer.TickSignal().Connect(this, &BridgeImpl::ReadScreenReaderEnabledTimerCallback);
564 mReadScreenReaderEnabledTimer.Start();
569 if(mReadScreenReaderEnabledTimer)
571 mReadScreenReaderEnabledTimer.Stop();
572 mReadScreenReaderEnabledTimer.Reset();
575 mIsScreenReaderEnabled = std::get<0>(msg);
580 void EmitScreenReaderEnabledSignal()
582 if (mIsScreenReaderEnabled)
584 mScreenReaderEnabledSignal.Emit();
588 mScreenReaderDisabledSignal.Emit();
592 void ListenScreenReaderEnabledProperty()
594 mAccessibilityStatusClient.addPropertyChangedEvent<bool>("ScreenReaderEnabled", [this](bool res) {
595 mIsScreenReaderEnabled = res;
596 EmitScreenReaderEnabledSignal();
601 void ReadAndListenProperties()
603 ReadIsEnabledProperty();
604 ListenIsEnabledProperty();
606 ReadScreenReaderEnabledProperty();
607 ListenScreenReaderEnabledProperty();
610 bool InitializeAccessibilityStatusClient()
612 mAccessibilityStatusClient = DBus::DBusClient{A11yDbusName, A11yDbusPath, A11yDbusStatusInterface, DBus::ConnectionType::SESSION};
614 if (!mAccessibilityStatusClient)
616 DALI_LOG_ERROR("Accessibility Status DbusClient is not ready\n");
623 bool InitializeTimerCallback()
625 if ( InitializeAccessibilityStatusClient() )
627 ReadAndListenProperties();
635 if ( InitializeAccessibilityStatusClient() )
637 ReadAndListenProperties();
638 mIdleCallback = NULL;
642 if(!mInitializeTimer)
644 mInitializeTimer = Dali::Timer::New(RETRY_INTERVAL);
645 mInitializeTimer.TickSignal().Connect(this, &BridgeImpl::InitializeTimerCallback);
647 mInitializeTimer.Start();
649 mIdleCallback = NULL;
654 * @copydoc Dali::Accessibility::Bridge::Initialize()
656 void Initialize() override
658 if ( InitializeAccessibilityStatusClient() )
660 ReadAndListenProperties();
664 // Initialize failed. Try it again on Idle
665 if( Dali::Adaptor::IsAvailable() )
667 Dali::Adaptor& adaptor = Dali::Adaptor::Get();
668 if( NULL == mIdleCallback )
670 mIdleCallback = MakeCallback( this, &BridgeImpl::OnIdleSignal );
671 adaptor.AddIdle( mIdleCallback, true );
677 * @copydoc Dali::Accessibility::Bridge::GetScreenReaderEnabled()
679 bool GetScreenReaderEnabled() override
681 return mIsScreenReaderEnabled;
685 * @copydoc Dali::Accessibility::Bridge::IsEnabled()
687 bool IsEnabled() override
692 Address EmbedSocket(const Address& plug, const Address& socket) override
694 auto client = CreateSocketClient(socket);
695 auto reply = client.method<Address(Address)>("Embed").call(plug);
699 DALI_LOG_ERROR("Failed to embed socket %s: %s", socket.ToString().c_str(), reply.getError().message.c_str());
703 return std::get<0>(reply.getValues());
706 void EmbedAtkSocket(const Address& plug, const Address& socket) override
708 auto client = CreateSocketClient(socket);
710 client.method<void(std::string)>("Embedded").call(ATSPI_PREFIX_PATH + plug.GetPath());
713 void UnembedSocket(const Address& plug, const Address& socket) override
715 auto client = CreateSocketClient(socket);
717 client.method<void(Address)>("Unembed").call(plug);
720 void SetSocketOffset(ProxyAccessible* socket, std::int32_t x, std::int32_t y) override
722 AddCoalescableMessage(CoalescableMessages::SET_OFFSET, socket, 1.0f, [=]() {
723 auto client = CreateSocketClient(socket->GetAddress());
725 client.method<void(std::int32_t, std::int32_t)>("SetOffset").asyncCall([](DBus::ValueOrError<void>) {}, x, y);
729 void SetExtentsOffset(std::int32_t x, std::int32_t y) override
733 mData->mExtentsOffset = {x, y};
737 void SetPreferredBusName(std::string_view preferredBusName) override
739 if(preferredBusName == mPreferredBusName)
744 std::string oldPreferredBusName = std::move(mPreferredBusName);
745 mPreferredBusName = std::string{preferredBusName};
749 ReleaseBusName(oldPreferredBusName);
750 RequestBusName(mPreferredBusName);
752 // else: request/release will be handled by ForceUp/ForceDown, respectively
756 DBus::DBusClient CreateSocketClient(const Address& socket)
758 return {socket.GetBus(), ATSPI_PREFIX_PATH + socket.GetPath(), Accessible::GetInterfaceName(AtspiInterface::SOCKET), mConnectionPtr};
761 void RequestBusName(const std::string& busName)
768 DBus::requestBusName(mConnectionPtr, busName);
771 void ReleaseBusName(const std::string& busName)
778 DBus::releaseBusName(mConnectionPtr, busName);
782 namespace // unnamed namespace
785 bool INITIALIZED_BRIDGE = false;
788 * @brief Creates BridgeImpl instance.
790 * @return The BridgeImpl instance
791 * @note This method is to check environment variable first. If ATSPI is disable using env, it returns dummy bridge instance.
793 std::shared_ptr<Bridge> CreateBridge()
795 INITIALIZED_BRIDGE = true;
799 /* check environment variable first */
800 const char* envAtspiDisabled = Dali::EnvironmentVariable::GetEnvironmentVariable(DALI_ENV_DISABLE_ATSPI);
801 if(envAtspiDisabled && std::atoi(envAtspiDisabled) != 0)
803 return Dali::Accessibility::DummyBridge::GetInstance();
806 return std::make_shared<BridgeImpl>();
808 catch(const std::exception&)
810 DALI_LOG_ERROR("Failed to initialize AT-SPI bridge");
811 return Dali::Accessibility::DummyBridge::GetInstance();
815 } // unnamed namespace
817 // Dali::Accessibility::Bridge class implementation
819 std::shared_ptr<Bridge> Bridge::GetCurrentBridge()
821 static std::shared_ptr<Bridge> bridge;
827 else if(mAutoInitState == AutoInitState::ENABLED)
829 bridge = CreateBridge();
831 /* check environment variable for suppressing screen-reader */
832 const char* envSuppressScreenReader = Dali::EnvironmentVariable::GetEnvironmentVariable(DALI_ENV_SUPPRESS_SCREEN_READER);
833 if(envSuppressScreenReader && std::atoi(envSuppressScreenReader) != 0)
835 bridge->SuppressScreenReader(true);
841 return Dali::Accessibility::DummyBridge::GetInstance();
844 void Bridge::DisableAutoInit()
846 if(INITIALIZED_BRIDGE)
848 DALI_LOG_ERROR("Bridge::DisableAutoInit() called after bridge auto-initialization");
851 mAutoInitState = AutoInitState::DISABLED;
854 void Bridge::EnableAutoInit()
856 mAutoInitState = AutoInitState::ENABLED;
858 if(INITIALIZED_BRIDGE)
863 auto rootLayer = Dali::Stage::GetCurrent().GetRootLayer(); // A root layer of the default window.
864 auto window = Dali::DevelWindow::Get(rootLayer);
865 auto applicationName = Dali::Internal::Adaptor::Adaptor::GetApplicationPackageName();
867 auto accessible = Accessibility::Accessible::Get(rootLayer);
869 auto bridge = Bridge::GetCurrentBridge();
870 bridge->AddTopLevelWindow(accessible);
871 bridge->SetApplicationName(applicationName);
872 bridge->Initialize();
874 if(window && window.IsVisible())
876 bridge->WindowShown(window);
880 std::string Bridge::MakeBusNameForWidget(std::string_view widgetInstanceId)
882 // The bus name should consist of dot-separated alphanumeric elements, e.g. "com.example.BusName123".
883 // Allowed characters in each element: "[A-Z][a-z][0-9]_", but no element may start with a digit.
885 static const char prefix[] = "com.samsung.dali.widget_";
886 static const char underscore = '_';
888 std::stringstream tmp;
892 for(char ch : widgetInstanceId)
894 tmp << (std::isalnum(ch) ? ch : underscore);