1 /*
2  * Copyright (c) 2022-2024 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 APP_FILE_ACCESS_EXT_CONNECTION_H
17 #define APP_FILE_ACCESS_EXT_CONNECTION_H
18 
19 #include <atomic>
20 #include <mutex>
21 
22 #include "ability_connect_callback_stub.h"
23 #include "element_name.h"
24 #include "ifile_access_ext_base.h"
25 #include "iremote_object.h"
26 #include "refbase.h"
27 #include "want.h"
28 
29 namespace OHOS {
30 namespace FileAccessFwk {
31 class AppFileAccessExtConnection : public AAFwk::AbilityConnectionStub {
32 public:
33     AppFileAccessExtConnection() = default;
34     virtual ~AppFileAccessExtConnection();
35 
36     void OnAbilityConnectDone(
37         const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode) override;
38     void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override;
39     void ConnectFileExtAbility(const AAFwk::Want &want);
40     void DisconnectFileExtAbility();
41     bool IsExtAbilityConnected();
42     void OnSchedulerDied(const wptr<IRemoteObject> &remote);
43     sptr<IFileAccessExtBase> GetFileExtProxy();
44 
45 private:
46     void AddFileAccessDeathRecipient(const sptr<IRemoteObject> &token);
47     void RemoveFileAccessDeathRecipient(const sptr<IRemoteObject> &token);
48     struct ThreadLockInfo {
49         std::condition_variable condition;
50         bool isReady = false;
51     };
52     ThreadLockInfo connectLockInfo_;
53 
54     static std::mutex mutex_;
55     std::atomic<bool> isConnected_ = {false};
56     sptr<IFileAccessExtBase> fileExtProxy_;
57     std::mutex deathRecipientMutex_;
58     std::mutex proxyMutex_;
59     sptr<IRemoteObject::DeathRecipient> callerDeathRecipient_ = nullptr;
60 };
61 
62 class FileAccessDeathRecipient : public IRemoteObject::DeathRecipient {
63 public:
64     using RemoteDiedHandler = std::function<void(const wptr<IRemoteObject> &)>;
65     explicit FileAccessDeathRecipient(RemoteDiedHandler handler);
66     virtual ~FileAccessDeathRecipient();
67     virtual void OnRemoteDied(const wptr<IRemoteObject> &remote);
68 
69 private:
70     RemoteDiedHandler handler_;
71 };
72 } // namespace FileAccessFwk
73 } // namespace OHOS
74 #endif // APP_FILE_ACCESS_EXT_CONNECTION_H
75