1 /*
2  * Copyright (C) 2008 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 <stdint.h>
20 #include <list>
21 
22 #include <binder/IBinder.h>
23 
24 #include <android-base/result.h>
25 #include <input/Input.h>
26 #include <utils/Errors.h>
27 #include <utils/Tokenizer.h>
28 #include <utils/Unicode.h>
29 #include <map>
30 
31 // Maximum number of keys supported by KeyCharacterMaps
32 #define MAX_KEYS 8192
33 
34 namespace android {
35 
36 /**
37  * Describes a mapping from Android key codes to characters.
38  * Also specifies other functions of the keyboard such as the keyboard type
39  * and key modifier semantics.
40  *
41  * This object is immutable after it has been loaded.
42  */
43 class KeyCharacterMap {
44 public:
45     enum class KeyboardType : int32_t {
46         UNKNOWN = 0,
47         NUMERIC = 1,
48         PREDICTIVE = 2,
49         ALPHA = 3,
50         FULL = 4,
51         /**
52          * Deprecated. Set 'keyboard.specialFunction' to '1' in the device's IDC file instead.
53          */
54         SPECIAL_FUNCTION = 5,
55         OVERLAY = 6,
56     };
57 
58     enum class Format {
59         // Base keyboard layout, may contain device-specific options, such as "type" declaration.
60         BASE = 0,
61         // Overlay keyboard layout, more restrictive, may be published by applications,
62         // cannot override device-specific options.
63         OVERLAY = 1,
64         // Either base or overlay layout ok.
65         ANY = 2,
66     };
67 
68     // Substitute key code and meta state for fallback action.
69     struct FallbackAction {
70         int32_t keyCode;
71         int32_t metaState;
72     };
73 
74     /* Loads a key character map from a file. */
75     static base::Result<std::shared_ptr<KeyCharacterMap>> load(const std::string& filename,
76                                                                Format format);
77 
78     /* Loads a key character map from its string contents. */
79     static base::Result<std::shared_ptr<KeyCharacterMap>> loadContents(const std::string& filename,
80                                                                        const char* contents,
81                                                                        Format format);
82 
83     const std::string getLoadFileName() const;
84 
85     /* Combines this key character map with the provided overlay. */
86     void combine(const KeyCharacterMap& overlay);
87 
88     /* Clears already applied layout overlay */
89     void clearLayoutOverlay();
90 
91     /* Gets the keyboard type. */
92     KeyboardType getKeyboardType() const;
93 
94     /* Gets the primary character for this key as in the label physically printed on it.
95      * Returns 0 if none (eg. for non-printing keys). */
96     char16_t getDisplayLabel(int32_t keyCode) const;
97 
98     /* Gets the Unicode character for the number or symbol generated by the key
99      * when the keyboard is used as a dialing pad.
100      * Returns 0 if no number or symbol is generated.
101      */
102     char16_t getNumber(int32_t keyCode) const;
103 
104     /* Gets the Unicode character generated by the key and meta key modifiers.
105      * Returns 0 if no character is generated.
106      */
107     char16_t getCharacter(int32_t keyCode, int32_t metaState) const;
108 
109     /* Gets the fallback action to use by default if the application does not
110      * handle the specified key.
111      * Returns true if an action was available, false if none.
112      */
113     bool getFallbackAction(int32_t keyCode, int32_t metaState,
114             FallbackAction* outFallbackAction) const;
115 
116     /* Gets the first matching Unicode character that can be generated by the key,
117      * preferring the one with the specified meta key modifiers.
118      * Returns 0 if no matching character is generated.
119      */
120     char16_t getMatch(int32_t keyCode, const char16_t* chars,
121             size_t numChars, int32_t metaState) const;
122 
123     /* Gets a sequence of key events that could plausibly generate the specified
124      * character sequence.  Returns false if some of the characters cannot be generated.
125      */
126     bool getEvents(int32_t deviceId, const char16_t* chars, size_t numChars,
127             Vector<KeyEvent>& outEvents) const;
128 
129     /* Maps an Android key code to another Android key code. This mapping is applied after scanCode
130      * and usageCodes are mapped to corresponding Android Keycode */
131     void addKeyRemapping(int32_t fromKeyCode, int32_t toKeyCode);
132 
133     /* Maps a scan code and usage code to a key code, in case this key map overrides
134      * the mapping in some way. */
135     status_t mapKey(int32_t scanCode, int32_t usageCode, int32_t* outKeyCode) const;
136 
137     /* Returns keycode after applying Android key code remapping defined in mKeyRemapping */
138     int32_t applyKeyRemapping(int32_t fromKeyCode) const;
139 
140     /* Returns the <keyCode, metaState> pair after applying key behavior defined in the kcm file,
141      * that tries to find a replacement key code based on current meta state */
142     std::pair<int32_t /*keyCode*/, int32_t /*metaState*/> applyKeyBehavior(int32_t keyCode,
143                                                                            int32_t metaState) const;
144 
145     /* Reads a key map from a parcel. */
146     static std::unique_ptr<KeyCharacterMap> readFromParcel(Parcel* parcel);
147 
148     /* Writes a key map to a parcel. */
149     void writeToParcel(Parcel* parcel) const;
150 
151     bool operator==(const KeyCharacterMap& other) const = default;
152 
153     KeyCharacterMap(const KeyCharacterMap& other) = default;
154 
155 private:
156     struct Behavior {
157         /* The meta key modifiers for this behavior. */
158         int32_t metaState = 0;
159 
160         /* The character to insert. */
161         char16_t character = 0;
162 
163         /* The fallback keycode if the key is not handled. */
164         int32_t fallbackKeyCode = 0;
165 
166         /* The replacement keycode if the key has to be replaced outright. */
167         int32_t replacementKeyCode = 0;
168 
169         bool operator==(const Behavior&) const = default;
170     };
171 
172     struct Key {
173         bool operator==(const Key&) const = default;
174 
175         /* The single character label printed on the key, or 0 if none. */
176         char16_t label = 0;
177 
178         /* The number or symbol character generated by the key, or 0 if none. */
179         char16_t number = 0;
180 
181         /* The list of key behaviors sorted from most specific to least specific
182          * meta key binding. */
183         std::list<Behavior> behaviors;
184     };
185 
186     class Parser {
187         enum State {
188             STATE_TOP = 0,
189             STATE_KEY = 1,
190         };
191 
192         enum {
193             PROPERTY_LABEL = 1,
194             PROPERTY_NUMBER = 2,
195             PROPERTY_META = 3,
196         };
197 
198         struct Property {
199             inline explicit Property(int32_t property = 0, int32_t metaState = 0) :
propertyProperty200                     property(property), metaState(metaState) { }
201 
202             int32_t property;
203             int32_t metaState;
204         };
205 
206         KeyCharacterMap* mMap;
207         Tokenizer* mTokenizer;
208         Format mFormat;
209         State mState;
210         int32_t mKeyCode;
211 
212     public:
213         Parser(KeyCharacterMap* map, Tokenizer* tokenizer, Format format);
214         status_t parse();
215 
216     private:
217         status_t parseType();
218         status_t parseMap();
219         status_t parseMapKey();
220         status_t parseKey();
221         status_t parseKeyProperty();
222         status_t finishKey(Key& key);
223         status_t parseModifier(const std::string& token, int32_t* outMetaState);
224         status_t parseCharacterLiteral(char16_t* outCharacter);
225     };
226 
227     std::map<int32_t, Key> mKeys;
228     KeyboardType mType = KeyboardType::UNKNOWN;
229     std::string mLoadFileName;
230     bool mLayoutOverlayApplied = false;
231 
232     std::map<int32_t /* fromAndroidKeyCode */, int32_t /* toAndroidKeyCode */> mKeyRemapping;
233     std::map<int32_t /* fromScanCode */, int32_t /* toAndroidKeyCode */> mKeysByScanCode;
234     std::map<int32_t /* fromHidUsageCode */, int32_t /* toAndroidKeyCode */> mKeysByUsageCode;
235 
236     KeyCharacterMap(const std::string& filename);
237 
238     const Key* getKey(int32_t keyCode) const;
239     const Behavior* getKeyBehavior(int32_t keyCode, int32_t metaState) const;
240     static bool matchesMetaState(int32_t eventMetaState, int32_t behaviorMetaState);
241 
242     bool findKey(char16_t ch, int32_t* outKeyCode, int32_t* outMetaState) const;
243 
244     static void addKey(Vector<KeyEvent>& outEvents,
245             int32_t deviceId, int32_t keyCode, int32_t metaState, bool down, nsecs_t time);
246     static void addMetaKeys(Vector<KeyEvent>& outEvents,
247             int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
248             int32_t* currentMetaState);
249     static bool addSingleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
250             int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
251             int32_t keyCode, int32_t keyMetaState,
252             int32_t* currentMetaState);
253     static void addDoubleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
254             int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
255             int32_t leftKeyCode, int32_t leftKeyMetaState,
256             int32_t rightKeyCode, int32_t rightKeyMetaState,
257             int32_t eitherKeyMetaState,
258             int32_t* currentMetaState);
259     static void addLockedMetaKey(Vector<KeyEvent>& outEvents,
260             int32_t deviceId, int32_t metaState, nsecs_t time,
261             int32_t keyCode, int32_t keyMetaState,
262             int32_t* currentMetaState);
263 
264     /* Clears all data stored in this key character map */
265     void clear();
266 
267     /* Loads the KeyCharacterMap provided by the tokenizer into this instance. */
268     status_t load(Tokenizer* tokenizer, Format format);
269 
270     /* Reloads the data from mLoadFileName and unapplies any overlay. */
271     status_t reloadBaseFromFile();
272 };
273 
274 } // namespace android
275