diff --git a/OAT.xml b/OAT.xml index 2e3e8eb9..83f92a23 100644 --- a/OAT.xml +++ b/OAT.xml @@ -20,9 +20,9 @@ licensefile: tasklist(only for batch mode): 1. task: Define oat check thread, each task will start a new thread. -2. task name: Only an name, no practical effect. -3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist. -4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist. +2. task name: Only a name, no practical effect. +3. task policy: Default policy for projects under this task, this field is required and the specified policy must be defined in policylist. +4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must be defined in filefilterlist. 5. task project: Projects to be checked, the path field define the source root dir of the project. @@ -39,7 +39,7 @@ policyList: "filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource 4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license. -5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem. +5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be excluded while process this policyitem. 6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed. 7. policyitem filefilter: Used to bind filefilter which define filter rules. 8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path. diff --git a/README_zh.md b/README_zh.md index de1489cb..f50bc53b 100644 --- a/README_zh.md +++ b/README_zh.md @@ -583,7 +583,7 @@ keyboardDelegate.off('textChange', (text) => {

hideKeyboard(): Promise<void>;

-

隐藏输入法,使用peomise形式返回结果。参数个数为0,否则抛出异常。

+

隐藏输入法,使用promise形式返回结果。参数个数为0,否则抛出异常。

diff --git a/bundle.json b/bundle.json index a0c2523d..0d10b290 100644 --- a/bundle.json +++ b/bundle.json @@ -84,9 +84,7 @@ } ], "test": [ - "//base/inputmethod/imf/unitest:InputMethodControllerTest", - "//base/inputmethod/imf/unitest:InputMethodAbilityTest", - "//base/inputmethod/imf/unitest:InputMethodServiceTest", + "//base/inputmethod/imf/unitest:unittest", "//base/inputmethod/imf/test/fuzztest:fuzztest", "//base/inputmethod/imf/test/unitest/src:unittest" ] diff --git a/etc/init/inputmethodservice.cfg b/etc/init/inputmethodservice.cfg index ec97081c..61228b60 100644 --- a/etc/init/inputmethodservice.cfg +++ b/etc/init/inputmethodservice.cfg @@ -4,6 +4,7 @@ "path" : ["/system/bin/sa_main", "/system/profile/inputmethod_service.xml"], "uid" : "inputmethod", "gid" : ["inputmethod", "shell"], + "permission" : ["ohos.permission.INPUT_MONITORING"], "caps" : [], "secon" : "u:r:inputmethod_service:s0" } diff --git a/etc/para/include/para_handle.h b/etc/para/include/para_handle.h index 5c10a451..6ecd2dd8 100644 --- a/etc/para/include/para_handle.h +++ b/etc/para/include/para_handle.h @@ -25,9 +25,10 @@ namespace OHOS { static bool SetDefaultIme(int32_t userId, const std::string &imeName); static std::string GetDefaultIme(int32_t userId); + static constexpr const char *DEFAULT_PACKAGE_NAME = "com.example.kikakeyboard"; + static constexpr const char *DEFAULT_ABILITY_NAME = "ServiceExtAbility"; private: static const char *DEFAULT_IME_KEY; - static const char *DEFAULT_IME_NAME; static constexpr int CONFIG_LEN = 128; static const int32_t main_userId = 100; }; diff --git a/etc/para/src/para_handle.cpp b/etc/para/src/para_handle.cpp index 44922058..dcc26a92 100644 --- a/etc/para/src/para_handle.cpp +++ b/etc/para/src/para_handle.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace MiscServices { const char *ParaHandle::DEFAULT_IME_KEY = "persist.sys.default_ime"; - const char *ParaHandle::DEFAULT_IME_NAME = "com.example.kikakeyboard/ServiceExtAbility"; bool ParaHandle::SetDefaultIme(int32_t userId, const std::string &imeName) { if (userId != main_userId) { @@ -41,9 +40,9 @@ namespace OHOS { if (code > 0) { return value; } - - SetDefaultIme(userId, DEFAULT_IME_NAME); - return DEFAULT_IME_NAME; + std::string defaultName = std::string(DEFAULT_PACKAGE_NAME) + "/" + std::string(DEFAULT_ABILITY_NAME); + SetDefaultIme(userId, defaultName); + return defaultName; } } // namespace MiscServices } // namespace OHOS diff --git a/frameworks/inputmethod_ability/include/input_method_ability.h b/frameworks/inputmethod_ability/include/input_method_ability.h index 76dcbb02..0ddcf0d3 100644 --- a/frameworks/inputmethod_ability/include/input_method_ability.h +++ b/frameworks/inputmethod_ability/include/input_method_ability.h @@ -43,7 +43,6 @@ public: InputMethodAbility(); ~InputMethodAbility(); static sptr GetInstance(); - sptr OnConnect(); int32_t InsertText(const std::string text); void setImeListener(std::shared_ptr imeListener); void setKdListener(std::shared_ptr kdListener); @@ -65,7 +64,7 @@ private: MessageHandler *msgHandler; bool mSupportPhysicalKbd = false; InputAttribute editorAttribute; - int32_t displyId = 0; + int32_t displayId = 0; sptr startInputToken; InputChannel *writeInputChannel; bool stop_; @@ -99,6 +98,7 @@ private: void Initialize(); void WorkThread(); + void QuitWorkThread(); void OnInitialInput(Message *msg); void OnStartInput(Message *msg); @@ -113,7 +113,7 @@ private: void InitialInputWindow(); void ShowInputWindow(bool isShowKeyboard, const SubProperty &subProperty); - void DissmissInputWindow(); + void DismissInputWindow(); void BindServiceAndClient(); }; diff --git a/frameworks/inputmethod_ability/src/input_method_ability.cpp b/frameworks/inputmethod_ability/src/input_method_ability.cpp index d35afc1f..5dec26bd 100644 --- a/frameworks/inputmethod_ability/src/input_method_ability.cpp +++ b/frameworks/inputmethod_ability/src/input_method_ability.cpp @@ -46,12 +46,11 @@ InputMethodAbility::InputMethodAbility() : stop_(false) InputMethodAbility::~InputMethodAbility() { IMSA_HILOGI("InputMethodAbility::~InputMethodAbility"); - instance_ = nullptr; + QuitWorkThread(); if (msgHandler) { delete msgHandler; msgHandler = nullptr; } - stop_ = true; } sptr InputMethodAbility::GetInstance() @@ -196,6 +195,7 @@ void InputMethodAbility::WorkThread() break; } default: { + IMSA_HILOGD("the message is %{public}d.", msg->msgId_); break; } } @@ -208,7 +208,7 @@ void InputMethodAbility::OnInitialInput(Message *msg) { IMSA_HILOGI("InputMethodAbility::OnInitialInput"); MessageParcel *data = msg->msgContent_; - displyId = data->ReadInt32(); + displayId = data->ReadInt32(); sptr channelObject = data->ReadRemoteObject(); if (channelObject == nullptr) { IMSA_HILOGI("InputMethodAbility::OnInitialInput channelObject is nullptr"); @@ -268,7 +268,7 @@ void InputMethodAbility::OnShowKeyboard(Message *msg) void InputMethodAbility::OnHideKeyboard(Message *msg) { IMSA_HILOGI("InputMethodAbility::OnHideKeyboard"); - DissmissInputWindow(); + DismissInputWindow(); } void InputMethodAbility::OnStopInput(Message *msg) @@ -376,17 +376,17 @@ void InputMethodAbility::ShowInputWindow(bool isShowKeyboard, const SubProperty channel->SendKeyboardStatus(KEYBOARD_SHOW); } -void InputMethodAbility::DissmissInputWindow() +void InputMethodAbility::DismissInputWindow() { - IMSA_HILOGI("InputMethodAbility::DissmissInputWindow"); + IMSA_HILOGI("InputMethodAbility::DismissInputWindow"); if (!imeListener_) { - IMSA_HILOGI("InputMethodAbility::DissmissInputWindow imeListener_ is nullptr"); + IMSA_HILOGI("InputMethodAbility::DismissInputWindow imeListener_ is nullptr"); return; } imeListener_->OnKeyboardStatus(false); std::shared_ptr channel = GetInputDataChannel(); if (channel == nullptr) { - IMSA_HILOGI("InputMethodAbility::DissmissInputWindow channel is nullptr"); + IMSA_HILOGI("InputMethodAbility::DismissInputWindow channel is nullptr"); return; } channel->SendKeyboardStatus(KEYBOARD_HIDE); @@ -518,12 +518,12 @@ void InputMethodAbility::SetInputDataChannel(sptr &object) { IMSA_HILOGI("run in SetInputDataChannel"); std::lock_guard lock(dataChannelLock_); - std::shared_ptr channalProxy = std::make_shared(object); - if (channalProxy == nullptr) { + std::shared_ptr channelProxy = std::make_shared(object); + if (channelProxy == nullptr) { IMSA_HILOGI("InputMethodAbility::SetInputDataChannel inputDataChannel is nullptr"); return; } - dataChannel_ = channalProxy; + dataChannel_ = channelProxy; } std::shared_ptr InputMethodAbility::GetInputDataChannel() @@ -536,12 +536,12 @@ void InputMethodAbility::SetInputControlChannel(sptr &object) { IMSA_HILOGI("run in SetInputControlChannel"); std::lock_guard lock(controlChannelLock_); - std::shared_ptr channalProxy = std::make_shared(object); - if (channalProxy == nullptr) { + std::shared_ptr channelProxy = std::make_shared(object); + if (channelProxy == nullptr) { IMSA_HILOGI("InputMethodAbility::SetInputControlChannel inputDataChannel is nullptr"); return; } - controlChannel_ = channalProxy; + controlChannel_ = channelProxy; } std::shared_ptr InputMethodAbility::GetInputControlChannel() @@ -574,5 +574,15 @@ void InputMethodAbility::BindServiceAndClient() sptr inputMethodAgent = sptr(new InputMethodAgentProxy(inputMethodAgentStub)); mImms->SetCoreAndAgent(stub, inputMethodAgent); } + +void InputMethodAbility::QuitWorkThread() +{ + stop_ = true; + Message *msg = new Message(MessageID::MSG_ID_QUIT_WORKER_THREAD, nullptr); + msgHandler->SendMessage(msg); + if (workThreadHandler.joinable()) { + workThreadHandler.join(); + } +} } // namespace MiscServices } // namespace OHOS diff --git a/frameworks/inputmethod_ability/src/input_method_core_proxy.cpp b/frameworks/inputmethod_ability/src/input_method_core_proxy.cpp index 419d8a01..7aa253a1 100644 --- a/frameworks/inputmethod_ability/src/input_method_core_proxy.cpp +++ b/frameworks/inputmethod_ability/src/input_method_core_proxy.cpp @@ -34,7 +34,7 @@ InputMethodCoreProxy::~InputMethodCoreProxy() = default; int32_t InputMethodCoreProxy::initializeInput( sptr &startInputToken, int32_t displayId, sptr &inputControlChannel) { - IMSA_HILOGI("InputMethodCoreProxy::initializeInput"); + IMSA_HILOGD("InputMethodCoreProxy::initializeInput"); auto remote = Remote(); if (!remote) { IMSA_HILOGI("remote is nullptr"); @@ -75,7 +75,7 @@ int32_t InputMethodCoreProxy::initializeInput( int32_t InputMethodCoreProxy::InitInputControlChannel(sptr &inputControlChannel) { - IMSA_HILOGI("InputMethodCoreProxy::InitInputControlChannel"); + IMSA_HILOGD("InputMethodCoreProxy::InitInputControlChannel"); auto remote = Remote(); if (!remote) { IMSA_HILOGI("remote is nullptr"); @@ -105,7 +105,7 @@ int32_t InputMethodCoreProxy::InitInputControlChannel(sptr void InputMethodCoreProxy::SetClientState(bool state) { - IMSA_HILOGI("InputMethodCoreProxy::SetClientState"); + IMSA_HILOGD("InputMethodCoreProxy::SetClientState"); auto remote = Remote(); if (!remote) { IMSA_HILOGI("remote is nullptr"); @@ -127,7 +127,7 @@ void InputMethodCoreProxy::SetClientState(bool state) bool InputMethodCoreProxy::startInput( const sptr &inputDataChannel, const InputAttribute &editorAttribute, bool supportPhysicalKbd) { - IMSA_HILOGI("InputMethodCoreProxy::startInput"); + IMSA_HILOGD("InputMethodCoreProxy::startInput"); auto remote = Remote(); if (!remote) { IMSA_HILOGI("remote is nullptr"); @@ -159,7 +159,7 @@ bool InputMethodCoreProxy::startInput( int32_t InputMethodCoreProxy::stopInput() { - IMSA_HILOGI("InputMethodCoreProxy::stopInput"); + IMSA_HILOGD("InputMethodCoreProxy::stopInput"); auto remote = Remote(); if (!remote) { IMSA_HILOGI("remote is nullptr"); @@ -184,7 +184,7 @@ int32_t InputMethodCoreProxy::stopInput() int32_t InputMethodCoreProxy::showKeyboard( const sptr &inputDataChannel, bool isShowKeyboard, const SubProperty &subProperty) { - IMSA_HILOGI("InputMethodCoreProxy::showKeyboard"); + IMSA_HILOGD("InputMethodCoreProxy::showKeyboard"); return SendRequest(SHOW_KEYBOARD, [&inputDataChannel, &isShowKeyboard, &subProperty](MessageParcel &data) { return ITypesUtil::Marshal(data, inputDataChannel->AsObject(), isShowKeyboard, subProperty); }); @@ -192,7 +192,7 @@ int32_t InputMethodCoreProxy::showKeyboard( void InputMethodCoreProxy::StopInputService(std::string imeId) { - IMSA_HILOGI("InputMethodCoreProxy::StopInputService"); + IMSA_HILOGD("InputMethodCoreProxy::StopInputService"); auto remote = Remote(); if (!remote) { IMSA_HILOGI("InputMethodCoreProxy::StopInputService remote is nullptr"); @@ -213,7 +213,7 @@ void InputMethodCoreProxy::StopInputService(std::string imeId) bool InputMethodCoreProxy::hideKeyboard(int32_t flags) { - IMSA_HILOGI("InputMethodCoreProxy::hideKeyboard"); + IMSA_HILOGD("InputMethodCoreProxy::hideKeyboard"); auto remote = Remote(); if (!remote) { return false; @@ -235,7 +235,7 @@ bool InputMethodCoreProxy::hideKeyboard(int32_t flags) int32_t InputMethodCoreProxy::setKeyboardType(const KeyboardType &type) { - IMSA_HILOGI("InputMethodCoreProxy::setKeyboardType"); + IMSA_HILOGD("InputMethodCoreProxy::setKeyboardType"); auto remote = Remote(); if (!remote) { IMSA_HILOGI("remote is nullptr"); @@ -255,7 +255,7 @@ int32_t InputMethodCoreProxy::setKeyboardType(const KeyboardType &type) int32_t InputMethodCoreProxy::getKeyboardWindowHeight(int32_t &retHeight) { - IMSA_HILOGI("InputMethodCoreProxy::getKeyboardWindowHeight"); + IMSA_HILOGD("InputMethodCoreProxy::getKeyboardWindowHeight"); auto remote = Remote(); if (!remote) { IMSA_HILOGI("remote is nullptr"); @@ -278,13 +278,13 @@ int32_t InputMethodCoreProxy::getKeyboardWindowHeight(int32_t &retHeight) int32_t InputMethodCoreProxy::SetSubtype(const SubProperty &property) { - IMSA_HILOGI("InputMethodCoreProxy::SetSubtype"); + IMSA_HILOGD("InputMethodCoreProxy::SetSubtype"); return SendRequest(SET_SUBTYPE, [&property](MessageParcel &data) { return ITypesUtil::Marshal(data, property); }); } int32_t InputMethodCoreProxy::SendRequest(int code, ParcelHandler input, ParcelHandler output) { - IMSA_HILOGI("InputMethodCoreProxy::%{public}s in", __func__); + IMSA_HILOGD("InputMethodCoreProxy::%{public}s in", __func__); MessageParcel data; MessageParcel reply; MessageOption option{ MessageOption::TF_SYNC }; diff --git a/frameworks/inputmethod_ability/src/input_method_core_stub.cpp b/frameworks/inputmethod_ability/src/input_method_core_stub.cpp index 3a668ad8..49c58adc 100644 --- a/frameworks/inputmethod_ability/src/input_method_core_stub.cpp +++ b/frameworks/inputmethod_ability/src/input_method_core_stub.cpp @@ -46,7 +46,7 @@ InputMethodCoreStub::~InputMethodCoreStub() int32_t InputMethodCoreStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - IMSA_HILOGI("InputMethodCoreStub::OnRemoteRequest"); + IMSA_HILOGD("InputMethodCoreStub::OnRemoteRequest"); auto descriptorToken = data.ReadInterfaceToken(); if (descriptorToken != GetDescriptor()) { IMSA_HILOGI("InputMethodCoreStub::OnRemoteRequest descriptorToken is invalid"); @@ -146,7 +146,7 @@ int32_t InputMethodCoreStub::OnRemoteRequest( int32_t InputMethodCoreStub::initializeInput( sptr &startInputToken, int32_t displayId, sptr &inputControlChannel) { - IMSA_HILOGI("InputMethodCoreStub::initializeInput"); + IMSA_HILOGD("InputMethodCoreStub::initializeInput"); if (!msgHandler_) { return ErrorCode::ERROR_NULL_POINTER; } @@ -168,7 +168,7 @@ int32_t InputMethodCoreStub::initializeInput( int32_t InputMethodCoreStub::InitInputControlChannel(sptr &inputControlChannel) { - IMSA_HILOGI("InputMethodCoreStub::initializeInput"); + IMSA_HILOGD("InputMethodCoreStub::initializeInput"); if (!msgHandler_) { return ErrorCode::ERROR_NULL_POINTER; } @@ -186,7 +186,7 @@ int32_t InputMethodCoreStub::InitInputControlChannel(sptr bool InputMethodCoreStub::startInput( const sptr &inputDataChannel, const InputAttribute &editorAttribute, bool supportPhysicalKbd) { - IMSA_HILOGI("InputMethodCoreStub::startInput"); + IMSA_HILOGD("InputMethodCoreStub::startInput"); if (!msgHandler_) { return ErrorCode::ERROR_NULL_POINTER; } @@ -204,7 +204,7 @@ bool InputMethodCoreStub::startInput( int32_t InputMethodCoreStub::stopInput() { - IMSA_HILOGI("InputMethodCoreStub::stopInput"); + IMSA_HILOGD("InputMethodCoreStub::stopInput"); if (!msgHandler_) { return ErrorCode::ERROR_NULL_POINTER; } @@ -216,7 +216,7 @@ int32_t InputMethodCoreStub::stopInput() void InputMethodCoreStub::SetClientState(bool state) { - IMSA_HILOGI("InputMethodCoreStub::SetClientState"); + IMSA_HILOGD("InputMethodCoreStub::SetClientState"); if (!msgHandler_) { return; } @@ -229,7 +229,7 @@ void InputMethodCoreStub::SetClientState(bool state) bool InputMethodCoreStub::hideKeyboard(int32_t flags) { - IMSA_HILOGI("InputMethodCoreStub::hideKeyboard"); + IMSA_HILOGD("InputMethodCoreStub::hideKeyboard"); if (!msgHandler_) { return ErrorCode::ERROR_NULL_POINTER; } @@ -244,7 +244,7 @@ bool InputMethodCoreStub::hideKeyboard(int32_t flags) int32_t InputMethodCoreStub::setKeyboardType(const KeyboardType &type) { - IMSA_HILOGI("InputMethodCoreStub::setKeyboardType"); + IMSA_HILOGD("InputMethodCoreStub::setKeyboardType"); if (!msgHandler_) { return ErrorCode::ERROR_NULL_POINTER; } @@ -258,7 +258,7 @@ int32_t InputMethodCoreStub::setKeyboardType(const KeyboardType &type) void InputMethodCoreStub::StopInputService(std::string imeId) { - IMSA_HILOGI("InputMethodCoreStub::StopInputService"); + IMSA_HILOGD("InputMethodCoreStub::StopInputService"); if (!msgHandler_) { return; } @@ -271,7 +271,7 @@ void InputMethodCoreStub::StopInputService(std::string imeId) int32_t InputMethodCoreStub::getKeyboardWindowHeight(int32_t &retHeight) { - IMSA_HILOGI("InputMethodCoreStub::getKeyboardWindowHeight"); + IMSA_HILOGD("InputMethodCoreStub::getKeyboardWindowHeight"); if (!msgHandler_) { return ErrorCode::ERROR_NULL_POINTER; } @@ -289,7 +289,7 @@ void InputMethodCoreStub::SetMessageHandler(MessageHandler *msgHandler) void InputMethodCoreStub::ShowKeyboardOnRemote(MessageParcel &data, MessageParcel &reply) { - IMSA_HILOGI("InputMethodCoreStub::ShowKeyboardOnRemote"); + IMSA_HILOGD("InputMethodCoreStub::ShowKeyboardOnRemote"); sptr channel; bool isShowKeyboard = false; SubProperty subProperty; @@ -303,7 +303,7 @@ void InputMethodCoreStub::ShowKeyboardOnRemote(MessageParcel &data, MessageParce void InputMethodCoreStub::SetSubtypeOnRemote(MessageParcel &data, MessageParcel &reply) { - IMSA_HILOGI("InputMethodCoreStub::SetSubtypeOnRemote"); + IMSA_HILOGD("InputMethodCoreStub::SetSubtypeOnRemote"); SubProperty property; int32_t ret = SendMessage(MessageID::MSG_ID_SET_SUBTYPE, [&data, &property](MessageParcel &parcel) { return ITypesUtil::Unmarshal(data, property) && ITypesUtil::Marshal(parcel, property); @@ -324,7 +324,7 @@ int32_t InputMethodCoreStub::SetSubtype(const SubProperty &property) int32_t InputMethodCoreStub::SendMessage(int code, ParcelHandler input) { - IMSA_HILOGI("InputMethodCoreStub::SendMessage"); + IMSA_HILOGD("InputMethodCoreStub::SendMessage"); if (msgHandler_ == nullptr) { IMSA_HILOGE("InputMethodCoreStub::msgHandler_ is nullptr"); return ErrorCode::ERROR_EX_NULL_POINTER; diff --git a/frameworks/inputmethod_controller/include/input_method_controller.h b/frameworks/inputmethod_controller/include/input_method_controller.h index ee6200a7..33acdc48 100644 --- a/frameworks/inputmethod_controller/include/input_method_controller.h +++ b/frameworks/inputmethod_controller/include/input_method_controller.h @@ -105,6 +105,7 @@ private: void OnSwitchInput(const Property &property, const SubProperty &subProperty); std::shared_ptr GetInputMethodAgent(); void WorkThread(); + void QuitWorkThread(); int32_t ListInputMethodCommon(InputMethodStatus status, std::vector &props); sptr mInputDataChannel; @@ -115,6 +116,7 @@ private: sptr deathRecipient_; std::mutex agentLock_; std::shared_ptr mAgent = nullptr; + std::mutex textListenerLock_; sptr textListener; InputAttribute mAttribute; std::u16string mTextString; diff --git a/frameworks/inputmethod_controller/include/input_method_setting_listener.h b/frameworks/inputmethod_controller/include/input_method_setting_listener.h index 308d5a11..1203fca7 100644 --- a/frameworks/inputmethod_controller/include/input_method_setting_listener.h +++ b/frameworks/inputmethod_controller/include/input_method_setting_listener.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef INPUTMETHOD_IMF_INPUT_METHOD_ENGINE_LISTENER_H -#define INPUTMETHOD_IMF_INPUT_METHOD_ENGINE_LISTENER_H +#ifndef INPUTMETHOD_IMF_INPUT_METHOD_SETTING_LISTENER_H +#define INPUTMETHOD_IMF_INPUT_METHOD_SETTING_LISTENER_H #include "input_method_property.h" @@ -28,4 +28,4 @@ public: } // namespace MiscServices } // namespace OHOS -#endif // INPUTMETHOD_IMF_INPUT_METHOD_ENGINE_LISTENER_H +#endif // INPUTMETHOD_IMF_INPUT_METHOD_SETTING_LISTENER_H diff --git a/frameworks/inputmethod_controller/src/input_method_controller.cpp b/frameworks/inputmethod_controller/src/input_method_controller.cpp index 57f216a9..9f41c9c1 100644 --- a/frameworks/inputmethod_controller/src/input_method_controller.cpp +++ b/frameworks/inputmethod_controller/src/input_method_controller.cpp @@ -43,14 +43,9 @@ using namespace MessageID; InputMethodController::~InputMethodController() { - if (msgHandler) { - delete msgHandler; - msgHandler = nullptr; - stop_ = false; - } - if (workThreadHandler.joinable()) { - workThreadHandler.join(); - } + QuitWorkThread(); + delete msgHandler; + msgHandler = nullptr; } sptr InputMethodController::GetInstance() @@ -93,10 +88,12 @@ using namespace MessageID; channel->SetHandler(msgHandler); mInputDataChannel = channel; - workThreadHandler = std::thread([this] {WorkThread();}); - mAttribute.inputPattern = InputAttribute::PATTERN_TEXT; - - textListener = nullptr; + workThreadHandler = std::thread([this] { WorkThread(); }); + mAttribute.inputPattern = InputAttribute::PATTERN_TEXT; + { + std::lock_guard lock(textListenerLock_); + textListener = nullptr; + } IMSA_HILOGI("InputMethodController::Initialize textListener is nullptr"); PrepareInput(0, mClient, mInputDataChannel, mAttribute); return true; @@ -139,6 +136,7 @@ using namespace MessageID; { while (!stop_) { Message *msg = msgHandler->GetMessage(); + std::lock_guard lock(textListenerLock_); switch (msg->msgId_) { case MSG_ID_INSERT_CHAR: { MessageParcel *data = msg->msgContent_; @@ -232,8 +230,10 @@ using namespace MessageID; break; } OnSwitchInput(property, subProperty); + break; } default: { + IMSA_HILOGD("the message is %{public}d.", msg->msgId_); break; } } @@ -242,6 +242,16 @@ using namespace MessageID; } } + void InputMethodController::QuitWorkThread() + { + stop_ = true; + Message *msg = new Message(MessageID::MSG_ID_QUIT_WORKER_THREAD, nullptr); + msgHandler->SendMessage(msg); + if (workThreadHandler.joinable()) { + workThreadHandler.join(); + } + } + void InputMethodController::OnSwitchInput(const Property &property, const SubProperty &subProperty) { IMSA_HILOGE("InputMethodController::OnSwitchInput"); @@ -259,6 +269,7 @@ using namespace MessageID; void InputMethodController::Attach(sptr &listener, bool isShowKeyboard) { + std::lock_guard lock(textListenerLock_); textListener = listener; IMSA_HILOGI("InputMethodController::Attach"); InputmethodTrace tracer("InputMethodController Attach trace."); @@ -275,13 +286,13 @@ using namespace MessageID; void InputMethodController::HideTextInput() { - IMSA_HILOGI("InputMethodController::HideTextInput"); + IMSA_HILOGD("InputMethodController::HideTextInput"); StopInput(mClient); } int32_t InputMethodController::HideCurrentInput() { - IMSA_HILOGI("InputMethodController::HideCurrentInput"); + IMSA_HILOGD("InputMethodController::HideCurrentInput"); auto proxy = GetSystemAbilityProxy(); if (proxy == nullptr) { IMSA_HILOGE("proxy is nullptr"); @@ -305,8 +316,11 @@ using namespace MessageID; { ReleaseInput(mClient); InputmethodTrace tracer("InputMethodController Close trace."); - textListener = nullptr; - IMSA_HILOGI("InputMethodController::Close"); + { + std::lock_guard lock(textListenerLock_); + textListener = nullptr; + } + IMSA_HILOGD("InputMethodController::Close"); } void InputMethodController::PrepareInput(int32_t displayId, sptr &client, @@ -357,7 +371,7 @@ using namespace MessageID; std::shared_ptr InputMethodController::GetCurrentInputMethod() { - IMSA_HILOGI("InputMethodController::GetCurrentInputMethod"); + IMSA_HILOGD("InputMethodController::GetCurrentInputMethod"); auto proxy = GetSystemAbilityProxy(); if (proxy == nullptr) { IMSA_HILOGE("proxy is nullptr"); @@ -373,7 +387,7 @@ using namespace MessageID; std::shared_ptr InputMethodController::GetCurrentInputMethodSubtype() { - IMSA_HILOGI("InputMethodController::GetCurrentInputMethod"); + IMSA_HILOGD("InputMethodController::GetCurrentInputMethod"); auto proxy = GetSystemAbilityProxy(); if (proxy == nullptr) { IMSA_HILOGE("proxy is nullptr"); @@ -401,7 +415,7 @@ using namespace MessageID; void InputMethodController::ReleaseInput(sptr &client) { - IMSA_HILOGI("InputMethodController::ReleaseInput"); + IMSA_HILOGD("InputMethodController::ReleaseInput"); isStopInput = true; auto proxy = GetSystemAbilityProxy(); if (proxy == nullptr) { @@ -413,7 +427,7 @@ using namespace MessageID; void InputMethodController::StopInput(sptr &client) { - IMSA_HILOGI("InputMethodController::StopInput"); + IMSA_HILOGD("InputMethodController::StopInput"); isStopInput = true; auto proxy = GetSystemAbilityProxy(); if (proxy == nullptr) { @@ -502,7 +516,7 @@ using namespace MessageID; int32_t InputMethodController::GetTextAfterCursor(int32_t number, std::u16string &text) { - IMSA_HILOGI("InputMethodController::GetTextBeforeCursor"); + IMSA_HILOGI("InputMethodController::GetTextAfterCursor"); if (!mTextString.empty() && mTextString.size() <= INT_MAX) { int32_t endPos = (mSelectNewEnd + number < static_cast(mTextString.size())) ? (mSelectNewEnd + number) diff --git a/frameworks/inputmethod_controller/src/input_method_system_ability_proxy.cpp b/frameworks/inputmethod_controller/src/input_method_system_ability_proxy.cpp index 18c03325..58189c19 100644 --- a/frameworks/inputmethod_controller/src/input_method_system_ability_proxy.cpp +++ b/frameworks/inputmethod_controller/src/input_method_system_ability_proxy.cpp @@ -39,7 +39,7 @@ int32_t InputMethodSystemAbilityProxy::PrepareInput(int32_t displayId, sptr client, bool isShowKeyboard) { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(START_INPUT, [isShowKeyboard, client](MessageParcel &data) { return data.WriteRemoteObject(client->AsObject()) && data.WriteBool(isShowKeyboard); }); @@ -47,25 +47,25 @@ int32_t InputMethodSystemAbilityProxy::StartInput(sptr client, boo int32_t InputMethodSystemAbilityProxy::ShowCurrentInput() { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(SHOW_CURRENT_INPUT); } int32_t InputMethodSystemAbilityProxy::HideCurrentInput() { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(HIDE_CURRENT_INPUT); } int32_t InputMethodSystemAbilityProxy::StopInputSession() { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(STOP_INPUT_SESSION); } int32_t InputMethodSystemAbilityProxy::StopInput(sptr client) { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(STOP_INPUT, [client](MessageParcel &data) { return data.WriteRemoteObject(client->AsObject()); }); } @@ -84,7 +84,7 @@ int32_t InputMethodSystemAbilityProxy::DisplayOptionalInputMethod() int32_t InputMethodSystemAbilityProxy::SetCoreAndAgent(sptr core, sptr agent) { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(SET_CORE_AND_AGENT, [core, agent](MessageParcel &data) { return data.WriteRemoteObject(core->AsObject()) && data.WriteRemoteObject(agent->AsObject()); }); @@ -92,14 +92,14 @@ int32_t InputMethodSystemAbilityProxy::SetCoreAndAgent(sptr co int32_t InputMethodSystemAbilityProxy::GetKeyboardWindowHeight(int32_t &retHeight) { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(GET_KEYBOARD_WINDOW_HEIGHT, nullptr, [&retHeight](MessageParcel &reply) { return reply.ReadInt32(retHeight); }); } std::shared_ptr InputMethodSystemAbilityProxy::GetCurrentInputMethod() { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); std::shared_ptr property = nullptr; int32_t ret = SendRequest(GET_CURRENT_INPUT_METHOD, nullptr, [&property](MessageParcel &reply) { property = std::make_shared(); @@ -118,7 +118,7 @@ std::shared_ptr InputMethodSystemAbilityProxy::GetCurrentInputMethod() std::shared_ptr InputMethodSystemAbilityProxy::GetCurrentInputMethodSubtype() { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); std::shared_ptr property = nullptr; int32_t ret = SendRequest(GET_CURRENT_INPUT_METHOD_SUBTYPE, nullptr, [&property](MessageParcel &reply) { property = std::make_shared(); @@ -137,7 +137,7 @@ std::shared_ptr InputMethodSystemAbilityProxy::GetCurrentInputMetho int32_t InputMethodSystemAbilityProxy::ListInputMethod(InputMethodStatus status, std::vector &props) { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); int32_t ret = SendRequest( LIST_INPUT_METHOD, [status](MessageParcel &data) { return ITypesUtil::Marshal(data, uint32_t(status)); }, [&props](MessageParcel &reply) { return ITypesUtil::Unmarshal(reply, props); }); @@ -149,26 +149,26 @@ int32_t InputMethodSystemAbilityProxy::ListInputMethod(InputMethodStatus status, int32_t InputMethodSystemAbilityProxy::ShowCurrentInputDeprecated() { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(SHOW_CURRENT_INPUT_DEPRECATED); } int32_t InputMethodSystemAbilityProxy::HideCurrentInputDeprecated() { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(HIDE_CURRENT_INPUT_DEPRECATED); } int32_t InputMethodSystemAbilityProxy::DisplayOptionalInputMethodDeprecated() { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(DISPLAY_OPTIONAL_INPUT_DEPRECATED); } int32_t InputMethodSystemAbilityProxy::SetCoreAndAgentDeprecated(sptr core, sptr agent) { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); return SendRequest(SET_CORE_AND_AGENT_DEPRECATED, [core, agent](MessageParcel &data) { return data.WriteRemoteObject(core->AsObject()) && data.WriteRemoteObject(agent->AsObject()); }); @@ -177,7 +177,7 @@ int32_t InputMethodSystemAbilityProxy::SetCoreAndAgentDeprecated(sptr &subProps) { - IMSA_HILOGI("InputMethodSystemAbilityProxy::ListInputMethodSubtype"); + IMSA_HILOGD("InputMethodSystemAbilityProxy::ListInputMethodSubtype"); int32_t ret = SendRequest( LIST_INPUT_METHOD_SUBTYPE, [&name](MessageParcel &data) { return ITypesUtil::Marshal(data, name); }, [&subProps](MessageParcel &reply) { return ITypesUtil::Unmarshal(reply, subProps); }); @@ -189,7 +189,7 @@ int32_t InputMethodSystemAbilityProxy::ListInputMethodSubtype( int32_t InputMethodSystemAbilityProxy::ListCurrentInputMethodSubtype(std::vector &subProps) { - IMSA_HILOGI("InputMethodSystemAbilityProxy::ListCurrentInputMethodSubtype"); + IMSA_HILOGD("InputMethodSystemAbilityProxy::ListCurrentInputMethodSubtype"); int32_t ret = SendRequest(LIST_CURRENT_INPUT_METHOD_SUBTYPE, nullptr, [&subProps](MessageParcel &reply) { return ITypesUtil::Unmarshal(reply, subProps); }); if (ret != ErrorCode::NO_ERROR) { @@ -200,14 +200,14 @@ int32_t InputMethodSystemAbilityProxy::ListCurrentInputMethodSubtype(std::vector int32_t InputMethodSystemAbilityProxy::SwitchInputMethod(const std::string &name, const std::string &subName) { - IMSA_HILOGI("InputMethodSystemAbilityProxy::SwitchInputMethod"); + IMSA_HILOGD("InputMethodSystemAbilityProxy::SwitchInputMethod"); return SendRequest(SWITCH_INPUT_METHOD, [&name, &subName](MessageParcel &data) { return ITypesUtil::Marshal(data, name, subName); }); } int32_t InputMethodSystemAbilityProxy::SendRequest(int code, ParcelHandler input, ParcelHandler output) { - IMSA_HILOGI("%{public}s in", __func__); + IMSA_HILOGD("%{public}s in", __func__); MessageParcel data; MessageParcel reply; MessageOption option{ MessageOption::TF_SYNC }; diff --git a/frameworks/kits/extension/include/js_inputmethod_extension_context.h b/frameworks/kits/extension/include/js_inputmethod_extension_context.h index be74c6da..eea4d3f5 100644 --- a/frameworks/kits/extension/include/js_inputmethod_extension_context.h +++ b/frameworks/kits/extension/include/js_inputmethod_extension_context.h @@ -47,19 +47,19 @@ private: std::unique_ptr jsConnectionObject_ = nullptr; }; -struct ConnecttionKey { +struct ConnectionKey { AAFwk::Want want; int64_t id; }; struct key_compare { - bool operator()(const ConnecttionKey &key1, const ConnecttionKey &key2) const + bool operator()(const ConnectionKey &key1, const ConnectionKey &key2) const { return key1.id < key2.id; } }; -static std::map, key_compare> connects_; +static std::map, key_compare> connects_; static int64_t serialNumber_ = 0; static std::shared_ptr handler_ = nullptr; } // namespace AbilityRuntime diff --git a/frameworks/kits/extension/src/js_inputmethod_extension_context.cpp b/frameworks/kits/extension/src/js_inputmethod_extension_context.cpp index 717fccf2..57e09e24 100644 --- a/frameworks/kits/extension/src/js_inputmethod_extension_context.cpp +++ b/frameworks/kits/extension/src/js_inputmethod_extension_context.cpp @@ -260,7 +260,7 @@ private: sptr connection = new JSInputMethodExtensionConnection(engine); connection->SetJsConnectionObject(info.argv[1]); int64_t connectId = serialNumber_; - ConnecttionKey key; + ConnectionKey key; key.id = serialNumber_; key.want = want; connects_.emplace(key, connection); @@ -316,7 +316,7 @@ private: sptr connection = new JSInputMethodExtensionConnection(engine); connection->SetJsConnectionObject(info.argv[1]); int64_t connectId = serialNumber_; - ConnecttionKey key; + ConnectionKey key; key.id = serialNumber_; key.want = want; connects_.emplace(key, connection); @@ -363,7 +363,7 @@ private: reinterpret_cast(&engine), reinterpret_cast(info.argv[INDEX_ZERO]), &connectId); IMSA_HILOGI("OnDisconnectAbility connection:%{public}d", static_cast(connectId)); auto item = std::find_if(connects_.begin(), connects_.end(), - [&connectId](const std::map>::value_type &obj) { return connectId == obj.first.id; }); @@ -596,7 +596,7 @@ void JSInputMethodExtensionConnection::HandleOnAbilityDisconnectDone( std::string abilityName = element.GetAbilityName(); auto item = std::find_if(connects_.begin(), connects_.end(), [bundleName, abilityName]( - const std::map>::value_type &obj) { + const std::map>::value_type &obj) { return (bundleName == obj.first.want.GetBundle()) && (abilityName == obj.first.want.GetElement().GetAbilityName()); }); diff --git a/interfaces/kits/js/napi/inputmethod_extension_ability/inputmethod_extension_ability_module.cpp b/interfaces/kits/js/napi/inputmethod_extension_ability/inputmethod_extension_ability_module.cpp index 4234dc2a..f06ee45a 100644 --- a/interfaces/kits/js/napi/inputmethod_extension_ability/inputmethod_extension_ability_module.cpp +++ b/interfaces/kits/js/napi/inputmethod_extension_ability/inputmethod_extension_ability_module.cpp @@ -41,7 +41,7 @@ extern "C" __attribute__((visibility("default"))) void NAPI_inputmethodextension } } -// inputmethod_extension_abiltiy JS register +// inputmethod_extension_ability JS register extern "C" __attribute__((visibility("default"))) void NAPI_inputmethodextensionability_GetABCCode( const char **buf, int *buflen) { diff --git a/interfaces/kits/js/napi/inputmethod_extension_context/inputmethod_extension_context.js b/interfaces/kits/js/napi/inputmethod_extension_context/inputmethod_extension_context.js index 1b27a1b7..e50ea058 100644 --- a/interfaces/kits/js/napi/inputmethod_extension_context/inputmethod_extension_context.js +++ b/interfaces/kits/js/napi/inputmethod_extension_context/inputmethod_extension_context.js @@ -13,7 +13,7 @@ * limitations under the License. */ -var ExtensionContext = requireNapi("application.ExtensionContext") +const ExtensionContext = requireNapi("application.ExtensionContext"); class InputMethodExtensionContext extends ExtensionContext { constructor(obj) { diff --git a/interfaces/kits/js/napi/inputmethodability/js_callback_object.h b/interfaces/kits/js/napi/inputmethodability/js_callback_object.h index 197ff0f8..60f7309e 100644 --- a/interfaces/kits/js/napi/inputmethodability/js_callback_object.h +++ b/interfaces/kits/js/napi/inputmethodability/js_callback_object.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef CALLBAKC_OBJECT_H -#define CALLBAKC_OBJECT_H +#ifndef JS_CALLBACK_OBJECT_H +#define JS_CALLBACK_OBJECT_H #include @@ -32,4 +32,4 @@ public: }; } // namespace MiscServices } // namespace OHOS -#endif // CALLBAKC_OBJECT_H \ No newline at end of file +#endif // JS_CALLBACK_OBJECT_H diff --git a/interfaces/kits/js/napi/inputmethodability/js_input_method_engine_setting.cpp b/interfaces/kits/js/napi/inputmethodability/js_input_method_engine_setting.cpp index 3d7de195..9338920e 100644 --- a/interfaces/kits/js/napi/inputmethodability/js_input_method_engine_setting.cpp +++ b/interfaces/kits/js/napi/inputmethodability/js_input_method_engine_setting.cpp @@ -226,7 +226,7 @@ void JsInputMethodEngineSetting::RegisterListener(napi_value callback, std::stri IMSA_HILOGI("RegisterListener %{public}s", type.c_str()); std::lock_guard lock(mutex_); if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) { - IMSA_HILOGE("methodName: %{public}s not registertd!", type.c_str()); + IMSA_HILOGE("methodName: %{public}s not registered!", type.c_str()); } for (auto &item : jsCbMap_[type]) { @@ -245,7 +245,7 @@ void JsInputMethodEngineSetting::UnRegisterListener(napi_value callback, std::st IMSA_HILOGI("UnRegisterListener %{public}s", type.c_str()); std::lock_guard lock(mutex_); if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) { - IMSA_HILOGE("methodName: %{public}s already unRegisterted!", type.c_str()); + IMSA_HILOGE("methodName: %{public}s already unRegistered!", type.c_str()); return; } @@ -255,7 +255,7 @@ void JsInputMethodEngineSetting::UnRegisterListener(napi_value callback, std::st return; } - for (auto item = jsCbMap_[type].begin(); item != jsCbMap_[type].end();) { + for (auto item = jsCbMap_[type].begin(); item != jsCbMap_[type].end(); item++) { if (Equals((*item)->env_, callback, (*item)->callback_, (*item)->threadId_)) { jsCbMap_[type].erase(item); break; @@ -734,7 +734,7 @@ void JsInputMethodEngineSetting::OnSetSubtype(const SubProperty &property) for (auto item : entry->vecCopy) { napi_value jsObject = GetResultOnSetSubtype(item->env_, entry->subProperty); if (jsObject == nullptr) { - IMSA_HILOGE("get GetResultOnSetSubtype failed: %{punlic}p", jsObject); + IMSA_HILOGE("get GetResultOnSetSubtype failed: jsObject is nullptr"); continue; } napi_value callback = nullptr; diff --git a/interfaces/kits/js/napi/inputmethodability/js_keyboard_delegate_setting.cpp b/interfaces/kits/js/napi/inputmethodability/js_keyboard_delegate_setting.cpp index c592ef3b..30d9ecb9 100644 --- a/interfaces/kits/js/napi/inputmethodability/js_keyboard_delegate_setting.cpp +++ b/interfaces/kits/js/napi/inputmethodability/js_keyboard_delegate_setting.cpp @@ -195,7 +195,7 @@ void JsKeyboardDelegateSetting::UnRegisterListener(napi_value callback, std::str IMSA_HILOGI("UnRegisterListener %{public}s", type.c_str()); std::lock_guard lock(mutex_); if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) { - IMSA_HILOGE("methodName %{public}s not unRegisterted!", type.c_str()); + IMSA_HILOGE("methodName %{public}s not unRegistered!", type.c_str()); return; } @@ -205,7 +205,7 @@ void JsKeyboardDelegateSetting::UnRegisterListener(napi_value callback, std::str return; } - for (auto item = jsCbMap_[type].begin(); item != jsCbMap_[type].end();) { + for (auto item = jsCbMap_[type].begin(); item != jsCbMap_[type].end(); item++) { if ((callback != nullptr) && (Equals((*item)->env_, callback, (*item)->callback_, (*item)->threadId_))) { jsCbMap_[type].erase(item); break; @@ -375,7 +375,7 @@ bool JsKeyboardDelegateSetting::OnKeyEvent(int32_t keyCode, int32_t keyStatus) napi_value jsObject = GetResultOnKeyEvent(item->env_, entry->keyEventPara.keyCode, entry->keyEventPara.keyStatus); if (jsObject == nullptr) { - IMSA_HILOGE("get GetResultOnKeyEvent failed: %{punlic}p", jsObject); + IMSA_HILOGE("get GetResultOnKeyEvent failed: jsObject is nullptr"); continue; } napi_value callback = nullptr; @@ -643,4 +643,4 @@ void JsKeyboardDelegateSetting::OnTextChange(std::string text) }); } } // namespace MiscServices -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/kits/js/napi/inputmethodability/js_text_input_client_engine.cpp b/interfaces/kits/js/napi/inputmethodability/js_text_input_client_engine.cpp index d1b4366b..1bfd5139 100644 --- a/interfaces/kits/js/napi/inputmethodability/js_text_input_client_engine.cpp +++ b/interfaces/kits/js/napi/inputmethodability/js_text_input_client_engine.cpp @@ -76,7 +76,7 @@ napi_value JsTextInputClientEngine::MoveCursor(napi_env env, napi_callback_info } }; ctxt->SetAction(std::move(input)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(ctxt), 0); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(ctxt)); return asyncCall.Call(env, exec); } diff --git a/interfaces/kits/js/napi/inputmethodability/js_text_input_client_engine.h b/interfaces/kits/js/napi/inputmethodability/js_text_input_client_engine.h index 403d4cd0..2493b5cb 100644 --- a/interfaces/kits/js/napi/inputmethodability/js_text_input_client_engine.h +++ b/interfaces/kits/js/napi/inputmethodability/js_text_input_client_engine.h @@ -45,7 +45,7 @@ struct SendKeyFunctionContext : public AsyncCall::Context { }; struct MoveCursorContext : public AsyncCall::Context { - bool num = false; + int32_t num = 0; napi_status status = napi_generic_failure; MoveCursorContext() : Context(nullptr, nullptr){}; MoveCursorContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)){}; diff --git a/interfaces/kits/js/napi/inputmethodclient/js_get_input_method_controller.h b/interfaces/kits/js/napi/inputmethodclient/js_get_input_method_controller.h index f916d9fc..1b9e9c5a 100644 --- a/interfaces/kits/js/napi/inputmethodclient/js_get_input_method_controller.h +++ b/interfaces/kits/js/napi/inputmethodclient/js_get_input_method_controller.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef INTERFACE_KITS_JS_GETINPUT_METHOD_CCONTROLLER_H -#define INTERFACE_KITS_JS_GETINPUT_METHOD_CCONTROLLER_H +#ifndef INTERFACE_KITS_JS_GET_INPUT_METHOD_CONTROLLER_H +#define INTERFACE_KITS_JS_GET_INPUT_METHOD_CONTROLLER_H #include "async_call.h" #include "global.h" @@ -63,4 +63,4 @@ private: }; } // namespace MiscServices } // namespace OHOS -#endif // INTERFACE_KITS_JS_GETINPUT_METHOD_CCONTROLLER_H +#endif // INTERFACE_KITS_JS_GET_INPUT_METHOD_CONTROLLER_H diff --git a/interfaces/kits/js/napi/inputmethodclient/js_get_input_method_setting.cpp b/interfaces/kits/js/napi/inputmethodclient/js_get_input_method_setting.cpp index e78c6902..33fce24e 100644 --- a/interfaces/kits/js/napi/inputmethodclient/js_get_input_method_setting.cpp +++ b/interfaces/kits/js/napi/inputmethodclient/js_get_input_method_setting.cpp @@ -427,7 +427,7 @@ void JsGetInputMethodSetting::RegisterListener( IMSA_HILOGI("RegisterListener %{public}s", type.c_str()); std::lock_guard lock(mutex_); if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) { - IMSA_HILOGE("methodName: %{public}s not registertd!", type.c_str()); + IMSA_HILOGE("methodName: %{public}s not registered!", type.c_str()); } for (auto &item : jsCbMap_[type]) { @@ -478,7 +478,7 @@ void JsGetInputMethodSetting::UnRegisterListener(napi_value callback, std::strin IMSA_HILOGI("UnRegisterListener %{public}s", type.c_str()); std::lock_guard lock(mutex_); if (jsCbMap_.empty() || jsCbMap_.find(type) == jsCbMap_.end()) { - IMSA_HILOGE("methodName: %{public}s already unRegisterted!", type.c_str()); + IMSA_HILOGE("methodName: %{public}s already unRegistered!", type.c_str()); return; } @@ -488,7 +488,7 @@ void JsGetInputMethodSetting::UnRegisterListener(napi_value callback, std::strin return; } - for (auto item = jsCbMap_[type].begin(); item != jsCbMap_[type].end();) { + for (auto item = jsCbMap_[type].begin(); item != jsCbMap_[type].end(); item++) { if (Equals((*item)->env_, callback, (*item)->callback_, (*item)->threadId_)) { jsCbMap_[type].erase(item); break; diff --git a/interfaces/kits/js/napi/inputmethodclient/js_utils.cpp b/interfaces/kits/js/napi/inputmethodclient/js_utils.cpp index 2a3b644e..afee9e40 100644 --- a/interfaces/kits/js/napi/inputmethodclient/js_utils.cpp +++ b/interfaces/kits/js/napi/inputmethodclient/js_utils.cpp @@ -20,9 +20,7 @@ namespace MiscServices { const std::map JsUtils::ERROR_CODE_MAP = { { ErrorCode::ERROR_STATUS_PERMISSION_DENIED, EXCEPTION_PERMISSION }, { ErrorCode::ERROR_REMOTE_IME_DIED, EXCEPTION_IMENGINE }, - { ErrorCode::ERROR_RESTART_IME_FAILED, EXCEPTION_IMENGINE }, { ErrorCode::ERROR_REMOTE_CLIENT_DIED, EXCEPTION_IMCLIENT }, - { ErrorCode::ERROR_CLIENT_DUPLICATED, EXCEPTION_IMCLIENT }, { ErrorCode::ERROR_CLIENT_NOT_FOUND, EXCEPTION_IMCLIENT }, { ErrorCode::ERROR_CLIENT_NULL_POINTER, EXCEPTION_IMCLIENT }, { ErrorCode::ERROR_NOT_IME_PACKAGE, EXCEPTION_SETTINGS }, @@ -42,19 +40,11 @@ const std::map JsUtils::ERROR_CODE_MAP = { { ErrorCode::ERROR_IME_BIND_FAILED, EXCEPTION_IMMS }, { ErrorCode::ERROR_IME_UNBIND_FAILED, EXCEPTION_IMMS }, { ErrorCode::ERROR_IME_START_FAILED, EXCEPTION_IMMS }, - { ErrorCode::ERROR_IME_STOP_FAILED, EXCEPTION_IMMS }, { ErrorCode::ERROR_KBD_SHOW_FAILED, EXCEPTION_IMMS }, { ErrorCode::ERROR_KBD_HIDE_FAILED, EXCEPTION_IMMS }, { ErrorCode::ERROR_IME_NOT_STARTED, EXCEPTION_IMMS }, { ErrorCode::ERROR_KBD_IS_OCCUPIED, EXCEPTION_IMMS }, { ErrorCode::ERROR_KBD_IS_NOT_SHOWING, EXCEPTION_IMMS }, - { ErrorCode::ERROR_IME_ALREADY_STARTED, EXCEPTION_IMMS }, - { ErrorCode::ERROR_NO_NEXT_IME, EXCEPTION_IMMS }, - { ErrorCode::ERROR_CLIENTWINDOW_NOT_FOCUSED, EXCEPTION_IMMS }, - { ErrorCode::ERROR_CLIENT_NOT_WINDOW, EXCEPTION_IMMS }, - { ErrorCode::ERROR_IME_PROPERTY_MARSHALL, EXCEPTION_IMMS }, - { ErrorCode::ERROR_GETTING_CURRENT_IME, EXCEPTION_IMMS }, - { ErrorCode::ERROR_LIST_IME, EXCEPTION_IMMS }, { ErrorCode::ERROR_EX_NULL_POINTER, EXCEPTION_IMMS }, { ErrorCode::ERROR_PERSIST_CONFIG, EXCEPTION_CONFPERSIST }, { ErrorCode::ERROR_PACKAGE_MANAGER, EXCEPTION_PACKAGEMANAGER }, @@ -83,86 +73,85 @@ const std::map JsUtils::ERROR_CODE_MAP = { }; const std::map JsUtils::ERROR_CODE_CONVERT_MESSAGE_MAP = { - { EXCEPTION_PERMISSION, "the permissions check fails." }, - { EXCEPTION_PARAMCHECK, "the parameters check fails." }, - { EXCEPTION_UNSUPPORTED, "call unsupported api." }, - { EXCEPTION_PACKAGEMANAGER, "package manager error." }, - { EXCEPTION_IMENGINE, "input method engine error." }, - { EXCEPTION_IMCLIENT, "input method client error." }, - { EXCEPTION_KEYEVENT, "key event processing error." }, - { EXCEPTION_CONFPERSIST, "configuration persisting error." }, - { EXCEPTION_CONTROLLER, "input method controller error." }, - { EXCEPTION_SETTINGS, "input method settings extension error." }, - { EXCEPTION_IMMS, "input method manager service error." }, - { EXCEPTION_OTHERS, "others error." }, - }; + { EXCEPTION_PERMISSION, "the permissions check fails." }, + { EXCEPTION_PARAMCHECK, "the parameters check fails." }, + { EXCEPTION_UNSUPPORTED, "call unsupported api." }, + { EXCEPTION_PACKAGEMANAGER, "package manager error." }, + { EXCEPTION_IMENGINE, "input method engine error." }, + { EXCEPTION_IMCLIENT, "input method client error." }, + { EXCEPTION_KEYEVENT, "key event processing error." }, + { EXCEPTION_CONFPERSIST, "configuration persisting error." }, + { EXCEPTION_CONTROLLER, "input method controller error." }, + { EXCEPTION_SETTINGS, "input method settings extension error." }, + { EXCEPTION_IMMS, "input method manager service error." }, + { EXCEPTION_OTHERS, "others error." }, +}; - const std::map JsUtils::PARAMETER_TYPE = { - { TYPE_UNDEFINED, "napi_undefine." }, - { TYPE_NULL, "napi_null." }, - { TYPE_BOOLEAN, "napi_boolean." }, - { TYPE_NUMBER, "napi_number." }, - { TYPE_STRING, "napi_string." }, - { TYPE_SYMBOL, "napi_symbol." }, - { TYPE_OBJECT, "napi_object." }, - { TYPE_FUNCTION, "napi_function." }, - { TYPE_EXTERNAL, "napi_external." }, - { TYPE_BIGINT, "napi_bigint." }, - }; +const std::map JsUtils::PARAMETER_TYPE = { + { TYPE_UNDEFINED, "napi_undefine." }, + { TYPE_NULL, "napi_null." }, + { TYPE_BOOLEAN, "napi_boolean." }, + { TYPE_NUMBER, "napi_number." }, + { TYPE_STRING, "napi_string." }, + { TYPE_SYMBOL, "napi_symbol." }, + { TYPE_OBJECT, "napi_object." }, + { TYPE_FUNCTION, "napi_function." }, + { TYPE_EXTERNAL, "napi_external." }, + { TYPE_BIGINT, "napi_bigint." }, +}; - void JsUtils::ThrowException(napi_env env, int32_t err, const std::string &msg, TypeCode type) - { - std::string errMsg = ToMessage(err); - if (type == TypeCode::TYPE_NONE) { - errMsg = errMsg + msg; - IMSA_HILOGE("THROW_PARAMTER_ERROR message: %{public}s", errMsg.c_str()); - } else { - auto iter = PARAMETER_TYPE.find(type); - if (iter != PARAMETER_TYPE.end()) { - errMsg = errMsg + "The type of " + msg + " must be " + iter->second; - IMSA_HILOGE("THROW_PARAMTER_TYPE_ERROR message: %{public}s", errMsg.c_str()); - } +void JsUtils::ThrowException(napi_env env, int32_t err, const std::string &msg, TypeCode type) +{ + std::string errMsg = ToMessage(err); + if (type == TypeCode::TYPE_NONE) { + errMsg = errMsg + msg; + IMSA_HILOGE("THROW_PARAMETER_ERROR message: %{public}s", errMsg.c_str()); + } else { + auto iter = PARAMETER_TYPE.find(type); + if (iter != PARAMETER_TYPE.end()) { + errMsg = errMsg + "The type of " + msg + " must be " + iter->second; + IMSA_HILOGE("THROW_PARAMETER_TYPE_ERROR message: %{public}s", errMsg.c_str()); } - napi_throw_error(env, std::to_string(err).c_str(), errMsg.c_str()); - } - - napi_value JsUtils::ToError(napi_env env, int32_t code) - { - IMSA_HILOGE("ToError start"); - napi_value errorObj; - NAPI_CALL(env, napi_create_object(env, &errorObj)); - napi_value errorCode = nullptr; - NAPI_CALL( - env, napi_create_string_utf8(env, std::to_string(Convert(code)).c_str(), NAPI_AUTO_LENGTH, &errorCode)); - napi_value errorMessage = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, ToMessage(Convert(code)).c_str(), NAPI_AUTO_LENGTH, &errorMessage)); - NAPI_CALL(env, napi_set_named_property(env, errorObj, "code", errorCode)); - NAPI_CALL(env, napi_set_named_property(env, errorObj, "message", errorMessage)); - IMSA_HILOGE("ToError end"); - return errorObj; - } - - int32_t JsUtils::Convert(int32_t code) - { - IMSA_HILOGI("Convert start"); - auto iter = ERROR_CODE_MAP.find(code); - if (iter != ERROR_CODE_MAP.end()) { - IMSA_HILOGE("ErrorCode: %{public}d", iter->second); - return iter->second; - } - IMSA_HILOGI("Convert end"); - return ERROR_CODE_QUERY_FAILED; - } - - const std::string JsUtils::ToMessage(int32_t code) - { - IMSA_HILOGI("ToMessage start"); - auto iter = ERROR_CODE_CONVERT_MESSAGE_MAP.find(code); - if (iter != ERROR_CODE_CONVERT_MESSAGE_MAP.end()) { - IMSA_HILOGI("ErrorMessage: %{public}s", (iter->second).c_str()); - return iter->second; - } - return "error is out of definition."; } + napi_throw_error(env, std::to_string(err).c_str(), errMsg.c_str()); } -} \ No newline at end of file + +napi_value JsUtils::ToError(napi_env env, int32_t code) +{ + IMSA_HILOGE("ToError start"); + napi_value errorObj; + NAPI_CALL(env, napi_create_object(env, &errorObj)); + napi_value errorCode = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, std::to_string(Convert(code)).c_str(), NAPI_AUTO_LENGTH, &errorCode)); + napi_value errorMessage = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, ToMessage(Convert(code)).c_str(), NAPI_AUTO_LENGTH, &errorMessage)); + NAPI_CALL(env, napi_set_named_property(env, errorObj, "code", errorCode)); + NAPI_CALL(env, napi_set_named_property(env, errorObj, "message", errorMessage)); + IMSA_HILOGE("ToError end"); + return errorObj; +} + +int32_t JsUtils::Convert(int32_t code) +{ + IMSA_HILOGI("Convert start"); + auto iter = ERROR_CODE_MAP.find(code); + if (iter != ERROR_CODE_MAP.end()) { + IMSA_HILOGE("ErrorCode: %{public}d", iter->second); + return iter->second; + } + IMSA_HILOGI("Convert end"); + return ERROR_CODE_QUERY_FAILED; +} + +const std::string JsUtils::ToMessage(int32_t code) +{ + IMSA_HILOGI("ToMessage start"); + auto iter = ERROR_CODE_CONVERT_MESSAGE_MAP.find(code); + if (iter != ERROR_CODE_CONVERT_MESSAGE_MAP.end()) { + IMSA_HILOGI("ErrorMessage: %{public}s", (iter->second).c_str()); + return iter->second; + } + return "error is out of definition."; +} +} // namespace MiscServices +} // namespace OHOS \ No newline at end of file diff --git a/services/BUILD.gn b/services/BUILD.gn index b70afced..abdcb50a 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -23,6 +23,7 @@ config("inputmethod_services_native_config") { "//base/notification/common_event_service/frameworks/core/include", "//base/notification/common_event_service/interfaces/innerkits/native/include", "//foundation/multimodalinput/input/interfaces/native/innerkits/event/include", + "${inputmethod_path}/services/adapter/keyboard/include", "${inputmethod_path}/services/dfx/include", ] @@ -57,7 +58,6 @@ ohos_shared_library("inputmethod_service") { deps = [ "${ability_runtime_inner_api_path}/ability_manager:ability_manager", - "${ability_runtime_services_path}/abilitymgr:abilityms", "${inputmethod_path}/services/adapter/keyboard:keboard_event_static", "${inputmethod_path}/services/dfx:inputmethod_dfx_static", "//base/global/resource_management/frameworks/resmgr:global_resmgr", diff --git a/services/adapter/keyboard/BUILD.gn b/services/adapter/keyboard/BUILD.gn index d07b86ae..cac9aca9 100644 --- a/services/adapter/keyboard/BUILD.gn +++ b/services/adapter/keyboard/BUILD.gn @@ -23,7 +23,10 @@ config("inputmethod_adapter_native_config") { } ohos_static_library("keboard_event_static") { - sources = [ "keyboard_event.cpp" ] + sources = [ + "src/input_event_callback.cpp", + "src/keyboard_event.cpp", + ] configs = [ ":inputmethod_adapter_native_config" ] diff --git a/services/adapter/keyboard/include/input_event_callback.h b/services/adapter/keyboard/include/input_event_callback.h new file mode 100644 index 00000000..1612fbe3 --- /dev/null +++ b/services/adapter/keyboard/include/input_event_callback.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INPUTMETHOD_IMF_INPUT_EVENT_CALLBACK_H +#define INPUTMETHOD_IMF_INPUT_EVENT_CALLBACK_H + +#include +#include +#include + +#include "input_manager.h" +#include "key_event.h" +#include "keyboard_event.h" + +namespace OHOS { +namespace MiscServices { +class InputEventCallback : public MMI::IInputEventConsumer { +public: + virtual void OnInputEvent(std::shared_ptr keyEvent) const; + virtual void OnInputEvent(std::shared_ptr pointerEvent) const; + virtual void OnInputEvent(std::shared_ptr axisEvent) const; + void SetKeyHandle(KeyHandle handle); + +private: + KeyHandle keyHandler_ = nullptr; + static uint32_t keyState_; +}; +} // namespace MiscServices +} // namespace OHOS + +#endif // INPUTMETHOD_IMF_INPUT_EVENT_CALLBACK_H diff --git a/services/adapter/keyboard/keyboard_event.h b/services/adapter/keyboard/include/keyboard_event.h similarity index 64% rename from services/adapter/keyboard/keyboard_event.h rename to services/adapter/keyboard/include/keyboard_event.h index 624f54b5..2ad7df15 100644 --- a/services/adapter/keyboard/keyboard_event.h +++ b/services/adapter/keyboard/include/keyboard_event.h @@ -20,21 +20,26 @@ #include #include -namespace OHOS ::MiscServices { +#include "global.h" +#include "key_event.h" -struct CombineKey { - std::set preKeys; - int32_t finalKey; -}; - -enum CombineKeyCode : uint32_t { COMBINE_KEYCODE_CAPS = 0, COMBINE_KEYCODE_SHIFT, COMBINE_KEYCODE_CTRL_SHIFT }; - -using KeyHandle = std::function; +namespace OHOS { +namespace MiscServices { +using KeyHandle = std::function; class KeyboardEvent { public: static KeyboardEvent &GetInstance(); - int32_t SubscribeKeyboardEvent(const CombineKey &combine, KeyHandle handle); + static int32_t AddKeyEventMonitor(KeyHandle handle); + static constexpr uint8_t SHIFT_LEFT_MASK = 0X1; + static constexpr uint8_t SHIFT_RIGHT_MASK = 0X1 << 1; + static constexpr uint8_t CTRL_LEFT_MASK = 0X1 << 2; + static constexpr uint8_t CTRL_RIGHT_MASK = 0X1 << 3; + static constexpr uint8_t CAPS_MASK = 0X1 << 4; + static constexpr bool IS_KEYS_DOWN(uint32_t state, uint8_t mask) + { + return state == mask; + } private: static constexpr int32_t PRESS_KEY_DELAY_MS = 200; @@ -44,11 +49,6 @@ private: KeyboardEvent &operator=(const KeyboardEvent &) = delete; KeyboardEvent &operator=(KeyboardEvent &&) = delete; }; - -struct KeyboardEventHandler { - CombineKey combine; - KeyHandle handle; -}; - -} // namespace OHOS::MiscServices +} // namespace MiscServices +} // namespace OHOS #endif // IMF_KEYBOARD_EVENT_H diff --git a/services/adapter/keyboard/keyboard_event.cpp b/services/adapter/keyboard/keyboard_event.cpp deleted file mode 100644 index 93da2434..00000000 --- a/services/adapter/keyboard/keyboard_event.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "keyboard_event.h" - -#include -#include -#include - -#include - -#include "global.h" - -namespace OHOS::MiscServices { - -using namespace MMI; - -KeyboardEvent &KeyboardEvent::GetInstance() -{ - static KeyboardEvent keyboardEvent; - return keyboardEvent; -} - -int32_t KeyboardEvent::SubscribeKeyboardEvent(const CombineKey &combine, KeyHandle handle) -{ - std::shared_ptr keyOption = std::make_shared(); - keyOption->SetPreKeys(combine.preKeys); - keyOption->SetFinalKey(combine.finalKey); - keyOption->SetFinalKeyDown(true); - keyOption->SetFinalKeyDownDuration(0); - auto ret = - InputManager::GetInstance()->SubscribeKeyEvent(keyOption, [this, handle](std::shared_ptr keyEvent) { - auto pressKeys = keyEvent->GetPressedKeys(); - for (auto &key : pressKeys) { - IMSA_HILOGI("key code: %{public}d", key); - } - if (handle != nullptr) { - handle(); - } - }); - IMSA_HILOGI("subscribe %{public}d key event %{public}s", combine.finalKey, ret >= 0 ? "OK" : "ERROR"); - return ret >= 0 ? ErrorCode::NO_ERROR : ErrorCode::ERROR_SUBSCRIBE_KEYBOARD_EVENT; -} -} // namespace OHOS::MiscServices diff --git a/services/adapter/keyboard/src/input_event_callback.cpp b/services/adapter/keyboard/src/input_event_callback.cpp new file mode 100644 index 00000000..3d213405 --- /dev/null +++ b/services/adapter/keyboard/src/input_event_callback.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "input_event_callback.h" + +#include "global.h" + +namespace OHOS { +namespace MiscServices { +uint32_t InputEventCallback::keyState_ = static_cast(0); +const std::map MASK_MAP{ + { MMI::KeyEvent::KEYCODE_SHIFT_LEFT, KeyboardEvent::SHIFT_LEFT_MASK }, + { MMI::KeyEvent::KEYCODE_SHIFT_RIGHT, KeyboardEvent::SHIFT_RIGHT_MASK }, + { MMI::KeyEvent::KEYCODE_CTRL_LEFT, KeyboardEvent::CTRL_LEFT_MASK }, + { MMI::KeyEvent::KEYCODE_CTRL_RIGHT, KeyboardEvent::CTRL_RIGHT_MASK }, + { MMI::KeyEvent::KEYCODE_CAPS_LOCK, KeyboardEvent::CAPS_MASK }, +}; + +void InputEventCallback::OnInputEvent(std::shared_ptr keyEvent) const +{ + auto keyCode = keyEvent->GetKeyCode(); + auto keyAction = keyEvent->GetKeyAction(); + auto currKey = MASK_MAP.find(keyCode); + if (currKey == MASK_MAP.end()) { + IMSA_HILOGD("key code unknown"); + return; + } + IMSA_HILOGD("keyCode: %{public}d, keyAction: %{public}d", keyCode, keyAction); + + if (keyAction == MMI::KeyEvent::KEY_ACTION_DOWN) { + IMSA_HILOGD("key %{public}d pressed down", keyCode); + keyState_ = static_cast(keyState_ | currKey->second); + return; + } + + if (keyAction == MMI::KeyEvent::KEY_ACTION_UP) { + if (keyHandler_ != nullptr) { + int32_t ret = keyHandler_(keyState_); + IMSA_HILOGI("handle key event ret: %{public}d", ret); + } + keyState_ = static_cast(keyState_ & ~currKey->second); + } +} + +void InputEventCallback::OnInputEvent(std::shared_ptr pointerEvent) const +{ +} + +void InputEventCallback::OnInputEvent(std::shared_ptr axisEvent) const +{ +} + +void InputEventCallback::SetKeyHandle(KeyHandle handle) +{ + keyHandler_ = std::move(handle); +} +} // namespace MiscServices +} // namespace OHOS \ No newline at end of file diff --git a/services/adapter/keyboard/src/keyboard_event.cpp b/services/adapter/keyboard/src/keyboard_event.cpp new file mode 100644 index 00000000..b843ae15 --- /dev/null +++ b/services/adapter/keyboard/src/keyboard_event.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "keyboard_event.h" + +#include + +#include + +#include "global.h" +#include "input_event_callback.h" +#include "key_event.h" + +namespace OHOS { +namespace MiscServices { +using namespace MMI; + +KeyboardEvent &KeyboardEvent::GetInstance() +{ + static KeyboardEvent keyboardEvent; + return keyboardEvent; +} + +int32_t KeyboardEvent::AddKeyEventMonitor(KeyHandle handle) +{ + IMSA_HILOGI("KeyboardEvent::AddKeyEventMonitor"); + std::shared_ptr callback = std::make_shared(); + callback->SetKeyHandle(handle); + int32_t monitorId = + InputManager::GetInstance()->AddMonitor(std::static_pointer_cast(callback)); + if (monitorId < 0) { + IMSA_HILOGE("add monitor failed, id: %{public}d", monitorId); + return ErrorCode::ERROR_SUBSCRIBE_KEYBOARD_EVENT; + } + IMSA_HILOGD("add monitor success, id: %{public}d", monitorId); + return ErrorCode::NO_ERROR; +} +} // namespace MiscServices +} // namespace OHOS diff --git a/services/dfx/include/inputmethod_dump.h b/services/dfx/include/inputmethod_dump.h index a525792b..5f7098b4 100644 --- a/services/dfx/include/inputmethod_dump.h +++ b/services/dfx/include/inputmethod_dump.h @@ -38,7 +38,7 @@ public: private: void ShowHelp(int fd); - void ShowIllealInfomation(int fd); + void ShowIllealInformation(int fd); mutable std::mutex hidumperMutex_; std::list errorInfo_; DumpNoParamFunc dumpAllMethod_; diff --git a/services/dfx/include/inputmethod_sysevent.h b/services/dfx/include/inputmethod_sysevent.h index 9cd32b6d..a5cbba5e 100644 --- a/services/dfx/include/inputmethod_sysevent.h +++ b/services/dfx/include/inputmethod_sysevent.h @@ -22,7 +22,7 @@ namespace OHOS { namespace MiscServices { -void FaultReporter(int32_t userId, std::string bundname, int32_t errCode); +void FaultReporter(int32_t userId, std::string bundleName, int32_t errCode); void CreateComponentFailed(int32_t userId, int32_t errCode); void BehaviourReporter(std::string ActiveName, const std::string &inputmethodName); } // namespace MiscServices diff --git a/services/dfx/src/inputmethod_dump.cpp b/services/dfx/src/inputmethod_dump.cpp index 61dbe14b..703f4471 100644 --- a/services/dfx/src/inputmethod_dump.cpp +++ b/services/dfx/src/inputmethod_dump.cpp @@ -25,7 +25,7 @@ namespace OHOS { namespace MiscServices { -constexpr int32_t MAX_RECORED_ERROR = 10; +constexpr int32_t MAX_RECORD_ERROR = 10; constexpr int32_t SUB_CMD_NAME = 0; constexpr int32_t CMD_ONE_PARAM = 1; constexpr const char *CMD_HELP = "-h"; @@ -43,7 +43,7 @@ void InputmethodDump::AddDumpAllMethod(const DumpNoParamFunc dumpAllMethod) void InputmethodDump::AddErrorInfo(const std::string &error) { std::lock_guard lock(hidumperMutex_); - if (errorInfo_.size() + 1 > MAX_RECORED_ERROR) { + if (errorInfo_.size() + 1 > MAX_RECORD_ERROR) { errorInfo_.pop_front(); errorInfo_.push_back(error); } else { @@ -58,7 +58,7 @@ bool InputmethodDump::Dump(int fd, const std::vector &args) if (args.size() == CMD_ONE_PARAM) { command = args.at(SUB_CMD_NAME); } else { - ShowIllealInfomation(fd); + ShowIllealInformation(fd); } if (command == CMD_HELP) { ShowHelp(fd); @@ -68,7 +68,7 @@ bool InputmethodDump::Dump(int fd, const std::vector &args) } dumpAllMethod_(fd); } else { - ShowIllealInfomation(fd); + ShowIllealInformation(fd); } IMSA_HILOGI("InputmethodDump::Dump command=%{public}s.", command.c_str()); return true; @@ -84,7 +84,7 @@ void InputmethodDump::ShowHelp(int fd) dprintf(fd, "%s\n", result.c_str()); } -void InputmethodDump::ShowIllealInfomation(int fd) +void InputmethodDump::ShowIllealInformation(int fd) { dprintf(fd, "%s\n", ILLEGAL_INFO.c_str()); } diff --git a/services/dfx/src/inputmethod_sysevent.cpp b/services/dfx/src/inputmethod_sysevent.cpp index 51970eea..ebbe54d3 100644 --- a/services/dfx/src/inputmethod_sysevent.cpp +++ b/services/dfx/src/inputmethod_sysevent.cpp @@ -24,10 +24,10 @@ using HiSysEventNameSpace = OHOS::HiviewDFX::HiSysEvent; const std::string DOMAIN_STR = std::string(HiSysEventNameSpace::Domain::INPUTMETHOD); } // namespace -void FaultReporter(int32_t userId, std::string bundname, int32_t errCode) +void FaultReporter(int32_t userId, std::string bundleName, int32_t errCode) { int ret = HiSysEventNameSpace::Write(DOMAIN_STR, "SERVICE_INIT_FAILED", HiSysEventNameSpace::EventType::FAULT, - "USER_ID", userId, "COMPONENT_ID", bundname, "ERROR_CODE", errCode); + "USER_ID", userId, "COMPONENT_ID", bundleName, "ERROR_CODE", errCode); if (ret != 0) { IMSA_HILOGE("hisysevent FaultReporter failed! ret %{public}d,errCode %{public}d", ret, errCode); } @@ -51,4 +51,4 @@ void BehaviourReporter(std::string ActiveName, const std::string &inputmethodNam } } } // namespace MiscServices -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/dialog/entry/src/main/ets/pages/index.ets b/services/dialog/entry/src/main/ets/pages/index.ets index 57e44022..ab2d1a9c 100644 --- a/services/dialog/entry/src/main/ets/pages/index.ets +++ b/services/dialog/entry/src/main/ets/pages/index.ets @@ -18,7 +18,7 @@ import inputMethod from '@ohos.inputmethod'; @Component struct Dialog { private arr: string[] = [] - private properityMap: Map = new Map(); + private propertyMap: Map = new Map(); @State private win: any = undefined @State private context: any = undefined private inputMethods: Array = null @@ -33,7 +33,7 @@ struct Dialog { for (let inputmethod of this.inputMethods) { let name = inputmethod.packageName this.arr.push(name) - this.properityMap.set(name, inputmethod) + this.propertyMap.set(name, inputmethod) } } @@ -67,8 +67,8 @@ struct Dialog { .borderRadius(10) .backgroundColor($r("app.color.btn_default")) .onClick(async () => { - if (this.properityMap.has(item)) { - let prop = this.properityMap.get(item) + if (this.propertyMap.has(item)) { + let prop = this.propertyMap.get(item) globalThis.chooseInputMethods(prop) } setTimeout(() => { diff --git a/services/include/global.h b/services/include/global.h index 42128ac7..f72530b6 100644 --- a/services/include/global.h +++ b/services/include/global.h @@ -101,65 +101,54 @@ enum { ERROR_STATUS_UNEXPECTED_NULL = ERROR_STATUS_UNKNOWN_ERROR + 8, // unexpected null, // binder exception error code from Status.h - ERROR_EX_ILLEGAL_ARGUMENT = -3, // illegal argument exception - ERROR_EX_NULL_POINTER = -4, // null pointer exception - ERROR_EX_ILLEGAL_STATE = -5, // illegal state exception - ERROR_EX_NETWORK_MAIN_THREAD = -6, // network main thread exception - ERROR_EX_UNSUPPORTED_OPERATION = -7, // unsupported operation exception - ERROR_EX_SERVICE_SPECIFIC = -8, // service specific exception - ERROR_EX_PARCELABLE = -9, // parcelable exception + ERROR_EX_ILLEGAL_ARGUMENT = -3, // illegal argument exception + ERROR_EX_NULL_POINTER = -4, // null pointer exception + ERROR_EX_ILLEGAL_STATE = -5, // illegal state exception + ERROR_EX_NETWORK_MAIN_THREAD = -6, // network main thread exception + ERROR_EX_UNSUPPORTED_OPERATION = -7, // unsupported operation exception + ERROR_EX_SERVICE_SPECIFIC = -8, // service specific exception + ERROR_EX_PARCELABLE = -9, // parcelable exception // no error - NO_ERROR = 0, // no error + NO_ERROR = 0, // no error // system service error - ERROR_NULL_POINTER, // null pointer - ERROR_BAD_PARAMETERS, // bad parameters - ERROR_SERVICE_START_FAILED, // failed to start service - ERROR_USER_NOT_STARTED, // user is not started - ERROR_USER_ALREADY_STARTED, // user has already started - ERROR_USER_NOT_UNLOCKED, // user is not unlocked - ERROR_USER_ALREADY_UNLOCKED, // user has already unlocked - ERROR_USER_NOT_LOCKED, // user is not locked + ERROR_NULL_POINTER = 1, // null pointer + ERROR_BAD_PARAMETERS = 2, // bad parameters + ERROR_USER_NOT_STARTED = 3, // user is not started + ERROR_USER_ALREADY_STARTED = 4, // user has already started + ERROR_USER_NOT_UNLOCKED = 5, // user is not unlocked + ERROR_USER_ALREADY_UNLOCKED = 6, // user has already unlocked + ERROR_USER_NOT_LOCKED = 7, // user is not locked - ERROR_IME_NOT_AVAILABLE, // input method engine is not available - ERROR_SECURITY_IME_NOT_AVAILABLE, // security input method engine is not available - ERROR_TOKEN_CREATE_FAILED, // failed to create window token - ERROR_TOKEN_DESTROY_FAILED, // failed to destroy window token - ERROR_IME_BIND_FAILED, // failed to bind IME service - ERROR_IME_UNBIND_FAILED, // failed to unbind IME service - ERROR_IME_START_FAILED, // failed to start IME service - ERROR_IME_STOP_FAILED, // failed to stop IME service - ERROR_KBD_SHOW_FAILED, // failed to show keyboard - ERROR_KBD_HIDE_FAILED, // failed to hide keyboard - ERROR_IME_NOT_STARTED, // input method service is not started - ERROR_KBD_IS_OCCUPIED, // keyboard is showing by other client - ERROR_KBD_IS_NOT_SHOWING, // keyboard is not showing - ERROR_IME_ALREADY_STARTED, // input method service has already started - ERROR_NOT_IME_PACKAGE, // not an IME package - ERROR_IME_PACKAGE_DUPLICATED, // duplicated IME package - ERROR_SETTING_SAME_VALUE, // same setting value - ERROR_NO_NEXT_IME, // no next ime is available - ERROR_CLIENTWINDOW_NOT_FOCUSED, // the input client window is not focused - ERROR_CLIENT_NOT_WINDOW, // the input client is not from a valid window - ERROR_ADD_CLIENT_FAILED, - ERROR_IME_PROPERTY_MARSHALL, // failed to marshall the ime property - ERROR_GETTING_CURRENT_IME, - ERROR_LIST_IME, - ERROR_SWITCH_IME, + ERROR_IME_NOT_AVAILABLE = 8, // input method engine is not available + ERROR_SECURITY_IME_NOT_AVAILABLE = 9, // security input method engine is not available + ERROR_TOKEN_CREATE_FAILED = 10, // failed to create window token + ERROR_TOKEN_DESTROY_FAILED = 11, // failed to destroy window token + ERROR_IME_BIND_FAILED = 12, // failed to bind IME service + ERROR_IME_UNBIND_FAILED = 13, // failed to unbind IME service + ERROR_IME_START_FAILED = 14, // failed to start IME service + ERROR_KBD_SHOW_FAILED = 15, // failed to show keyboard + ERROR_KBD_HIDE_FAILED = 16, // failed to hide keyboard + ERROR_IME_NOT_STARTED = 17, // input method service is not started + ERROR_KBD_IS_OCCUPIED = 18, // keyboard is showing by other client + ERROR_KBD_IS_NOT_SHOWING = 19, // keyboard is not showing + ERROR_NOT_IME_PACKAGE = 20, // not an IME package + ERROR_IME_PACKAGE_DUPLICATED = 21, // duplicated IME package + ERROR_SETTING_SAME_VALUE = 22, // same setting value + ERROR_ADD_CLIENT_FAILED = 23, // add client failed + ERROR_SWITCH_IME = 24, // error from ime - ERROR_REMOTE_IME_DIED, // remote input method service died abnormally - ERROR_RESTART_IME_FAILED, // failed to restart input method service - ERROR_IME_NULL_POINTER, // null pointer + ERROR_REMOTE_IME_DIED = 25, // remote input method service died abnormally // error from client - ERROR_REMOTE_CLIENT_DIED, // remote client died abnormally - ERROR_CLIENT_DUPLICATED, // duplicated client - ERROR_CLIENT_NOT_FOUND, // client is not found - ERROR_CLIENT_NULL_POINTER, // null pointer - ERROR_SUBSCRIBE_KEYBOARD_EVENT, - ERROR_CONTROLLER_INVOKING_FAILED, - ERROR_PERSIST_CONFIG, - ERROR_PACKAGE_MANAGER, - ERROR_ABILITY_ACTIVATING, + ERROR_REMOTE_CLIENT_DIED = 26, // remote client died abnormally + ERROR_CLIENT_NOT_FOUND = 27, // client is not found + ERROR_CLIENT_NULL_POINTER = 28, // null pointer + ERROR_SUBSCRIBE_KEYBOARD_EVENT = 29, + ERROR_CONTROLLER_INVOKING_FAILED = 30, + ERROR_PERSIST_CONFIG = 31, + ERROR_PACKAGE_MANAGER = 32, + ERROR_SERVICE_START_FAILED = 33, + ERROR_ABILITY_ACTIVATING = 34, }; const char *ToString(int errorCode); }; // namespace ErrorCode diff --git a/services/include/im_common_event_manager.h b/services/include/im_common_event_manager.h index ebfa4fc0..9e70d693 100644 --- a/services/include/im_common_event_manager.h +++ b/services/include/im_common_event_manager.h @@ -20,12 +20,12 @@ #include #include -#include "../adapter/keyboard/keyboard_event.h" #include "common_event_data.h" #include "common_event_manager.h" #include "common_event_subscribe_info.h" #include "common_event_subscriber.h" #include "common_event_support.h" +#include "keyboard_event.h" #include "matching_skills.h" #include "system_ability_status_change_stub.h" @@ -37,7 +37,7 @@ public: ~ImCommonEventManager(); static sptr GetInstance(); bool SubscribeEvent(const std::string &event); - bool SubscribeKeyboardEvent(const std::vector &handlers); + bool SubscribeKeyboardEvent(KeyHandle handle); bool UnsubscribeEvent(); class EventSubscriber : public EventFwk::CommonEventSubscriber { @@ -47,6 +47,7 @@ public: { } void OnReceiveEvent(const EventFwk::CommonEventData &data); + void HandlePackageRemove(const AAFwk::Want &want, const std::string action); void startUser(int32_t newUserId); }; diff --git a/services/include/input_method_system_ability.h b/services/include/input_method_system_ability.h index 8518aa0b..efc2c0d7 100644 --- a/services/include/input_method_system_ability.h +++ b/services/include/input_method_system_ability.h @@ -20,7 +20,6 @@ #include #include -#include "../adapter/keyboard/keyboard_event.h" #include "ability_manager_interface.h" #include "application_info.h" #include "bundle_mgr_proxy.h" @@ -29,6 +28,7 @@ #include "input_method_system_ability_stub.h" #include "inputmethod_dump.h" #include "inputmethod_trace.h" +#include "keyboard_event.h" #include "peruser_session.h" #include "peruser_setting.h" #include "system_ability.h" @@ -136,11 +136,11 @@ private: static constexpr const char *SELECT_DIALOG_HAP = "cn.openharmony.inputmethodchoosedialog"; static constexpr const char *SELECT_DIALOG_ABILITY = "InputMethod"; - int32_t SubscribeKeyboardEvent(); + int32_t InitKeyEventMonitor(); using CompareHandler = std::function; SubProperty FindSubPropertyByCompare(const std::string &bundleName, CompareHandler compare); SubProperty GetExtends(const std::vector &metaData); - int32_t SwitchByCombinedKey(const CombineKeyCode &property); + int32_t SwitchByCombinationKey(uint32_t state); int32_t QueryImeInfos(int32_t userId, std::vector &infos); }; diff --git a/services/include/message_handler.h b/services/include/message_handler.h index dd352692..c999b3de 100644 --- a/services/include/message_handler.h +++ b/services/include/message_handler.h @@ -89,6 +89,8 @@ enum { // the request from IMC to IMA MSG_ID_ON_CURSOR_UPDATE, MSG_ID_ON_SELECTION_CHANGE, + + MSG_ID_QUIT_WORKER_THREAD, }; } diff --git a/services/include/peruser_session.h b/services/include/peruser_session.h index ed29d5b9..f49e9266 100644 --- a/services/include/peruser_session.h +++ b/services/include/peruser_session.h @@ -115,27 +115,24 @@ private: int userId_; // the id of the user to whom the object is linking int userState = UserState::USER_STATE_STARTED; // the state of the user to whom the object is linking int displayId; // the id of the display screen on which the user is - int currentIndex; std::map, std::shared_ptr> mapClients; static const int MIN_IME = 2; static const int MAX_RESTART_NUM = 3; static const int IME_RESET_TIME_OUT = 300; static const int MAX_RESET_WAIT_TIME = 1600000; - static const int SLEEP_TIME = 300000; InputMethodInfo *currentIme[MAX_IME] = { nullptr, nullptr }; // 0 - the default ime. 1 - security ime InputControlChannelStub *localControlChannel[MAX_IME]; sptr inputControlChannel[MAX_IME]; + std::mutex imsCoreLock_; sptr imsCore[MAX_IME]; // the remote handlers of input method service sptr inputMethodToken[MAX_IME]; // the window token of keyboard int currentKbdIndex[MAX_IME]; // current keyboard index - int lastImeIndex; // The last ime which showed keyboard + int lastImeIndex = DEFAULT_IME; // The last ime which showed keyboard InputMethodSetting *inputMethodSetting; // The pointer referred to the object in PerUserSetting - int currentDisplayMode; // the display mode of the current keyboard sptr imsAgent; - InputChannel *imsChannel; // the write channel created by input method service std::mutex clientLock_; sptr currentClient; // the current input client sptr needReshowClient = nullptr; // the input client for which keyboard need to re-show @@ -144,7 +141,6 @@ private: MessageHandler *msgHandler = nullptr; // message handler working with Work Thread std::thread workThreadHandler; // work thread handler std::recursive_mutex mtx; // mutex to lock the operations among multi work threads - sptr connCallback; std::mutex resetLock; ResetManager manager[MAX_IME]; @@ -172,7 +168,6 @@ private: int StopInputMethod(int index); int ShowKeyboard(const sptr &inputClient, bool isShowKeyboard); int HideKeyboard(const sptr &inputClient); - void SetDisplayId(int displayId); int GetImeIndex(const sptr &inputClient); static sptr GetAbilityManagerService(); void SendAgentToSingleClient(const ClientInfo &clientInfo); @@ -183,6 +178,17 @@ private: void ClearImeData(uint32_t index); void SetCurrentClient(sptr client); sptr GetCurrentClient(); + void SetImsCore(int32_t index, sptr core); + sptr GetImsCore(int32_t index); + int32_t SetClientState(bool isAlive); + static inline bool IsValid(int32_t index) + { + return index >= DEFAULT_IME && index <= SECURITY_IME; + } + inline bool IsIMEEqual() + { + return GetImsCore(DEFAULT_IME) == GetImsCore(SECURITY_IME); + } std::mutex propertyLock_; SubProperty currentSubProperty; diff --git a/services/src/global.cpp b/services/src/global.cpp index 2d123132..7cbe8ec2 100644 --- a/services/src/global.cpp +++ b/services/src/global.cpp @@ -82,8 +82,8 @@ const char *ToString(int errorCode) case ERROR_IME_START_FAILED: { return "failed to start input"; } - case ERROR_IME_STOP_FAILED: { - return "failed to stop input"; + case ERROR_ADD_CLIENT_FAILED: { + return "failed fo add client"; } case ERROR_KBD_SHOW_FAILED: { return "failed to show keyboard"; @@ -100,9 +100,6 @@ const char *ToString(int errorCode) case ERROR_KBD_IS_NOT_SHOWING: { return "keyboard is not showing"; } - case ERROR_IME_ALREADY_STARTED: { - return "input method service has already started"; - } case ERROR_NOT_IME_PACKAGE: { return "not an input method engine package"; } @@ -112,27 +109,12 @@ const char *ToString(int errorCode) case ERROR_SETTING_SAME_VALUE: { return "same setting value"; } - case ERROR_NO_NEXT_IME: { - return "next input method engine is not available"; - } - case ERROR_CLIENTWINDOW_NOT_FOCUSED: { - return "input client window is not focused"; - } - case ERROR_CLIENT_NOT_WINDOW: { - return "input client is not from a valid window"; - } case ERROR_REMOTE_IME_DIED: { return "input method service died"; } - case ERROR_RESTART_IME_FAILED: { - return "failed to restart input method service"; - } case ERROR_REMOTE_CLIENT_DIED: { return "input client died"; } - case ERROR_CLIENT_DUPLICATED: { - return "duplicated client"; - } case ERROR_CLIENT_NOT_FOUND: { return "client is not found"; } diff --git a/services/src/im_common_event_manager.cpp b/services/src/im_common_event_manager.cpp index de2a1b20..a5f5e688 100644 --- a/services/src/im_common_event_manager.cpp +++ b/services/src/im_common_event_manager.cpp @@ -17,11 +17,11 @@ #include -#include "../adapter/keyboard/keyboard_event.h" #include "global.h" #include "input_method_system_ability_stub.h" #include "ipc_skeleton.h" #include "iservice_registry.h" +#include "itypes_util.h" #include "message_handler.h" #include "system_ability_definition.h" @@ -33,15 +33,11 @@ std::mutex ImCommonEventManager::instanceLock_; /*! Constructor */ -ImCommonEventManager::ImCommonEventManager() -{ -} +ImCommonEventManager::ImCommonEventManager() {} /*! Destructor */ -ImCommonEventManager::~ImCommonEventManager() -{ -} +ImCommonEventManager::~ImCommonEventManager() {} sptr ImCommonEventManager::GetInstance() { @@ -59,6 +55,7 @@ bool ImCommonEventManager::SubscribeEvent(const std::string &event) { EventFwk::MatchingSkills matchingSkills; matchingSkills.AddEvent(event); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills); @@ -89,27 +86,25 @@ bool ImCommonEventManager::SubscribeEvent(const std::string &event) return true; } -bool ImCommonEventManager::SubscribeKeyboardEvent(const std::vector &handlers) +bool ImCommonEventManager::SubscribeKeyboardEvent(KeyHandle handle) { + IMSA_HILOGI("ImCommonEventManager::SubscribeKeyboardEvent"); auto abilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (abilityManager == nullptr) { - IMSA_HILOGE("SubscribeEvent abilityManager is nullptr"); + IMSA_HILOGE("SubscribeKeyboardEvent abilityManager is nullptr"); return false; } - sptr listener = new (std::nothrow) SystemAbilityStatusChangeListener([handlers]() { - for (const auto &handler : handlers) { - int32_t ret = KeyboardEvent::GetInstance().SubscribeKeyboardEvent(handler.combine, handler.handle); - IMSA_HILOGI("subscribe %{public}d key event %{public}s", handler.combine.finalKey, - ret == ErrorCode::NO_ERROR ? "OK" : "ERROR"); - } + sptr listener = new (std::nothrow) SystemAbilityStatusChangeListener([&handle]() { + int32_t ret = KeyboardEvent::GetInstance().AddKeyEventMonitor(handle); + IMSA_HILOGI("SubscribeKeyboardEvent add monitor %{public}s", ret == ErrorCode::NO_ERROR ? "success" : "failed"); }); if (listener == nullptr) { - IMSA_HILOGE("SubscribeEvent listener is nullptr"); + IMSA_HILOGE("SubscribeKeyboardEvent listener is nullptr"); return false; } int32_t ret = abilityManager->SubscribeSystemAbility(MULTIMODAL_INPUT_SERVICE_ID, listener); if (ret != ERR_OK) { - IMSA_HILOGE("SubscribeEvent SubscribeSystemAbility failed. ret = %{public}d", ret); + IMSA_HILOGE("SubscribeKeyboardEvent SubscribeSystemAbility failed. ret = %{public}d", ret); return false; } keyboardEventListener_ = listener; @@ -129,6 +124,9 @@ void ImCommonEventManager::EventSubscriber::OnReceiveEvent(const EventFwk::Commo if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { IMSA_HILOGI("ImCommonEventManager::OnReceiveEvent user switched!!!"); startUser(data.GetCode()); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + IMSA_HILOGI("ImCommonEventManager::OnReceiveEvent package removed!!!"); + HandlePackageRemove(want, action); } } @@ -145,6 +143,21 @@ void ImCommonEventManager::EventSubscriber::startUser(int newUserId) IMSA_HILOGI("ImCommonEventManager::startUser 3"); } +void ImCommonEventManager::EventSubscriber::HandlePackageRemove(const AAFwk::Want &want, const std::string action) +{ + auto element = want.GetElement(); + std::string bundleName = element.GetBundleName(); + int32_t userId = want.GetIntParam("userId", 0); + IMSA_HILOGD("bundleName = %{public}s, userId = %{public}d", bundleName.c_str(), userId); + MessageParcel *parcel = new MessageParcel(); + if (!ITypesUtil::Marshal(*parcel, userId, bundleName)) { + IMSA_HILOGE("Failed to write message parcel"); + return; + } + Message *msg = new Message(MessageID::MSG_ID_PACKAGE_REMOVED, parcel); + MessageHandler::Instance()->SendMessage(msg); +} + ImCommonEventManager::SystemAbilityStatusChangeListener::SystemAbilityStatusChangeListener(std::function func) : func_(std::move(func)) { diff --git a/services/src/input_method_system_ability.cpp b/services/src/input_method_system_ability.cpp index 02c50f7d..e9147b7f 100644 --- a/services/src/input_method_system_ability.cpp +++ b/services/src/input_method_system_ability.cpp @@ -17,9 +17,7 @@ #include #include -#include -#include "../adapter/keyboard/keyboard_event.h" #include "ability_connect_callback_proxy.h" #include "ability_manager_errors.h" #include "ability_manager_interface.h" @@ -32,11 +30,12 @@ #include "input_method_status.h" #include "ipc_skeleton.h" #include "iservice_registry.h" +#include "itypes_util.h" +#include "key_event.h" #include "message_handler.h" #include "os_account_manager.h" #include "para_handle.h" #include "resource_manager.h" -#include "sa_mgr_client.h" #include "system_ability.h" #include "system_ability_definition.h" #include "ui_service_mgr_client.h" @@ -185,8 +184,8 @@ namespace MiscServices { std::string defaultIme = ParaHandle::GetDefaultIme(userId_); StartInputService(defaultIme); StartUserIdListener(); - int32_t ret = SubscribeKeyboardEvent(); - IMSA_HILOGI("subscribe key event ret %{public}d", ret); + int32_t ret = InitKeyEventMonitor(); + IMSA_HILOGI("init KeyEvent monitor %{public}s", ret == ErrorCode::NO_ERROR ? "success" : "failed"); return ErrorCode::NO_ERROR; } @@ -554,7 +553,8 @@ namespace MiscServices { int32_t InputMethodSystemAbility::SwitchInputMethod(const std::string &name, const std::string &subName) { - IMSA_HILOGI("InputMethodSystemAbility::SwitchInputMethod"); + IMSA_HILOGD("InputMethodSystemAbility name: %{public}s, subName: %{public}s", name.c_str(), + subName.c_str()); return subName.empty() ? SwitchInputMethodType(name) : SwitchInputMethodSubtype(name, subName); } @@ -740,6 +740,7 @@ namespace MiscServices { property.descriptionId = applicationInfo.descriptionId; property.label = Str8ToStr16(labelString); property.description = Str8ToStr16(descriptionString); + properties.emplace_back(property); } return properties; } @@ -879,6 +880,8 @@ namespace MiscServices { } case MSG_ID_PACKAGE_REMOVED: { OnPackageRemoved(msg); + delete msg; + msg = nullptr; break; } case MSG_ID_SETTING_CHANGED: { @@ -1175,39 +1178,29 @@ namespace MiscServices { { IMSA_HILOGI("Start...\n"); MessageParcel *data = msg->msgContent_; - if (!data) { + if (data == nullptr) { IMSA_HILOGI("InputMethodSystemAbility::OnPackageRemoved data is nullptr"); return ErrorCode::ERROR_NULL_POINTER; } - int32_t userId = data->ReadInt32(); - int32_t size = data->ReadInt32(); - - if (size <= 0) { - IMSA_HILOGE("Aborted! %s\n", ErrorCode::ToString(ErrorCode::ERROR_BAD_PARAMETERS)); - return ErrorCode::ERROR_BAD_PARAMETERS; + int32_t userId = 0; + std::string packageName = ""; + if (!ITypesUtil::Unmarshal(*data, userId, packageName)) { + IMSA_HILOGE("Failed to read message parcel"); + return ErrorCode::ERROR_EX_PARCELABLE; } - std::u16string packageName = data->ReadString16(); + PerUserSetting *setting = GetUserSetting(userId); - if (!setting || setting->GetUserState() != UserState::USER_STATE_UNLOCKED) { + if (setting == nullptr || setting->GetUserState() != UserState::USER_STATE_UNLOCKED) { IMSA_HILOGE("Aborted! %s %d\n", ErrorCode::ToString(ErrorCode::ERROR_USER_NOT_UNLOCKED), userId); return ErrorCode::ERROR_USER_NOT_UNLOCKED; } - auto session = GetUserSession(userId); - if (session == nullptr) { - IMSA_HILOGI("InputMethodSystemAbility::OnPackageRemoved session is nullptr"); - return ErrorCode::ERROR_NULL_POINTER; - } - session->OnPackageRemoved(packageName); - bool securityImeFlag = false; - int32_t ret = setting->OnPackageRemoved(packageName, securityImeFlag); - if (ret != ErrorCode::NO_ERROR) { - IMSA_HILOGI("End...\n"); - return ret; - } - if (securityImeFlag) { - InputMethodInfo *securityIme = setting->GetSecurityInputMethod(); - InputMethodInfo *defaultIme = setting->GetCurrentInputMethod(); - session->ResetIme(defaultIme, securityIme); + + std::string defaultIme = ParaHandle::GetDefaultIme(userId); + std::string::size_type pos = defaultIme.find("/"); + std::string currentIme = defaultIme.substr(0, pos); + if (packageName == currentIme) { + int32_t ret = OnSwitchInputMethod(ParaHandle::DEFAULT_PACKAGE_NAME, ParaHandle::DEFAULT_ABILITY_NAME); + IMSA_HILOGI("InputMethodSystemAbility::OnPackageRemoved ret = %{public}d", ret); } return 0; } @@ -1377,13 +1370,19 @@ namespace MiscServices { sptr InputMethodSystemAbility::GetAbilityManagerService() { - IMSA_HILOGE("InputMethodSystemAbility::GetAbilityManagerService start"); - sptr abilityMsObj = - OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); - if (!abilityMsObj) { - IMSA_HILOGE("failed to get ability manager service"); + IMSA_HILOGD("InputMethodSystemAbility::GetAbilityManagerService start"); + auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + IMSA_HILOGE("SystemAbilityManager is nullptr."); return nullptr; } + + auto abilityMsObj = systemAbilityManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (abilityMsObj == nullptr) { + IMSA_HILOGE("Failed to get ability manager service."); + return nullptr; + } + return iface_cast(abilityMsObj); } @@ -1406,16 +1405,16 @@ namespace MiscServices { return {}; } - int32_t InputMethodSystemAbility::SwitchByCombinedKey(const CombineKeyCode &keyCode) + int32_t InputMethodSystemAbility::SwitchByCombinationKey(uint32_t state) { - IMSA_HILOGI("InputMethodSystemAbility::SwitchByCombinedKey"); + IMSA_HILOGI("InputMethodSystemAbility::SwitchByCombinationKey"); auto current = GetCurrentInputMethodSubtype(); if (current == nullptr) { IMSA_HILOGE("GetCurrentInputMethodSubtype failed"); return ErrorCode::ERROR_EX_NULL_POINTER; } - if (keyCode == CombineKeyCode::COMBINE_KEYCODE_CAPS) { - IMSA_HILOGI("COMBINE_KEYCODE_CAPS press"); + if (KeyboardEvent::IS_KEYS_DOWN(state, KeyboardEvent::CAPS_MASK)) { + IMSA_HILOGI("CAPS press"); auto target = current->mode == "upper" ? FindSubPropertyByCompare(current->id, [¤t](const SubProperty &property) { return property.mode == "lower"; }) @@ -1423,8 +1422,9 @@ namespace MiscServices { [¤t](const SubProperty &property) { return property.mode == "upper"; }); return SwitchInputMethod(target.id, target.label); } - if (keyCode == CombineKeyCode::COMBINE_KEYCODE_SHIFT) { - IMSA_HILOGI("COMBINE_KEYCODE_SHIFT press"); + if (KeyboardEvent::IS_KEYS_DOWN(state, KeyboardEvent::SHIFT_LEFT_MASK) + || KeyboardEvent::IS_KEYS_DOWN(state, KeyboardEvent::SHIFT_RIGHT_MASK)) { + IMSA_HILOGI("SHIFT press"); auto target = current->language == "chinese" ? FindSubPropertyByCompare(current->id, [¤t](const SubProperty &property) { return property.language == "english"; }) @@ -1432,8 +1432,11 @@ namespace MiscServices { [¤t](const SubProperty &property) { return property.language == "chinese"; }); return SwitchInputMethod(target.id, target.label); } - if (keyCode == CombineKeyCode::COMBINE_KEYCODE_CTRL_SHIFT) { - IMSA_HILOGI("COMBINE_KEYCODE_CTRL_SHIFT press"); + if (KeyboardEvent::IS_KEYS_DOWN(state, KeyboardEvent::CTRL_LEFT_MASK | KeyboardEvent::SHIFT_LEFT_MASK) + || KeyboardEvent::IS_KEYS_DOWN(state, KeyboardEvent::CTRL_LEFT_MASK | KeyboardEvent::SHIFT_RIGHT_MASK) + || KeyboardEvent::IS_KEYS_DOWN(state, KeyboardEvent::CTRL_RIGHT_MASK | KeyboardEvent::SHIFT_LEFT_MASK) + || KeyboardEvent::IS_KEYS_DOWN(state, KeyboardEvent::CTRL_RIGHT_MASK | KeyboardEvent::SHIFT_RIGHT_MASK)) { + IMSA_HILOGI("CTRL_SHIFT press"); std::vector props = {}; auto ret = ListProperty(MAIN_USER_ID, props); if (ret != ErrorCode::NO_ERROR) { @@ -1442,53 +1445,20 @@ namespace MiscServices { } for (const auto &prop : props) { if (prop.name != current->id) { - return SwitchInputMethod(current->name, current->id); + return SwitchInputMethod(prop.name, prop.id); } } } - IMSA_HILOGI("keycode undefined"); + IMSA_HILOGD("keycode undefined"); return ErrorCode::ERROR_EX_UNSUPPORTED_OPERATION; } - int32_t InputMethodSystemAbility::SubscribeKeyboardEvent() + int32_t InputMethodSystemAbility::InitKeyEventMonitor() { - ImCommonEventManager::GetInstance()->SubscribeKeyboardEvent( - { { { - .preKeys = {}, - .finalKey = MMI::KeyEvent::KEYCODE_CAPS_LOCK, - }, - [this]() { SwitchByCombinedKey(CombineKeyCode::COMBINE_KEYCODE_CAPS); } }, - { { - .preKeys = {}, - .finalKey = MMI::KeyEvent::KEYCODE_SHIFT_LEFT, - }, - [this]() { SwitchByCombinedKey(CombineKeyCode::COMBINE_KEYCODE_SHIFT); } }, - { { - .preKeys = {}, - .finalKey = MMI::KeyEvent::KEYCODE_SHIFT_RIGHT, - }, - [this]() { SwitchByCombinedKey(CombineKeyCode::COMBINE_KEYCODE_SHIFT); } }, - { { - .preKeys = { MMI::KeyEvent::KEYCODE_CTRL_LEFT }, - .finalKey = MMI::KeyEvent::KEYCODE_SHIFT_LEFT, - }, - [this]() { SwitchByCombinedKey(CombineKeyCode::COMBINE_KEYCODE_CTRL_SHIFT); } }, - { { - .preKeys = { MMI::KeyEvent::KEYCODE_CTRL_LEFT }, - .finalKey = MMI::KeyEvent::KEYCODE_SHIFT_RIGHT, - }, - [this]() { SwitchByCombinedKey(CombineKeyCode::COMBINE_KEYCODE_CTRL_SHIFT); } }, - { { - .preKeys = { MMI::KeyEvent::KEYCODE_CTRL_RIGHT }, - .finalKey = MMI::KeyEvent::KEYCODE_SHIFT_LEFT, - }, - [this]() { SwitchByCombinedKey(CombineKeyCode::COMBINE_KEYCODE_CTRL_SHIFT); } }, - { { - .preKeys = { MMI::KeyEvent::KEYCODE_CTRL_RIGHT }, - .finalKey = MMI::KeyEvent::KEYCODE_SHIFT_RIGHT, - }, - [this]() { SwitchByCombinedKey(CombineKeyCode::COMBINE_KEYCODE_CTRL_SHIFT); } } }); - return 0; + IMSA_HILOGI("InputMethodSystemAbility::InitKeyEventMonitor"); + bool ret = ImCommonEventManager::GetInstance()->SubscribeKeyboardEvent( + [this](uint32_t keyCode) { return SwitchByCombinationKey(keyCode); }); + return ret ? ErrorCode::NO_ERROR : ErrorCode::ERROR_SERVICE_START_FAILED; } } // namespace MiscServices } // namespace OHOS diff --git a/services/src/peruser_session.cpp b/services/src/peruser_session.cpp index 8a1a834f..c50ec899 100644 --- a/services/src/peruser_session.cpp +++ b/services/src/peruser_session.cpp @@ -31,7 +31,7 @@ #include "para_handle.h" #include "parcel.h" #include "platform.h" -#include "sa_mgr_client.h" +#include "iservice_registry.h" #include "system_ability_definition.h" #include "unistd.h" #include "utils.h" @@ -137,14 +137,6 @@ namespace MiscServices { } } - /*! Set display Id - \param displayId the Id of display screen on which the input method keyboard show. - */ - void PerUserSession::SetDisplayId(int displayId) - { - this->displayId = displayId; - } - /*! Set the current input method engine \param ime the current (default) IME pointer referred to the instance in PerUserSetting. */ @@ -178,14 +170,15 @@ namespace MiscServices { */ void PerUserSession::ResetIme(InputMethodInfo *defaultIme, InputMethodInfo *securityIme) { - IMSA_HILOGI("PerUserSession::ResetIme"); + IMSA_HILOGD("PerUserSession::ResetIme"); std::lock_guard lock(mtx); InputMethodInfo *ime[] = {defaultIme, securityIme}; for (int i = 0; i < MIN_IME; i++) { if (currentIme[i] == ime[i] && ime[i]) { continue; } - if (imsCore[i]) { + sptr core = GetImsCore(i); + if (core != nullptr) { StopInputMethod(i); } ResetImeError(i); @@ -224,7 +217,7 @@ namespace MiscServices { */ void PerUserSession::OnPackageRemoved(const std::u16string& packageName) { - IMSA_HILOGI("PerUserSession::OnPackageRemoved"); + IMSA_HILOGD("PerUserSession::OnPackageRemoved"); InputMethodSetting tmpSetting; bool flag = false; std::lock_guard lock(mtx); @@ -255,7 +248,7 @@ namespace MiscServices { int PerUserSession::AddClient(sptr inputClient, const ClientInfo &clientInfo) { - IMSA_HILOGI("PerUserSession::AddClient"); + IMSA_HILOGD("PerUserSession::AddClient"); std::lock_guard lock(mtx); auto cacheClient = GetClientInfo(inputClient); if (cacheClient != nullptr) { @@ -287,7 +280,7 @@ namespace MiscServices { */ void PerUserSession::RemoveClient(sptr inputClient) { - IMSA_HILOGE("PerUserSession::RemoveClient"); + IMSA_HILOGD("PerUserSession::RemoveClient"); std::lock_guard lock(mtx); auto it = mapClients.find(inputClient); if (it == mapClients.end()) { @@ -311,17 +304,17 @@ namespace MiscServices { int PerUserSession::StartInputMethod(int index) { IMSA_HILOGI("PerUserSession::StartInputMethod index = %{public}d [%{public}d]\n", index, userId_); - - if (!imsCore[index]) { + sptr core = GetImsCore(index); + if (core == nullptr) { IMSA_HILOGI("PerUserSession::StartInputMethod imscore is null"); return ErrorCode::ERROR_IME_BIND_FAILED; } - sptr b = imsCore[index]->AsObject(); + sptr b = core->AsObject(); inputMethodToken[index] = IPCSkeleton::GetInstance().GetContextObject(); localControlChannel[index] = new InputControlChannelStub(userId_); inputControlChannel[index] = localControlChannel[index]; - int ret_init = imsCore[index]->initializeInput(inputMethodToken[index], displayId, inputControlChannel[index]); + int ret_init = core->initializeInput(inputMethodToken[index], displayId, inputControlChannel[index]); if (ret_init != ErrorCode::NO_ERROR) { IMSA_HILOGE("PerUserSession::StartInputMethod initializeInput fail %{public}s", ErrorCode::ToString(ret_init)); localControlChannel[index] = nullptr; @@ -346,12 +339,13 @@ namespace MiscServices { IMSA_HILOGE("Aborted! %{public}s", ErrorCode::ToString(ErrorCode::ERROR_BAD_PARAMETERS)); return ErrorCode::ERROR_BAD_PARAMETERS; } - if (!imsCore[index] || !currentIme[index]) { + sptr core = GetImsCore(index); + if (core == nullptr || currentIme[index] == nullptr) { IMSA_HILOGE("Aborted! %{public}s", ErrorCode::ToString(ErrorCode::ERROR_IME_NOT_STARTED)); return ErrorCode::ERROR_IME_NOT_STARTED; } - if (currentIme[index] == currentIme[1 - index] && imsCore[1 - index]) { - imsCore[index] = nullptr; + if (currentIme[index] == currentIme[1 - index] && GetImsCore((1 - index)) != nullptr) { + SetImsCore(index, nullptr); inputControlChannel[index] = nullptr; localControlChannel[index] = nullptr; IMSA_HILOGI("End...[%{public}d]\n", userId_); @@ -368,12 +362,12 @@ namespace MiscServices { IMSA_HILOGE("destroyWindowTaskId return : %{public}s [%{public}d]\n", ErrorCode::ToString(ret), userId_); errorCode = ErrorCode::ERROR_TOKEN_DESTROY_FAILED; } - sptr b = imsCore[index]->AsObject(); + sptr b = core->AsObject(); ret = b->RemoveDeathRecipient(imsDeathRecipient); if (ret != ErrorCode::NO_ERROR) { IMSA_HILOGE("RemoveDeathRecipient return : %{public}s [%{public}d]\n", ErrorCode::ToString(ret), userId_); } - imsCore[index] = nullptr; + SetImsCore(index, nullptr); inputControlChannel[index] = nullptr; localControlChannel[index] = nullptr; IMSA_HILOGI("End...[%{public}d]\n", userId_); @@ -392,21 +386,21 @@ namespace MiscServices { */ int PerUserSession::ShowKeyboard(const sptr& inputClient, bool isShowKeyboard) { - IMSA_HILOGI("PerUserSession::ShowKeyboard"); + IMSA_HILOGD("PerUserSession::ShowKeyboard"); auto clientInfo = GetClientInfo(inputClient->AsObject()); int index = GetImeIndex(inputClient); if (index == -1 || clientInfo == nullptr) { IMSA_HILOGE("PerUserSession::ShowKeyboard Aborted! index = -1 or clientInfo is nullptr"); return ErrorCode::ERROR_CLIENT_NOT_FOUND; } - - if (imsCore[0] == nullptr) { + sptr core = GetImsCore(DEFAULT_IME); + if (core == nullptr) { IMSA_HILOGE("PerUserSession::ShowKeyboard Aborted! imsCore[%{public}d] is nullptr", index); return ErrorCode::ERROR_NULL_POINTER; } auto subProperty = GetCurrentSubProperty(); - int32_t ret = imsCore[0]->showKeyboard(clientInfo->channel, isShowKeyboard, subProperty); + int32_t ret = core->showKeyboard(clientInfo->channel, isShowKeyboard, subProperty); if (ret != ErrorCode::NO_ERROR) { IMSA_HILOGE("PerUserSession::showKeyboard failed ret: %{public}d", ret); return ErrorCode::ERROR_KBD_SHOW_FAILED; @@ -427,7 +421,7 @@ namespace MiscServices { */ int PerUserSession::HideKeyboard(const sptr& inputClient) { - IMSA_HILOGI("PerUserSession::HideKeyboard"); + IMSA_HILOGD("PerUserSession::HideKeyboard"); int index = GetImeIndex(inputClient); if (index == -1) { IMSA_HILOGE("PerUserSession::HideKeyboard Aborted! ErrorCode::ERROR_CLIENT_NOT_FOUND"); @@ -437,12 +431,13 @@ namespace MiscServices { if (clientInfo == nullptr) { IMSA_HILOGE("PerUserSession::HideKeyboard GetClientInfo pointer nullptr"); } - if (imsCore[0] == nullptr) { + sptr core = GetImsCore(DEFAULT_IME); + if (core == nullptr) { IMSA_HILOGE("PerUserSession::HideKeyboard imsCore[index] is nullptr"); return ErrorCode::ERROR_IME_NOT_STARTED; } - bool ret = imsCore[0]->hideKeyboard(1); + bool ret = core->hideKeyboard(1); if (!ret) { IMSA_HILOGE("PerUserSession::HideKeyboard [imsCore->hideKeyboard] failed"); return ErrorCode::ERROR_KBD_HIDE_FAILED; @@ -457,15 +452,16 @@ namespace MiscServices { */ int PerUserSession::OnGetKeyboardWindowHeight(int &retHeight) { - if (imsCore[lastImeIndex]) { - int ret = imsCore[lastImeIndex]->getKeyboardWindowHeight(retHeight); - if (ret != ErrorCode::NO_ERROR) { - IMSA_HILOGE("getKeyboardWindowHeight return : %{public}s", ErrorCode::ToString(ret)); - } - return ret; + sptr core = GetImsCore(lastImeIndex); + if (core == nullptr) { + IMSA_HILOGE("imsCore[0] is nullptr"); + return ErrorCode::ERROR_IME_NOT_AVAILABLE; } - IMSA_HILOGW("No IME is started [%{public}d]\n", userId_); - return ErrorCode::ERROR_IME_NOT_STARTED; + int ret = core->getKeyboardWindowHeight(retHeight); + if (ret != ErrorCode::NO_ERROR) { + IMSA_HILOGE("getKeyboardWindowHeight return : %{public}s", ErrorCode::ToString(ret)); + } + return ret; } /*! Get the current keyboard type @@ -507,6 +503,7 @@ namespace MiscServices { void PerUserSession::OnClientDied(sptr remote) { IMSA_HILOGI("PerUserSession::OnClientDied Start...[%{public}d]\n", userId_); + SetClientState(false); sptr client = GetCurrentClient(); if (client == nullptr) { IMSA_HILOGE("current client is nullptr"); @@ -530,7 +527,8 @@ namespace MiscServices { IMSA_HILOGI("Start...[%{public}d]\n", userId_); int index = 0; for (int i = 0; i < MAX_IME; i++) { - if (imsCore[i] == remote) { + sptr core = GetImsCore(i); + if (core == remote) { index = i; break; } @@ -556,7 +554,7 @@ namespace MiscServices { } usleep(MAX_RESET_WAIT_TIME); MessageHandler::Instance()->SendMessage(msg); - IMSA_HILOGI("End...[%{public}d]\n", userId_); + IMSA_HILOGD("End...[%{public}d]\n", userId_); } /*! It's called when input method setting data in the system is changed @@ -567,16 +565,15 @@ namespace MiscServices { */ int PerUserSession::OnSettingChanged(const std::u16string& key, const std::u16string& value) { - IMSA_HILOGI("Start...[%{public}d]\n", userId_); + IMSA_HILOGD("Start...[%{public}d]\n", userId_); std::lock_guard lock(mtx); if (!inputMethodSetting) { return ErrorCode::ERROR_NULL_POINTER; } std::u16string currentValue = inputMethodSetting->GetValue(key); - IMSA_HILOGD("PerUserSession::OnSettingChanged key = %{public}s", Utils::ToStr8(key).c_str()); - IMSA_HILOGD("PerUserSession::OnSettingChanged value = %{public}s", Utils::ToStr8(value).c_str()); - IMSA_HILOGD("PerUserSession::OnSettingChanged currentValue = %{public}s", Utils::ToStr8(currentValue).c_str()); + IMSA_HILOGD("key = %{public}s, value = %{public}s, currentValue = %{public}s", Utils::ToStr8(key).c_str(), + Utils::ToStr8(value).c_str(), Utils::ToStr8(currentValue).c_str()); if (currentValue == value) { IMSA_HILOGI("End...[%{public}d]\n", userId_); @@ -612,7 +609,7 @@ namespace MiscServices { inputMethodSetting->SetCurrentKeyboardType(-1); } } - IMSA_HILOGI("End...[%{public}d]\n", userId_); + IMSA_HILOGD("End...[%{public}d]\n", userId_); return ErrorCode::NO_ERROR; } @@ -659,12 +656,12 @@ namespace MiscServices { if (type) { sptr client = GetCurrentClient(); if (client != nullptr) { - int ret = imsCore[index]->setKeyboardType(*type); + int ret = GetImsCore(index)->setKeyboardType(*type); if (ret != ErrorCode::NO_ERROR) { IMSA_HILOGE("setKeyboardType ret: %{public}s [%{public}d]\n", ErrorCode::ToString(ret), userId_); } } - if (imsCore[index] == imsCore[1 - index]) { + if (IsIMEEqual()) { inputMethodSetting->SetCurrentKeyboardType(type->getHashCode()); inputMethodSetting->SetCurrentSysKeyboardType(type->getHashCode()); currentKbdIndex[1 - index] = currentKbdIndex[index]; @@ -682,7 +679,7 @@ namespace MiscServices { */ int PerUserSession::OnHideKeyboardSelf(int flags) { - IMSA_HILOGW("PerUserSession::OnHideKeyboardSelf"); + IMSA_HILOGD("PerUserSession::OnHideKeyboardSelf"); (void)flags; sptr client = GetCurrentClient(); if (client == nullptr) { @@ -694,7 +691,7 @@ namespace MiscServices { int PerUserSession::OnShowKeyboardSelf() { - IMSA_HILOGI("PerUserSession::OnShowKeyboardSelf"); + IMSA_HILOGD("PerUserSession::OnShowKeyboardSelf"); sptr client = GetCurrentClient(); if (client == nullptr) { IMSA_HILOGE("current client is nullptr"); @@ -740,7 +737,7 @@ namespace MiscServices { return; } InputMethodSetting tmpSetting; - if (imsCore[index] == imsCore[1 - index]) { + if (IsIMEEqual()) { tmpSetting.SetCurrentKeyboardType(type->getHashCode()); tmpSetting.SetCurrentSysKeyboardType(type->getHashCode()); } @@ -758,7 +755,6 @@ namespace MiscServices { */ void PerUserSession::OnSetDisplayMode(int mode) { - currentDisplayMode = mode; sptr client = GetCurrentClient(); if (client == nullptr) { IMSA_HILOGE("current client is nullptr"); @@ -784,7 +780,7 @@ namespace MiscServices { if (index < 0 || index >= MAX_IME) { return; } - IMSA_HILOGI("Start...[%{public}d]\n", userId_); + IMSA_HILOGD("Start...[%{public}d]\n", userId_); if (currentIme[index] && currentIme[index]->mImeId == imeId) { int ret = StartInputMethod(index); if (needReshowClient && GetImeIndex(needReshowClient) == index) { @@ -794,14 +790,14 @@ namespace MiscServices { needReshowClient = nullptr; } } - IMSA_HILOGI("End...[%{public}d]\n", userId_); + IMSA_HILOGD("End...[%{public}d]\n", userId_); } /*! It's called when this user is locked */ void PerUserSession::OnUserLocked() { - IMSA_HILOGI("PerUserSession::OnUserLocked"); + IMSA_HILOGD("PerUserSession::OnUserLocked"); std::lock_guard lock(mtx); if (userState == UserState::USER_STATE_STARTED) { IMSA_HILOGI("End...[%{public}d]\n", userId_); @@ -913,13 +909,13 @@ namespace MiscServices { if (!flag) { IMSA_HILOGW("The current keyboard type is not found in the current IME. Reset it!"); type = GetKeyboardType(imeIndex, currentKbdIndex[imeIndex]); - } else if (imsCore[imeIndex] == imsCore[1 - imeIndex]) { + } else if (IsIMEEqual()) { currentKbdIndex[1 - imeIndex] = currentKbdIndex[imeIndex]; } } if (type) { InputMethodSetting tmpSetting; - if (imsCore[imeIndex] == imsCore[1 - imeIndex]) { + if (IsIMEEqual()) { inputMethodSetting->SetCurrentKeyboardType(type->getHashCode()); inputMethodSetting->SetCurrentSysKeyboardType(type->getHashCode()); currentKbdIndex[1 - imeIndex] = currentKbdIndex[imeIndex]; @@ -967,7 +963,7 @@ namespace MiscServices { */ void PerUserSession::CopyInputMethodService(int imeIndex) { - imsCore[imeIndex] = imsCore[1 - imeIndex]; + SetImsCore(imeIndex, GetImsCore((1 - imeIndex))); localControlChannel[imeIndex] = localControlChannel[1 - imeIndex]; inputControlChannel[imeIndex] = inputControlChannel[1 - imeIndex]; inputMethodToken[imeIndex] = inputMethodToken[1 - imeIndex]; @@ -1030,12 +1026,18 @@ namespace MiscServices { sptr PerUserSession::GetAbilityManagerService() { IMSA_HILOGE("GetAbilityManagerService start"); - sptr abilityMsObj = - OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); - if (!abilityMsObj) { - IMSA_HILOGE("failed to get ability manager service"); + auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + IMSA_HILOGE("SystemAbilityManager is nullptr."); return nullptr; } + + auto abilityMsObj = systemAbilityManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (abilityMsObj == nullptr) { + IMSA_HILOGE("Failed to get ability manager service."); + return nullptr; + } + return iface_cast(abilityMsObj); } @@ -1046,7 +1048,7 @@ namespace MiscServices { */ int32_t PerUserSession::OnPrepareInput(const ClientInfo &clientInfo) { - IMSA_HILOGI("PerUserSession::OnPrepareInput Start\n"); + IMSA_HILOGD("PerUserSession::OnPrepareInput Start\n"); int ret = AddClient(clientInfo.client->AsObject(), clientInfo); if (ret != ErrorCode::NO_ERROR) { IMSA_HILOGE("PerUserSession::OnPrepareInput %{public}s", ErrorCode::ToString(ret)); @@ -1058,7 +1060,7 @@ namespace MiscServices { void PerUserSession::SendAgentToSingleClient(const ClientInfo &clientInfo) { - IMSA_HILOGI("PerUserSession::SendAgentToSingleClient"); + IMSA_HILOGD("PerUserSession::SendAgentToSingleClient"); if (imsAgent == nullptr) { IMSA_HILOGI("PerUserSession::SendAgentToSingleClient imsAgent is nullptr"); CreateComponentFailed(userId_, ErrorCode::ERROR_NULL_POINTER); @@ -1074,14 +1076,19 @@ namespace MiscServices { */ int32_t PerUserSession::OnReleaseInput(sptr client) { - IMSA_HILOGI("PerUserSession::OnReleaseInput Start\n"); - if (imsCore[0] == nullptr) { - return ErrorCode::ERROR_IME_NOT_AVAILABLE; + IMSA_HILOGI("PerUserSession::OnReleaseInput Start"); + int ret = SetClientState(false); + if (ret != ErrorCode::NO_ERROR) { + IMSA_HILOGE("failed to set client state, ret %{public}d", ret); + return ret; + } + ret = HideKeyboard(client); + if (ret != ErrorCode::NO_ERROR) { + IMSA_HILOGE("failed to hide keyboard ret %{public}d", ret); + return ret; } - imsCore[0]->SetClientState(false); - HideKeyboard(client); RemoveClient(client->AsObject()); - IMSA_HILOGI("PerUserSession::OnReleaseInput End...[%{public}d]\n", userId_); + IMSA_HILOGD("PerUserSession::OnReleaseInput End...[%{public}d]\n", userId_); return ErrorCode::NO_ERROR; } @@ -1093,21 +1100,22 @@ namespace MiscServices { int32_t PerUserSession::OnStartInput(sptr client, bool isShowKeyboard) { IMSA_HILOGI("PerUserSession::OnStartInput"); - if (imsCore[0] == nullptr) { - return ErrorCode::ERROR_IME_NOT_AVAILABLE; + int32_t ret = SetClientState(true); + if (ret != ErrorCode::NO_ERROR) { + IMSA_HILOGE("failed to set client state"); + return ret; } - imsCore[0]->SetClientState(true); return ShowKeyboard(client, isShowKeyboard); } int32_t PerUserSession::OnSetCoreAndAgent(sptr core, sptr agent) { - IMSA_HILOGI("PerUserSession::SetCoreAndAgent Start\n"); + IMSA_HILOGD("PerUserSession::SetCoreAndAgent Start\n"); if (core == nullptr || agent == nullptr) { IMSA_HILOGE("PerUserSession::SetCoreAndAgent core or agent nullptr"); return ErrorCode::ERROR_EX_NULL_POINTER; } - imsCore[0] = core; + SetImsCore(DEFAULT_IME, core); if (imsDeathRecipient != nullptr) { imsDeathRecipient->SetDeathRecipient([this, core](const wptr &) { this->OnImsDied(core); }); bool ret = core->AsObject()->AddDeathRecipient(imsDeathRecipient); @@ -1121,7 +1129,7 @@ namespace MiscServices { void PerUserSession::SendAgentToAllClients() { - IMSA_HILOGI("PerUserSession::SendAgentToAllClients"); + IMSA_HILOGD("PerUserSession::SendAgentToAllClients"); std::lock_guard lock(mtx); if (imsAgent == nullptr) { IMSA_HILOGE("PerUserSession::SendAgentToAllClients imsAgent is nullptr"); @@ -1138,9 +1146,14 @@ namespace MiscServices { void PerUserSession::InitInputControlChannel() { - IMSA_HILOGI("PerUserSession::InitInputControlChannel"); + IMSA_HILOGD("PerUserSession::InitInputControlChannel"); sptr inputControlChannel = new InputControlChannelStub(userId_); - int ret = imsCore[0]->InitInputControlChannel(inputControlChannel); + sptr core = GetImsCore(DEFAULT_IME); + if (core == nullptr) { + IMSA_HILOGE("PerUserSession::InitInputControlChannel core is nullptr"); + return; + } + int ret = core->InitInputControlChannel(inputControlChannel); if (ret != ErrorCode::NO_ERROR) { IMSA_HILOGI("PerUserSession::InitInputControlChannel fail %{public}s", ErrorCode::ToString(ret)); } @@ -1153,25 +1166,26 @@ namespace MiscServices { */ int32_t PerUserSession::OnStopInput(sptr client) { - IMSA_HILOGI("PerUserSession::OnStopInput"); + IMSA_HILOGD("PerUserSession::OnStopInput"); return HideKeyboard(client); } void PerUserSession::StopInputService(std::string imeId) { IMSA_HILOGI("PerUserSession::StopInputService"); - if (imsCore[0] == nullptr) { + sptr core = GetImsCore(DEFAULT_IME); + if (core == nullptr) { IMSA_HILOGE("imsCore[0] is nullptr"); return; } IMSA_HILOGI("Remove death recipient"); - imsCore[0]->AsObject()->RemoveDeathRecipient(imsDeathRecipient); - imsCore[0]->StopInputService(imeId); + core->AsObject()->RemoveDeathRecipient(imsDeathRecipient); + core->StopInputService(imeId); } bool PerUserSession::IsRestartIme(uint32_t index) { - IMSA_HILOGI("PerUserSession::IsRestartIme"); + IMSA_HILOGD("PerUserSession::IsRestartIme"); std::lock_guard lock(resetLock); auto now = time(nullptr); if (difftime(now, manager[index].last) > IME_RESET_TIME_OUT) { @@ -1191,9 +1205,10 @@ namespace MiscServices { void PerUserSession::ClearImeData(uint32_t index) { IMSA_HILOGI("Clear ime...index = %{public}d", index); - if (imsCore[index] != nullptr) { - imsCore[index]->AsObject()->RemoveDeathRecipient(imsDeathRecipient); - imsCore[index] = nullptr; + sptr core = GetImsCore(index); + if (core != nullptr) { + core->AsObject()->RemoveDeathRecipient(imsDeathRecipient); + SetImsCore(index, nullptr); } inputControlChannel[index] = nullptr; localControlChannel[index] = nullptr; @@ -1215,7 +1230,7 @@ namespace MiscServices { int32_t PerUserSession::OnInputMethodSwitched(const Property &property, const SubProperty &subProperty) { - IMSA_HILOGI("PerUserSession::OnInputMethodSwitched"); + IMSA_HILOGD("PerUserSession::OnInputMethodSwitched"); std::lock_guard lock(mtx); for (const auto &client : mapClients) { auto clientInfo = client.second; @@ -1234,11 +1249,12 @@ namespace MiscServices { return ErrorCode::NO_ERROR; } SetCurrentSubProperty(subProperty); - if (imsCore[0] == nullptr) { + sptr core = GetImsCore(DEFAULT_IME); + if (core == nullptr) { IMSA_HILOGE("imsCore is nullptr"); return ErrorCode::ERROR_EX_NULL_POINTER; } - int32_t ret = imsCore[0]->SetSubtype(subProperty); + int32_t ret = core->SetSubtype(subProperty); if (ret != ErrorCode::NO_ERROR) { IMSA_HILOGE("PerUserSession::SetSubtype failed, ret %{public}d", ret); return ret; @@ -1248,16 +1264,46 @@ namespace MiscServices { SubProperty PerUserSession::GetCurrentSubProperty() { - IMSA_HILOGI("PerUserSession::GetCurrentSubProperty"); + IMSA_HILOGD("PerUserSession::GetCurrentSubProperty"); std::lock_guard lock(propertyLock_); return currentSubProperty; } void PerUserSession::SetCurrentSubProperty(const SubProperty &subProperty) { - IMSA_HILOGI("PerUserSession::SetCurrentSubProperty"); + IMSA_HILOGD("PerUserSession::SetCurrentSubProperty"); std::lock_guard lock(propertyLock_); currentSubProperty = subProperty; } + + sptr PerUserSession::GetImsCore(int32_t index) + { + std::lock_guard lock(imsCoreLock_); + if (!IsValid(index)) { + return nullptr; + } + return imsCore[index]; + } + + void PerUserSession::SetImsCore(int32_t index, sptr core) + { + std::lock_guard lock(imsCoreLock_); + if (!IsValid(index)) { + return; + } + imsCore[index] = core; + } + + int32_t PerUserSession::SetClientState(bool isAlive) + { + IMSA_HILOGD("set client state %{public}s", isAlive ? "alive" : "dead"); + auto core = GetImsCore(DEFAULT_IME); + if (core == nullptr) { + IMSA_HILOGE("imsCore is nullptr"); + return ErrorCode::ERROR_EX_NULL_POINTER; + } + core->SetClientState(isAlive); + return ErrorCode::NO_ERROR; + } } // namespace MiscServices } // namespace OHOS diff --git a/services/src/peruser_setting.cpp b/services/src/peruser_setting.cpp index 8d449834..55efd27e 100644 --- a/services/src/peruser_setting.cpp +++ b/services/src/peruser_setting.cpp @@ -167,7 +167,7 @@ namespace MiscServices { return ErrorCode::NO_ERROR; } Platform::Instance()->SetInputMethodSetting(userId_, imSetting); - // wait for some time so that the setting change will not be overrided by the followed transact + // wait for some time so that the setting change will not be override by the followed transact usleep(COMMON_COUNT_ONE_HUNDRED_THOUSAND); return ErrorCode::NO_ERROR; } diff --git a/test/fuzztest/BUILD.gn b/test/fuzztest/BUILD.gn index 23f56c7b..26a87a3e 100644 --- a/test/fuzztest/BUILD.gn +++ b/test/fuzztest/BUILD.gn @@ -22,6 +22,12 @@ group("fuzztest") { "corestub_fuzzer:fuzztest", "datachannelstub_fuzzer:fuzztest", "inputclientstub_fuzzer:fuzztest", + "inputmethod_fuzzer:fuzztest", + "inputmethodability_fuzzer:fuzztest", + "inputmethodcontroller_fuzzer:fuzztest", + "inputmethodsetting_fuzzer:fuzztest", + "perusersession_fuzzer:fuzztest", + "perusersetting_fuzzer:fuzztest", "platformcallbackstub_fuzzer:fuzztest", "systemabilitystub_fuzzer:fuzztest", ] diff --git a/test/fuzztest/agentstub_fuzzer/BUILD.gn b/test/fuzztest/agentstub_fuzzer/BUILD.gn index e8815da7..0dcf66bd 100644 --- a/test/fuzztest/agentstub_fuzzer/BUILD.gn +++ b/test/fuzztest/agentstub_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at diff --git a/test/fuzztest/agentstub_fuzzer/agentstub_fuzzer.cpp b/test/fuzztest/agentstub_fuzzer/agentstub_fuzzer.cpp index 843b8457..db828906 100644 --- a/test/fuzztest/agentstub_fuzzer/agentstub_fuzzer.cpp +++ b/test/fuzztest/agentstub_fuzzer/agentstub_fuzzer.cpp @@ -52,6 +52,8 @@ namespace OHOS { MessageOption option; sptr stub = new InputMethodAgentStub(); + MessageHandler *handler = MessageHandler::Instance(); + stub->SetMessageHandler(handler); stub->OnRemoteRequest(code, data, reply, option); return true; diff --git a/test/fuzztest/agentstub_fuzzer/agentstub_fuzzer.h b/test/fuzztest/agentstub_fuzzer/agentstub_fuzzer.h index 81295dac..ad7d049a 100644 --- a/test/fuzztest/agentstub_fuzzer/agentstub_fuzzer.h +++ b/test/fuzztest/agentstub_fuzzer/agentstub_fuzzer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,4 +18,4 @@ #define FUZZ_PROJECT_NAME "agentstub_fuzzer" -#endif // TEST_FUZZTEST_AGENTSTUB_FUZZER_AGENTSTUB_FUZZER_H +#endif // TEST_FUZZTEST_AGENTSTUB_FUZZER_AGENTSTUB_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/agentstub_fuzzer/project.xml b/test/fuzztest/agentstub_fuzzer/project.xml index 85e7ef2c..6e8ad2cf 100644 --- a/test/fuzztest/agentstub_fuzzer/project.xml +++ b/test/fuzztest/agentstub_fuzzer/project.xml @@ -1,5 +1,5 @@ - + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/inputmethodability_fuzzer/BUILD.gn b/test/fuzztest/inputmethodability_fuzzer/BUILD.gn new file mode 100644 index 00000000..dd7be398 --- /dev/null +++ b/test/fuzztest/inputmethodability_fuzzer/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/inputmethod/imf/inputmethod.gni") + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("InputMethodAbilityFuzzTest") { + module_out_path = "inputmethod/inputmethod" + + fuzz_config_file = + "//base/inputmethod/imf/test/fuzztest/inputmethodability_fuzzer" + + include_dirs = [ + "//base/inputmethod/imf/services/include", + "//foundation/ability/ability_runtime/interfaces/inner_api/app_manager/include/appmgr", + "//foundation/ability/ability_runtime/services/abilitymgr/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "inputmethodability_fuzzer.cpp" ] + + deps = [ + "//base/inputmethod/imf/frameworks/inputmethod_ability:inputmethod_ability", + "//base/inputmethod/imf/services:inputmethod_service", + "//foundation/ability/ability_runtime/services/abilitymgr:abilityms", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":InputMethodAbilityFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/inputmethodability_fuzzer/corpus/init b/test/fuzztest/inputmethodability_fuzzer/corpus/init new file mode 100644 index 00000000..bc977bd9 --- /dev/null +++ b/test/fuzztest/inputmethodability_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/inputmethodability_fuzzer/inputmethodability_fuzzer.cpp b/test/fuzztest/inputmethodability_fuzzer/inputmethodability_fuzzer.cpp new file mode 100644 index 00000000..1a1d2ac4 --- /dev/null +++ b/test/fuzztest/inputmethodability_fuzzer/inputmethodability_fuzzer.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "inputmethodability_fuzzer.h" + +#include + +#include "input_method_ability.h" + +using namespace OHOS::MiscServices; +namespace OHOS { +class EngineListener : public InputMethodEngineListener { + void OnKeyboardStatus(bool isShow) {} + void OnInputStart() {} + void OnInputStop(std::string imeId) {} + void OnSetCallingWindow(uint32_t windowId) {} + void OnSetSubtype(const SubProperty &property) {} +}; + +class KeyboardListenerImpl : public KeyboardListener { + bool OnKeyEvent(int32_t keyCode, int32_t keyStatus) + { + return true; + } + void OnCursorUpdate(int32_t positionX, int32_t positionY, int32_t height) {} + void OnSelectionChange(int32_t oldBegin, int32_t oldEnd, int32_t newBegin, int32_t newEnd) {} + void OnTextChange(std::string text) {} +}; + +void TestInsertText(std::string fuzzedString) +{ + sptr ability = InputMethodAbility::GetInstance(); + ability->InsertText(std::move(fuzzedString)); +} + +void TestSetImeListener() +{ + sptr ability = InputMethodAbility::GetInstance(); + auto engineListener = std::make_shared(); + ability->setImeListener(engineListener); +} + +void TestSetKdListener() +{ + sptr ability = InputMethodAbility::GetInstance(); + auto keyBoardListener = std::make_shared(); + ability->setKdListener(keyBoardListener); +} + +void TestDeleteForward(int32_t fuzzedInt32) +{ + sptr ability = InputMethodAbility::GetInstance(); + ability->DeleteForward(fuzzedInt32); +} + +void TestDeleteBackward(int32_t fuzzedInt32) +{ + sptr ability = InputMethodAbility::GetInstance(); + ability->DeleteBackward(fuzzedInt32); +} + +void TestHideKeyboardSelf() +{ + sptr ability = InputMethodAbility::GetInstance(); + ability->HideKeyboardSelf(); +} + +void TestGetTextBeforeCursor(int32_t fuzzedInt32) +{ + sptr ability = InputMethodAbility::GetInstance(); + std::u16string text; + ability->GetTextBeforeCursor(fuzzedInt32, text); +} + +void TestGetTextAfterCursor(int32_t fuzzedInt32) +{ + sptr ability = InputMethodAbility::GetInstance(); + std::u16string text; + ability->GetTextAfterCursor(fuzzedInt32, text); +} + +void TestSendFunctionKey(int32_t fuzzedInt32) +{ + sptr ability = InputMethodAbility::GetInstance(); + ability->SendFunctionKey(fuzzedInt32); +} + +void TestMoveCursor(int32_t fuzzedInt32) +{ + sptr ability = InputMethodAbility::GetInstance(); + ability->MoveCursor(fuzzedInt32); +} + +void TestDispatchKeyEvent(int32_t fuzzedInt32) +{ + sptr ability = InputMethodAbility::GetInstance(); + ability->DispatchKeyEvent(fuzzedInt32, fuzzedInt32); +} + +void TestSetCallingWindow(int32_t fuzzedInt32) +{ + sptr ability = InputMethodAbility::GetInstance(); + ability->SetCallingWindow(fuzzedInt32); +} + +void TestGetEnterKeyType() +{ + sptr ability = InputMethodAbility::GetInstance(); + int32_t keyType; + ability->GetEnterKeyType(keyType); +} + +void TestGetInputPattern() +{ + sptr ability = InputMethodAbility::GetInstance(); + int32_t inputPattern; + ability->GetInputPattern(inputPattern); +} + +void TestStopInput() +{ + sptr ability = InputMethodAbility::GetInstance(); + ability->StopInput(); +} + +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + std::string fuzzedString(reinterpret_cast(data), size); + auto fuzzedInt32 = static_cast(size); + + OHOS::TestInsertText(fuzzedString); + + OHOS::TestSetImeListener(); + + OHOS::TestSetKdListener(); + + OHOS::TestDeleteForward(fuzzedInt32); + OHOS::TestDeleteBackward(fuzzedInt32); + + OHOS::TestHideKeyboardSelf(); + + OHOS::TestGetTextBeforeCursor(fuzzedInt32); + OHOS::TestGetTextAfterCursor(fuzzedInt32); + + OHOS::TestSendFunctionKey(fuzzedInt32); + OHOS::TestMoveCursor(fuzzedInt32); + + OHOS::TestDispatchKeyEvent(fuzzedInt32); + + OHOS::TestSetCallingWindow(fuzzedInt32); + + OHOS::TestGetEnterKeyType(); + OHOS::TestGetInputPattern(); + + OHOS::TestStopInput(); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/inputmethodability_fuzzer/inputmethodability_fuzzer.h b/test/fuzztest/inputmethodability_fuzzer/inputmethodability_fuzzer.h new file mode 100644 index 00000000..6941a92a --- /dev/null +++ b/test/fuzztest/inputmethodability_fuzzer/inputmethodability_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INPUTMETHOD_IMF_CHOOSEDIALOG_INPUTMETHODABILITY_FUZZER_H +#define INPUTMETHOD_IMF_CHOOSEDIALOG_INPUTMETHODABILITY_FUZZER_H + +#define FUZZ_PROJECT_NAME "inputmethodability_fuzzer" + +#endif // INPUTMETHOD_IMF_CHOOSEDIALOG_INPUTMETHODABILITY_FUZZER_H diff --git a/test/fuzztest/inputmethodability_fuzzer/project.xml b/test/fuzztest/inputmethodability_fuzzer/project.xml new file mode 100644 index 00000000..6e8ad2cf --- /dev/null +++ b/test/fuzztest/inputmethodability_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/inputmethodcontroller_fuzzer/BUILD.gn b/test/fuzztest/inputmethodcontroller_fuzzer/BUILD.gn new file mode 100644 index 00000000..7d1b1439 --- /dev/null +++ b/test/fuzztest/inputmethodcontroller_fuzzer/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/inputmethod/imf/inputmethod.gni") + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("InputMethodControllerFuzzTest") { + module_out_path = "inputmethod/inputmethod" + + fuzz_config_file = + "//base/inputmethod/imf/test/fuzztest/inputmethodcontroller_fuzzer" + + include_dirs = [ + "//base/inputmethod/imf/services/include", + "//foundation/ability/ability_runtime/interfaces/inner_api/app_manager/include/appmgr", + "//foundation/ability/ability_runtime/services/abilitymgr/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "inputmethodcontroller_fuzzer.cpp" ] + + deps = [ + "//base/inputmethod/imf/frameworks/inputmethod_controller:inputmethod_client", + "//base/inputmethod/imf/services:inputmethod_service", + "//foundation/ability/ability_runtime/services/abilitymgr:abilityms", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ ":InputMethodControllerFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/inputmethodcontroller_fuzzer/corpus/init b/test/fuzztest/inputmethodcontroller_fuzzer/corpus/init new file mode 100644 index 00000000..bc977bd9 --- /dev/null +++ b/test/fuzztest/inputmethodcontroller_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/inputmethodcontroller_fuzzer/inputmethodcontroller_fuzzer.cpp b/test/fuzztest/inputmethodcontroller_fuzzer/inputmethodcontroller_fuzzer.cpp new file mode 100644 index 00000000..d07f1ef9 --- /dev/null +++ b/test/fuzztest/inputmethodcontroller_fuzzer/inputmethodcontroller_fuzzer.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "inputmethodcontroller_fuzzer.h" + +#include +#include + +#include "global.h" +#include "input_method_controller.h" +#include "key_event.h" +#include "message_parcel.h" + +using namespace OHOS::MiscServices; +namespace OHOS { +class TextListener : public OnTextChangedListener { +public: + TextListener() {} + ~TextListener() {} + void InsertText(const std::u16string &text) {} + void DeleteBackward(int32_t length) {} + void SetKeyboardStatus(bool status) {} + void DeleteForward(int32_t length) {} + void SendKeyEventFromInputMethod(const KeyEvent &event) {} + void SendKeyboardInfo(const KeyboardInfo &status) {} + void MoveCursor(const Direction direction) {} +}; + +class SettingListener : public InputMethodSettingListener { + void OnImeChange(const Property &property, const SubProperty &subProperty) {} +}; + +void TestListInputMethod(sptr imc) +{ + std::vector properties = {}; + imc->ListInputMethod(properties); + imc->ListInputMethod(false, properties); + imc->ListInputMethod(true, properties); + imc->DisplayOptionalInputMethod(); +} + +void TestListInputMethodSubtype(sptr imc, const std::string &fuzzedString, int32_t fuzzedInt32) +{ + std::vector subProperties = {}; + Property property; + property.name = fuzzedString; + property.id = fuzzedString; + property.label = fuzzedString; + property.icon = fuzzedString; + property.iconId = fuzzedInt32; + imc->ListInputMethodSubtype(property, subProperties); +} + +void TestDispatchKeyEvent(sptr imc, int32_t fuzzedInt32) +{ + sptr textListener = new TextListener(); + imc->Attach(textListener); + + std::shared_ptr keyEvent = MMI::KeyEvent::Create(); + keyEvent->SetKeyAction(fuzzedInt32); + keyEvent->SetKeyCode(fuzzedInt32); + imc->dispatchKeyEvent(keyEvent); +} + +void TestOnSelectionChange( + sptr imc, std::u16string fuzzedU16String, int fuzzedInt, double fuzzedDouble) +{ + sptr textListener = new TextListener(); + imc->Attach(textListener); + + CursorInfo cursorInfo; + cursorInfo.height = fuzzedDouble; + cursorInfo.left = fuzzedDouble; + cursorInfo.top = fuzzedDouble; + cursorInfo.width = fuzzedDouble; + imc->OnCursorUpdate(cursorInfo); + + imc->OnSelectionChange(fuzzedU16String, fuzzedInt, fuzzedInt); +} + +void TestOnConfigurationChange(sptr imc) +{ + sptr textListener = new TextListener(); + imc->Attach(textListener); + + Configuration info; + EnterKeyType keyType = EnterKeyType::DONE; + info.SetEnterKeyType(keyType); + TextInputType textInputType = TextInputType::DATETIME; + info.SetTextInputType(textInputType); + imc->OnConfigurationChange(info); + int32_t enterKeyType; + int32_t inputPattern; + imc->GetEnterKeyType(enterKeyType); + imc->GetInputPattern(inputPattern); +} + +void TestSwitchInputMethod(sptr imc, std::string fuzzedString) +{ + imc->SwitchInputMethod(fuzzedString, fuzzedString); + imc->ShowOptionalInputMethod(); +} + +void TestSetCallingWindow(sptr imc, uint32_t fuzzedUInt32) +{ + sptr textListener = new TextListener(); + imc->Attach(textListener); + + imc->SetCallingWindow(fuzzedUInt32); + imc->ShowSoftKeyboard(); + imc->HideSoftKeyboard(); +} + +void TestShowSomething(sptr imc) +{ + sptr textListener = new TextListener(); + imc->Attach(textListener); + imc->ShowCurrentInput(); + imc->HideCurrentInput(); + + imc->ShowTextInput(); + imc->HideTextInput(); + + imc->GetCurrentInputMethod(); + imc->GetCurrentInputMethodSubtype(); + + auto settingListener = std::make_shared(); + imc->setImeListener(settingListener); + + imc->StopInputSession(); + imc->Close(); +} + +void TestGetTextBeforeCursor(sptr imc, int32_t fuzzedInt32) +{ + sptr textListener = new TextListener(); + imc->Attach(textListener); + + std::u16string text; + imc->GetTextBeforeCursor(fuzzedInt32, text); +} + +void TestTextAfterCursor(sptr imc, int32_t fuzzedInt32) +{ + sptr textListener = new TextListener(); + imc->Attach(textListener); + + std::u16string text; + imc->GetTextAfterCursor(fuzzedInt32, text); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + std::string fuzzedString(data, data + size); + std::u16string fuzzedU16String = u"insert text"; + + auto fuzzedInt = static_cast(size); + auto fuzzedInt32 = static_cast(size); + auto fuzzedUInt32 = static_cast(size); + auto fuzzedDouble = static_cast(size); + + OHOS::sptr imc = InputMethodController::GetInstance(); + + OHOS::TestListInputMethod(imc); + OHOS::TestListInputMethodSubtype(imc, fuzzedString, fuzzedInt32); + OHOS::TestOnSelectionChange(imc, fuzzedU16String, fuzzedInt, fuzzedDouble); + OHOS::TestOnConfigurationChange(imc); + OHOS::TestSwitchInputMethod(imc, fuzzedString); + OHOS::TestGetTextBeforeCursor(imc, fuzzedInt32); + OHOS::TestSetCallingWindow(imc, fuzzedUInt32); + OHOS::TestDispatchKeyEvent(imc, fuzzedInt32); + OHOS::TestShowSomething(imc); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/inputmethodcontroller_fuzzer/inputmethodcontroller_fuzzer.h b/test/fuzztest/inputmethodcontroller_fuzzer/inputmethodcontroller_fuzzer.h new file mode 100644 index 00000000..6ba3e566 --- /dev/null +++ b/test/fuzztest/inputmethodcontroller_fuzzer/inputmethodcontroller_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_INPUTMETHODCONTROLLER_FUZZER_INPUTMETHODCONTROLLER_FUZZER_H +#define TEST_FUZZTEST_INPUTMETHODCONTROLLER_FUZZER_INPUTMETHODCONTROLLER_FUZZER_H + +#define FUZZ_PROJECT_NAME "inputmethodcontroller_fuzzer" + +#endif // TEST_FUZZTEST_INPUTMETHODCONTROLLER_FUZZER_INPUTMETHODCONTROLLER_FUZZER_H diff --git a/test/fuzztest/inputmethodcontroller_fuzzer/project.xml b/test/fuzztest/inputmethodcontroller_fuzzer/project.xml new file mode 100644 index 00000000..6e8ad2cf --- /dev/null +++ b/test/fuzztest/inputmethodcontroller_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/inputmethodsetting_fuzzer/BUILD.gn b/test/fuzztest/inputmethodsetting_fuzzer/BUILD.gn new file mode 100644 index 00000000..40db8500 --- /dev/null +++ b/test/fuzztest/inputmethodsetting_fuzzer/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/inputmethod/imf/inputmethod.gni") + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("InputMethodSettingFuzzTest") { + module_out_path = "inputmethod/inputmethod" + + fuzz_config_file = + "//base/inputmethod/imf/test/fuzztest/inputmethodsetting_fuzzer" + + include_dirs = [ + "//base/inputmethod/imf/services/include", + "//foundation/ability/ability_runtime/interfaces/inner_api/app_manager/include/appmgr", + "//foundation/ability/ability_runtime/services/abilitymgr/include", + "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager/include/", + "//third_party/jsoncpp/include/", + "//foundation/bundlemanager/bundle_framework/interfaces/inner_api/appexecfwk_core/include/bundlemgr", + "//foundation/multimedia/image_framework/interfaces/innerkits/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "inputmethodsetting_fuzzer.cpp" ] + + deps = [ + "${ability_runtime_services_path}/abilitymgr:abilityms", + "//base/inputmethod/imf/frameworks/inputmethod_controller:inputmethod_client", + "//base/inputmethod/imf/services:inputmethod_service", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + ] + + external_deps = [ + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":InputMethodSettingFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/inputmethodsetting_fuzzer/corpus/init b/test/fuzztest/inputmethodsetting_fuzzer/corpus/init new file mode 100644 index 00000000..bc977bd9 --- /dev/null +++ b/test/fuzztest/inputmethodsetting_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/inputmethodsetting_fuzzer/inputmethodsetting_fuzzer.cpp b/test/fuzztest/inputmethodsetting_fuzzer/inputmethodsetting_fuzzer.cpp new file mode 100644 index 00000000..e9850f16 --- /dev/null +++ b/test/fuzztest/inputmethodsetting_fuzzer/inputmethodsetting_fuzzer.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "inputmethodsetting_fuzzer.h" + +#include +#include + +#include "peruser_session.h" +#include "peruser_setting.h" +#include "input_method_system_ability.h" +#include "input_method_setting.h" +#include "input_method_controller.h" +#include "global.h" + +#include "message_parcel.h" + +using namespace OHOS::MiscServices; +namespace OHOS { + class TextListener : public OnTextChangedListener { + public: + TextListener() {} + ~TextListener() {} + void InsertText(const std::u16string& text) {} + void DeleteBackward(int32_t length) {} + void SetKeyboardStatus(bool status) {} + void DeleteForward(int32_t length) {} + void SendKeyEventFromInputMethod(const KeyEvent& event) {} + void SendKeyboardInfo(const KeyboardInfo& status) {} + void MoveCursor(const Direction direction) {} + }; + bool FuzzInputMethodSetting(const uint8_t* rawData, size_t size) + { + sptr imc = InputMethodController::GetInstance(); + sptr textListener = new TextListener(); + imc->Attach(textListener); + + constexpr int32_t MAIN_USER_ID = 100; + PerUserSetting *setting = new (std::nothrow) PerUserSetting(MAIN_USER_ID); + if (setting == nullptr) { + return true; + } + InputMethodSetting *methodSetting = setting->GetInputMethodSetting(); + if (methodSetting == nullptr) { + return true; + } + + InputMethodSetting setting_ = *methodSetting; + std::u16string imeId = Str8ToStr16(std::string(rawData, rawData + size)); + std::vector types; + for (size_t i = 0; i < size; ++i) { + types.push_back(static_cast(*rawData)); + } + setting_.GetCurrentInputMethod(); + setting_.SetCurrentInputMethod(imeId); + setting_.GetEnabledInputMethodList(); + setting_.AddEnabledInputMethod(imeId, types); + setting_.RemoveEnabledInputMethod(imeId); + setting_.GetEnabledKeyboardTypes(imeId); + setting_.GetCurrentKeyboardType(); + setting_.SetCurrentKeyboardType(static_cast(*rawData)); + setting_.GetCurrentSysKeyboardType(); + setting_.SetCurrentSysKeyboardType(static_cast(*rawData)); + setting_.FindKey(imeId); + setting_.ClearData(); + + delete setting; + setting = nullptr; + return true; + } +} +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::FuzzInputMethodSetting(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/inputmethodsetting_fuzzer/inputmethodsetting_fuzzer.h b/test/fuzztest/inputmethodsetting_fuzzer/inputmethodsetting_fuzzer.h new file mode 100644 index 00000000..af1ebb2d --- /dev/null +++ b/test/fuzztest/inputmethodsetting_fuzzer/inputmethodsetting_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_INPUTMETHODSETTING_FUZZER_INPUTMETHODSETTING_FUZZER_H +#define TEST_FUZZTEST_INPUTMETHODSETTING_FUZZER_INPUTMETHODSETTING_FUZZER_H + +#define FUZZ_PROJECT_NAME "inputmethodsetting_fuzzer" + +#endif // TEST_FUZZTEST_INPUTMETHODSETTING_FUZZER_INPUTMETHODSETTING_FUZZER_H diff --git a/test/fuzztest/inputmethodsetting_fuzzer/project.xml b/test/fuzztest/inputmethodsetting_fuzzer/project.xml new file mode 100644 index 00000000..6e8ad2cf --- /dev/null +++ b/test/fuzztest/inputmethodsetting_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/perusersession_fuzzer/BUILD.gn b/test/fuzztest/perusersession_fuzzer/BUILD.gn new file mode 100644 index 00000000..6bd0ad79 --- /dev/null +++ b/test/fuzztest/perusersession_fuzzer/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/inputmethod/imf/inputmethod.gni") + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("PerUserSessionFuzzTest") { + module_out_path = "inputmethod/inputmethod" + + fuzz_config_file = + "//base/inputmethod/imf/test/fuzztest/perusersession_fuzzer" + + include_dirs = [ + "//base/inputmethod/imf/services/include", + "//base/inputmethod/imf/frameworks/inputmethod_controller/include", + "//base/inputmethod/imf/services/include", + "//foundation/ability/ability_runtime/services/abilitymgr/include", + "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager/include", + "//third_party/jsoncpp/include", + "//foundation/ability/ability_runtime/interfaces/inner_api/app_manager/include/appmgr", + "//foundation/multimedia/image_framework/interfaces/innerkits/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "perusersession_fuzzer.cpp" ] + + deps = [ + "//base/inputmethod/imf/frameworks/inputmethod_ability:inputmethod_ability", + "//base/inputmethod/imf/frameworks/inputmethod_controller:inputmethod_client", + "//base/inputmethod/imf/services:inputmethod_service", + "//foundation/ability/ability_runtime/services/abilitymgr:abilityms", + "//foundation/arkui/napi:ace_napi", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PerUserSessionFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/perusersession_fuzzer/corpus/init b/test/fuzztest/perusersession_fuzzer/corpus/init new file mode 100644 index 00000000..bc977bd9 --- /dev/null +++ b/test/fuzztest/perusersession_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/perusersession_fuzzer/perusersession_fuzzer.cpp b/test/fuzztest/perusersession_fuzzer/perusersession_fuzzer.cpp new file mode 100644 index 00000000..2038216e --- /dev/null +++ b/test/fuzztest/perusersession_fuzzer/perusersession_fuzzer.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perusersession_fuzzer.h" + +#include +#include +#include +#include + +#include "global.h" +#include "i_input_method_agent.h" +#include "i_input_method_core.h" +#include "input_client_proxy.h" +#include "input_method_ability.h" +#include "input_method_agent_proxy.h" +#include "input_method_agent_stub.h" +#include "input_method_core_proxy.h" +#include "input_method_info.h" +#include "input_method_property.h" +#include "iremote_broker.h" +#include "message_parcel.h" +#include "peruser_session.h" +#include "peruser_setting.h" + +using namespace OHOS::MiscServices; +namespace OHOS { + constexpr size_t THRESHOLD = 10; + + uint32_t ConvertToUint32(const uint8_t *ptr) + { + if (ptr == nullptr) { + return 0; + } + uint32_t bigVar = (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | (ptr[3]); + return bigVar; + } + + bool FuzzPerUserSession(const uint8_t *rawData, size_t size) + { + Property property; + SubProperty subProperty; + + int flags = static_cast(*rawData); + std::string str(rawData, rawData + size); + std::u16string packageName = Str8ToStr16(str); + bool isShowKeyboard = true; + constexpr int32_t MAIN_USER_ID = 100; + sptr client = new (std::nothrow) InputClientStub(); + sptr object = client->AsObject(); + std::shared_ptr userSessions = std::make_shared(MAIN_USER_ID); + sptr core = new InputMethodCoreProxy(object); + sptr agent = new InputMethodAgentProxy(object); + InputMethodInfo *ime = new InputMethodInfo(); + + userSessions->OnPackageRemoved(packageName); + userSessions->OnShowKeyboardSelf(); + userSessions->OnInputMethodSwitched(property, subProperty); + userSessions->GetCurrentSubProperty(); + userSessions->StartInputService(); + userSessions->SetCurrentSubProperty(subProperty); + userSessions->StopInputService(str); + userSessions->JoinWorkThread(); + userSessions->OnHideKeyboardSelf(flags); + userSessions->OnStartInput(client, isShowKeyboard); + userSessions->OnStopInput(client); + userSessions->OnReleaseInput(client); + userSessions->SetCurrentIme(ime); + userSessions->SetSecurityIme(ime); + userSessions->ResetIme(ime, ime); + userSessions->OnSetCoreAndAgent(core, agent); + + delete ime; + ime = nullptr; + return true; + } +} +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + if (size < OHOS::THRESHOLD) { + return 0; + } + /* Run your code on data */ + OHOS::FuzzPerUserSession(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/perusersession_fuzzer/perusersession_fuzzer.h b/test/fuzztest/perusersession_fuzzer/perusersession_fuzzer.h new file mode 100644 index 00000000..0fd6520a --- /dev/null +++ b/test/fuzztest/perusersession_fuzzer/perusersession_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_PERUSERSESSION_FUZZER_AGENTSTUB_FUZZER_H +#define TEST_FUZZTEST_PERUSERSESSION_FUZZER_AGENTSTUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "perusersession_fuzzer" + +#endif // TEST_FUZZTEST_PERUSERSESSION_FUZZER_AGENTSTUB_FUZZER_H diff --git a/test/fuzztest/perusersession_fuzzer/project.xml b/test/fuzztest/perusersession_fuzzer/project.xml new file mode 100644 index 00000000..6e8ad2cf --- /dev/null +++ b/test/fuzztest/perusersession_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/perusersetting_fuzzer/BUILD.gn b/test/fuzztest/perusersetting_fuzzer/BUILD.gn new file mode 100644 index 00000000..1891d30f --- /dev/null +++ b/test/fuzztest/perusersetting_fuzzer/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/inputmethod/imf/inputmethod.gni") + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("PerUserSettingFuzzTest") { + module_out_path = "inputmethod/inputmethod" + + fuzz_config_file = + "//base/inputmethod/imf/test/fuzztest/perusersetting_fuzzer" + + include_dirs = [ + "//base/inputmethod/imf/services/include", + "//base/inputmethod/imf/frameworks/inputmethod_controller/include", + "//base/inputmethod/imf/services/include", + "//foundation/ability/ability_runtime/services/abilitymgr/include", + "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager/include", + "//third_party/jsoncpp/include", + "//foundation/ability/ability_runtime/interfaces/inner_api/app_manager/include/appmgr", + "//foundation/multimedia/image_framework/interfaces/innerkits/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "perusersetting_fuzzer.cpp" ] + + deps = [ + "//base/inputmethod/imf/frameworks/inputmethod_ability:inputmethod_ability", + "//base/inputmethod/imf/frameworks/inputmethod_controller:inputmethod_client", + "//base/inputmethod/imf/services:inputmethod_service", + "//foundation/ability/ability_runtime/services/abilitymgr:abilityms", + "//foundation/arkui/napi:ace_napi", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PerUserSettingFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/perusersetting_fuzzer/corpus/init b/test/fuzztest/perusersetting_fuzzer/corpus/init new file mode 100644 index 00000000..bc977bd9 --- /dev/null +++ b/test/fuzztest/perusersetting_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/perusersetting_fuzzer/perusersetting_fuzzer.cpp b/test/fuzztest/perusersetting_fuzzer/perusersetting_fuzzer.cpp new file mode 100644 index 00000000..8ab13359 --- /dev/null +++ b/test/fuzztest/perusersetting_fuzzer/perusersetting_fuzzer.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perusersetting_fuzzer.h" + +#include +#include +#include +#include + +#include "global.h" +#include "input_method_agent_stub.h" +#include "input_method_info.h" +#include "message_parcel.h" +#include "peruser_setting.h" + +using namespace OHOS::MiscServices; +namespace OHOS { + constexpr size_t THRESHOLD = 10; + + uint32_t ConvertToUint32(const uint8_t *ptr) + { + if (ptr == nullptr) { + return 0; + } + uint32_t bigVar = (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | (ptr[3]); + return bigVar; + } + bool FuzzPerUserSetting(const uint8_t *rawData, size_t size) + { + std::string str(reinterpret_cast(rawData), size); + std::u16string imeId = Str8ToStr16(str); + std::u16string packageName = Str8ToStr16(str); + std::u16string key = Str8ToStr16(str); + std::u16string value = Str8ToStr16(str); + bool isSecurityIme = true; + constexpr int32_t MAIN_USER_ID = 100; + + std::shared_ptr userSetting = std::make_shared(MAIN_USER_ID); + + userSetting->Initialize(); + userSetting->GetUserState(); + userSetting->GetCurrentInputMethod(); + userSetting->GetSecurityInputMethod(); + userSetting->GetNextInputMethod(); + userSetting->GetInputMethodSetting(); + userSetting->GetInputMethodProperty(imeId); + userSetting->OnPackageAdded(packageName, isSecurityIme); + userSetting->OnPackageRemoved(packageName, isSecurityIme); + userSetting->OnSettingChanged(key, value); + userSetting->OnAdvanceToNext(); + userSetting->OnUserLocked(); + + return true; + } +} +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + if (size < OHOS::THRESHOLD) { + return 0; + } + /* Run your code on data */ + OHOS::FuzzPerUserSetting(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/perusersetting_fuzzer/perusersetting_fuzzer.h b/test/fuzztest/perusersetting_fuzzer/perusersetting_fuzzer.h new file mode 100644 index 00000000..5b3ba89e --- /dev/null +++ b/test/fuzztest/perusersetting_fuzzer/perusersetting_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_PERUSERSETTING_FUZZER_AGENTSTUB_FUZZER_H +#define TEST_FUZZTEST_PERUSERSETTING_FUZZER_AGENTSTUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "perusersetting_fuzzer" + +#endif // TEST_FUZZTEST_PERUSERSETTING_FUZZER_AGENTSTUB_FUZZER_H diff --git a/test/fuzztest/perusersetting_fuzzer/project.xml b/test/fuzztest/perusersetting_fuzzer/project.xml new file mode 100644 index 00000000..6e8ad2cf --- /dev/null +++ b/test/fuzztest/perusersetting_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/platformcallbackstub_fuzzer/BUILD.gn b/test/fuzztest/platformcallbackstub_fuzzer/BUILD.gn index 059e81af..78e5c815 100644 --- a/test/fuzztest/platformcallbackstub_fuzzer/BUILD.gn +++ b/test/fuzztest/platformcallbackstub_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at diff --git a/test/fuzztest/platformcallbackstub_fuzzer/platformcallbackstub_fuzzer.h b/test/fuzztest/platformcallbackstub_fuzzer/platformcallbackstub_fuzzer.h index beec2e26..0a10d07e 100644 --- a/test/fuzztest/platformcallbackstub_fuzzer/platformcallbackstub_fuzzer.h +++ b/test/fuzztest/platformcallbackstub_fuzzer/platformcallbackstub_fuzzer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/test/fuzztest/platformcallbackstub_fuzzer/project.xml b/test/fuzztest/platformcallbackstub_fuzzer/project.xml index 85e7ef2c..6e8ad2cf 100644 --- a/test/fuzztest/platformcallbackstub_fuzzer/project.xml +++ b/test/fuzztest/platformcallbackstub_fuzzer/project.xml @@ -1,5 +1,5 @@ -