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