1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <utils/Singleton.h>
20 
21 #include <fstream>
22 #include <optional>
23 #include <sstream>
24 #include <unordered_map>
25 
26 #include <log/log.h>
27 
28 namespace android::hardware::graphics::composer {
29 
30 class FileNode {
31 public:
32     FileNode(const std::string& nodePath);
33     ~FileNode();
34 
35     std::string dump();
36 
37     std::optional<std::string> getLastWrittenString(const std::string& nodeName);
38 
39     template <typename T>
getLastWrittenValue(const std::string & nodeName,T & value)40     status_t getLastWrittenValue(const std::string& nodeName, T& value) {
41         int fd = getFileHandler(nodeName);
42         if (fd < 0) return BAD_VALUE;
43 
44         auto iter = mLastWrittenString.find(fd);
45         if (iter == mLastWrittenString.end()) return BAD_VALUE;
46 
47         std::istringstream iss(iter->second);
48         iss >> value;
49         return NO_ERROR;
50     }
51 
52     std::optional<std::string> readString(const std::string& nodeName);
53 
54     template <typename T>
writeValue(const std::string & nodeName,const T value)55     bool writeValue(const std::string& nodeName, const T value) {
56         return writeString(nodeName, std::to_string(value));
57     }
58 
59     int getFileHandler(const std::string& nodeName);
60 
61 private:
62     std::string mNodePath;
63     std::unordered_map<std::string, int> mFds;
64     std::unordered_map<int, std::string> mLastWrittenString;
65     bool writeString(const std::string& nodeName, const std::string& str);
66 };
67 
68 class FileNodeManager : public Singleton<FileNodeManager> {
69 public:
70     FileNodeManager() = default;
71     ~FileNodeManager() = default;
72 
getFileNode(const std::string & nodePath)73     std::shared_ptr<FileNode> getFileNode(const std::string& nodePath) {
74         if (mFileNodes.find(nodePath) == mFileNodes.end()) {
75             mFileNodes[nodePath] = std::make_shared<FileNode>(nodePath);
76         }
77         return mFileNodes[nodePath];
78     }
79 
80 private:
81     std::unordered_map<std::string, std::shared_ptr<FileNode>> mFileNodes;
82 };
83 
84 } // namespace android::hardware::graphics::composer
85