else if (menu_item->type_ == "separator")

menu_items_.insert(menu_items_.begin() + pos, menu_item);

void Menu::Remove(MenuItem* menu_item, int pos) {

keep keep keep keep keep replace keep keep keep

// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/api/menuitem/menuitem.h"

#include "base/files/file_path.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "content/nw/src/api/object_manager.h"
#include "content/nw/src/api/menu/menu.h"
#include "content/nw/src/nw_base.h"
#include "content/nw/src/nw_content.h"
#include "content/nw/src/nw_package.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/events/event_constants.h"//for modifier key code
#include "base/logging.h"

namespace nw {

namespace {

static const int kIconWidth = 16;
static const int kIconHeight = 16;

} // namespace

void MenuItem::Create(const base::DictionaryValue& option) {
  is_modified_ = false;
  is_checked_ = false;
  is_enabled_ = true;
  type_ = "normal";
  submenu_ = NULL;
  meta_down_flag_ = false;

  focus_manager_ = NULL;
  menu_ = NULL;

  option.GetString("type", &type_);
  option.GetString("label", &label_);
  option.GetString("tooltip", &tooltip_);
  option.GetBoolean("checked", &is_checked_);
  option.GetBoolean("enabled", &is_enabled_);

  std::string key;
  std::string modifiers;
  option.GetString("key",&key);
  option.GetString("modifiers",&modifiers);

  ui::KeyboardCode keyval = ui::VKEY_UNKNOWN;

  keyval = GetKeycodeFromText(key);
  if (keyval == ui::VKEY_UNKNOWN){
    enable_shortcut_ = false;
  } else {
    enable_shortcut_ = true;
    //only code for ctrl, shift, alt, super and meta modifiers
    int modifiers_value = ui::EF_NONE;
    modifiers = base::ToLowerASCII(modifiers);
    if (modifiers.find("ctrl")!=std::string::npos){
      modifiers_value |= ui::EF_CONTROL_DOWN;
    }
    if (modifiers.find("shift")!=std::string::npos){
      modifiers_value |= ui::EF_SHIFT_DOWN ;
    }
    if (modifiers.find("alt")!=std::string::npos){
      modifiers_value |= ui::EF_ALT_DOWN;
    }
    if (modifiers.find("super")!=std::string::npos
     || modifiers.find("cmd")!=std::string::npos
     || modifiers.find("command")!=std::string::npos){
      modifiers_value |= ui::EF_COMMAND_DOWN;
    }
    if (modifiers.find("meta")!=std::string::npos){
      meta_down_flag_ = true;
    }
    accelerator_ = ui::Accelerator(keyval,modifiers_value);
  }

  std::string icon;
  if (option.GetString("icon", &icon) && !icon.empty())
    SetIcon(icon);

  int menu_id;
  if (option.GetInteger("submenu", &menu_id))
    SetSubmenu(object_manager()->GetApiObject<Menu>(menu_id));
}

void MenuItem::Destroy() {
}

void MenuItem::OnClick() {
  // Automatically flip checkbox.
  if (type_ == "checkbox")
    is_checked_ = !is_checked_;

  // Send event.
  base::ListValue args;
  object_manager()->SendEvent(this, "click", args);
}

void MenuItem::SetLabel(const std::string& label) {
  is_modified_ = true;
  label_ = base::UTF8ToUTF16(label);

  if (menu_)
    menu_->UpdateStates();
}

void MenuItem::SetIcon(const std::string& icon) {
  base::ThreadRestrictions::ScopedAllowIO allow_io;
  is_modified_ = true;
  if (icon.empty()) {
    icon_ = gfx::Image();
    return;
  }

  gfx::Image originImage;
  nw::Package* package = nw::InitNWPackage();
  if (nw::GetImage(package, base::FilePath::FromUTF8Unsafe(icon), &originImage)) {
    const gfx::ImageSkia* originImageSkia = originImage.ToImageSkia();
    gfx::ImageSkia resizedImageSkia = gfx::ImageSkiaOperations::CreateResizedImage(*originImageSkia,
                                                                                skia::ImageOperations::RESIZE_GOOD,
                                                                                gfx::Size(kIconWidth, kIconHeight));
    icon_ = gfx::Image(resizedImageSkia);
  }
}

void MenuItem::SetIconIsTemplate(bool isTemplate) {
}

void MenuItem::SetTooltip(const std::string& tooltip) {
  is_modified_ = true;
  tooltip_ = base::UTF8ToUTF16(tooltip);
  if (menu_)
    menu_->UpdateStates();
}

void MenuItem::SetEnabled(bool enabled) {
  is_enabled_ = enabled;
  if (menu_)
    menu_->UpdateStates();
}

void MenuItem::SetChecked(bool checked) {
  is_checked_ = checked;
  if (menu_)
    menu_->UpdateStates();
}

void MenuItem::SetSubmenu(Menu* menu) {
  if (submenu_) submenu_->RemoveKeys();

  submenu_ = menu;
}

bool MenuItem::GetChecked() {
  return is_checked_;
}

void MenuItem::UpdateKeys(views::FocusManager *focus_manager){
  if (focus_manager == NULL){
    return ;
  } else {
    focus_manager_ = focus_manager;
    if (enable_shortcut_){
      focus_manager->RegisterAccelerator(
        accelerator_,
        ui::AcceleratorManager::kHighPriority,
        this);
    }
    if (submenu_ != NULL){
      submenu_->UpdateKeys(focus_manager);
    }
  }
}

void MenuItem::RemoveKeys() {
  if (!focus_manager_) return;

  if (enable_shortcut_) {
    focus_manager_->UnregisterAccelerator(accelerator_, this);
  }
  if (submenu_) {
    submenu_->RemoveKeys();
  }
  focus_manager_ = NULL;
}

#if defined(OS_WIN) || defined(OS_LINUX)
bool MenuItem::AcceleratorPressed(const ui::Accelerator& accelerator) {
#if defined(OS_WIN)
  if (meta_down_flag_) {
    if ((::GetKeyState(VK_APPS) & 0x8000) != 0x8000) {
      return true;
    }
  }
#endif
  OnClick();
  return true;
}

bool MenuItem::CanHandleAccelerators() const {
  return enable_shortcut_ && is_enabled_;
}

#endif
}  // namespace nwapi


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/browser/shell_download_manager_delegate.h"

#if defined(OS_WIN)
#include <windows.h>
#include <commdlg.h>
#endif

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/platform_util.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/web_contents.h"
#include "net/base/net_util.h"

#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"

namespace content {

void ShellDownloadManagerDelegate::ChooseDownloadPath(
    int32 download_id,
    const DownloadTargetCallback& callback,
    const base::FilePath& suggested_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DownloadItem* item = download_manager_->GetDownload(download_id);
  if (!item || (item->GetState() != DownloadItem::IN_PROGRESS))
    return;

  WebContents* web_contents = item->GetWebContents();
  select_file_dialog_ = ui::SelectFileDialog::Create(this, NULL);
  ui::SelectFileDialog::FileTypeInfo file_type_info;
  // Platform file pickers, notably on Mac and Windows, tend to break
  // with double extensions like .tar.gz, so only pass in normal ones.
  base::FilePath::StringType extension = suggested_path.FinalExtension();
  if (!extension.empty()) {
    extension.erase(extension.begin());  // drop the .
    file_type_info.extensions.resize(1);
    file_type_info.extensions[0].push_back(extension);
  }
  file_type_info.include_all_files = true;
  file_type_info.support_drive = true;
  gfx::NativeWindow owning_window = web_contents ?
      platform_util::GetTopLevel(web_contents->GetNativeView()) : NULL;

  callback_ = callback;
  base::FilePath working_path;
  select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_SAVEAS_FILE,
                                  base::string16(),
                                  suggested_path,
                                  &file_type_info,
                                  0,
                                  base::FilePath::StringType(),
                                  owning_window,
                                  NULL, working_path);
}

void ShellDownloadManagerDelegate::OnFileSelected(const base::FilePath& path) {
  callback_.Run(path, DownloadItem::TARGET_DISPOSITION_PROMPT,
                DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path);
}

void ShellDownloadManagerDelegate::FileSelected(const base::FilePath& path,
                                      int index,
                                      void* params) {
  OnFileSelected(path);
}

void ShellDownloadManagerDelegate::FileSelectionCanceled(void* params) {
  OnFileSelected(base::FilePath());
}

}  // namespace content


language: node_js
node_js:
  - 0.10
  - 0.11


# minimatch

A minimal matching utility.

[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)

This is the matching library used internally by npm.

It works by converting glob expressions into JavaScript `RegExp`
objects.

## Usage

```javascript
var minimatch = require("minimatch")

minimatch("bar.foo", "*.foo") // true!
minimatch("bar.foo", "*.bar") // false!
minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
```

## Features

Supports these glob features:

* Brace Expansion
* Extended glob matching
* "Globstar" `**` matching

See:

* `man sh`
* `man bash`
* `man 3 fnmatch`
* `man 5 gitignore`

## Minimatch Class

Create a minimatch object by instanting the `minimatch.Minimatch` class.

```javascript
var Minimatch = require("minimatch").Minimatch
var mm = new Minimatch(pattern, options)
```

### Properties

* `pattern` The original pattern the minimatch object represents.
* `options` The options supplied to the constructor.
* `set` A 2-dimensional array of regexp or string expressions.
  Each row in the
  array corresponds to a brace-expanded pattern.  Each item in the row
  corresponds to a single path-part.  For example, the pattern
  `{a,b/c}/d` would expand to a set of patterns like:

        [ [ a, d ]
        , [ b, c, d ] ]

    If a portion of the pattern doesn't have any "magic" in it
    (that is, it's something like `"foo"` rather than `fo*o?`), then it
    will be left as a string rather than converted to a regular
    expression.

* `regexp` Created by the `makeRe` method.  A single regular expression
  expressing the entire pattern.  This is useful in cases where you wish
  to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
* `negate` True if the pattern is negated.
* `comment` True if the pattern is a comment.
* `empty` True if the pattern is `""`.

### Methods

* `makeRe` Generate the `regexp` member if necessary, and return it.
  Will return `false` if the pattern is invalid.
* `match(fname)` Return true if the filename matches the pattern, or
  false otherwise.
* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
  filename, and match it against a single row in the `regExpSet`.  This
  method is mainly for internal use, but is exposed so that it can be
  used by a glob-walker that needs to avoid excessive filesystem calls.

All other methods are internal, and will be called as necessary.

## Functions

The top-level exported function has a `cache` property, which is an LRU
cache set to store 100 items.  So, calling these methods repeatedly
with the same pattern and options will use the same Minimatch object,
saving the cost of parsing it multiple times.

### minimatch(path, pattern, options)

Main export.  Tests a path against the pattern using the options.

```javascript
var isJS = minimatch(file, "*.js", { matchBase: true })
```

### minimatch.filter(pattern, options)

Returns a function that tests its
supplied argument, suitable for use with `Array.filter`.  Example:

```javascript
var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
```

### minimatch.match(list, pattern, options)

Match against the list of
files, in the style of fnmatch or glob.  If nothing is matched, and
options.nonull is set, then return a list containing the pattern itself.

```javascript
var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}))
```

### minimatch.makeRe(pattern, options)

Make a regular expression object from the pattern.

## Options

All options are `false` by default.

### debug

Dump a ton of stuff to stderr.

### nobrace

Do not expand `{a,b}` and `{1..3}` brace sets.

### noglobstar

Disable `**` matching against multiple folder names.

### dot

Allow patterns to match filenames starting with a period, even if
the pattern does not explicitly have a period in that spot.

Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
is set.

### noext

Disable "extglob" style patterns like `+(a|b)`.

### nocase

Perform a case-insensitive match.

### nonull

When a match is not found by `minimatch.match`, return a list containing
the pattern itself if this option is set.  When not set, an empty list
is returned if there are no matches.

### matchBase

If set, then patterns without slashes will be matched
against the basename of the path if it contains slashes.  For example,
`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.

### nocomment

Suppress the behavior of treating `#` at the start of a pattern as a
comment.

### nonegate

Suppress the behavior of treating a leading `!` character as negation.

### flipNegate

Returns from negate expressions the same as if they were not negated.
(Ie, true on a hit, false on a miss.)

## Comparisons to other fnmatch/glob implementations

While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between minimatch and other
implementations, and are intentional.

If the pattern starts with a `!` character, then it is negated.  Set the
`nonegate` flag to suppress this behavior, and treat leading `!`
characters normally.  This is perhaps relevant if you wish to start the
pattern with a negative extglob pattern like `!(a|B)`.  Multiple `!`
characters at the start of a pattern will negate the pattern multiple
times.

If a pattern starts with `#`, then it is treated as a comment, and
will not match anything.  Use `\#` to match a literal `#` at the
start of a line, or set the `nocomment` flag to suppress this behavior.

The double-star character `**` is supported by default, unless the
`noglobstar` flag is set.  This is supported in the manner of bsdglob
and bash 4.1, where `**` only has special significance if it is the only
thing in a path part.  That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.

If an escaped pattern has no matches, and the `nonull` flag is set,
then minimatch.match returns the pattern as-provided, rather than
interpreting the character escapes.  For example,
`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`.  This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.

If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern.  Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity.  Since those two are valid, matching proceeds.


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/api/menu/menu.h"

#include "base/values.h"
#include "base/strings/utf_string_conversions.h"
#include "content/nw/src/api/object_manager.h"
#include "content/nw/src/api/menuitem/menuitem.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/app_window/app_window.h"
#include "skia/ext/image_operations.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/widget/widget.h"
#include "ui/views/focus/focus_manager.h"
#include "vector"

namespace ui {

NwMenuModel::NwMenuModel(Delegate* delegate) : SimpleMenuModel(delegate) {
}

bool NwMenuModel::HasIcons() const {
  // Always return false, see the comment about |NwMenuModel|.
  return false;
}

} // namespace ui

namespace nw {

void Menu::Create(const base::DictionaryValue& option) {
  is_menu_modified_ = true;
  menu_delegate_.reset(new MenuDelegate(object_manager()));
  menu_model_.reset(new ui::NwMenuModel(menu_delegate_.get()));

  focus_manager_ = NULL;
  window_ = NULL;

  std::string type;

  menu_items_.empty();
}

void Menu::Destroy() {
}

void Menu::Append(MenuItem* menu_item) {
  if (menu_item->submenu_)
    menu_model_->AddSubMenu(menu_item->id(), menu_item->label_,
                            menu_item->submenu_->menu_model_.get());
  else if (menu_item->type_ == "normal")
    menu_model_->AddItem(menu_item->id(), menu_item->label_);
  else if (menu_item->type_ == "checkbox")
    menu_model_->AddCheckItem(menu_item->id(), menu_item->label_);
  else if (menu_item->type_ == "separator")
    menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);

  is_menu_modified_ = true;
  menu_items_.push_back(menu_item);
  menu_item->menu_ = this;
}

void Menu::Insert(MenuItem* menu_item, int pos) {
  if (pos < 0 || pos > menu_items_.size()) return;

  if (menu_item->submenu_)
    menu_model_->InsertSubMenuAt(pos, menu_item->id(), menu_item->label_,
                                 menu_item->submenu_->menu_model_.get());
  else if (menu_item->type_ == "normal")
    menu_model_->InsertItemAt(pos, menu_item->id(), menu_item->label_);
  else if (menu_item->type_ == "checkbox")
    menu_model_->InsertCheckItemAt(pos, menu_item->id(), menu_item->label_);
  else if (menu_item->type_ == "separator")
    menu_model_->InsertSeparatorAt(pos, ui::NORMAL_SEPARATOR);

  is_menu_modified_ = true;
  menu_item->menu_ = this;
  menu_items_.insert(menu_items_.begin() + pos, menu_item);
}

void Menu::Remove(MenuItem* menu_item, int pos) {
  if (pos < 0 || pos >= menu_items_.size()) return;

  menu_model_->RemoveItemAt(pos);
  menu_items_.erase(menu_items_.begin() + pos);
  is_menu_modified_ = true;
  menu_item->menu_ = NULL;
  menu_item->RemoveKeys();
}

void Menu::Popup(int x, int y, content::RenderFrameHost* rfh) {
  // Rebuild();

  // Map point from document to screen.
  gfx::Point screen_point(x, y);

  // Convert from content coordinates to window coordinates.
  // This code copied from chrome_web_contents_view_delegate_views.cc
  aura::Window* target_window = GetActiveNativeView(rfh);
  aura::Window* root_window = target_window->GetRootWindow();
  views::Widget* top_level_widget =
    views::Widget::GetTopLevelWidgetForNativeView(target_window);
  aura::client::ScreenPositionClient* screen_position_client =
        aura::client::GetScreenPositionClient(root_window);
  if (screen_position_client) {
    screen_position_client->ConvertPointToScreen(target_window,
             &screen_point);
  }
  set_delay_destruction(true);
  views::MenuRunner runner(menu_model_.get(), views::MenuRunner::CONTEXT_MENU);
  ignore_result(
      runner.RunMenuAt(top_level_widget,
                       NULL,
                       gfx::Rect(screen_point, gfx::Size()),
                       views::MENU_ANCHOR_TOPRIGHT,
                       ui::MENU_SOURCE_NONE));
  set_delay_destruction(false);
  if (pending_destruction())
    object_manager_->OnDeallocateObject(id_);
}

void Menu::UpdateKeys(views::FocusManager *focus_manager){
  if (focus_manager == NULL){
    return ;
  } else {
    focus_manager_ = focus_manager;
    for(auto item : menu_items_) {
      item->UpdateKeys(focus_manager);
    }
  }
}

void Menu::RemoveKeys() {
  if (!focus_manager_) return;

  for(auto item: menu_items_) {
    item->RemoveKeys();
  }

  focus_manager_ = NULL;
}

void Menu::UpdateStates() {
}

aura::Window* Menu::GetActiveNativeView(content::RenderFrameHost* rfh) {
  content::WebContents* web_contents =
    content::WebContents::FromRenderFrameHost(rfh);
  if (!web_contents) {
    LOG(ERROR) << "Menu: couldn't find WebContents";
    return NULL;
  }
  return web_contents->GetFullscreenRenderWidgetHostView()
             ? web_contents->GetFullscreenRenderWidgetHostView()
                   ->GetNativeView()
             : web_contents->GetNativeView();
}

}  // namespace nw


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef CONTENT_NW_SRC_BROWSER_NATIVE_WINDOW_TOOLBAR_AURA_H_
#define CONTENT_NW_SRC_BROWSER_NATIVE_WINDOW_TOOLBAR_AURA_H_

#include "base/basictypes.h"
#include "content/nw/src/browser/native_window.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/widget/widget_delegate.h"

namespace content {
class Shell;
}

namespace views {
class ImageButton;
class Textfield;
}

namespace nw {

class NativeWindowToolbarAura : public views::WidgetDelegateView,
                               public views::TextfieldController,
                               public views::ButtonListener {
 public:
  explicit NativeWindowToolbarAura(content::Shell* shell);
  ~NativeWindowToolbarAura() override;

  void SetButtonEnabled(NativeWindow::TOOLBAR_BUTTON button,
                        bool enabled);
  void SetUrlEntry(const std::string& url);
  void SetIsLoading(bool loading);

 protected:
  // Overridden from WidgetDelegateView:
   views::View* GetContentsView() override;

  // Overridden from View:
   void Layout() override;
   void ViewHierarchyChanged(
      const ViewHierarchyChangedDetails& details) override;

  // Overridden from TextfieldController:
   void ContentsChanged(views::Textfield* sender,
                               const base::string16& new_contents) override;
   bool HandleKeyEvent(views::Textfield* sender,
                              const ui::KeyEvent& key_event) override;

  // Overridden from ButtonListener:
   void ButtonPressed(views::Button* sender,
                             const ui::Event& event) override;

 private:
  void InitToolbar();

  content::Shell* shell_;

  views::ImageButton* back_button_;
  views::ImageButton* forward_button_;
  views::ImageButton* stop_or_refresh_button_;
  views::Textfield* url_entry_;
  views::ImageButton* devtools_button_;
  views::ImageButton* dev_reload_button_;

  DISALLOW_COPY_AND_ASSIGN(NativeWindowToolbarAura);
};

}  // namespace nw

#endif  // CONTENT_NW_SRC_BROWSER_NATIVE_WINDOW_TOOLBAR_AURA_H_


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/nw/src/browser/nw_autofill_client.h"

#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "components/autofill/content/browser/content_autofill_driver.h"
#include "components/autofill/content/common/autofill_messages.h"
#include "components/autofill/core/common/autofill_pref_names.h"
#include "content/nw/src/browser/autofill_popup_controller_impl.h"
#include "content/nw/src/browser/nw_form_database_service.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/public/browser/render_view_host.h"
#include "ui/gfx/geometry/rect.h"

#if defined(OS_ANDROID)
#include "chrome/browser/ui/android/autofill/autofill_logger_android.h"
#endif

DEFINE_WEB_CONTENTS_USER_DATA_KEY(autofill::NWAutofillClient);

namespace autofill {

NWAutofillClient::NWAutofillClient(content::WebContents* web_contents)
    : content::WebContentsObserver(web_contents), web_contents_(web_contents) {
  DCHECK(web_contents);
#if defined(OS_MACOSX) && !defined(OS_IOS)
  RegisterForKeystoneNotifications();
#endif  // defined(OS_MACOSX) && !defined(OS_IOS)
}

NWAutofillClient::~NWAutofillClient() {
  // NOTE: It is too late to clean up the autofill popup; that cleanup process
  // requires that the WebContents instance still be valid and it is not at
  // this point (in particular, the WebContentsImpl destructor has already
  // finished running and we are now in the base class destructor).
  DCHECK(!popup_controller_);
#if defined(OS_MACOSX) && !defined(OS_IOS)
  UnregisterFromKeystoneNotifications();
#endif  // defined(OS_MACOSX) && !defined(OS_IOS)
}

void NWAutofillClient::TabActivated() {
}

PersonalDataManager* NWAutofillClient::GetPersonalDataManager() {
  return NULL;
}

scoped_refptr<AutofillWebDataService> NWAutofillClient::GetDatabase() {
  nw::NwFormDatabaseService* service =
      static_cast<content::ShellBrowserContext*>(
          web_contents_->GetBrowserContext())->GetFormDatabaseService();
  return service->get_autofill_webdata_service();
}

PrefService* NWAutofillClient::GetPrefs() {
  return NULL;
}

void NWAutofillClient::ShowAutofillSettings() {
  NOTIMPLEMENTED();
}

void NWAutofillClient::ConfirmSaveCreditCard(
    const base::Closure& save_card_callback) {
  NOTIMPLEMENTED();
}

void NWAutofillClient::ShowRequestAutocompleteDialog(
    const FormData& form,
    content::RenderFrameHost* render_frame_host,
    const ResultCallback& callback) {
  NOTIMPLEMENTED();
}

void NWAutofillClient::ShowAutofillPopup(
    const gfx::RectF& element_bounds,
    base::i18n::TextDirection text_direction,
    const std::vector<autofill::Suggestion>& suggestions,
    base::WeakPtr<AutofillPopupDelegate> delegate) {
  // Convert element_bounds to be in screen space.
  gfx::Rect client_area = web_contents_->GetContainerBounds();
  gfx::RectF element_bounds_in_screen_space =
      element_bounds + client_area.OffsetFromOrigin();

  // Will delete or reuse the old |popup_controller_|.
  popup_controller_ =
      AutofillPopupControllerImpl::GetOrCreate(popup_controller_,
                                               delegate,
                                               web_contents(),
                                               web_contents()->GetNativeView(),
                                               element_bounds_in_screen_space,
                                               text_direction);

  popup_controller_->Show(suggestions);
}

void NWAutofillClient::UpdateAutofillPopupDataListValues(
    const std::vector<base::string16>& values,
    const std::vector<base::string16>& labels) {
  if (popup_controller_.get())
    popup_controller_->UpdateDataListValues(values, labels);
}

void NWAutofillClient::HideAutofillPopup() {
  if (popup_controller_.get())
    popup_controller_->Hide();
}

bool NWAutofillClient::IsAutocompleteEnabled() {
  return true;
}

void NWAutofillClient::HideRequestAutocompleteDialog() {
  NOTIMPLEMENTED();
}

void NWAutofillClient::WebContentsDestroyed() {
  HideAutofillPopup();
}

void NWAutofillClient::DetectAccountCreationForms(
      content::RenderFrameHost* rfh,
      const std::vector<autofill::FormStructure*>& forms) {
  NOTIMPLEMENTED();
}

void NWAutofillClient::DidFillOrPreviewField(
    const base::string16& autofilled_value,
    const base::string16& profile_full_name) {
}

bool NWAutofillClient::HasCreditCardScanFeature() {
  return false;
}

void NWAutofillClient::ScanCreditCard(const CreditCardScanCallback& callback) {
  NOTIMPLEMENTED();
}

void NWAutofillClient::ShowUnmaskPrompt(
    const autofill::CreditCard& card,
    base::WeakPtr<autofill::CardUnmaskDelegate> delegate) {
  NOTIMPLEMENTED();
}

void NWAutofillClient::OnUnmaskVerificationResult(bool success) {
  NOTIMPLEMENTED();
}

void NWAutofillClient::OnFirstUserGestureObserved() {
  //NOTIMPLEMENTED();
}

}  // namespace autofill


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>no opener</title>
</head>
<body>
  <button id="winopen" type="button" onclick="winopen()">Open</button>
  <button id="showopener" type="button" onclick="showopener('result')">Show Opener</button>
  <script>
    function out(id, msg) {
      var result = document.createElement('h1');
      result.setAttribute('id', id);
      result.innerHTML = msg;
      document.body.appendChild(result);
    }

    function winopen() {
      window.open('https://localhost:{port}/index.html');
    }

    function showopener(id) {
      out(id, window.opener ? 'success': 'false');
    }
  </script>
</body>
</html>


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef CONTENT_NW_SRC_API_MENUITEM_MENUITEM_H_
#define CONTENT_NW_SRC_API_MENUITEM_MENUITEM_H_

#include "base/compiler_specific.h"
#include "content/nw/src/api/base/base.h"
#include "ui/events/keycodes/dom/keycode_converter.h"
#include "ui/events/keycodes/keyboard_codes.h"//for keycode
#include "ui/events/keycodes/keyboard_code_conversion.h"

#include <string>

#if defined(OS_MACOSX)
#if __OBJC__
@class NSMenuItem;
@class MenuItemDelegate;
#else
class NSMenuItem;
class MenuItemDelegate;
#endif  // __OBJC__
#elif defined(OS_WIN) || defined(OS_LINUX)
#include "base/strings/string16.h"
#include "ui/gfx/image/image.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/views/focus/focus_manager.h"
#endif  // defined(OS_MACOSX)

namespace nw {

ui::KeyboardCode GetKeycodeFromText(std::string text);

class Menu;

#if defined(OS_WIN) || defined(OS_LINUX)
class MenuItem : public Base ,
                 public ui::AcceleratorTarget {
#else
class MenuItem : public Base {
#endif
 public:
  MenuItem(int id,
           const base::WeakPtr<ObjectManager>& dispatcher_host,
           const base::DictionaryValue& option,
           const std::string& extension_id);
  ~MenuItem() override;

  void Call(const std::string& method,
             const base::ListValue& arguments,
             content::RenderFrameHost* rvh = nullptr) override;
  void CallSync(const std::string& method,
                        const base::ListValue& arguments,
                        base::ListValue* result) override;

#if defined(OS_MACOSX)
  static std::unique_ptr<base::DictionaryValue> CreateFromNative(NSMenuItem* menu_item, Menu* menu, int index);
  static MenuItem* GetMenuItemFromNative(NSMenuItem* menu_item);
#endif

#if defined(OS_WIN) || defined(OS_LINUX)
  bool AcceleratorPressed(const ui::Accelerator& accelerator) override;
  bool CanHandleAccelerators() const override;
  void UpdateKeys(views::FocusManager *focus_manager);
  void RemoveKeys();
#endif

  void OnClick();

 private:
  friend class Menu;

  // Platform-independent implementations
  void Create(const base::DictionaryValue& option);
  void Destroy();
  void SetLabel(const std::string& label);
  void SetIcon(const std::string& icon);
  void SetTooltip(const std::string& tooltip);
  void SetKey(const std::string& key);
  void SetModifiers(const std::string& modifiers);
  void SetEnabled(bool enabled);
  void SetChecked(bool checked);
  void SetSubmenu(Menu* sub_menu);

  bool GetChecked();

  // Template icon works only on Mac OS X
  void SetIconIsTemplate(bool isTemplate);

#if defined(OS_MACOSX)
  std::string type_;

  NSMenuItem* menu_item_;
  MenuItemDelegate* delegate_;
  bool iconIsTemplate;
  bool native_;

#elif defined(OS_WIN) || defined(OS_LINUX)
  friend class MenuDelegate;

  Menu* menu_;
  //**Never Try to free this pointer**
  //We get it from top widget
  views::FocusManager *focus_manager_;

  ui::Accelerator accelerator_;

  // Flag to indicate we need refresh.
  bool is_modified_;

  // Item attributes.
  bool is_checked_;
  bool is_enabled_;
  gfx::Image icon_;
  std::string type_;
  base::string16 label_;
  base::string16 tooltip_;
  Menu* submenu_;
  bool enable_shortcut_;

  bool meta_down_flag_;

#endif

  DISALLOW_COPY_AND_ASSIGN(MenuItem);
};

}  // namespace nw

#endif  // CONTENT_NW_SRC_API_MENUITEM_MENUITEM_H_


<?xml version="1.0" encoding="UTF-8"?>
<archive type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="7.10">
  <data>
    <int key="IBDocument.SystemTarget">1060</int>
    <string key="IBDocument.SystemVersion">11D50b</string>
    <string key="IBDocument.InterfaceBuilderVersion">851</string>
    <string key="IBDocument.AppKitVersion">1138.32</string>
    <string key="IBDocument.HIToolboxVersion">568.00</string>
    <object class="NSMutableDictionary" key="IBDocument.PluginVersions">
      <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaPlugin</string>
      <string key="NS.object.0">851</string>
    </object>
    <object class="NSMutableArray" key="IBDocument.EditedObjectIDs">
      <bool key="EncodedWithXMLCoder">YES</bool>
      <integer value="1"/>
    </object>
    <object class="NSArray" key="IBDocument.PluginDependencies">
      <bool key="EncodedWithXMLCoder">YES</bool>
      <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
    </object>
    <object class="NSMutableDictionary" key="IBDocument.Metadata">
      <bool key="EncodedWithXMLCoder">YES</bool>
      <object class="NSArray" key="dict.sortedKeys" id="0">
        <bool key="EncodedWithXMLCoder">YES</bool>
      </object>
      <object class="NSMutableArray" key="dict.values">
        <bool key="EncodedWithXMLCoder">YES</bool>
      </object>
    </object>
    <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000">
      <bool key="EncodedWithXMLCoder">YES</bool>
      <object class="NSCustomObject" id="1001">
        <string key="NSClassName">NSObject</string>
      </object>
      <object class="NSCustomObject" id="1003">
        <string key="NSClassName">FirstResponder</string>
      </object>
      <object class="NSCustomObject" id="1004">
        <string key="NSClassName">NSApplication</string>
      </object>
      <object class="NSCustomView" id="1005">
        <reference key="NSNextResponder"/>
        <int key="NSvFlags">268</int>
        <object class="NSMutableArray" key="NSSubviews">
          <bool key="EncodedWithXMLCoder">YES</bool>
          <object class="NSSecureTextField" id="870871897">
            <reference key="NSNextResponder" ref="1005"/>
            <int key="NSvFlags">268</int>
            <string key="NSFrame">{{99, 20}, {156, 22}}</string>
            <reference key="NSSuperview" ref="1005"/>
            <string key="NSReuseIdentifierKey">_NS:3407</string>
            <int key="NSTag">2</int>
            <bool key="NSEnabled">YES</bool>
            <object class="NSSecureTextFieldCell" key="NSCell" id="789371868">
              <int key="NSCellFlags">343014976</int>
              <int key="NSCellFlags2">272630848</int>
              <string key="NSContents"/>
              <object class="NSFont" key="NSSupport" id="749592131">
                <string key="NSName">LucidaGrande</string>
                <double key="NSSize">13</double>
                <int key="NSfFlags">1040</int>
              </object>
              <string key="NSCellIdentifier">_NS:3407</string>
              <reference key="NSControlView" ref="870871897"/>
              <bool key="NSDrawsBackground">YES</bool>
              <object class="NSColor" key="NSBackgroundColor" id="359621337">
                <int key="NSColorSpace">6</int>
                <string key="NSCatalogName">System</string>
                <string key="NSColorName">textBackgroundColor</string>
                <object class="NSColor" key="NSColor">
                  <int key="NSColorSpace">3</int>
                  <bytes key="NSWhite">MQA</bytes>
                </object>
              </object>
              <object class="NSColor" key="NSTextColor" id="1064189586">
                <int key="NSColorSpace">6</int>
                <string key="NSCatalogName">System</string>
                <string key="NSColorName">textColor</string>
                <object class="NSColor" key="NSColor" id="976070126">
                  <int key="NSColorSpace">3</int>
                  <bytes key="NSWhite">MAA</bytes>
                </object>
              </object>
              <object class="NSArray" key="NSAllowedInputLocales">
                <bool key="EncodedWithXMLCoder">YES</bool>
                <string>NSAllRomanInputSourcesLocaleIdentifier</string>
              </object>
            </object>
          </object>
          <object class="NSTextField" id="249141654">
            <reference key="NSNextResponder" ref="1005"/>
            <int key="NSvFlags">268</int>
            <string key="NSFrame">{{99, 52}, {156, 22}}</string>
            <reference key="NSSuperview" ref="1005"/>
            <string key="NSReuseIdentifierKey">_NS:817</string>
            <int key="NSTag">1</int>
            <bool key="NSEnabled">YES</bool>
            <object class="NSTextFieldCell" key="NSCell" id="270667430">
              <int key="NSCellFlags">-1804468671</int>
              <int key="NSCellFlags2">272630784</int>
              <string key="NSContents"/>
              <reference key="NSSupport" ref="749592131"/>
              <string key="NSCellIdentifier">_NS:817</string>
              <reference key="NSControlView" ref="249141654"/>
              <bool key="NSDrawsBackground">YES</bool>
              <reference key="NSBackgroundColor" ref="359621337"/>
              <reference key="NSTextColor" ref="1064189586"/>
            </object>
          </object>
          <object class="NSTextField" id="298854538">
            <reference key="NSNextResponder" ref="1005"/>
            <int key="NSvFlags">268</int>
            <string key="NSFrame">{{17, 22}, {77, 17}}</string>
            <reference key="NSSuperview" ref="1005"/>
            <string key="NSReuseIdentifierKey">_NS:4068</string>
            <bool key="NSEnabled">YES</bool>
            <object class="NSTextFieldCell" key="NSCell" id="212881775">
              <int key="NSCellFlags">68288064</int>
              <int key="NSCellFlags2">71304192</int>
              <string key="NSContents">Password:</string>
              <reference key="NSSupport" ref="749592131"/>
              <string key="NSCellIdentifier">_NS:4068</string>
              <reference key="NSControlView" ref="298854538"/>
              <object class="NSColor" key="NSBackgroundColor" id="818604237">
                <int key="NSColorSpace">6</int>
                <string key="NSCatalogName">System</string>
                <string key="NSColorName">controlColor</string>
                <object class="NSColor" key="NSColor">
                  <int key="NSColorSpace">3</int>
                  <bytes key="NSWhite">MC42NjY2NjY2NjY3AA</bytes>
                </object>
              </object>
              <object class="NSColor" key="NSTextColor" id="1040089286">
                <int key="NSColorSpace">6</int>
                <string key="NSCatalogName">System</string>
                <string key="NSColorName">controlTextColor</string>
                <reference key="NSColor" ref="976070126"/>
              </object>
            </object>
          </object>
          <object class="NSTextField" id="881326141">
            <reference key="NSNextResponder" ref="1005"/>
            <int key="NSvFlags">268</int>
            <string key="NSFrame">{{17, 54}, {77, 17}}</string>
            <reference key="NSSuperview" ref="1005"/>
            <string key="NSReuseIdentifierKey">_NS:4068</string>
            <bool key="NSEnabled">YES</bool>
            <object class="NSTextFieldCell" key="NSCell" id="509864529">
              <int key="NSCellFlags">68288064</int>
              <int key="NSCellFlags2">71304192</int>
              <string key="NSContents">Username:</string>
              <reference key="NSSupport" ref="749592131"/>
              <string key="NSCellIdentifier">_NS:4068</string>
              <reference key="NSControlView" ref="881326141"/>
              <reference key="NSBackgroundColor" ref="818604237"/>
              <reference key="NSTextColor" ref="1040089286"/>
            </object>
          </object>
        </object>
        <string key="NSFrameSize">{275, 94}</string>
        <reference key="NSSuperview"/>
        <string key="NSClassName">NSView</string>
      </object>
    </object>
    <object class="IBObjectContainer" key="IBDocument.Objects">
      <object class="NSMutableArray" key="connectionRecords">
        <bool key="EncodedWithXMLCoder">YES</bool>
      </object>
      <object class="IBMutableOrderedSet" key="objectRecords">
        <object class="NSArray" key="orderedObjects">
          <bool key="EncodedWithXMLCoder">YES</bool>
          <object class="IBObjectRecord">
            <int key="objectID">0</int>
            <reference key="object" ref="0"/>
            <reference key="children" ref="1000"/>
            <nil key="parent"/>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">-2</int>
            <reference key="object" ref="1001"/>
            <reference key="parent" ref="0"/>
            <string key="objectName">File's Owner</string>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">-1</int>
            <reference key="object" ref="1003"/>
            <reference key="parent" ref="0"/>
            <string key="objectName">First Responder</string>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">-3</int>
            <reference key="object" ref="1004"/>
            <reference key="parent" ref="0"/>
            <string key="objectName">Application</string>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">1</int>
            <reference key="object" ref="1005"/>
            <object class="NSMutableArray" key="children">
              <bool key="EncodedWithXMLCoder">YES</bool>
              <reference ref="249141654"/>
              <reference ref="870871897"/>
              <reference ref="298854538"/>
              <reference ref="881326141"/>
            </object>
            <reference key="parent" ref="0"/>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">2</int>
            <reference key="object" ref="881326141"/>
            <object class="NSMutableArray" key="children">
              <bool key="EncodedWithXMLCoder">YES</bool>
              <reference ref="509864529"/>
            </object>
            <reference key="parent" ref="1005"/>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">3</int>
            <reference key="object" ref="509864529"/>
            <reference key="parent" ref="881326141"/>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">4</int>
            <reference key="object" ref="298854538"/>
            <object class="NSMutableArray" key="children">
              <bool key="EncodedWithXMLCoder">YES</bool>
              <reference ref="212881775"/>
            </object>
            <reference key="parent" ref="1005"/>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">5</int>
            <reference key="object" ref="212881775"/>
            <reference key="parent" ref="298854538"/>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">6</int>
            <reference key="object" ref="249141654"/>
            <object class="NSMutableArray" key="children">
              <bool key="EncodedWithXMLCoder">YES</bool>
              <reference ref="270667430"/>
            </object>
            <reference key="parent" ref="1005"/>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">7</int>
            <reference key="object" ref="270667430"/>
            <reference key="parent" ref="249141654"/>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">8</int>
            <reference key="object" ref="870871897"/>
            <object class="NSMutableArray" key="children">
              <bool key="EncodedWithXMLCoder">YES</bool>
              <reference ref="789371868"/>
            </object>
            <reference key="parent" ref="1005"/>
          </object>
          <object class="IBObjectRecord">
            <int key="objectID">9</int>
            <reference key="object" ref="789371868"/>
            <reference key="parent" ref="870871897"/>
          </object>
        </object>
      </object>
      <object class="NSMutableDictionary" key="flattenedProperties">
        <bool key="EncodedWithXMLCoder">YES</bool>
        <object class="NSArray" key="dict.sortedKeys">
          <bool key="EncodedWithXMLCoder">YES</bool>
          <string>-1.IBPluginDependency</string>
          <string>-2.IBPluginDependency</string>
          <string>-3.IBPluginDependency</string>
          <string>1.IBEditorWindowLastContentRect</string>
          <string>1.IBPluginDependency</string>
          <string>1.WindowOrigin</string>
          <string>1.editorWindowContentRectSynchronizationRect</string>
          <string>2.IBPluginDependency</string>
          <string>2.IBViewBoundsToFrameTransform</string>
          <string>3.IBPluginDependency</string>
          <string>4.IBPluginDependency</string>
          <string>4.IBViewBoundsToFrameTransform</string>
          <string>5.IBPluginDependency</string>
          <string>6.IBPluginDependency</string>
          <string>6.IBViewBoundsToFrameTransform</string>
          <string>7.IBPluginDependency</string>
          <string>8.IBPluginDependency</string>
          <string>8.IBViewBoundsToFrameTransform</string>
          <string>9.IBPluginDependency</string>
        </object>
        <object class="NSMutableArray" key="dict.values">
          <bool key="EncodedWithXMLCoder">YES</bool>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <string>{{969, 1048}, {275, 94}}</string>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <string>{628, 654}</string>
          <string>{{357, 416}, {480, 272}}</string>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <object class="NSAffineTransform">
            <bytes key="NSTransformStruct">P4AAAL+AAABBiAAAwpAAAA</bytes>
          </object>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <object class="NSAffineTransform">
            <bytes key="NSTransformStruct">P4AAAL+AAABBiAAAwiAAAA</bytes>
          </object>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <object class="NSAffineTransform">
            <bytes key="NSTransformStruct">P4AAAL+AAABCxgAAwpAAAA</bytes>
          </object>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
          <object class="NSAffineTransform">
            <bytes key="NSTransformStruct">P4AAAL+AAABCxgAAwiAAAA</bytes>
          </object>
          <string>com.apple.InterfaceBuilder.CocoaPlugin</string>
        </object>
      </object>
      <object class="NSMutableDictionary" key="unlocalizedProperties">
        <bool key="EncodedWithXMLCoder">YES</bool>
        <reference key="dict.sortedKeys" ref="0"/>
        <object class="NSMutableArray" key="dict.values">
          <bool key="EncodedWithXMLCoder">YES</bool>
        </object>
      </object>
      <nil key="activeLocalization"/>
      <object class="NSMutableDictionary" key="localizations">
        <bool key="EncodedWithXMLCoder">YES</bool>
        <reference key="dict.sortedKeys" ref="0"/>
        <object class="NSMutableArray" key="dict.values">
          <bool key="EncodedWithXMLCoder">YES</bool>
        </object>
      </object>
      <nil key="sourceID"/>
      <int key="maxID">9</int>
    </object>
    <object class="IBClassDescriber" key="IBDocument.Classes"/>
    <int key="IBDocument.localizationMode">0</int>
    <string key="IBDocument.TargetRuntimeIdentifier">IBCocoaFramework</string>
    <object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies">
      <string key="NS.key.0">com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3</string>
      <integer value="3000" key="NS.object.0"/>
    </object>
    <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool>
    <nil key="IBDocument.LastKnownRelativeProjectPath"/>
    <int key="IBDocument.defaultPropertyAccessControl">3</int>
  </data>
</archive>


path-is-absolute

Node.js 0.12 path.isAbsolute() ponyfill

path paths file dir absolute isabsolute is-absolute built-in util utils core ponyfill polyfill shim is detect check


/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

	/**
	 * Copyright (c) 2015-present, Facebook, Inc.
	 * All rights reserved.
	 *
	 * This source code is licensed under the BSD-style license found in the
	 * LICENSE file in the root directory of this source tree. An additional grant
	 * of patent rights can be found in the PATENTS file in the same directory.
	 *
	 *
	 */
	'use strict';

	/* global chrome */

	var panelCreated = false;

	function createPanelIfReactLoaded() {
	  if (panelCreated) {
	    return;
	  }
	  chrome.devtools.inspectedWindow.eval('!!(\n    Object.keys(window.__REACT_DEVTOOLS_GLOBAL_HOOK__._renderers).length || window.React\n  )', function (pageHasReact, err) {
	    if (!pageHasReact || panelCreated) {
	      return;
	    }

	    clearInterval(loadCheckInterval);
	    panelCreated = true;
	    chrome.devtools.panels.create('React', '', 'panel.html', function (panel) {
	      var reactPanel = null;
	      panel.onShown.addListener(function (window) {
	        // when the user switches to the panel, check for an elements tab
	        // selection
	        window.panel.getNewSelection();
	        reactPanel = window.panel;
	        reactPanel.resumeTransfer();
	      });
	      panel.onHidden.addListener(function () {
	        if (reactPanel) {
	          reactPanel.hideHighlight();
	          reactPanel.pauseTransfer();
	        }
	      });
	    });
	  });
	}

	chrome.devtools.network.onNavigated.addListener(function () {
	  createPanelIfReactLoaded();
	});

	// Check to see if React has loaded once per second in case React is added
	// after page load
	var loadCheckInterval = setInterval(function () {
	  createPanelIfReactLoaded();
	}, 1000);

	createPanelIfReactLoaded();

/***/ }
/******/ ]);


void Menu::Popup(int x, int y, content::RenderFrameHost* rfh) {

keep keep replace keep keep keep keep keep


<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>minimum</title>

success


// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_CHROMEOS_POLICY_POLICY_CERT_VERIFIER_H_
#define CHROME_BROWSER_CHROMEOS_POLICY_POLICY_CERT_VERIFIER_H_

#include <memory>
#include <vector>

#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "net/base/completion_callback.h"
#include "net/cert/cert_verifier.h"

namespace net {
class CertVerifyProc;
class CertVerifyResult;
class X509Certificate;
typedef std::vector<scoped_refptr<X509Certificate> > CertificateList;
}

namespace nw {

// Wraps a MultiThreadedCertVerifier to make it use the additional trust anchors
// configured by the ONC user policy.
class PolicyCertVerifier : public net::CertVerifier {
 public:
  // Except for tests, PolicyCertVerifier should only be created by
  // PolicyCertService, which is the counterpart of this class on the UI thread.
  // Except of the constructor, all methods and the destructor must be called on
  // the IO thread. Calls |anchor_used_callback| on the IO thread everytime a
  // certificate from the additional trust anchors (set with SetTrustAnchors) is
  // used.
  explicit PolicyCertVerifier(const base::Closure& anchor_used_callback);
  ~PolicyCertVerifier() override;

  void InitializeOnIOThread(
      const scoped_refptr<net::CertVerifyProc>& verify_proc);

  // Sets the additional trust anchors.
  void SetTrustAnchors(const net::CertificateList& trust_anchors);

  // CertVerifier:
  // Note: |callback| can be null.
  int Verify(const RequestParams& params,
             net::CRLSet* crl_set,
             net::CertVerifyResult* verify_result,
             const net::CompletionCallback& callback,
             std::unique_ptr<Request>* out_req,
             const net::NetLogWithSource& net_log) override;

  bool SupportsOCSPStapling() override;

 private:
  net::CertificateList trust_anchors_;
  base::Closure anchor_used_callback_;
  std::unique_ptr<CertVerifier> delegate_;

  DISALLOW_COPY_AND_ASSIGN(PolicyCertVerifier);
};

}  // namespace policy

#endif  // CHROME_BROWSER_CHROMEOS_POLICY_POLICY_CERT_VERIFIER_H_


if (focus_manager == NULL){
return ;
} else {
focus_manager_ = focus_manager;
for(auto item : menu_items_) {
item->UpdateKeys(focus_manager);
}
}
}

keep keep keep keep replace replace keep keep keep keep

std::vector<MenuItem*>::iterator it = menu_items_.begin();

#include "content/nw/src/api/nw_window_api.h"

#include "base/base64.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/render_widget_host.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/extensions/devtools_util.h"
#include "chrome/browser/ui/webui/print_preview/printer_backend_proxy.h"
#include "components/zoom/zoom_controller.h"
#include "content/nw/src/api/menu/menu.h"
#include "content/nw/src/api/object_manager.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/browser/extension_zoom_request_client.h"
#include "extensions/components/native_app_window/native_app_window_views.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/constants.h"
#include "ui/gfx/codec/jpeg_codec.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/display/display.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/display/screen.h"
#include "content/nw/src/api/nw_current_window_internal.h"

#if defined(OS_WIN)
#include <shobjidl.h>
#include <dwmapi.h>

#include "base/win/windows_version.h"
#include "ui/base/win/hidden_window.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/icon_util.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/platform_font.h"
#include "ui/display/win/dpi.h"
#include "ui/views/win/hwnd_util.h"
#endif

#if defined(OS_LINUX)
#include "chrome/browser/ui/libgtkui/gtk_ui.h"
#endif

#if defined(OS_LINUX) || defined(OS_WIN)
#include "content/nw/src/browser/menubar_view.h"
#include "content/nw/src/browser/browser_view_layout.h"
using nw::BrowserViewLayout;
#endif

#if defined(OS_MACOSX)
#include "content/nw/src/nw_content_mac.h"
#endif

#include "chrome/browser/ui/webui/print_preview/print_preview_handler.h"

using content::RenderWidgetHost;
using content::RenderWidgetHostView;
using content::WebContents;
using zoom::ZoomController;

using nw::Menu;

#if defined(OS_LINUX) || defined(OS_WIN)
using nw::MenuBarView;
#endif

#if defined(OS_LINUX)
static void SetDeskopEnvironment() {
  static bool runOnce = false;
  if (runOnce) return;
  runOnce = true;

  std::unique_ptr<base::Environment> env(base::Environment::Create());
  std::string name;
  //if (env->GetVar("CHROME_DESKTOP", &name) && !name.empty())
  //  return;

  if (!env->GetVar("NW_DESKTOP", &name) || name.empty())
    name = "nw.desktop";

  env->SetVar("CHROME_DESKTOP", name);
}

#endif

namespace extensions {
namespace {

const char kNoAssociatedAppWindow[] =
    "The context from which the function was called did not have an "
    "associated app window.";
}

static AppWindow* getAppWindow(UIThreadExtensionFunction* func) {
  AppWindowRegistry* registry = AppWindowRegistry::Get(func->browser_context());
  DCHECK(registry);
  content::WebContents* web_contents = func->GetSenderWebContents();
  if (!web_contents) {
    // No need to set an error, since we won't return to the caller anyway if
    // there's no RVH.
    return NULL;
  }
  return registry->GetAppWindowForWebContents(web_contents);
}

#ifdef OS_WIN
static HWND getHWND(AppWindow* window) {
  if (window == NULL) return NULL;
  native_app_window::NativeAppWindowViews* native_app_window_views =
    static_cast<native_app_window::NativeAppWindowViews*>(
    window->GetBaseWindow());
  return views::HWNDForWidget(native_app_window_views->widget()->GetTopLevelWidget());
}
#endif

void NwCurrentWindowInternalCloseFunction::DoClose(AppWindow* window) {
  window->GetBaseWindow()->ForceClose();
}

bool NwCurrentWindowInternalCloseFunction::RunAsync() {
  std::unique_ptr<nwapi::nw_current_window_internal::Close::Params> params(
      nwapi::nw_current_window_internal::Close::Params::Create(*args_));
  EXTENSION_FUNCTION_VALIDATE(params.get());

  bool force = params->force.get() ? *params->force : false;
  AppWindow* window = getAppWindow(this);
  if (force)
    base::MessageLoop::current()->task_runner()->PostTask(FROM_HERE,
         base::Bind(&NwCurrentWindowInternalCloseFunction::DoClose, window));
  else if (window->NWCanClose())
    base::MessageLoop::current()->task_runner()->PostTask(FROM_HERE,
         base::Bind(&NwCurrentWindowInternalCloseFunction::DoClose, window));

  SendResponse(true);
  return true;
}

void NwCurrentWindowInternalShowDevToolsInternalFunction::OnOpened() {
  SendResponse(true);
}

bool NwCurrentWindowInternalShowDevToolsInternalFunction::RunAsync() {
  content::RenderFrameHost* rfh = render_frame_host();
  content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(rfh);
  scoped_refptr<content::DevToolsAgentHost> agent(
      content::DevToolsAgentHost::GetOrCreateFor(web_contents));
  DevToolsWindow::OpenDevToolsWindow(web_contents);
  DevToolsWindow* devtools_window =
      DevToolsWindow::FindDevToolsWindow(agent.get());
  if (devtools_window)
    devtools_window->SetLoadCompletedCallback(base::Bind(&NwCurrentWindowInternalShowDevToolsInternalFunction::OnOpened, this));
  else
    OnOpened();

  return true;
}

bool NwCurrentWindowInternalCloseDevToolsFunction::RunAsync() {
  content::RenderFrameHost* rfh = render_frame_host();
  content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(rfh);
  scoped_refptr<content::DevToolsAgentHost> agent(
      content::DevToolsAgentHost::GetOrCreateFor(web_contents));
  DevToolsWindow* devtools_window =
      DevToolsWindow::FindDevToolsWindow(agent.get());
  if (devtools_window) {
    devtools_window->Close();
  }
  return true;
}

NwCurrentWindowInternalCapturePageInternalFunction::NwCurrentWindowInternalCapturePageInternalFunction() {
}

NwCurrentWindowInternalCapturePageInternalFunction::~NwCurrentWindowInternalCapturePageInternalFunction() {
}

bool NwCurrentWindowInternalCapturePageInternalFunction::RunAsync() {
  EXTENSION_FUNCTION_VALIDATE(args_);

  std::unique_ptr<ImageDetails> image_details;
  if (args_->GetSize() > 0) {
    base::Value* spec = NULL;
    EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &spec) && spec);
    image_details = ImageDetails::FromValue(*spec);
  }

  content::RenderFrameHost* rfh = render_frame_host();
  WebContents* contents = content::WebContents::FromRenderFrameHost(rfh);
  if (!contents)
    return false;

  // The default format and quality setting used when encoding jpegs.
  const api::extension_types::ImageFormat kDefaultFormat =
      api::extension_types::IMAGE_FORMAT_JPEG;
  const int kDefaultQuality = 90;

  image_format_ = kDefaultFormat;
  image_quality_ = kDefaultQuality;

  if (image_details) {
    if (image_details->format !=
        api::extension_types::IMAGE_FORMAT_NONE)
      image_format_ = image_details->format;
    if (image_details->quality.get())
      image_quality_ = *image_details->quality;
  }

  // TODO(miu): Account for fullscreen render widget?  http://crbug.com/419878
  RenderWidgetHostView* const view = contents->GetRenderWidgetHostView();
  RenderWidgetHost* const host = view ? view->GetRenderWidgetHost() : nullptr;
  if (!view || !host) {
    OnCaptureFailure(FAILURE_REASON_VIEW_INVISIBLE);
    return false;
  }

  // By default, the requested bitmap size is the view size in screen
  // coordinates.  However, if there's more pixel detail available on the
  // current system, increase the requested bitmap size to capture it all.
  const gfx::Size view_size = view->GetViewBounds().size();
  gfx::Size bitmap_size = view_size;
  const gfx::NativeView native_view = view->GetNativeView();
  display::Screen* const screen = display::Screen::GetScreen();
  const float scale =
      screen->GetDisplayNearestWindow(native_view).device_scale_factor();
  if (scale > 1.0f)
    bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);

  host->CopyFromBackingStore(
      gfx::Rect(view_size),
      bitmap_size,
      base::Bind(&NwCurrentWindowInternalCapturePageInternalFunction::CopyFromBackingStoreComplete,
                 this),
      kN32_SkColorType);
  return true;
}

void NwCurrentWindowInternalCapturePageInternalFunction::CopyFromBackingStoreComplete(
    const SkBitmap& bitmap,
    content::ReadbackResponse response) {
  if (response == content::READBACK_SUCCESS) {
    OnCaptureSuccess(bitmap);
    return;
  }
  OnCaptureFailure(FAILURE_REASON_UNKNOWN);
}

void NwCurrentWindowInternalCapturePageInternalFunction::OnCaptureSuccess(const SkBitmap& bitmap) {
  std::vector<unsigned char> data;
  SkAutoLockPixels screen_capture_lock(bitmap);
  bool encoded = false;
  std::string mime_type;
  switch (image_format_) {
    case api::extension_types::IMAGE_FORMAT_JPEG:
      encoded = gfx::JPEGCodec::Encode(
          reinterpret_cast<unsigned char*>(bitmap.getAddr32(0, 0)),
          gfx::JPEGCodec::FORMAT_SkBitmap,
          bitmap.width(),
          bitmap.height(),
          static_cast<int>(bitmap.rowBytes()),
          image_quality_,
          &data);
      mime_type = kMimeTypeJpeg;
      break;
    case api::extension_types::IMAGE_FORMAT_PNG:
      encoded =
          gfx::PNGCodec::EncodeBGRASkBitmap(bitmap,
                                            true,  // Discard transparency.
                                            &data);
      mime_type = kMimeTypePng;
      break;
    default:
      NOTREACHED() << "Invalid image format.";
  }

  if (!encoded) {
    OnCaptureFailure(FAILURE_REASON_ENCODING_FAILED);
    return;
  }

  std::string base64_result;
  base::StringPiece stream_as_string(
                                     reinterpret_cast<const char*>(data.data()), data.size());

  base::Base64Encode(stream_as_string, &base64_result);
  base64_result.insert(
      0, base::StringPrintf("data:%s;base64,", mime_type.c_str()));
  SetResult(base::MakeUnique<base::StringValue>(base64_result.c_str()));
  SendResponse(true);
}

void NwCurrentWindowInternalCapturePageInternalFunction::OnCaptureFailure(FailureReason reason) {
  const char* reason_description = "internal error";
  switch (reason) {
    case FAILURE_REASON_UNKNOWN:
      reason_description = "unknown error";
      break;
    case FAILURE_REASON_ENCODING_FAILED:
      reason_description = "encoding failed";
      break;
    case FAILURE_REASON_VIEW_INVISIBLE:
      reason_description = "view is invisible";
      break;
  }
  error_ = ErrorUtils::FormatErrorMessage("Failed to capture tab: *",
                                          reason_description);
  SendResponse(false);
}

NwCurrentWindowInternalClearMenuFunction::NwCurrentWindowInternalClearMenuFunction() {
}

NwCurrentWindowInternalClearMenuFunction::~NwCurrentWindowInternalClearMenuFunction() {
}

bool NwCurrentWindowInternalClearMenuFunction::RunAsync() {
  AppWindow* window = getAppWindow(this);
  if (!window) {
    error_ = kNoAssociatedAppWindow;
    return false;
  }

#if defined(OS_MACOSX)
  NWChangeAppMenu(NULL);
#endif

#if defined(OS_LINUX) || defined(OS_WIN)
  native_app_window::NativeAppWindowViews* native_app_window_views =
      static_cast<native_app_window::NativeAppWindowViews*>(
          window->GetBaseWindow());

  BrowserViewLayout *browser_view_layout = static_cast<BrowserViewLayout*>(native_app_window_views->GetLayoutManager());
  views::View* menubar = browser_view_layout->menu_bar();
  if (menubar) {
    native_app_window_views->RemoveChildView(menubar);
  }
  browser_view_layout->set_menu_bar(NULL);
  native_app_window_views->layout_();
  native_app_window_views->SchedulePaint();
  window->menu_->RemoveKeys();
  window->menu_ = NULL;
#endif
  return true;
}

NwCurrentWindowInternalSetMenuFunction::NwCurrentWindowInternalSetMenuFunction() {
}

NwCurrentWindowInternalSetMenuFunction::~NwCurrentWindowInternalSetMenuFunction() {
}

bool NwCurrentWindowInternalSetMenuFunction::RunNWSync(base::ListValue* response, std::string* error) {
  int id = 0;
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &id));
  AppWindow* window = getAppWindow(this);
  if (!window) {
    error_ = kNoAssociatedAppWindow;
    return false;
  }
  nw::ObjectManager* obj_manager = nw::ObjectManager::Get(browser_context());
  Menu* menu = (Menu*)obj_manager->GetApiObject(id);

  Menu* old_menu = window->menu_;
  window->menu_ = menu;
#if defined(OS_MACOSX)
  response->Append(NWChangeAppMenu(menu));
#endif

#if defined(OS_LINUX) || defined(OS_WIN)
  native_app_window::NativeAppWindowViews* native_app_window_views =
      static_cast<native_app_window::NativeAppWindowViews*>(
          window->GetBaseWindow());

  MenuBarView* menubar = new MenuBarView();
  static_cast<BrowserViewLayout*>(native_app_window_views->GetLayoutManager())->set_menu_bar(menubar);
  native_app_window_views->AddChildView(menubar);
  menubar->UpdateMenu(menu->model());
  native_app_window_views->layout_();
  native_app_window_views->SchedulePaint();
  if (old_menu) old_menu->RemoveKeys();
  menu->UpdateKeys( native_app_window_views->widget()->GetFocusManager() );
  response->Append(std::unique_ptr<base::ListValue>(new base::ListValue()));
#endif
  return true;
}

#if defined(OS_WIN)
static base::win::ScopedHICON createBadgeIcon(const HWND hWnd, const TCHAR *value, const int sizeX, const int sizeY) {
  // canvas for the overlay icon
  gfx::Canvas canvas(gfx::Size(sizeX, sizeY), 1, false);

  // drawing red circle
  SkPaint paint;
  paint.setColor(SK_ColorRED);
  canvas.DrawCircle(gfx::Point(sizeX / 2, sizeY / 2), sizeX / 2, paint);

  // drawing the text
  gfx::PlatformFont *platform_font = gfx::PlatformFont::CreateDefault();
  const int fontSize = sizeY * 0.65f;
  gfx::Font font(platform_font->GetFontName(), fontSize);
  platform_font->Release();
  platform_font = NULL;
  const int yMargin = (sizeY - fontSize) / 2;
  canvas.DrawStringRectWithFlags(value, gfx::FontList(font), SK_ColorWHITE, gfx::Rect(sizeX, fontSize + yMargin + 1), gfx::Canvas::TEXT_ALIGN_CENTER);

  // return the canvas as windows native icon handle
  return std::move(IconUtil::CreateHICONFromSkBitmap(canvas.ExtractImageRep().sk_bitmap()));
}
#endif

#ifndef OS_MACOSX
bool NwCurrentWindowInternalSetBadgeLabelFunction::RunAsync() {
  EXTENSION_FUNCTION_VALIDATE(args_);
  std::string badge;
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &badge));
#if defined(OS_WIN)
  base::win::ScopedComPtr<ITaskbarList3> taskbar;
  HRESULT result = taskbar.CreateInstance(CLSID_TaskbarList, NULL,
    CLSCTX_INPROC_SERVER);

  if (FAILED(result)) {
    error_ = "Failed creating a TaskbarList3 object: ";
    LOG(ERROR) << error_ << result;
    return false;
  }

  result = taskbar->HrInit();
  if (FAILED(result)) {
    error_ = "Failed initializing an ITaskbarList3 interface.";
    LOG(ERROR) << error_;
    return false;
  }

  base::win::ScopedHICON icon;
  HWND hWnd = getHWND(getAppWindow(this));
  if (hWnd == NULL) {
    error_ = kNoAssociatedAppWindow;
    LOG(ERROR) << error_;
    return false;
  }
  const float scale = display::win::GetDPIScale();
  if (badge.size())
    icon = createBadgeIcon(hWnd, base::UTF8ToUTF16(badge).c_str(), 16 * scale, 16 * scale);

  taskbar->SetOverlayIcon(hWnd, icon.get(), L"Status");
#elif defined(OS_LINUX)
  views::LinuxUI* linuxUI = views::LinuxUI::instance();
  if (linuxUI == NULL) {
    error_ = "LinuxUI::instance() is NULL";
    return false;
  }
  SetDeskopEnvironment();
  linuxUI->SetDownloadCount(atoi(badge.c_str()));
#else
  error_ = "NwCurrentWindowInternalSetBadgeLabelFunction NOT Implemented"
  NOTIMPLEMENTED() << error_;
  return false;
#endif
  return true;
}

bool NwCurrentWindowInternalRequestAttentionInternalFunction::RunAsync() {
  EXTENSION_FUNCTION_VALIDATE(args_);
  int count;
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &count));
#if defined(OS_WIN)
  FLASHWINFO fwi;
  fwi.cbSize = sizeof(fwi);
  fwi.hwnd = getHWND(getAppWindow(this));
  if (fwi.hwnd == NULL) {
    error_ = kNoAssociatedAppWindow;
    LOG(ERROR) << error_;
    return false;
  }
  if (count != 0) {
    fwi.dwFlags = FLASHW_ALL;
    fwi.uCount = count < 0 ? 4 : count;
    fwi.dwTimeout = 0;
  }
  else {
    fwi.dwFlags = FLASHW_STOP;
  }
  FlashWindowEx(&fwi);
#elif defined(OS_LINUX) || defined(OS_MACOSX)
  AppWindow* window = getAppWindow(this);
  if (!window) {
    error_ = kNoAssociatedAppWindow;
    return false;
  }
  window->GetBaseWindow()->FlashFrame(count);
#endif
  return true;
}

bool NwCurrentWindowInternalSetProgressBarFunction::RunAsync() {
  EXTENSION_FUNCTION_VALIDATE(args_);
  double progress;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDouble(0, &progress));
#if defined(OS_WIN)
  base::win::ScopedComPtr<ITaskbarList3> taskbar;
  HRESULT result = taskbar.CreateInstance(CLSID_TaskbarList, NULL,
    CLSCTX_INPROC_SERVER);

  if (FAILED(result)) {
    error_ = "Failed creating a TaskbarList3 object: ";
    LOG(ERROR) <<  error_ << result;
    return false;
  }

  result = taskbar->HrInit();
  if (FAILED(result)) {
    error_ = "Failed initializing an ITaskbarList3 interface.";
    LOG(ERROR) << error_;
    return false;
  }

  HWND hWnd = getHWND(getAppWindow(this));
  if (hWnd == NULL) {
    error_ = kNoAssociatedAppWindow;
    LOG(ERROR) << error_;
    return false;
  }
  TBPFLAG tbpFlag = TBPF_NOPROGRESS;

  if (progress > 1) {
    tbpFlag = TBPF_INDETERMINATE;
  }
  else if (progress >= 0) {
    tbpFlag = TBPF_NORMAL;
    taskbar->SetProgressValue(hWnd, progress * 100, 100);
  }

  taskbar->SetProgressState(hWnd, tbpFlag);
#elif defined(OS_LINUX)
  views::LinuxUI* linuxUI = views::LinuxUI::instance();
  if (linuxUI == NULL) {
    error_ = "LinuxUI::instance() is NULL";
    return false;
  }
  SetDeskopEnvironment();
  linuxUI->SetProgressFraction(progress);
#else
  error_ = "NwCurrentWindowInternalSetProgressBarFunction NOT Implemented"
  NOTIMPLEMENTED() << error_;
  return false;
#endif
  return true;
}
#endif

bool NwCurrentWindowInternalReloadIgnoringCacheFunction::RunAsync() {
  content::WebContents* web_contents = GetSenderWebContents();
  web_contents->GetController().ReloadBypassingCache(false);
  SendResponse(true);
  return true;
}

bool NwCurrentWindowInternalGetZoomFunction::RunNWSync(base::ListValue* response, std::string* error) {
  content::WebContents* web_contents = GetSenderWebContents();
  if (!web_contents)
    return false;
  double zoom_level =
      ZoomController::FromWebContents(web_contents)->GetZoomLevel();
  response->AppendDouble(zoom_level);
  return true;
}

bool NwCurrentWindowInternalSetZoomFunction::RunNWSync(base::ListValue* response, std::string* error) {
  double zoom_level;

  EXTENSION_FUNCTION_VALIDATE(args_->GetDouble(0, &zoom_level));
  content::WebContents* web_contents = GetSenderWebContents();
  if (!web_contents)
    return false;
  ZoomController* zoom_controller =
      ZoomController::FromWebContents(web_contents);
  scoped_refptr<ExtensionZoomRequestClient> client(
      new ExtensionZoomRequestClient(extension()));
  zoom_controller->SetZoomMode(zoom::ZoomController::ZOOM_MODE_ISOLATED);
  if (!zoom_controller->SetZoomLevelByClient(zoom_level, client)) {
    return false;
  }
  return true;
}

bool NwCurrentWindowInternalEnterKioskModeFunction::RunAsync() {
  AppWindow* window = getAppWindow(this);
  window->ForcedFullscreen();
  SendResponse(true);
  return true;
}

bool NwCurrentWindowInternalLeaveKioskModeFunction::RunAsync() {
  AppWindow* window = getAppWindow(this);
  window->Restore();
  SendResponse(true);
  return true;
}

bool NwCurrentWindowInternalToggleKioskModeFunction::RunAsync() {
  AppWindow* window = getAppWindow(this);
  if (window->IsFullscreen() || window->IsForcedFullscreen())
    window->Restore();
  else
    window->ForcedFullscreen();
  SendResponse(true);
  return true;
}

bool NwCurrentWindowInternalIsKioskInternalFunction::RunNWSync(base::ListValue* response, std::string* error) {
  AppWindow* window = getAppWindow(this);
  if (window->IsFullscreen() || window->IsForcedFullscreen())
    response->AppendBoolean(true);
  else
    response->AppendBoolean(false);
  return true;
}

bool NwCurrentWindowInternalGetTitleInternalFunction::RunNWSync(base::ListValue* response, std::string* error) {
  AppWindow* window = getAppWindow(this);
  response->AppendString(window->title_override());
  return true;
}

bool NwCurrentWindowInternalSetTitleInternalFunction::RunNWSync(base::ListValue* response, std::string* error) {
  EXTENSION_FUNCTION_VALIDATE(args_);
  std::string title;
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &title));
  AppWindow* window = getAppWindow(this);
  window->set_title_override(title);
  window->GetBaseWindow()->UpdateWindowTitle();
  return true;
}

bool NwCurrentWindowInternalGetPrintersFunction::RunAsync() {
  printing::EnumeratePrinters(Profile::FromBrowserContext(browser_context()),
      base::Bind(&NwCurrentWindowInternalGetPrintersFunction::OnGetPrinterList,
                 this));
  return true;
}

void NwCurrentWindowInternalGetPrintersFunction::OnGetPrinterList(const printing::PrinterList& printer_list) {
  base::ListValue* printers = new base::ListValue();
  chrome::PrintersToValues(printer_list, printers);
  SetResult(base::WrapUnique(printers));
  SendResponse(true);
}

bool NwCurrentWindowInternalSetPrintSettingsInternalFunction::RunNWSync(base::ListValue* response, std::string* error) {
  EXTENSION_FUNCTION_VALIDATE(args_);

  if (!args_->GetSize())
    return false;
  base::Value* spec = NULL;
  EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &spec) && spec);
  if (!spec->IsType(base::Value::TYPE_DICTIONARY))
    return false;
  const base::DictionaryValue* dict = static_cast<const base::DictionaryValue*>(spec);
  bool auto_print;
  std::string printer_name, pdf_path;
  if (dict->GetBoolean("autoprint", &auto_print))
    chrome::NWPrintSetCustomPrinting(auto_print);
  if (dict->GetString("printer", &printer_name))
    chrome::NWPrintSetDefaultPrinter(printer_name);
  if (dict->GetString("pdf_path", &pdf_path))
    chrome::NWPrintSetPDFPath(base::FilePath::FromUTF8Unsafe(pdf_path));
  chrome::NWPrintSetOptions(dict);
  return true;
}

bool NwCurrentWindowInternalGetWinParamInternalFunction::RunNWSync(base::ListValue* response, std::string* error) {
  AppWindow* app_window = getAppWindow(this);

  if (!app_window) {
    *error = "cannot get current window; are you in background page/node context?";
    return false;
  }
  //from app_window_api.cc
  content::RenderFrameHost* created_frame =
      app_window->web_contents()->GetMainFrame();
  int frame_id = created_frame->GetRoutingID();

  base::DictionaryValue* result = new base::DictionaryValue;
  result->Set("frameId", new base::FundamentalValue(frame_id));
  result->Set("id", new base::StringValue(app_window->window_key()));
  app_window->GetSerializedState(result);

  response->Append(base::WrapUnique(result));

  return true;
}

bool NwCurrentWindowInternalSetShowInTaskbarFunction::RunAsync() {
  EXTENSION_FUNCTION_VALIDATE(args_);
  bool show;
  EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(0, &show));
#if defined(OS_WIN)
  AppWindow* window = getAppWindow(this);

  native_app_window::NativeAppWindowViews* native_app_window_views =
      static_cast<native_app_window::NativeAppWindowViews*>(
          window->GetBaseWindow());

  views::Widget* widget = native_app_window_views->widget()->GetTopLevelWidget();

  if (show == false && base::win::GetVersion() < base::win::VERSION_VISTA) {
    // Change the owner of native window. Only needed on Windows XP.
    ::SetParent(views::HWNDForWidget(widget),
                ui::GetHiddenWindow());
  }

  base::win::ScopedComPtr<ITaskbarList> taskbar;
  HRESULT result = taskbar.CreateInstance(CLSID_TaskbarList, NULL,
                                          CLSCTX_INPROC_SERVER);
  if (FAILED(result)) {
    VLOG(1) << "Failed creating a TaskbarList object: " << result;
    SendResponse(true);
    return true;
  }

  result = taskbar->HrInit();
  if (FAILED(result)) {
    LOG(ERROR) << "Failed initializing an ITaskbarList interface.";
    SendResponse(true);
    return true;
  }

  if (show)
    result = taskbar->AddTab(views::HWNDForWidget(widget));
  else
    result = taskbar->DeleteTab(views::HWNDForWidget(widget));

  if (FAILED(result)) {
    LOG(ERROR) << "Failed to change the show in taskbar attribute";
    SendResponse(true);
    return true;
  }
#elif defined(OS_MACOSX)
  AppWindow* app_window = getAppWindow(this);
  extensions::NativeAppWindow* native_window = app_window->GetBaseWindow();
  NWSetNSWindowShowInTaskbar(native_window, show);
#endif
  SendResponse(true);
  return true;
}

} // namespace extensions


// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef NW_BROWSER_PRINTING_PRINTING_UI_WEB_CONTENTS_OBSERVER_H_
#define NW_BROWSER_PRINTING_PRINTING_UI_WEB_CONTENTS_OBSERVER_H_

#include "base/basictypes.h"
#include "content/public/browser/web_contents_observer.h"
#include "ui/gfx/native_widget_types.h"

// Wrapper used to keep track of the lifetime of a WebContents.
// Lives on the UI thread.
class PrintingUIWebContentsObserver : public content::WebContentsObserver {
 public:
  explicit PrintingUIWebContentsObserver(content::WebContents* web_contents);

  // Return the parent NativeView of the observed WebContents.
  gfx::NativeView GetParentView();

 private:
  DISALLOW_COPY_AND_ASSIGN(PrintingUIWebContentsObserver);
};

#endif  // CHROME_BROWSER_PRINTING_PRINTING_UI_WEB_CONTENTS_OBSERVER_H_


This software is released under the MIT license:

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


// Copyright 2015 The NW.js Authors. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.

// nw Shell API
[implemented_in="content/nw/src/api/nw_shell_api.h"]
namespace nw.Shell {
  interface Functions {
    static void openExternal(DOMString uri);
    static void openItem(DOMString filePath);
    static void showItemInFolder(DOMString filePath);
  };
};


}
}
}
void Menu::RemoveKeys() {
if (!focus_manager_) return;
for(auto item: menu_items_) {
item->RemoveKeys();
}
focus_manager_ = NULL;
}
void Menu::UpdateStates() {
}

keep keep keep keep replace replace replace replace replace replace replace replace replace replace keep keep keep


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/nw/src/browser/printing/printer_query.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "content/nw/src/browser/printing/print_job_worker.h"

using base::MessageLoop;

namespace printing {

PrinterQuery::PrinterQuery()
    : io_message_loop_(MessageLoop::current()),
      worker_(new PrintJobWorker(this)),
      is_print_dialog_box_shown_(false),
      cookie_(PrintSettings::NewCookie()),
      last_status_(PrintingContext::FAILED) {
  DCHECK_EQ(io_message_loop_->type(), MessageLoop::TYPE_IO);
}

PrinterQuery::~PrinterQuery() {
  // The job should be finished (or at least canceled) when it is destroyed.
  DCHECK(!is_print_dialog_box_shown_);
  // If this fires, it is that this pending printer context has leaked.
  DCHECK(!worker_.get());
}

void PrinterQuery::GetSettingsDone(const PrintSettings& new_settings,
                                   PrintingContext::Result result) {
  is_print_dialog_box_shown_ = false;
  last_status_ = result;
  if (result != PrintingContext::FAILED) {
    settings_ = new_settings;
    cookie_ = PrintSettings::NewCookie();
  } else {
    // Failure.
    cookie_ = 0;
  }

  if (!callback_.is_null()) {
    // This may cause reentrancy like to call StopWorker().
    callback_.Run();
    callback_.Reset();
  }
}

PrintJobWorker* PrinterQuery::DetachWorker(PrintJobWorkerOwner* new_owner) {
  DCHECK(callback_.is_null());
  DCHECK(worker_.get());

  worker_->SetNewOwner(new_owner);
  return worker_.release();
}

MessageLoop* PrinterQuery::message_loop() {
  return io_message_loop_;
}

const PrintSettings& PrinterQuery::settings() const {
  return settings_;
}

int PrinterQuery::cookie() const {
  return cookie_;
}

void PrinterQuery::GetSettings(
    GetSettingsAskParam ask_user_for_settings,
    scoped_ptr<PrintingUIWebContentsObserver> web_contents_observer,
    int expected_page_count,
    bool has_selection,
    MarginType margin_type,
    const base::Closure& callback) {
  DCHECK_EQ(io_message_loop_, MessageLoop::current());
  DCHECK(!is_print_dialog_box_shown_);

  StartWorker(callback);

  // Real work is done in PrintJobWorker::Init().
  is_print_dialog_box_shown_ = ask_user_for_settings == ASK_USER;
  worker_->message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&PrintJobWorker::GetSettings,
                 base::Unretained(worker_.get()),
                 is_print_dialog_box_shown_,
                 base::Passed(&web_contents_observer),
                 expected_page_count,
                 has_selection,
                 margin_type));
}

void PrinterQuery::SetSettings(const base::DictionaryValue& new_settings,
                               const base::Closure& callback) {
  StartWorker(callback);

  worker_->message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&PrintJobWorker::SetSettings,
                 base::Unretained(worker_.get()),
                 new_settings.DeepCopy()));
}

void PrinterQuery::SetWorkerDestination(
    PrintDestinationInterface* destination) {
  worker_->SetPrintDestination(destination);
}

void PrinterQuery::StartWorker(const base::Closure& callback) {
  DCHECK(callback_.is_null());
  DCHECK(worker_.get());

  // Lazily create the worker thread. There is one worker thread per print job.
  if (!worker_->message_loop())
    worker_->Start();

  callback_ = callback;
}

void PrinterQuery::StopWorker() {
  if (worker_.get()) {
    // http://crbug.com/66082: We're blocking on the PrinterQuery's worker
    // thread.  It's not clear to me if this may result in blocking the current
    // thread for an unacceptable time.  We should probably fix it.
    base::ThreadRestrictions::ScopedAllowIO allow_io;
    worker_->Stop();
    worker_.reset();
  }
}

bool PrinterQuery::is_callback_pending() const {
  return !callback_.is_null();
}

bool PrinterQuery::is_valid() const {
  return worker_.get() != NULL;
}

}  // namespace printing


static std::unique_ptr<base::DictionaryValue> CreateFromNative(NSMenuItem* menu_item, Menu* menu, int index);

static MenuItem* GetMenuItemFromNative(NSMenuItem* menu_item);

#if defined(OS_WIN) || defined(OS_LINUX)

bool AcceleratorPressed(const ui::Accelerator& accelerator) override;

bool CanHandleAccelerators() const override;

keep keep keep keep keep replace replace keep


// Copyright (c) 2014 Intel Corp
// Copyright (c) 2014 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef CONTENT_NW_SRC_API_SHORTCUT_GLOBAL_SHORTCUT_LISTENER_WIN_H_
#define CONTENT_NW_SRC_API_SHORTCUT_GLOBAL_SHORTCUT_LISTENER_WIN_H_

#include <windows.h>

#include "content/nw/src/api/shortcut/global_shortcut_listener.h"
#include "ui/gfx/win/singleton_hwnd.h"

namespace nwapi {

// Windows-specific implementation of the GlobalShortcutListener class that
// listens for global shortcuts. Handles setting up a keyboard hook and
// forwarding its output to the base class for processing.
class GlobalShortcutListenerWin : public GlobalShortcutListener,
                                  public gfx::SingletonHwnd::Observer {
 public:
  GlobalShortcutListenerWin();
  virtual ~GlobalShortcutListenerWin();

 private:
  // The implementation of our Window Proc, called by SingletonHwnd.
  virtual void OnWndProc(HWND hwnd,
                         UINT message,
                         WPARAM wparam,
                         LPARAM lparam) override;

  // GlobalShortcutListener implementation.
  virtual void StartListening() override;
  virtual void StopListening() override;
  virtual bool RegisterAcceleratorImpl(
      const ui::Accelerator& accelerator) override;
  virtual void UnregisterAcceleratorImpl(
      const ui::Accelerator& accelerator) override;

  // Whether this object is listening for global shortcuts.
  bool is_listening_;

  // A map of registered accelerators and their registration ids.
  typedef std::map<ui::Accelerator, int> HotkeyIdMap;
  HotkeyIdMap hotkey_ids_;

  DISALLOW_COPY_AND_ASSIGN(GlobalShortcutListenerWin);
};

}  // namespace nwapi

#endif  // CONTENT_NW_SRC_API_SHORTCUT_GLOBAL_SHORTCUT_LISTENER_WIN_H_


import time
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from nw_util import *

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("nwapp=" + os.path.dirname(os.path.abspath(__file__)))

driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_options=chrome_options)
try:
    print driver.current_url
    link = driver.find_element_by_link_text('new window')
    print link.text
    link.click()
    #raw_input("Press Enter to continue...")
    wait_window_handles(driver, 2)
    print driver.window_handles
    driver.switch_to_window(driver.window_handles[-1])
    output = driver.find_element_by_id('output')
    assert(output.get_attribute('value') == '["inject-js-start","body-start","inject-js-end","onload-dom"]')
finally:
    #time.sleep(50)
    driver.quit()


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/nw/src/browser/nw_autofill_client.h"

#import <Cocoa/Cocoa.h>

#include "base/logging.h"
#include "base/mac/scoped_nsobject.h"
#include "components/autofill/core/browser/personal_data_manager.h"

namespace autofill {

void NWAutofillClient::RegisterForKeystoneNotifications() {
}

void NWAutofillClient::UnregisterFromKeystoneNotifications() {
}

}  // namespace autofill