command.cc revision c2e0dbddbe15c98d52c4786dac06cb8952a8ae6d
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/string_util.h"
9#include "base/strings/string_number_conversions.h"
10#include "base/strings/string_split.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 = extension_manifest_keys;
20namespace values = extension_manifest_values;
21
22using extensions::ErrorUtils;
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
31
32ui::Accelerator ParseImpl(const std::string& accelerator,
33                          const std::string& platform_key,
34                          int index,
35                          string16* error) {
36  if (platform_key != values::kKeybindingPlatformWin &&
37      platform_key != values::kKeybindingPlatformMac &&
38      platform_key != values::kKeybindingPlatformChromeOs &&
39      platform_key != values::kKeybindingPlatformLinux &&
40      platform_key != values::kKeybindingPlatformDefault) {
41    *error = ErrorUtils::FormatErrorMessageUTF16(
42        errors::kInvalidKeyBindingUnknownPlatform,
43        base::IntToString(index),
44        platform_key);
45    return ui::Accelerator();
46  }
47
48  std::vector<std::string> tokens;
49  base::SplitString(accelerator, '+', &tokens);
50  if (tokens.size() < 2 || tokens.size() > 3) {
51    *error = ErrorUtils::FormatErrorMessageUTF16(
52        errors::kInvalidKeyBinding,
53        base::IntToString(index),
54        platform_key,
55        accelerator);
56    return ui::Accelerator();
57  }
58
59  // Now, parse it into an accelerator.
60  int modifiers = ui::EF_NONE;
61  ui::KeyboardCode key = ui::VKEY_UNKNOWN;
62  for (size_t i = 0; i < tokens.size(); i++) {
63    if (tokens[i] == "Ctrl") {
64      modifiers |= ui::EF_CONTROL_DOWN;
65    } else if (tokens[i] == "Command") {
66      if (platform_key == "mac") {
67        // Either the developer specified Command+foo in the manifest for Mac or
68        // they specified Ctrl and it got normalized to Command (to get Ctrl on
69        // Mac the developer has to specify MacCtrl). Therefore we treat this
70        // as Command.
71        modifiers |= ui::EF_COMMAND_DOWN;
72#if defined(OS_MACOSX)
73      } else if (platform_key == "default") {
74        // If we see "Command+foo" in the Default section it can mean two
75        // things, depending on the platform:
76        // The developer specified "Ctrl+foo" for Default and it got normalized
77        // on Mac to "Command+foo". This is fine. Treat it as Command.
78        modifiers |= ui::EF_COMMAND_DOWN;
79#endif
80      } else {
81        // No other platform supports Command.
82        key = ui::VKEY_UNKNOWN;
83        break;
84      }
85    } else if (tokens[i] == "Alt") {
86      modifiers |= ui::EF_ALT_DOWN;
87    } else if (tokens[i] == "Shift") {
88      modifiers |= ui::EF_SHIFT_DOWN;
89    } else if (tokens[i].size() == 1) {
90      if (key != ui::VKEY_UNKNOWN) {
91        // Multiple key assignments.
92        key = ui::VKEY_UNKNOWN;
93        break;
94      }
95      if (tokens[i][0] >= 'A' && tokens[i][0] <= 'Z') {
96        key = static_cast<ui::KeyboardCode>(ui::VKEY_A + (tokens[i][0] - 'A'));
97      } else if (tokens[i][0] >= '0' && tokens[i][0] <= '9') {
98        key = static_cast<ui::KeyboardCode>(ui::VKEY_0 + (tokens[i][0] - '0'));
99      } else {
100        key = ui::VKEY_UNKNOWN;
101        break;
102      }
103    } else {
104      *error = ErrorUtils::FormatErrorMessageUTF16(
105          errors::kInvalidKeyBinding,
106          base::IntToString(index),
107          platform_key,
108          accelerator);
109      return ui::Accelerator();
110    }
111  }
112  bool command = (modifiers & ui::EF_COMMAND_DOWN) != 0;
113  bool ctrl = (modifiers & ui::EF_CONTROL_DOWN) != 0;
114  bool alt = (modifiers & ui::EF_ALT_DOWN) != 0;
115  bool shift = (modifiers & ui::EF_SHIFT_DOWN) != 0;
116
117  // We support Ctrl+foo, Alt+foo, Ctrl+Shift+foo, Alt+Shift+foo, but not
118  // Ctrl+Alt+foo and not Shift+foo either. For a more detailed reason why we
119  // don't support Ctrl+Alt+foo see this article:
120  // http://blogs.msdn.com/b/oldnewthing/archive/2004/03/29/101121.aspx.
121  // On Mac Command can also be used in combination with Shift or on its own,
122  // as a modifier.
123  if (key == ui::VKEY_UNKNOWN || (ctrl && alt) || (command && alt) ||
124      (shift && !ctrl && !alt && !command)) {
125    *error = ErrorUtils::FormatErrorMessageUTF16(
126        errors::kInvalidKeyBinding,
127        base::IntToString(index),
128        platform_key,
129        accelerator);
130    return ui::Accelerator();
131  }
132
133  return ui::Accelerator(key, modifiers);
134}
135
136// For Mac, we convert "Ctrl" to "Command" and "MacCtrl" to "Ctrl". Other
137// platforms leave the shortcut untouched.
138std::string NormalizeShortcutSuggestion(const std::string& suggestion,
139                                        const std::string& platform) {
140  bool normalize = false;
141  if (platform == "mac") {
142    normalize = true;
143  } else if (platform == "default") {
144#if defined(OS_MACOSX)
145    normalize = true;
146#endif
147  }
148
149  if (!normalize)
150    return suggestion;
151
152  std::string key;
153  std::vector<std::string> tokens;
154  base::SplitString(suggestion, '+', &tokens);
155  for (size_t i = 0; i < tokens.size(); i++) {
156    if (tokens[i] == "Ctrl")
157      tokens[i] = "Command";
158    else if (tokens[i] == "MacCtrl")
159      tokens[i] = "Ctrl";
160  }
161  return JoinString(tokens, '+');
162}
163
164}  // namespace
165
166namespace extensions {
167
168Command::Command() {}
169
170Command::Command(const std::string& command_name,
171                 const string16& description,
172                 const std::string& accelerator)
173    : command_name_(command_name),
174      description_(description) {
175  string16 error;
176  accelerator_ = ParseImpl(accelerator, CommandPlatform(), 0, &error);
177}
178
179Command::~Command() {}
180
181// static
182std::string Command::CommandPlatform() {
183#if defined(OS_WIN)
184  return values::kKeybindingPlatformWin;
185#elif defined(OS_MACOSX)
186  return values::kKeybindingPlatformMac;
187#elif defined(OS_CHROMEOS)
188  return values::kKeybindingPlatformChromeOs;
189#elif defined(OS_LINUX)
190  return values::kKeybindingPlatformLinux;
191#else
192  return "";
193#endif
194}
195
196// static
197ui::Accelerator Command::StringToAccelerator(const std::string& accelerator) {
198  string16 error;
199  Command command;
200  ui::Accelerator parsed =
201      ParseImpl(accelerator, Command::CommandPlatform(), 0, &error);
202  return parsed;
203}
204
205bool Command::Parse(const DictionaryValue* command,
206                    const std::string& command_name,
207                    int index,
208                    string16* error) {
209  DCHECK(!command_name.empty());
210
211  string16 description;
212  if (command_name != values::kPageActionCommandEvent &&
213      command_name != values::kBrowserActionCommandEvent &&
214      command_name != values::kScriptBadgeCommandEvent) {
215    if (!command->GetString(keys::kDescription, &description) ||
216        description.empty()) {
217      *error = ErrorUtils::FormatErrorMessageUTF16(
218          errors::kInvalidKeyBindingDescription,
219          base::IntToString(index));
220      return false;
221    }
222  }
223
224  // We'll build up a map of platform-to-shortcut suggestions.
225  typedef std::map<const std::string, std::string> SuggestionMap;
226  SuggestionMap suggestions;
227
228  // First try to parse the |suggested_key| as a dictionary.
229  const DictionaryValue* suggested_key_dict;
230  if (command->GetDictionary(keys::kSuggestedKey, &suggested_key_dict)) {
231    for (DictionaryValue::Iterator iter(*suggested_key_dict); !iter.IsAtEnd();
232         iter.Advance()) {
233      // For each item in the dictionary, extract the platforms specified.
234      std::string suggested_key_string;
235      if (iter.value().GetAsString(&suggested_key_string) &&
236          !suggested_key_string.empty()) {
237        // Found a platform, add it to the suggestions list.
238        suggestions[iter.key()] = suggested_key_string;
239      } else {
240        *error = ErrorUtils::FormatErrorMessageUTF16(
241            errors::kInvalidKeyBinding,
242            base::IntToString(index),
243            keys::kSuggestedKey,
244            kMissing);
245        return false;
246      }
247    }
248  } else {
249    // No dictionary was found, fall back to using just a string, so developers
250    // don't have to specify a dictionary if they just want to use one default
251    // for all platforms.
252    std::string suggested_key_string;
253    if (command->GetString(keys::kSuggestedKey, &suggested_key_string) &&
254        !suggested_key_string.empty()) {
255      // If only a single string is provided, it must be default for all.
256      suggestions["default"] = suggested_key_string;
257    } else {
258      suggestions["default"] = "";
259    }
260  }
261
262  // Normalize the suggestions.
263  for (SuggestionMap::iterator iter = suggestions.begin();
264       iter != suggestions.end(); ++iter) {
265    // Before we normalize Ctrl to Command we must detect when the developer
266    // specified Command in the Default section, which will work on Mac after
267    // normalization but only fail on other platforms when they try it out on
268    // other platforms, which is not what we want.
269    if (iter->first == "default" &&
270        iter->second.find("Command+") != std::string::npos) {
271      *error = ErrorUtils::FormatErrorMessageUTF16(
272          errors::kInvalidKeyBinding,
273          base::IntToString(index),
274          keys::kSuggestedKey,
275          kCommandKeyNotSupported);
276      return false;
277    }
278
279    suggestions[iter->first] = NormalizeShortcutSuggestion(iter->second,
280                                                           iter->first);
281  }
282
283  std::string platform = CommandPlatform();
284  std::string key = platform;
285  if (suggestions.find(key) == suggestions.end())
286    key = values::kKeybindingPlatformDefault;
287  if (suggestions.find(key) == suggestions.end()) {
288    *error = ErrorUtils::FormatErrorMessageUTF16(
289        errors::kInvalidKeyBindingMissingPlatform,
290        base::IntToString(index),
291        keys::kSuggestedKey,
292        platform);
293    return false;  // No platform specified and no fallback. Bail.
294  }
295
296  // For developer convenience, we parse all the suggestions (and complain about
297  // errors for platforms other than the current one) but use only what we need.
298  std::map<const std::string, std::string>::const_iterator iter =
299      suggestions.begin();
300  for ( ; iter != suggestions.end(); ++iter) {
301    ui::Accelerator accelerator;
302    if (!iter->second.empty()) {
303      // Note that we pass iter->first to pretend we are on a platform we're not
304      // on.
305      accelerator = ParseImpl(iter->second, iter->first, index, error);
306      if (accelerator.key_code() == ui::VKEY_UNKNOWN) {
307        *error = ErrorUtils::FormatErrorMessageUTF16(
308            errors::kInvalidKeyBinding,
309            base::IntToString(index),
310            iter->first,
311            iter->second);
312        return false;
313      }
314    }
315
316    if (iter->first == key) {
317      // This platform is our platform, so grab this key.
318      accelerator_ = accelerator;
319      command_name_ = command_name;
320      description_ = description;
321    }
322  }
323  return true;
324}
325
326DictionaryValue* Command::ToValue(const Extension* extension,
327                                  bool active) const {
328  DictionaryValue* extension_data = new DictionaryValue();
329
330  string16 command_description;
331  if (command_name() == values::kBrowserActionCommandEvent ||
332      command_name() == values::kPageActionCommandEvent ||
333      command_name() == values::kScriptBadgeCommandEvent) {
334    command_description =
335        l10n_util::GetStringUTF16(IDS_EXTENSION_COMMANDS_GENERIC_ACTIVATE);
336  } else {
337    command_description = description();
338  }
339  extension_data->SetString("description", command_description);
340  extension_data->SetBoolean("active", active);
341  extension_data->SetString("keybinding", accelerator().GetShortcutText());
342  extension_data->SetString("command_name", command_name());
343  extension_data->SetString("extension_id", extension->id());
344
345  return extension_data;
346}
347
348}  // namespace extensions
349