command.cc revision d0247b1b59f9c528cb6df88b4f2b9afaf80d181e
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/common/extensions/command.h"
6
7#include "base/logging.h"
8#include "base/strings/string_number_conversions.h"
9#include "base/strings/string_split.h"
10#include "base/strings/string_util.h"
11#include "base/values.h"
12#include "chrome/common/extensions/extension.h"
13#include "extensions/common/error_utils.h"
14#include "extensions/common/manifest_constants.h"
15#include "grit/generated_resources.h"
16#include "ui/base/l10n/l10n_util.h"
17
18namespace extensions {
19
20namespace errors = manifest_errors;
21namespace keys = manifest_keys;
22namespace values = manifest_values;
23
24namespace {
25
26static const char kMissing[] = "Missing";
27
28static const char kCommandKeyNotSupported[] =
29    "Command key is not supported. Note: Ctrl means Command on Mac";
30
31bool IsNamedCommand(const std::string& command_name) {
32  return command_name != values::kPageActionCommandEvent &&
33         command_name != values::kBrowserActionCommandEvent &&
34         command_name != values::kScriptBadgeCommandEvent;
35}
36
37bool DoesRequireModifier(const std::string& accelerator) {
38  return accelerator != values::kKeyMediaNextTrack &&
39         accelerator != values::kKeyMediaPlayPause &&
40         accelerator != values::kKeyMediaPrevTrack &&
41         accelerator != values::kKeyMediaStop;
42}
43
44ui::Accelerator ParseImpl(const std::string& accelerator,
45                          const std::string& platform_key,
46                          int index,
47                          bool should_parse_media_keys,
48                          string16* error) {
49  error->clear();
50  if (platform_key != values::kKeybindingPlatformWin &&
51      platform_key != values::kKeybindingPlatformMac &&
52      platform_key != values::kKeybindingPlatformChromeOs &&
53      platform_key != values::kKeybindingPlatformLinux &&
54      platform_key != values::kKeybindingPlatformDefault) {
55    *error = ErrorUtils::FormatErrorMessageUTF16(
56        errors::kInvalidKeyBindingUnknownPlatform,
57        base::IntToString(index),
58        platform_key);
59    return ui::Accelerator();
60  }
61
62  std::vector<std::string> tokens;
63  base::SplitString(accelerator, '+', &tokens);
64  if (tokens.size() == 0 ||
65      (tokens.size() == 1 && DoesRequireModifier(accelerator)) ||
66      tokens.size() > 3) {
67    *error = ErrorUtils::FormatErrorMessageUTF16(
68        errors::kInvalidKeyBinding,
69        base::IntToString(index),
70        platform_key,
71        accelerator);
72    return ui::Accelerator();
73  }
74
75  // Now, parse it into an accelerator.
76  int modifiers = ui::EF_NONE;
77  ui::KeyboardCode key = ui::VKEY_UNKNOWN;
78  for (size_t i = 0; i < tokens.size(); i++) {
79    if (tokens[i] == values::kKeyCtrl) {
80      modifiers |= ui::EF_CONTROL_DOWN;
81    } else if (tokens[i] == values::kKeyCommand) {
82      if (platform_key == values::kKeybindingPlatformMac) {
83        // Either the developer specified Command+foo in the manifest for Mac or
84        // they specified Ctrl and it got normalized to Command (to get Ctrl on
85        // Mac the developer has to specify MacCtrl). Therefore we treat this
86        // as Command.
87        modifiers |= ui::EF_COMMAND_DOWN;
88#if defined(OS_MACOSX)
89      } else if (platform_key == values::kKeybindingPlatformDefault) {
90        // If we see "Command+foo" in the Default section it can mean two
91        // things, depending on the platform:
92        // The developer specified "Ctrl+foo" for Default and it got normalized
93        // on Mac to "Command+foo". This is fine. Treat it as Command.
94        modifiers |= ui::EF_COMMAND_DOWN;
95#endif
96      } else {
97        // No other platform supports Command.
98        key = ui::VKEY_UNKNOWN;
99        break;
100      }
101    } else if (tokens[i] == values::kKeyAlt) {
102      modifiers |= ui::EF_ALT_DOWN;
103    } else if (tokens[i] == values::kKeyShift) {
104      modifiers |= ui::EF_SHIFT_DOWN;
105    } else if (tokens[i].size() == 1 ||  // A-Z, 0-9.
106               tokens[i] == values::kKeyComma ||
107               tokens[i] == values::kKeyPeriod ||
108               tokens[i] == values::kKeyUp ||
109               tokens[i] == values::kKeyDown ||
110               tokens[i] == values::kKeyLeft ||
111               tokens[i] == values::kKeyRight ||
112               tokens[i] == values::kKeyIns ||
113               tokens[i] == values::kKeyDel ||
114               tokens[i] == values::kKeyHome ||
115               tokens[i] == values::kKeyEnd ||
116               tokens[i] == values::kKeyPgUp ||
117               tokens[i] == values::kKeyPgDwn ||
118               tokens[i] == values::kKeyTab ||
119               tokens[i] == values::kKeyMediaNextTrack ||
120               tokens[i] == values::kKeyMediaPlayPause ||
121               tokens[i] == values::kKeyMediaPrevTrack ||
122               tokens[i] == values::kKeyMediaStop) {
123      if (key != ui::VKEY_UNKNOWN) {
124        // Multiple key assignments.
125        key = ui::VKEY_UNKNOWN;
126        break;
127      }
128
129      if (tokens[i] == values::kKeyComma) {
130        key = ui::VKEY_OEM_COMMA;
131      } else if (tokens[i] == values::kKeyPeriod) {
132        key = ui::VKEY_OEM_PERIOD;
133      } else if (tokens[i] == values::kKeyUp) {
134        key = ui::VKEY_UP;
135      } else if (tokens[i] == values::kKeyDown) {
136        key = ui::VKEY_DOWN;
137      } else if (tokens[i] == values::kKeyLeft) {
138        key = ui::VKEY_LEFT;
139      } else if (tokens[i] == values::kKeyRight) {
140        key = ui::VKEY_RIGHT;
141      } else if (tokens[i] == values::kKeyIns) {
142        key = ui::VKEY_INSERT;
143      } else if (tokens[i] == values::kKeyDel) {
144        key = ui::VKEY_DELETE;
145      } else if (tokens[i] == values::kKeyHome) {
146        key = ui::VKEY_HOME;
147      } else if (tokens[i] == values::kKeyEnd) {
148        key = ui::VKEY_END;
149      } else if (tokens[i] == values::kKeyPgUp) {
150        key = ui::VKEY_PRIOR;
151      } else if (tokens[i] == values::kKeyPgDwn) {
152        key = ui::VKEY_NEXT;
153      } else if (tokens[i] == values::kKeyTab) {
154        key = ui::VKEY_TAB;
155      } else if (tokens[i] == values::kKeyMediaNextTrack &&
156                 should_parse_media_keys) {
157        key = ui::VKEY_MEDIA_NEXT_TRACK;
158      } else if (tokens[i] == values::kKeyMediaPlayPause &&
159                 should_parse_media_keys) {
160        key = ui::VKEY_MEDIA_PLAY_PAUSE;
161      } else if (tokens[i] == values::kKeyMediaPrevTrack &&
162                 should_parse_media_keys) {
163        key = ui::VKEY_MEDIA_PREV_TRACK;
164      } else if (tokens[i] == values::kKeyMediaStop &&
165                 should_parse_media_keys) {
166        key = ui::VKEY_MEDIA_STOP;
167      } else if (tokens[i].size() == 1 &&
168                 tokens[i][0] >= 'A' && tokens[i][0] <= 'Z') {
169        key = static_cast<ui::KeyboardCode>(ui::VKEY_A + (tokens[i][0] - 'A'));
170      } else if (tokens[i].size() == 1 &&
171                 tokens[i][0] >= '0' && tokens[i][0] <= '9') {
172        key = static_cast<ui::KeyboardCode>(ui::VKEY_0 + (tokens[i][0] - '0'));
173      } else {
174        key = ui::VKEY_UNKNOWN;
175        break;
176      }
177    } else {
178      *error = ErrorUtils::FormatErrorMessageUTF16(
179          errors::kInvalidKeyBinding,
180          base::IntToString(index),
181          platform_key,
182          accelerator);
183      return ui::Accelerator();
184    }
185  }
186
187  bool command = (modifiers & ui::EF_COMMAND_DOWN) != 0;
188  bool ctrl = (modifiers & ui::EF_CONTROL_DOWN) != 0;
189  bool alt = (modifiers & ui::EF_ALT_DOWN) != 0;
190  bool shift = (modifiers & ui::EF_SHIFT_DOWN) != 0;
191
192  // We support Ctrl+foo, Alt+foo, Ctrl+Shift+foo, Alt+Shift+foo, but not
193  // Ctrl+Alt+foo and not Shift+foo either. For a more detailed reason why we
194  // don't support Ctrl+Alt+foo see this article:
195  // http://blogs.msdn.com/b/oldnewthing/archive/2004/03/29/101121.aspx.
196  // On Mac Command can also be used in combination with Shift or on its own,
197  // as a modifier.
198  if (key == ui::VKEY_UNKNOWN || (ctrl && alt) || (command && alt) ||
199      (shift && !ctrl && !alt && !command)) {
200    *error = ErrorUtils::FormatErrorMessageUTF16(
201        errors::kInvalidKeyBinding,
202        base::IntToString(index),
203        platform_key,
204        accelerator);
205    return ui::Accelerator();
206  }
207
208  if ((key == ui::VKEY_MEDIA_NEXT_TRACK ||
209       key == ui::VKEY_MEDIA_PREV_TRACK ||
210       key == ui::VKEY_MEDIA_PLAY_PAUSE ||
211       key == ui::VKEY_MEDIA_STOP) &&
212      (shift || ctrl || alt || command)) {
213    *error = ErrorUtils::FormatErrorMessageUTF16(
214        errors::kInvalidKeyBindingMediaKeyWithModifier,
215        base::IntToString(index),
216        platform_key,
217        accelerator);
218    return ui::Accelerator();
219  }
220
221  return ui::Accelerator(key, modifiers);
222}
223
224// For Mac, we convert "Ctrl" to "Command" and "MacCtrl" to "Ctrl". Other
225// platforms leave the shortcut untouched.
226std::string NormalizeShortcutSuggestion(const std::string& suggestion,
227                                        const std::string& platform) {
228  bool normalize = false;
229  if (platform == values::kKeybindingPlatformMac) {
230    normalize = true;
231  } else if (platform == values::kKeybindingPlatformDefault) {
232#if defined(OS_MACOSX)
233    normalize = true;
234#endif
235  }
236
237  if (!normalize)
238    return suggestion;
239
240  std::vector<std::string> tokens;
241  base::SplitString(suggestion, '+', &tokens);
242  for (size_t i = 0; i < tokens.size(); i++) {
243    if (tokens[i] == values::kKeyCtrl)
244      tokens[i] = values::kKeyCommand;
245    else if (tokens[i] == values::kKeyMacCtrl)
246      tokens[i] = values::kKeyCtrl;
247  }
248  return JoinString(tokens, '+');
249}
250
251}  // namespace
252
253Command::Command() {}
254
255Command::Command(const std::string& command_name,
256                 const string16& description,
257                 const std::string& accelerator)
258    : command_name_(command_name),
259      description_(description) {
260  string16 error;
261  accelerator_ = ParseImpl(accelerator, CommandPlatform(), 0,
262                           IsNamedCommand(command_name), &error);
263}
264
265Command::~Command() {}
266
267// static
268std::string Command::CommandPlatform() {
269#if defined(OS_WIN)
270  return values::kKeybindingPlatformWin;
271#elif defined(OS_MACOSX)
272  return values::kKeybindingPlatformMac;
273#elif defined(OS_CHROMEOS)
274  return values::kKeybindingPlatformChromeOs;
275#elif defined(OS_LINUX)
276  return values::kKeybindingPlatformLinux;
277#else
278  return "";
279#endif
280}
281
282// static
283ui::Accelerator Command::StringToAccelerator(const std::string& accelerator,
284                                             const std::string& command_name) {
285  string16 error;
286  ui::Accelerator parsed =
287      ParseImpl(accelerator, Command::CommandPlatform(), 0,
288                IsNamedCommand(command_name), &error);
289  return parsed;
290}
291
292// static
293std::string Command::AcceleratorToString(const ui::Accelerator& accelerator) {
294  std::string shortcut;
295
296  // Ctrl and Alt are mutually exclusive.
297  if (accelerator.IsCtrlDown())
298    shortcut += values::kKeyCtrl;
299  else if (accelerator.IsAltDown())
300    shortcut += values::kKeyAlt;
301  if (!shortcut.empty())
302    shortcut += values::kKeySeparator;
303
304  if (accelerator.IsCmdDown()) {
305    shortcut += values::kKeyCommand;
306    shortcut += values::kKeySeparator;
307  }
308
309  if (accelerator.IsShiftDown()) {
310    shortcut += values::kKeyShift;
311    shortcut += values::kKeySeparator;
312  }
313
314  if (accelerator.key_code() >= ui::VKEY_0 &&
315      accelerator.key_code() <= ui::VKEY_9) {
316    shortcut += '0' + (accelerator.key_code() - ui::VKEY_0);
317  } else if (accelerator.key_code() >= ui::VKEY_A &&
318           accelerator.key_code() <= ui::VKEY_Z) {
319    shortcut += 'A' + (accelerator.key_code() - ui::VKEY_A);
320  } else {
321    switch (accelerator.key_code()) {
322      case ui::VKEY_OEM_COMMA:
323        shortcut += values::kKeyComma;
324        break;
325      case ui::VKEY_OEM_PERIOD:
326        shortcut += values::kKeyPeriod;
327        break;
328      case ui::VKEY_UP:
329        shortcut += values::kKeyUp;
330        break;
331      case ui::VKEY_DOWN:
332        shortcut += values::kKeyDown;
333        break;
334      case ui::VKEY_LEFT:
335        shortcut += values::kKeyLeft;
336        break;
337      case ui::VKEY_RIGHT:
338        shortcut += values::kKeyRight;
339        break;
340      case ui::VKEY_INSERT:
341        shortcut += values::kKeyIns;
342        break;
343      case ui::VKEY_DELETE:
344        shortcut += values::kKeyDel;
345        break;
346      case ui::VKEY_HOME:
347        shortcut += values::kKeyHome;
348        break;
349      case ui::VKEY_END:
350        shortcut += values::kKeyEnd;
351        break;
352      case ui::VKEY_PRIOR:
353        shortcut += values::kKeyPgUp;
354        break;
355      case ui::VKEY_NEXT:
356        shortcut += values::kKeyPgDwn;
357        break;
358      case ui::VKEY_TAB:
359        shortcut += values::kKeyTab;
360        break;
361      case ui::VKEY_MEDIA_NEXT_TRACK:
362        shortcut += values::kKeyMediaNextTrack;
363        break;
364      case ui::VKEY_MEDIA_PLAY_PAUSE:
365        shortcut += values::kKeyMediaPlayPause;
366        break;
367      case ui::VKEY_MEDIA_PREV_TRACK:
368        shortcut += values::kKeyMediaPrevTrack;
369        break;
370      case ui::VKEY_MEDIA_STOP:
371        shortcut += values::kKeyMediaStop;
372        break;
373      default:
374        return "";
375    }
376  }
377  return shortcut;
378}
379
380bool Command::Parse(const base::DictionaryValue* command,
381                    const std::string& command_name,
382                    int index,
383                    string16* error) {
384  DCHECK(!command_name.empty());
385
386  string16 description;
387  if (IsNamedCommand(command_name)) {
388    if (!command->GetString(keys::kDescription, &description) ||
389        description.empty()) {
390      *error = ErrorUtils::FormatErrorMessageUTF16(
391          errors::kInvalidKeyBindingDescription,
392          base::IntToString(index));
393      return false;
394    }
395  }
396
397  // We'll build up a map of platform-to-shortcut suggestions.
398  typedef std::map<const std::string, std::string> SuggestionMap;
399  SuggestionMap suggestions;
400
401  // First try to parse the |suggested_key| as a dictionary.
402  const base::DictionaryValue* suggested_key_dict;
403  if (command->GetDictionary(keys::kSuggestedKey, &suggested_key_dict)) {
404    for (base::DictionaryValue::Iterator iter(*suggested_key_dict);
405         !iter.IsAtEnd(); iter.Advance()) {
406      // For each item in the dictionary, extract the platforms specified.
407      std::string suggested_key_string;
408      if (iter.value().GetAsString(&suggested_key_string) &&
409          !suggested_key_string.empty()) {
410        // Found a platform, add it to the suggestions list.
411        suggestions[iter.key()] = suggested_key_string;
412      } else {
413        *error = ErrorUtils::FormatErrorMessageUTF16(
414            errors::kInvalidKeyBinding,
415            base::IntToString(index),
416            keys::kSuggestedKey,
417            kMissing);
418        return false;
419      }
420    }
421  } else {
422    // No dictionary was found, fall back to using just a string, so developers
423    // don't have to specify a dictionary if they just want to use one default
424    // for all platforms.
425    std::string suggested_key_string;
426    if (command->GetString(keys::kSuggestedKey, &suggested_key_string) &&
427        !suggested_key_string.empty()) {
428      // If only a single string is provided, it must be default for all.
429      suggestions[values::kKeybindingPlatformDefault] = suggested_key_string;
430    } else {
431      suggestions[values::kKeybindingPlatformDefault] = "";
432    }
433  }
434
435  // Normalize the suggestions.
436  for (SuggestionMap::iterator iter = suggestions.begin();
437       iter != suggestions.end(); ++iter) {
438    // Before we normalize Ctrl to Command we must detect when the developer
439    // specified Command in the Default section, which will work on Mac after
440    // normalization but only fail on other platforms when they try it out on
441    // other platforms, which is not what we want.
442    if (iter->first == values::kKeybindingPlatformDefault &&
443        iter->second.find("Command+") != std::string::npos) {
444      *error = ErrorUtils::FormatErrorMessageUTF16(
445          errors::kInvalidKeyBinding,
446          base::IntToString(index),
447          keys::kSuggestedKey,
448          kCommandKeyNotSupported);
449      return false;
450    }
451
452    suggestions[iter->first] = NormalizeShortcutSuggestion(iter->second,
453                                                           iter->first);
454  }
455
456  std::string platform = CommandPlatform();
457  std::string key = platform;
458  if (suggestions.find(key) == suggestions.end())
459    key = values::kKeybindingPlatformDefault;
460  if (suggestions.find(key) == suggestions.end()) {
461    *error = ErrorUtils::FormatErrorMessageUTF16(
462        errors::kInvalidKeyBindingMissingPlatform,
463        base::IntToString(index),
464        keys::kSuggestedKey,
465        platform);
466    return false;  // No platform specified and no fallback. Bail.
467  }
468
469  // For developer convenience, we parse all the suggestions (and complain about
470  // errors for platforms other than the current one) but use only what we need.
471  std::map<const std::string, std::string>::const_iterator iter =
472      suggestions.begin();
473  for ( ; iter != suggestions.end(); ++iter) {
474    ui::Accelerator accelerator;
475    if (!iter->second.empty()) {
476      // Note that we pass iter->first to pretend we are on a platform we're not
477      // on.
478      accelerator = ParseImpl(iter->second, iter->first, index,
479                              IsNamedCommand(command_name), error);
480      if (accelerator.key_code() == ui::VKEY_UNKNOWN) {
481        if (error->empty()) {
482          *error = ErrorUtils::FormatErrorMessageUTF16(
483              errors::kInvalidKeyBinding,
484              base::IntToString(index),
485              iter->first,
486              iter->second);
487        }
488        return false;
489      }
490    }
491
492    if (iter->first == key) {
493      // This platform is our platform, so grab this key.
494      accelerator_ = accelerator;
495      command_name_ = command_name;
496      description_ = description;
497    }
498  }
499  return true;
500}
501
502base::DictionaryValue* Command::ToValue(const Extension* extension,
503                                        bool active) const {
504  base::DictionaryValue* extension_data = new base::DictionaryValue();
505
506  string16 command_description;
507  if (command_name() == values::kBrowserActionCommandEvent ||
508      command_name() == values::kPageActionCommandEvent ||
509      command_name() == values::kScriptBadgeCommandEvent) {
510    command_description =
511        l10n_util::GetStringUTF16(IDS_EXTENSION_COMMANDS_GENERIC_ACTIVATE);
512  } else {
513    command_description = description();
514  }
515  extension_data->SetString("description", command_description);
516  extension_data->SetBoolean("active", active);
517  extension_data->SetString("keybinding", accelerator().GetShortcutText());
518  extension_data->SetString("command_name", command_name());
519  extension_data->SetString("extension_id", extension->id());
520
521  return extension_data;
522}
523
524}  // namespace extensions
525