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