1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#ifndef ACCESSIBILITY_COMMON_HELPER_H
17#define ACCESSIBILITY_COMMON_HELPER_H
18
19#include <atomic>
20#include <chrono>
21#include <functional>
22#include <thread>
23
24namespace OHOS {
25namespace Accessibility {
26namespace {
27    constexpr int32_t WAIT_PUBLISH_SLEEPTIME = 10;
28    constexpr int32_t WAIT_LOOP_SLEEPTIME = 100;
29} // namespace
30
31class AccessibilityCommonHelper {
32public:
33    static AccessibilityCommonHelper& GetInstance()
34    {
35        static AccessibilityCommonHelper helper;
36        return helper;
37    }
38
39    bool GetIsServicePublished()
40    {
41        return isServicePublished_;
42    }
43
44    void SetIsServicePublished(bool publish)
45    {
46        isServicePublished_ = publish;
47    }
48
49    void WaitForServicePublish()
50    {
51        while (1) {
52            std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_PUBLISH_SLEEPTIME));
53            if (isServicePublished_) {
54                return;
55            }
56        }
57    }
58
59    bool WaitForLoop(const std::function<bool()> &compare, int32_t timeout)
60    {
61        int32_t count = timeout * 1000 / WAIT_LOOP_SLEEPTIME;
62        while (count > 0) {
63            std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_LOOP_SLEEPTIME));
64            if (compare() == true) {
65                return true;
66            } else {
67                count--;
68            }
69        }
70        return false;
71    }
72
73    void SetRemoteObjectNotNullFlag(bool flag)
74    {
75        isRemoteObjectNotNulll_ = flag;
76    }
77
78    bool GetRemoteObjectNotNullFlag() const
79    {
80        return isRemoteObjectNotNulll_;
81    }
82
83private:
84    bool isServicePublished_ = false;
85    bool isRemoteObjectNotNulll_ = false;
86};
87} // namespace Accessibility
88} // namespace OHOS
89#endif // ACCESSIBILITY_COMMON_HELPER_H