Refactor InputMapper creation and collection type

Move the creation of InputMappers from InputReader into InputDevice
and change the collection type from a vector of raw pointers to a
vector of unique_ptrs.

Add helper functions for iterating over the mappers data structure.

InputDevice::addMapper(...) is preserved for test cases, except
rather than taking a bare pointer to a mapper, it creates the mapper,
adds it's mapper vector, and returns a reference to this mapper. The
unit tests have been updated for this change.

Test: atest inputflinger_tests libinput_tests
Change-Id: I1e1b69e8bd13dcfa835b2f846fd5cf0d6a4e1719
diff --git a/services/inputflinger/reader/include/InputDevice.h b/services/inputflinger/reader/include/InputDevice.h
index 882407d..d06cc20 100644
--- a/services/inputflinger/reader/include/InputDevice.h
+++ b/services/inputflinger/reader/include/InputDevice.h
@@ -67,7 +67,7 @@
     void setEnabled(bool enabled, nsecs_t when);
 
     void dump(std::string& dump);
-    void addMapper(InputMapper* mapper);
+    void populateMappers();
     void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
     void reset(nsecs_t when);
     void process(const RawEvent* rawEvents, size_t count);
@@ -116,6 +116,14 @@
 
     std::optional<int32_t> getAssociatedDisplayId();
 
+    // construct and add a mapper to the input device
+    template <class T, typename... Args>
+    T& addMapper(Args... args) {
+        T* mapper = new T(this, args...);
+        mMappers.emplace_back(mapper);
+        return *mapper;
+    }
+
 private:
     InputReaderContext* mContext;
     int32_t mId;
@@ -125,7 +133,7 @@
     std::string mAlias;
     uint32_t mClasses;
 
-    std::vector<InputMapper*> mMappers;
+    std::vector<std::unique_ptr<InputMapper>> mMappers;
 
     uint32_t mSources;
     bool mIsExternal;
@@ -138,6 +146,26 @@
     int32_t getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc);
 
     PropertyMap mConfiguration;
+
+    // run a function against every mapper
+    inline void for_each_mapper(std::function<void(InputMapper&)> f) {
+        for (auto& mapperPtr : mMappers) {
+            f(*mapperPtr);
+        }
+    }
+
+    // return the first value returned by a function over every mapper.
+    // if all mappers return nullopt, return nullopt.
+    template <typename T>
+    inline std::optional<T> first_in_mappers(std::function<std::optional<T>(InputMapper&)> f) {
+        for (auto& mapperPtr : mMappers) {
+            std::optional<T> ret = f(*mapperPtr);
+            if (ret) {
+                return ret;
+            }
+        }
+        return std::nullopt;
+    }
 };
 
 } // namespace android