// 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/shell.h"

#include "base/auto_reset.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/nw/src/browser/file_select_helper.h"
#include "content/nw/src/browser/shell_devtools_delegate.h"
#include "content/nw/src/browser/shell_javascript_dialog_creator.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/media/media_stream_devices_controller.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/shell_browser_main_parts.h"
#include "content/nw/src/shell_content_browser_client.h"
#include "ui/gfx/size.h"

namespace content {

std::vector<Shell*> Shell::windows_;
base::Callback<void(Shell*)> Shell::shell_created_callback_;

bool Shell::quit_message_loop_ = true;

Shell::Shell(WebContents* web_contents, base::DictionaryValue* manifest)
    : window_(NULL),
      url_edit_view_(NULL),
      window_manifest_(manifest),
      is_show_devtools_(false),
      is_toolbar_open_(true),
      max_height_(-1),
      max_width_(-1),
      min_height_(-1),
      min_width_(-1)
#if defined(OS_WIN) && !defined(USE_AURA)
      , default_edit_wnd_proc_(0)
#endif
  {
  if (window_manifest_) {
    window_manifest_->GetBoolean(switches::kmToolbar, &is_toolbar_open_);
    window_manifest_->GetBoolean(switches::kDeveloper, &is_show_devtools_);
    window_manifest_->GetInteger(switches::kmMaxHeight, &max_height_);
    window_manifest_->GetInteger(switches::kmMaxWidth, &max_width_);
    window_manifest_->GetInteger(switches::kmMinHeight, &min_height_);
    window_manifest_->GetInteger(switches::kmMinWidth, &min_width_);
  }

  registrar_.Add(this, NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
      Source<WebContents>(web_contents));
  windows_.push_back(this);

  if (!shell_created_callback_.is_null()) {
    shell_created_callback_.Run(this);
    shell_created_callback_.Reset();
  }
}

Shell::~Shell() {
  PlatformCleanUp();

  for (size_t i = 0; i < windows_.size(); ++i) {
    if (windows_[i] == this) {
      windows_.erase(windows_.begin() + i);
      break;
    }
  }

  if (windows_.empty() && quit_message_loop_)
    MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}

Shell* Shell::CreateShell(WebContents* web_contents,
                          base::DictionaryValue* manifest) {
  int width = 700;
  int height = 450;
  manifest->GetInteger(switches::kmWidth, &width);
  manifest->GetInteger(switches::kmHeight, &height);

  Shell* shell = new Shell(web_contents, manifest);
  shell->PlatformCreateWindow(width, height);

  shell->web_contents_.reset(web_contents);
  web_contents->SetDelegate(shell);

  shell->PlatformSetContents();

  shell->PlatformResizeSubViews();
  return shell;
}

void Shell::CloseAllWindows() {
  AutoReset<bool> auto_reset(&quit_message_loop_, false);
  std::vector<Shell*> open_windows(windows_);
  for (size_t i = 0; i < open_windows.size(); ++i)
    open_windows[i]->Close();
  MessageLoop::current()->RunAllPending();
}

void Shell::SetShellCreatedCallback(
    base::Callback<void(Shell*)> shell_created_callback) {
  DCHECK(shell_created_callback_.is_null());
  shell_created_callback_ = shell_created_callback;
}

Shell* Shell::FromRenderViewHost(RenderViewHost* rvh) {
  for (size_t i = 0; i < windows_.size(); ++i) {
    if (windows_[i]->web_contents() &&
        windows_[i]->web_contents()->GetRenderViewHost() == rvh) {
      return windows_[i];
    }
  }
  return NULL;
}

Shell* Shell::CreateNewWindow(BrowserContext* browser_context,
                              const GURL& url,
                              SiteInstance* site_instance,
                              int routing_id,
                              WebContents* base_web_contents) {
  WebContents* web_contents = WebContents::Create(
      browser_context,
      site_instance,
      routing_id,
      base_web_contents);

  // Create with package's manifest
  base::DictionaryValue *manifest = NULL;
  nw::GetManifest()->GetDictionary(switches::kmWindow, &manifest);
  manifest->SetBoolean(switches::kDeveloper,
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kDeveloper));

  // Center window by default
  if (!manifest->HasKey(switches::kmPosition))
    manifest->SetString(switches::kmPosition, "center");

  Shell* shell = CreateShell(web_contents, manifest);
  if (!url.is_empty())
    shell->LoadURL(url);
  return shell;
}

void Shell::LoadURL(const GURL& url) {
  web_contents_->GetController().LoadURL(
      url,
      Referrer(),
      PAGE_TRANSITION_TYPED,
      std::string());
  web_contents_->Focus();
}

void Shell::GoBackOrForward(int offset) {
  web_contents_->GetController().GoToOffset(offset);
  web_contents_->Focus();
}

void Shell::Reload() {
  web_contents_->GetController().Reload(false);
  web_contents_->Focus();
}

void Shell::Stop() {
  web_contents_->Stop();
  web_contents_->Focus();
}

void Shell::UpdateNavigationControls() {
  int current_index = web_contents_->GetController().GetCurrentEntryIndex();
  int max_index = web_contents_->GetController().GetEntryCount() - 1;

  PlatformEnableUIControl(BACK_BUTTON, current_index > 0);
  PlatformEnableUIControl(FORWARD_BUTTON, current_index < max_index);
  PlatformEnableUIControl(STOP_BUTTON, web_contents_->IsLoading());
}

void Shell::ShowDevTools() {
  ShellContentBrowserClient* browser_client =
      static_cast<ShellContentBrowserClient*>(
          GetContentClient()->browser());
  ShellDevToolsDelegate* delegate =
      browser_client->shell_browser_main_parts()->devtools_delegate();
  GURL url = delegate->devtools_http_handler()->GetFrontendURL(
      web_contents()->GetRenderViewHost());

  // Use our minimum set manifest
  base::DictionaryValue manifest;
  manifest.SetBoolean(switches::kmToolbar, false);
  manifest.SetBoolean(switches::kDeveloper, true);
  manifest.SetInteger(switches::kmWidth, 600);
  manifest.SetInteger(switches::kmHeight, 500);

  Shell* shell = CreateShell(
      WebContents::Create(web_contents()->GetBrowserContext(),
                          NULL, MSG_ROUTING_NONE, NULL),
      &manifest);
  shell->LoadURL(url);
}

gfx::NativeView Shell::GetContentView() {
  if (!web_contents_.get())
    return NULL;
  return web_contents_->GetNativeView();
}

WebContents* Shell::OpenURLFromTab(WebContents* source,
                                   const OpenURLParams& params) {
  // The only one we implement for now.
  DCHECK(params.disposition == CURRENT_TAB);
  source->GetController().LoadURL(
      params.url, params.referrer, params.transition, std::string());
  return source;
}

void Shell::LoadingStateChanged(WebContents* source) {
  UpdateNavigationControls();
  PlatformSetIsLoading(source->IsLoading());
}

void Shell::ActivateContents(content::WebContents* contents) {
  LOG(ERROR) << "activate";
}

void Shell::DeactivateContents(content::WebContents* contents) {
  LOG(ERROR) << "deactivate";
}

void Shell::CloseContents(WebContents* source) {
  Close();
}

void Shell::MoveContents(WebContents* source, const gfx::Rect& pos) {
  Move(pos);
}

bool Shell::IsPopupOrPanel(const WebContents* source) const {
  // Treat very window as popup so we can use window operations
  return true;
}

bool Shell::TakeFocus(WebContents* soruce,
                      bool reverse) {
  return true;
}

void Shell::LostCapture() {
}

void Shell::WebContentsFocused(WebContents* contents) {
}

void Shell::WebContentsCreated(WebContents* source_contents,
                               int64 source_frame_id,
                               const GURL& target_url,
                               WebContents* new_contents) {
  // Create with package's manifest
  base::DictionaryValue *manifest = NULL;
  nw::GetManifest()->GetDictionary(switches::kmWindow, &manifest);
  manifest->SetBoolean(switches::kDeveloper,
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kDeveloper));

  // Get window features
  WebKit::WebWindowFeatures features = new_contents->GetWindowFeatures();
  if (features.widthSet)
    manifest->SetInteger(switches::kmWidth, features.width);
  if (features.heightSet)
    manifest->SetInteger(switches::kmHeight, features.height);
  if (features.xSet)
    manifest->SetInteger(switches::kmX, features.x);
  if (features.ySet)
    manifest->SetInteger(switches::kmY, features.y);

  CreateShell(new_contents, manifest);
}

void Shell::RunFileChooser(WebContents* web_contents,
                           const content::FileChooserParams& params) {
  FileSelectHelper::RunFileChooser(web_contents, params);
}

void Shell::EnumerateDirectory(WebContents* web_contents,
                               int request_id,
                               const FilePath& path) {
  FileSelectHelper::EnumerateDirectory(web_contents, request_id, path);
}

void Shell::DidNavigateMainFramePostCommit(WebContents* web_contents) {
  PlatformSetAddressBarURL(web_contents->GetURL());
}

JavaScriptDialogCreator* Shell::GetJavaScriptDialogCreator() {
  if (!dialog_creator_.get())
    dialog_creator_.reset(new ShellJavaScriptDialogCreator());
  return dialog_creator_.get();
}

bool Shell::AddMessageToConsole(WebContents* source,
                                int32 level,
                                const string16& message,
                                int32 line_no,
                                const string16& source_id) {
  return false;
}

void Shell::RequestMediaAccessPermission(
      content::WebContents* web_contents,
      const content::MediaStreamRequest* request,
      const content::MediaResponseCallback& callback) {
  scoped_ptr<MediaStreamDevicesController>
      controller(new MediaStreamDevicesController(request,
                                                  callback));
  controller->DismissInfoBarAndTakeActionOnSettings();
}

void Shell::Observe(int type,
                    const NotificationSource& source,
                    const NotificationDetails& details) {
  if (type == NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED) {
    std::pair<NavigationEntry*, bool>* title =
        Details<std::pair<NavigationEntry*, bool> >(details).ptr();

    if (title->first) {
      string16 text = title->first->GetTitle();
      PlatformSetTitle(text);
    }
  }
}

}  // namespace content


// Show version and quit
const char kVersion[] = "version";
// Open specified url
const char kUrl[] = "url";
const char kmMain[]      = "main";
const char kmName[]      = "name";
const char kmWebkit[]    = "webkit";
const char kmNodejs[]    = "nodejs";

keep keep keep replace replace keep keep keep keep keep

const char kWorkingDirectory[] = "working-directory";

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>node-webkit versions</title>

  node-webkit v

  node.js v


// 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.

// Defines all the "content_shell" command-line switches.

#ifndef CONTENT_NW_SRC_SHELL_SWITCHES_H_
#define CONTENT_NW_SRC_SHELL_SWITCHES_H_

namespace switches {

extern const char kCheckLayoutTestSysDeps[];
extern const char kContentBrowserTest[];
extern const char kContentShellDataPath[];
extern const char kDeveloper[];
extern const char kDumpRenderTree[];
extern const char kNoTimeout[];
extern const char kNoToolbar[];
extern const char kVersion[];
extern const char kUrl[];

// Manifest settings
extern const char kmMain[];
extern const char kmName[];
extern const char kmWebkit[];
extern const char kmNodejs[];
extern const char kmRoot[];
extern const char kmWindow[];
extern const char kmTitle[];
extern const char kmToolbar[];
extern const char kmIcon[];
extern const char kmWidth[];
extern const char kmHeight[];
extern const char kmX[];
extern const char kmY[];
extern const char kmResizable[];
extern const char kmPosition[];
extern const char kmMinWidth[];
extern const char kmMinHeight[];
extern const char kmMaxWidth[];
extern const char kmMaxHeight[];
extern const char kmAsDesktop[];

}  // namespace switches

#endif  // CONTENT_NW_SRC_SHELL_SWITCHES_H_


// 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.

#ifndef CONTENT_SHELL_SHELL_BROWSER_MAIN_H_
#define CONTENT_SHELL_SHELL_BROWSER_MAIN_H_

namespace content {
struct MainFunctionParams;
}

int ShellBrowserMain(const content::MainFunctionParams& parameters);

#endif  // CONTENT_SHELL_SHELL_BROWSER_MAIN_H_


// 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_login_dialog.h"

#include <gtk/gtk.h>

#include "base/logging.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/base/gtk/gtk_hig_constants.h"

namespace content {

void ShellLoginDialog::PlatformCreateDialog(const string16& message) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  int render_process_id;
  int render_view_id;
  if (!ResourceRequestInfo::ForRequest(request_)->GetAssociatedRenderView(
          &render_process_id,  &render_view_id)) {
    NOTREACHED();
  }

  WebContents* web_contents = NULL;
  RenderViewHost* render_view_host =
      RenderViewHost::FromID(render_process_id, render_view_id);
  if (render_view_host)
    web_contents = WebContents::FromRenderViewHost(render_view_host);
  DCHECK(web_contents);

  gfx::NativeWindow parent_window =
      web_contents->GetView()->GetTopLevelNativeWindow();

  root_ = gtk_message_dialog_new(parent_window,
                                 GTK_DIALOG_MODAL,
                                 GTK_MESSAGE_INFO,
                                 GTK_BUTTONS_OK_CANCEL,
                                 "Please log in.");

  GtkWidget* content_area = gtk_dialog_get_content_area(GTK_DIALOG(root_));
  GtkWidget* label = gtk_label_new(UTF16ToUTF8(message).c_str());
  gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
  gtk_box_pack_start(GTK_BOX(content_area), label, FALSE, FALSE, 0);

  username_entry_ = gtk_entry_new();
  gtk_entry_set_activates_default(GTK_ENTRY(username_entry_), TRUE);

  password_entry_ = gtk_entry_new();
  gtk_entry_set_activates_default(GTK_ENTRY(password_entry_), TRUE);
  gtk_entry_set_visibility(GTK_ENTRY(password_entry_), FALSE);

  GtkWidget* table = gtk_table_new(2, 2, FALSE);
  gtk_table_set_col_spacing(GTK_TABLE(table), 0, ui::kLabelSpacing);
  gtk_table_set_row_spacings(GTK_TABLE(table), ui::kControlSpacing);

  GtkWidget* username_label = gtk_label_new("Username:");
  gtk_misc_set_alignment(GTK_MISC(username_label), 0, 0.5);

  gtk_table_attach(GTK_TABLE(table), username_label, 0, 1, 0, 1, GTK_FILL,
                   GTK_FILL, 0, 0);
  gtk_table_attach_defaults(GTK_TABLE(table), username_entry_, 1, 2, 0, 1);

  GtkWidget* password_label = gtk_label_new("Password:");
  gtk_misc_set_alignment(GTK_MISC(password_label), 0, 0.5);

  gtk_table_attach(GTK_TABLE(table), password_label, 0, 1, 1, 2, GTK_FILL,
                   GTK_FILL, 0, 0);
  gtk_table_attach_defaults(GTK_TABLE(table), password_entry_, 1, 2, 1, 2);

  gtk_box_pack_start(GTK_BOX(content_area), table, FALSE, FALSE, 0);

  g_signal_connect(root_, "response", G_CALLBACK(OnResponseThunk), this);
  gtk_widget_grab_focus(username_entry_);
  gtk_widget_show_all(GTK_WIDGET(root_));
}

void ShellLoginDialog::PlatformCleanUp() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

void ShellLoginDialog::PlatformRequestCancelled() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

void ShellLoginDialog::OnResponse(GtkWidget* sender, int response_id) {
  switch (response_id) {
    case GTK_RESPONSE_OK:
      UserAcceptedAuth(
          UTF8ToUTF16(gtk_entry_get_text(GTK_ENTRY(username_entry_))),
          UTF8ToUTF16(gtk_entry_get_text(GTK_ENTRY(password_entry_))));
      break;
    case GTK_RESPONSE_CANCEL:
    case GTK_RESPONSE_DELETE_EVENT:
      UserCancelledAuth();
      break;
    default:
      NOTREACHED();
  }

  gtk_widget_destroy(root_);
}

}  // namespace content


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>en</string>
	<key>CFBundleDisplayName</key>
	<string>${EXECUTABLE_NAME}</string>
	<key>CFBundleExecutable</key>
	<string>${EXECUTABLE_NAME}</string>
	<key>CFBundleIdentifier</key>
	<string>com.intel.nw.helper</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>${PRODUCT_NAME}</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>LSFileQuarantineEnabled</key>
	<true/>
	<key>LSMinimumSystemVersion</key>
	<string>${MACOSX_DEPLOYMENT_TARGET}.0</string>
	<key>LSUIElement</key>
	<string>1</string>
	<key>NSSupportsAutomaticGraphicsSwitching</key>
	<true/>
</dict>
</plist>


extern const char kUrl[];
// Manifest settings
extern const char kmMain[];
extern const char kmName[];

extern const char kVersion[];
extern const char kWorkingDirectory[];

// 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/common/shell_switches.h"

namespace switches {

// Check whether all system dependencies for running layout tests are met.
const char kCheckLayoutTestSysDeps[] = "check-layout-test-sys-deps";

// Tells Content Shell that it's running as a content_browsertest.
const char kContentBrowserTest[] = "browser-test";

// Makes Content Shell use the given path for its data directory.
const char kContentShellDataPath[] = "data-path";

// Enable developer tools
const char kDeveloper[] = "developer";

// Request pages to be dumped as text once they finished loading.
const char kDumpRenderTree[] = "dump-render-tree";

// Disables the timeout for layout tests.
const char kNoTimeout[] = "no-timeout";

// Display no toolbar
const char kNoToolbar[] = "no-toolbar";

// Show version and quit
const char kVersion[] = "version";

// Open specified url
const char kUrl[] = "url";

const char kmMain[]      = "main";
const char kmName[]      = "name";
const char kmWebkit[]    = "webkit";
const char kmNodejs[]    = "nodejs";
const char kmRoot[]      = "root";
const char kmWindow[]    = "window";
const char kmTitle[]     = "title";
const char kmToolbar[]   = "toolbar";
const char kmIcon[]      = "icon";
const char kmWidth[]     = "width";
const char kmHeight[]    = "height";
const char kmX[]         = "x";
const char kmY[]         = "y";
const char kmResizable[] = "resizable";
const char kmPosition[]  = "position";
const char kmMinWidth[]  = "min_width";
const char kmMinHeight[] = "min_height";
const char kmMaxWidth[]  = "max_width";
const char kmMaxHeight[] = "max_height";
const char kmAsDesktop[] = "as_desktop";

}  // namespace switches


// 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.

#ifndef CONTENT_SHELL_PATHS_MAC_H_
#define CONTENT_SHELL_PATHS_MAC_H_

#include "base/file_path.h"

// Sets up base::mac::FrameworkBundle.
void OverrideFrameworkBundlePath();

// Sets up the CHILD_PROCESS_EXE path to properly point to the helper app.
void OverrideChildProcessPath();

// Gets the path to the content shell's pak file.
FilePath GetResourcesPakFilePath();

#endif  // CONTENT_SHELL_PATHS_MAC_H_


// 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/tray/tray.h"

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

#import <Cocoa/Cocoa.h>

namespace api {

Tray::Tray(CreationOption option) {
  NSStatusBar *status_bar = [NSStatusBar systemStatusBar];
  status_item_ = [status_bar statusItemWithLength:NSVariableStatusItemLength];
  [status_item_ retain];
  [status_item_ setHighlightMode:YES];

  if (!option.icon.empty())
    SetIcon(option.icon);
  if (!option.title.empty())
    SetTitle(option.title);
  if (!option.tooltip.empty())
    SetTooltip(option.tooltip);
}

Tray::~Tray() {
  [status_item_ release];
}

void Tray::SetTitle(const std::string& title) {
  [status_item_ setTitle:
      [NSString stringWithUTF8String:title.c_str()]];
}

std::string Tray::GetTitle() {
  return [[status_item_ title] UTF8String];
}

void Tray::SetIcon(const std::string& path) {
  NSString* icon_path = [NSString stringWithUTF8String:path.c_str()];
  NSImage* icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
  [status_item_ setImage:icon];
}

void Tray::SetTooltip(const std::string& tooltip) {
  [status_item_ setToolTip:
      [NSString stringWithUTF8String:tooltip.c_str()]];
}

std::string Tray::GetTooltip() {
  NSString* tooltip = [status_item_ toolTip];
  return tooltip == nil ? "" : [tooltip UTF8String];
}

void Tray::SetMenu(Menu* menu) {
  [status_item_ setMenu:menu->menu_];
}

void Tray::Remove() {
  [[NSStatusBar systemStatusBar] removeStatusItem:status_item_];
}

}  // namespace api


// 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/shell_browser_main.h"

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/threading/thread_restrictions.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/shell.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/nw/src/shell_content_browser_client.h"
#include "content/public/browser/browser_main_runner.h"

// Main routine for running as the Browser process.
int ShellBrowserMain(const content::MainFunctionParams& parameters) {
  scoped_ptr<content::BrowserMainRunner> main_runner_(
      content::BrowserMainRunner::Create());

  int exit_code = main_runner_->Initialize(parameters);

  if (exit_code >= 0)
    return exit_code;

  exit_code = main_runner_->Run();

  main_runner_->Shutdown();

  return exit_code;
}


//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "base/file_path.h"
#include "base/file_util.h"


// 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_RENDERER_PRERENDERER_PRERENDERER_CLIENT_H_
#define CONTENT_NW_SRC_RENDERER_PRERENDERER_PRERENDERER_CLIENT_H_

#include "base/compiler_specific.h"
#include "content/public/renderer/render_view_observer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPrerendererClient.h"

namespace prerender {

class PrerendererClient : public content::RenderViewObserver,
                          public WebKit::WebPrerendererClient {
 public:
  explicit PrerendererClient(content::RenderView* render_view);

 private:
  virtual ~PrerendererClient();

  // Implements WebKit::WebPrerendererClient
  virtual void willAddPrerender(WebKit::WebPrerender* prerender) OVERRIDE;
};

}  // namespace prerender

#endif  // CONTENT_NW_SRC_RENDERER_PRERENDERER_PRERENDERER_CLIENT_H_


// 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_javascript_dialog_creator.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "content/nw/src/browser/shell_javascript_dialog.h"
#include "content/nw/src/common/shell_switches.h"
#include "net/base/net_util.h"

namespace content {

ShellJavaScriptDialogCreator::ShellJavaScriptDialogCreator() {
}

ShellJavaScriptDialogCreator::~ShellJavaScriptDialogCreator() {
}

void ShellJavaScriptDialogCreator::RunJavaScriptDialog(
    WebContents* web_contents,
    const GURL& origin_url,
    const std::string& accept_lang,
    JavaScriptMessageType javascript_message_type,
    const string16& message_text,
    const string16& default_prompt_text,
    const DialogClosedCallback& callback,
    bool* did_suppress_message) {
  if (!dialog_request_callback_.is_null()) {
    dialog_request_callback_.Run();
    callback.Run(true, string16());
    dialog_request_callback_.Reset();
    return;
  }

#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK)
  *did_suppress_message = false;

  if (dialog_.get()) {
    // One dialog at a time, please.
    *did_suppress_message = true;
    return;
  }

  string16 new_message_text = net::FormatUrl(origin_url, accept_lang) +
                              ASCIIToUTF16("\n\n") +
                              message_text;
  gfx::NativeWindow parent_window =
      web_contents->GetView()->GetTopLevelNativeWindow();

  dialog_.reset(new ShellJavaScriptDialog(this,
                                          parent_window,
                                          javascript_message_type,
                                          new_message_text,
                                          default_prompt_text,
                                          callback));
#else
  // TODO: implement ShellJavaScriptDialog for other platforms, drop this #if
  *did_suppress_message = true;
  return;
#endif
}

void ShellJavaScriptDialogCreator::RunBeforeUnloadDialog(
    WebContents* web_contents,
    const string16& message_text,
    bool is_reload,
    const DialogClosedCallback& callback) {
  if (!dialog_request_callback_.is_null()) {
    dialog_request_callback_.Run();
    callback.Run(true, string16());
    dialog_request_callback_.Reset();
    return;
  }

#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK)
  if (dialog_.get()) {
    // Seriously!?
    callback.Run(true, string16());
    return;
  }

  string16 new_message_text =
      message_text +
      ASCIIToUTF16("\n\nIs it OK to leave/reload this page?");

  gfx::NativeWindow parent_window =
      web_contents->GetView()->GetTopLevelNativeWindow();

  dialog_.reset(new ShellJavaScriptDialog(this,
                                          parent_window,
                                          JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
                                          new_message_text,
                                          string16(),  // default_prompt_text
                                          callback));
#else
  // TODO: implement ShellJavaScriptDialog for other platforms, drop this #if
  callback.Run(true, string16());
  return;
#endif
}

void ShellJavaScriptDialogCreator::ResetJavaScriptState(
    WebContents* web_contents) {
#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK)
  if (dialog_.get()) {
    dialog_->Cancel();
    dialog_.reset();
  }
#else
  // TODO: implement ShellJavaScriptDialog for other platforms, drop this #if
#endif
}

void ShellJavaScriptDialogCreator::DialogClosed(ShellJavaScriptDialog* dialog) {
#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK)
  DCHECK_EQ(dialog, dialog_.get());
  dialog_.reset();
#else
  // TODO: implement ShellJavaScriptDialog for other platforms, drop this #if
#endif
}

}  // namespace content


<html>
<head>
  <script type="text/javascript" src="../assert.js"></script>
</head>
<body>
<script>
  var gui = require('nw.gui');

  var menu = new gui.Menu({ title: 'Tray Menu' });
  assert(menu.length == 0, 'Empty Menu');

  menu.append(new gui.MenuItem({
    label: 'Item 1',
    click: function() {
      console.log('Click on Item 1');
    }
  }));
  assert(menu.length == 1, menu[0].label == 'Item 1', 'One Menu');

  menu.append(new gui.MenuItem({ type: 'separator' }));
  menu.append(new gui.MenuItem({
    label: 'Item 2',
    click: function() {
      console.log('Click on Item 2');
    }
  }));
  menu.append(new gui.MenuItem({ label: 'Item 3' }));
  menu.append(new gui.MenuItem({ label: 'Item 4', tooltip: 'tooltip' }));
  menu.append(new gui.MenuItem({ label: 'Item 5' }));
  menu.insert(new gui.MenuItem({ label: 'Item Papa' }), 1);
  assert(menu.length == 7,
         menu[0].label == 'Item 1',
         menu[1].label == 'Item Papa',
         menu[2].type == 'separator',
         menu[3].label == 'Item 2',
         menu[4].label == 'Item 3',
         menu[4].tooltip == '',
         menu[5].label == 'Item 4',
         menu[5].tooltip == 'tooltip',
         menu[6].label == 'Item 5',
         'More Menu');

  menu[4].tooltip = 'tooltip';
  menu[5].tooltip = '';
  assert(
  menu[4].tooltip == 'tooltip',
  menu[5].tooltip == '',
  'Change Tooltip');

  var removedItem = new gui.MenuItem({ label: 'Item Deleted' });
  menu.insert(removedItem, 4);
  assert(menu.length == 8,
         menu[4].label == 'Item Deleted',
         'Before Delete');

  menu.remove(removedItem);
  assert(menu.length == 7,
         menu[4].label == 'Item 3',
         'After Delete');

  menu.insert(new gui.MenuItem({ label: 'Item Deleted' }), 1);
  assert(
  menu.length == 8,
  menu[1].label == 'Item Deleted',
  'Before Delete 2');

  menu.removeAt(1);
  assert(
  menu.length == 7,
  menu[1].label == 'Item Papa',
  'After Delete 2');

  menu[1].label = 'Item Mama';
  assert(
  menu[1].label == 'Item Mama',
  'Update MenuItem');

  menu.append(new gui.MenuItem({
    label: 'Click Me',
    click: function() {
      var element = document.createElement('div');
      element.appendChild(document.createTextNode('Clicked OK'));
      document.body.appendChild(element);
    }
  }));

  var submenu = new gui.Menu({ title: 'SubMenu' });
  submenu.append(new gui.MenuItem({ label: 'Sub 1', checked: true, enabled: false }));
  submenu.append(new gui.MenuItem({ label: 'Sub 2', checked: true, enabled: false }));
  submenu.append(new gui.MenuItem({ label: 'Sub 3', checked: true, enabled: false }));
  submenu.append(new gui.MenuItem({ label: 'Sub 4', checked: true, enabled: false }));
  menu.append(new gui.MenuItem({ type: 'separator' }));
  menu.append(new gui.MenuItem({ label: 'I have submenu', submenu: submenu }));

  assert(
  submenu == menu[menu.length - 1].submenu,
  menu.length == 10,
  menu[9].label == 'I have submenu',
  submenu.length == 4,
  'Submenu');

  assert(
  submenu[0].checked == true,
  submenu[1].checked == true,
  submenu[2].checked == true,
  submenu[3].checked == true,
  submenu[0].enabled == false,
  submenu[1].enabled == false,
  submenu[2].enabled == false,
  submenu[3].enabled == false,
  'Before flip checked and enabled');

  submenu[1].checked = false,
  submenu[2].checked = false,
  submenu[3].checked = false,
  submenu[1].enabled = true,
  submenu[2].enabled = true,
  submenu[3].enabled = true,

  assert(
  submenu[0].checked == true,
  submenu[1].checked == false,
  submenu[2].checked == false,
  submenu[3].checked == false,
  submenu[0].enabled == false,
  submenu[1].enabled == true,
  submenu[2].enabled == true,
  submenu[3].enabled == true,
  'After flip checked and enabled');

  // Click to flip other items
  var lastone = submenu[0];
  submenu[0].click = submenu[1].click = submenu[2].click = submenu[3].click = function() {
    lastone.checked = false;
    lastone.enabled = true;
    this.checked = true;
    this.enabled = false;
    lastone = this;
  }

  var tray = new gui.Tray({ title: 'Test Menu', menu: menu });
  menu[0].icon = tray.icon = 'icon1.png';
</script>
</body>
</html>


// Initialize node after render thread is started

keep keep keep keep add keep keep keep keep

CommandLine* command_line = CommandLine::ForCurrentProcess();


// 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"

namespace api {

using namespace v8;

Menu::Menu(CreationOptions options) {
}

Menu::~Menu() {
}

}  // namespace api


// 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_javascript_dialog.h"

#import <Cocoa/Cocoa.h>

#import "base/memory/scoped_nsobject.h"
#include "base/sys_string_conversions.h"
#include "content/nw/src/browser/shell_javascript_dialog_creator.h"

// Helper object that receives the notification that the dialog/sheet is
// going away. Is responsible for cleaning itself up.
@interface ShellJavaScriptDialogHelper : NSObject<NSAlertDelegate> {
 @private
  scoped_nsobject<NSAlert> alert_;
  NSTextField* textField_;  // WEAK; owned by alert_

  // Copies of the fields in ShellJavaScriptDialog because they're private.
  content::ShellJavaScriptDialogCreator* creator_;
  content::JavaScriptDialogCreator::DialogClosedCallback callback_;
}

- (id)initHelperWithCreator:(content::ShellJavaScriptDialogCreator*)creator
   andCallback:(content::JavaScriptDialogCreator::DialogClosedCallback)callback;
- (NSAlert*)alert;
- (NSTextField*)textField;
- (void)alertDidEnd:(NSAlert*)alert
         returnCode:(int)returnCode
        contextInfo:(void*)contextInfo;
- (void)cancel;

@end

@implementation ShellJavaScriptDialogHelper

- (id)initHelperWithCreator:(content::ShellJavaScriptDialogCreator*)creator
  andCallback:(content::JavaScriptDialogCreator::DialogClosedCallback)callback {
  if (self = [super init]) {
    creator_ = creator;
    callback_ = callback;
  }

  return self;
}

- (NSAlert*)alert {
  alert_.reset([[NSAlert alloc] init]);
  return alert_;
}

- (NSTextField*)textField {
  textField_ = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 22)];
  [[textField_ cell] setLineBreakMode:NSLineBreakByTruncatingTail];
  [alert_ setAccessoryView:textField_];
  [textField_ release];

  return textField_;
}

- (void)alertDidEnd:(NSAlert*)alert
         returnCode:(int)returnCode
        contextInfo:(void*)contextInfo {
  if (returnCode == NSRunStoppedResponse)
    return;

  bool success = returnCode == NSAlertFirstButtonReturn;
  string16 input;
  if (textField_)
    input = base::SysNSStringToUTF16([textField_ stringValue]);

  content::ShellJavaScriptDialog* native_dialog =
      reinterpret_cast<content::ShellJavaScriptDialog*>(contextInfo);
  callback_.Run(success, input);
  creator_->DialogClosed(native_dialog);
}

- (void)cancel {
  [NSApp endSheet:[alert_ window]];
  alert_.reset();
}

@end

namespace content {

ShellJavaScriptDialog::ShellJavaScriptDialog(
    ShellJavaScriptDialogCreator* creator,
    gfx::NativeWindow parent_window,
    JavaScriptMessageType message_type,
    const string16& message_text,
    const string16& default_prompt_text,
    const JavaScriptDialogCreator::DialogClosedCallback& callback)
    : creator_(creator),
      callback_(callback) {
  bool text_field = message_type == JAVASCRIPT_MESSAGE_TYPE_PROMPT;
  bool one_button = message_type == JAVASCRIPT_MESSAGE_TYPE_ALERT;

  helper_ =
      [[ShellJavaScriptDialogHelper alloc] initHelperWithCreator:creator
                                                     andCallback:callback];

  // Show the modal dialog.
  NSAlert* alert = [helper_ alert];
  NSTextField* field = nil;
  if (text_field) {
    field = [helper_ textField];
    [field setStringValue:base::SysUTF16ToNSString(default_prompt_text)];
  }
  [alert setDelegate:helper_];
  [alert setInformativeText:base::SysUTF16ToNSString(message_text)];
  [alert setMessageText:@"Javascript alert"];
  [alert addButtonWithTitle:@"OK"];
  if (!one_button) {
    NSButton* other = [alert addButtonWithTitle:@"Cancel"];
    [other setKeyEquivalent:@"\e"];
  }

  [alert
      beginSheetModalForWindow:nil  // nil here makes it app-modal
                 modalDelegate:helper_
                didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
                   contextInfo:this];

  if ([alert accessoryView])
    [[alert window] makeFirstResponder:[alert accessoryView]];
}

ShellJavaScriptDialog::~ShellJavaScriptDialog() {
  [helper_ release];
}

void ShellJavaScriptDialog::Cancel() {
  [helper_ cancel];
}

}  // namespace content


// 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_MEDIA_MEDIA_INTERNALS_H_
#define CONTENT_NW_SRC_MEDIA_MEDIA_INTERNALS_H_

#include "base/memory/ref_counted.h"
#include "base/memory/singleton.h"
#include "base/observer_list.h"
#include "base/values.h"
#include "content/public/browser/media_observer.h"

// This class stores information about currently active media.
// It's constructed on the UI thread but all of its methods are called on the IO
// thread.
class MediaInternals : public content::MediaObserver {
 public:
  virtual ~MediaInternals();

  static MediaInternals* GetInstance();

  // Overridden from content::MediaObserver:
  virtual void OnDeleteAudioStream(void* host, int stream_id) OVERRIDE;
  virtual void OnSetAudioStreamPlaying(void* host,
                                       int stream_id,
                                       bool playing) OVERRIDE;
  virtual void OnSetAudioStreamStatus(void* host,
                                      int stream_id,
                                      const std::string& status) OVERRIDE;
  virtual void OnSetAudioStreamVolume(void* host,
                                      int stream_id,
                                      double volume) OVERRIDE;
  virtual void OnMediaEvent(int render_process_id,
                            const media::MediaLogEvent& event) OVERRIDE;
  virtual void OnCaptureDevicesOpened(
      int render_process_id,
      int render_view_id,
      const content::MediaStreamDevices& devices) OVERRIDE;
  virtual void OnCaptureDevicesClosed(
      int render_process_id,
      int render_view_id,
      const content::MediaStreamDevices& devices) OVERRIDE;

 private:
  friend struct DefaultSingletonTraits<MediaInternals>;

  MediaInternals();

  DISALLOW_COPY_AND_ASSIGN(MediaInternals);
};

#endif  // CONTENT_NW_SRC_MEDIA_MEDIA_INTERNALS_H_


// 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/v8_utils.h"

using namespace v8;

namespace api {

Handle<Value> CallMethod(Handle<Value> recv,
                         const char* method,
                         int argc,
                         Handle<Value> argv[]) {
  Handle<Object> object = recv->ToObject();
  Handle<Function> func = Handle<Function>::Cast(
      object->Get(String::New(method)));
  return func->Call(object, argc, argv);
}

}  // api


// 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"

#import <Cocoa/Cocoa.h>
#include "content/nw/src/api/menuitem/menuitem.h"

namespace api {

using namespace v8;

Menu::Menu(CreationOption option) {
  menu_ = [[NSMenu alloc]
      initWithTitle:[NSString stringWithUTF8String:option.title.c_str()]];
  [menu_ setAutoenablesItems:NO];
}

Menu::~Menu() {
  [menu_ release];
}

void Menu::SetTitle(const std::string& title) {
  [menu_ setTitle:[NSString stringWithUTF8String:title.c_str()]];
}

std::string Menu::GetTitle() {
  return [[menu_ title] UTF8String];
}

void Menu::Append(MenuItem* menu_item) {
  [menu_ addItem:menu_item->menu_item_];
}

void Menu::Insert(MenuItem* menu_item, int pos) {
  [menu_ insertItem:menu_item->menu_item_ atIndex:pos];
}

void Menu::Remove(MenuItem* menu_item) {
  [menu_ removeItem:menu_item->menu_item_];
}

void Menu::Remove(int pos) {
  [menu_ removeItemAtIndex:pos];
}

}  // namespace api


// 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.

#ifndef CHROME_BROWSER_PLATFORM_UTIL_H_
#define CHROME_BROWSER_PLATFORM_UTIL_H_

#include <string>

#include "base/string16.h"
#include "ui/gfx/native_widget_types.h"

class FilePath;
class GURL;

namespace platform_util {

// Show the given file in a file manager. If possible, select the file.
// Must be called from the UI thread.
void ShowItemInFolder(const FilePath& full_path);

// Open the given file in the desktop's default manner.
// Must be called from the UI thread.
void OpenItem(const FilePath& full_path);

// Open the given external protocol URL in the desktop's default manner.
// (For example, mailto: URLs in the default mail user agent.)
void OpenExternal(const GURL& url);

// Get the top level window for the native view. This can return NULL.
gfx::NativeWindow GetTopLevel(gfx::NativeView view);

// Get the direct parent of |view|, may return NULL.
gfx::NativeView GetParent(gfx::NativeView view);

// Returns true if |window| is the foreground top level window.
bool IsWindowActive(gfx::NativeWindow window);

// Activate the window, bringing it to the foreground top level.
void ActivateWindow(gfx::NativeWindow window);

// Returns true if the view is visible. The exact definition of this is
// platform-specific, but it is generally not "visible to the user", rather
// whether the view has the visible attribute set.
bool IsVisible(gfx::NativeView view);

#if defined(OS_MACOSX)
// On 10.7+, back and forward swipe gestures can be triggered using a scroll
// gesture, if enabled in System Preferences. This function returns true if
// the feature is supported and enabled, and false otherwise.
bool IsSwipeTrackingFromScrollEventsEnabled();
#endif

}  // platform_util

#endif  // CHROME_BROWSER_PLATFORM_UTIL_H_


if (nw::GetManifest() && nw::GetUseNode()) {


<?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>


// 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/shell_content_browser_client.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "content/public/common/content_switches.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/nw/src/browser/shell_devtools_delegate.h"
#include "content/nw/src/browser/shell_resource_dispatcher_host_delegate.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/media/media_internals.h"
#include "content/nw/src/shell.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/nw/src/shell_browser_main_parts.h"
#include "content/nw/src/nw_package.h"
#include "geolocation/shell_access_token_store.h"
#include "googleurl/src/gurl.h"
#include "ui/base/l10n/l10n_util.h"

#if defined(OS_ANDROID)
#include "base/android/path_utils.h"
#include "base/path_service.h"
#include "base/platform_file.h"
#include "content/shell/android/shell_descriptors.h"
#endif

namespace content {

ShellContentBrowserClient::ShellContentBrowserClient()
    : shell_browser_main_parts_(NULL) {
}

ShellContentBrowserClient::~ShellContentBrowserClient() {
}

BrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts(
    const MainFunctionParams& parameters) {
  shell_browser_main_parts_ = new ShellBrowserMainParts(parameters);
  return shell_browser_main_parts_;
}

void ShellContentBrowserClient::RenderViewHostCreated(
    RenderViewHost* render_view_host) {
}

void ShellContentBrowserClient::AppendExtraCommandLineSwitches(
    CommandLine* command_line, int child_process_id) {
  // Disable web security
  command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
  command_line->AppendSwitch(switches::kDisableWebSecurity);

  if (nw::GetManifest() && nw::GetUseNode())
    command_line->AppendSwitch(switches::kmNodejs);
}

std::string ShellContentBrowserClient::GetApplicationLocale() {
  return l10n_util::GetApplicationLocale("en-US");
}

void ShellContentBrowserClient::ResourceDispatcherHostCreated() {
  resource_dispatcher_host_delegate_.reset(
      new ShellResourceDispatcherHostDelegate());
  ResourceDispatcherHost::Get()->SetDelegate(
      resource_dispatcher_host_delegate_.get());
}

std::string ShellContentBrowserClient::GetDefaultDownloadName() {
  return "download";
}

MediaObserver* ShellContentBrowserClient::GetMediaObserver() {
  return MediaInternals::GetInstance();
}

void ShellContentBrowserClient::BrowserURLHandlerCreated(
    BrowserURLHandler* handler) {
}

#if defined(OS_ANDROID)
void ShellContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
    const CommandLine& command_line,
    base::GlobalDescriptors::Mapping* mappings) {
  int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ;
  FilePath pak_file;
  DCHECK(PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_file));
  pak_file = pak_file.Append(FILE_PATH_LITERAL("paks"));
  pak_file = pak_file.Append(FILE_PATH_LITERAL("nw.pak"));

  base::PlatformFile f =
      base::CreatePlatformFile(pak_file, flags, NULL, NULL);
  if (f == base::kInvalidPlatformFileValue) {
    NOTREACHED() << "Failed to open file when creating renderer process: "
                 << "nw.pak";
  }
  mappings->push_back(std::pair<base::GlobalDescriptors::Key, int>(
      kShellPakDescriptor, f));
}
#endif

ShellBrowserContext* ShellContentBrowserClient::browser_context() {
  return shell_browser_main_parts_->browser_context();
}

ShellBrowserContext*
    ShellContentBrowserClient::off_the_record_browser_context() {
  return shell_browser_main_parts_->off_the_record_browser_context();
}

AccessTokenStore* ShellContentBrowserClient::CreateAccessTokenStore() {
  return new ShellAccessTokenStore(browser_context()->GetRequestContext());
}

}  // namespace content


// 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.

#ifndef CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_
#define CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_

#include <string>

#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "content/public/browser/content_browser_client.h"

namespace content {

class ShellBrowserContext;
class ShellBrowserMainParts;
class ShellResourceDispatcherHostDelegate;

class ShellContentBrowserClient : public ContentBrowserClient {
 public:
  ShellContentBrowserClient();
  virtual ~ShellContentBrowserClient();

  // ContentBrowserClient overrides.
  virtual BrowserMainParts* CreateBrowserMainParts(
      const MainFunctionParams& parameters) OVERRIDE;
  virtual void RenderViewHostCreated(
      RenderViewHost* render_view_host) OVERRIDE;
  virtual void AppendExtraCommandLineSwitches(CommandLine* command_line,
                                              int child_process_id) OVERRIDE;
  virtual std::string GetApplicationLocale() OVERRIDE;
  virtual void ResourceDispatcherHostCreated() OVERRIDE;
  virtual AccessTokenStore* CreateAccessTokenStore() OVERRIDE;
  virtual std::string GetDefaultDownloadName() OVERRIDE;
  virtual MediaObserver* GetMediaObserver() OVERRIDE;
  virtual void BrowserURLHandlerCreated(BrowserURLHandler* handler) OVERRIDE;

#if defined(OS_ANDROID)
  virtual void GetAdditionalMappedFilesForChildProcess(
      const CommandLine& command_line,
      base::GlobalDescriptors::Mapping* mappings) OVERRIDE;
#endif

  ShellBrowserContext* browser_context();
  ShellBrowserContext* off_the_record_browser_context();
  ShellResourceDispatcherHostDelegate* resource_dispatcher_host_delegate() {
    return resource_dispatcher_host_delegate_.get();
  }
  ShellBrowserMainParts* shell_browser_main_parts() {
    return shell_browser_main_parts_;
  }

 private:
  scoped_ptr<ShellResourceDispatcherHostDelegate>
      resource_dispatcher_host_delegate_;

  ShellBrowserMainParts* shell_browser_main_parts_;
};

}  // namespace content

#endif  // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_


// 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 "zip_reader.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "net/base/file_stream.h"
#include "third_party/zlib/contrib/minizip/unzip.h"
#if defined(OS_WIN)
#include "third_party/zlib/contrib/minizip/iowin32.h"
#endif
#include "zip_internal.h"

namespace zip {

// TODO(satorux): The implementation assumes that file names in zip files
// are encoded in UTF-8. This is true for zip files created by Zip()
// function in zip.h, but not true for user-supplied random zip files.
ZipReader::EntryInfo::EntryInfo(const std::string& file_name_in_zip,
                                const unz_file_info& raw_file_info)
    : file_path_(FilePath::FromUTF8Unsafe(file_name_in_zip)),
      is_directory_(false) {
  original_size_ = raw_file_info.uncompressed_size;

  // Directory entries in zip files end with "/".
  is_directory_ = EndsWith(file_name_in_zip, "/", false);

  // Check the file name here for directory traversal issues. In the name of
  // simplicity and security, we might reject a valid file name such as "a..b".
  is_unsafe_ = file_name_in_zip.find("..") != std::string::npos;

  // We also consider that the file name is unsafe, if it's invalid UTF-8.
  string16 file_name_utf16;
  if (!UTF8ToUTF16(file_name_in_zip.data(), file_name_in_zip.size(),
                   &file_name_utf16)) {
    is_unsafe_ = true;
  }

  // We also consider that the file name is unsafe, if it's absolute.
  // On Windows, IsAbsolute() returns false for paths starting with "/".
  if (file_path_.IsAbsolute() || StartsWithASCII(file_name_in_zip, "/", false))
    is_unsafe_ = true;

  // Construct the last modified time. The timezone info is not present in
  // zip files, so we construct the time as local time.
  base::Time::Exploded exploded_time = {};  // Zero-clear.
  exploded_time.year = raw_file_info.tmu_date.tm_year;
  // The month in zip file is 0-based, whereas ours is 1-based.
  exploded_time.month = raw_file_info.tmu_date.tm_mon + 1;
  exploded_time.day_of_month = raw_file_info.tmu_date.tm_mday;
  exploded_time.hour = raw_file_info.tmu_date.tm_hour;
  exploded_time.minute = raw_file_info.tmu_date.tm_min;
  exploded_time.second = raw_file_info.tmu_date.tm_sec;
  exploded_time.millisecond = 0;
  if (exploded_time.HasValidValues()) {
    last_modified_ = base::Time::FromLocalExploded(exploded_time);
  } else {
    // Use Unix time epoch if the time stamp data is invalid.
    last_modified_ = base::Time::UnixEpoch();
  }
}

ZipReader::ZipReader() {
  Reset();
}

ZipReader::~ZipReader() {
  Close();
}

bool ZipReader::Open(const FilePath& zip_file_path) {
  DCHECK(!zip_file_);

  // Use of "Unsafe" function does not look good, but there is no way to do
  // this safely on Linux. See file_util.h for details.
  zip_file_ = internal::OpenForUnzipping(zip_file_path.AsUTF8Unsafe());
  if (!zip_file_) {
    return false;
  }

  return OpenInternal();
}

#if defined(OS_POSIX)
bool ZipReader::OpenFromFd(const int zip_fd) {
  DCHECK(!zip_file_);

  zip_file_ = internal::OpenFdForUnzipping(zip_fd);
  if (!zip_file_) {
    return false;
  }

  return OpenInternal();
}
#endif

void ZipReader::Close() {
  if (zip_file_) {
    unzClose(zip_file_);
  }
  Reset();
}

bool ZipReader::HasMore() {
  return !reached_end_;
}

bool ZipReader::AdvanceToNextEntry() {
  DCHECK(zip_file_);

  // Should not go further if we already reached the end.
  if (reached_end_)
    return false;

  unz_file_pos position = {};
  if (unzGetFilePos(zip_file_, &position) != UNZ_OK)
    return false;
  const int current_entry_index = position.num_of_file;
  // If we are currently at the last entry, then the next position is the
  // end of the zip file, so mark that we reached the end.
  if (current_entry_index + 1 == num_entries_) {
    reached_end_ = true;
  } else {
    DCHECK_LT(current_entry_index + 1, num_entries_);
    if (unzGoToNextFile(zip_file_) != UNZ_OK) {
      return false;
    }
  }
  current_entry_info_.reset();
  return true;
}

bool ZipReader::OpenCurrentEntryInZip() {
  DCHECK(zip_file_);

  unz_file_info raw_file_info = {};
  char raw_file_name_in_zip[internal::kZipMaxPath] = {};
  const int result = unzGetCurrentFileInfo(zip_file_,
                                           &raw_file_info,
                                           raw_file_name_in_zip,
                                           sizeof(raw_file_name_in_zip) - 1,
                                           NULL,  // extraField.
                                           0,  // extraFieldBufferSize.
                                           NULL,  // szComment.
                                           0);  // commentBufferSize.
  if (result != UNZ_OK)
    return false;
  if (raw_file_name_in_zip[0] == '\0')
    return false;
  current_entry_info_.reset(
      new EntryInfo(raw_file_name_in_zip, raw_file_info));
  return true;
}

bool ZipReader::LocateAndOpenEntry(const FilePath& path_in_zip) {
  DCHECK(zip_file_);

  current_entry_info_.reset();
  reached_end_ = false;
  const int kDefaultCaseSensivityOfOS = 0;
  const int result = unzLocateFile(zip_file_,
                                   path_in_zip.AsUTF8Unsafe().c_str(),
                                   kDefaultCaseSensivityOfOS);
  if (result != UNZ_OK)
    return false;

  // Then Open the entry.
  return OpenCurrentEntryInZip();
}

bool ZipReader::ExtractCurrentEntryToFilePath(
    const FilePath& output_file_path) {
  DCHECK(zip_file_);

  // If this is a directory, just create it and return.
  if (current_entry_info()->is_directory())
    return file_util::CreateDirectory(output_file_path);

  const int open_result = unzOpenCurrentFile(zip_file_);
  if (open_result != UNZ_OK)
    return false;

  // We can't rely on parent directory entries being specified in the
  // zip, so we make sure they are created.
  FilePath output_dir_path = output_file_path.DirName();
  if (!file_util::CreateDirectory(output_dir_path))
    return false;

  net::FileStream stream(NULL);
  const int flags = (base::PLATFORM_FILE_CREATE_ALWAYS |
                     base::PLATFORM_FILE_WRITE);
  if (stream.OpenSync(output_file_path, flags) != 0)
    return false;

  bool success = true;  // This becomes false when something bad happens.
  while (true) {
    char buf[internal::kZipBufSize];
    const int num_bytes_read = unzReadCurrentFile(zip_file_, buf,
                                                  internal::kZipBufSize);
    if (num_bytes_read == 0) {
      // Reached the end of the file.
      break;
    } else if (num_bytes_read < 0) {
      // If num_bytes_read < 0, then it's a specific UNZ_* error code.
      success = false;
      break;
    } else if (num_bytes_read > 0) {
      // Some data is read. Write it to the output file.
      if (num_bytes_read != stream.WriteSync(buf, num_bytes_read)) {
        success = false;
        break;
      }
    }
  }

  stream.CloseSync();
  unzCloseCurrentFile(zip_file_);
  return success;
}

bool ZipReader::ExtractCurrentEntryIntoDirectory(
    const FilePath& output_directory_path) {
  DCHECK(current_entry_info_.get());

  FilePath output_file_path = output_directory_path.Append(
      current_entry_info()->file_path());
  return ExtractCurrentEntryToFilePath(output_file_path);
}

#if defined(OS_POSIX)
bool ZipReader::ExtractCurrentEntryToFd(const int fd) {
  DCHECK(zip_file_);

  // If this is a directory, there's nothing to extract to the file descriptor,
  // so return false.
  if (current_entry_info()->is_directory())
    return false;

  const int open_result = unzOpenCurrentFile(zip_file_);
  if (open_result != UNZ_OK)
    return false;

  bool success = true;  // This becomes false when something bad happens.
  while (true) {
    char buf[internal::kZipBufSize];
    const int num_bytes_read = unzReadCurrentFile(zip_file_, buf,
                                                  internal::kZipBufSize);
    if (num_bytes_read == 0) {
      // Reached the end of the file.
      break;
    } else if (num_bytes_read < 0) {
      // If num_bytes_read < 0, then it's a specific UNZ_* error code.
      success = false;
      break;
    } else if (num_bytes_read > 0) {
      // Some data is read. Write it to the output file descriptor.
      if (num_bytes_read !=
          file_util::WriteFileDescriptor(fd, buf, num_bytes_read)) {
        success = false;
        break;
      }
    }
  }

  unzCloseCurrentFile(zip_file_);
  return success;
}
#endif  // defined(OS_POSIX)

bool ZipReader::OpenInternal() {
  DCHECK(zip_file_);

  unz_global_info zip_info = {};  // Zero-clear.
  if (unzGetGlobalInfo(zip_file_, &zip_info) != UNZ_OK) {
    return false;
  }
  num_entries_ = zip_info.number_entry;
  if (num_entries_ < 0)
    return false;

  // We are already at the end if the zip file is empty.
  reached_end_ = (num_entries_ == 0);
  return true;
}

void ZipReader::Reset() {
  zip_file_ = NULL;
  num_entries_ = 0;
  reached_end_ = false;
  current_entry_info_.reset();
}

}  // namespace zip


// 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/shell/geolocation/shell_access_token_store.h"

#include "base/bind.h"
#include "base/message_loop.h"
#include "base/utf_string_conversions.h"

ShellAccessTokenStore::ShellAccessTokenStore(
    net::URLRequestContextGetter* request_context)
    : request_context_(request_context) {
}

ShellAccessTokenStore::~ShellAccessTokenStore() {
}

void ShellAccessTokenStore::LoadAccessTokens(
    const LoadAccessTokensCallbackType& callback) {
  MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&ShellAccessTokenStore::DidLoadAccessTokens,
                 request_context_, callback));
}

void ShellAccessTokenStore::DidLoadAccessTokens(
    net::URLRequestContextGetter* request_context,
    const LoadAccessTokensCallbackType& callback) {
  // Since content_shell is a test executable, rather than an end user program,
  // we provide a dummy access_token set to avoid hitting the server.
  AccessTokenSet access_token_set;
  access_token_set[GURL()] = ASCIIToUTF16("chromium_content_shell");
  callback.Run(access_token_set, request_context);
}

void ShellAccessTokenStore::SaveAccessToken(
    const GURL& server_url, const string16& access_token) {
}


* The `meteor-babel` npm package has been updated to version 7.4.12.

* The `meteor-babel` npm package has been updated to version 7.4.13.


//
// When an oauth request is made, Meteor receives oauth credentials
// in one browser tab, and temporarily persists them while that
// tab is closed, then retrieves them in the browser tab that
// initiated the credential request.
//
// _pendingCredentials is the storage mechanism used to share the
// credential between the 2 tabs
//

// Collection containing pending credentials of oauth credential requests
// Has key, credential, and createdAt fields.
OAuth._pendingCredentials = new Mongo.Collection(
  "meteor_oauth_pendingCredentials", {
    _preventAutopublish: true
  });

OAuth._pendingCredentials._ensureIndex('key', {unique: 1});
OAuth._pendingCredentials._ensureIndex('credentialSecret');
OAuth._pendingCredentials._ensureIndex('createdAt');

// Periodically clear old entries that were never retrieved
const _cleanStaleResults = () => {
  // Remove credentials older than 1 minute
  const timeCutoff = new Date();
  timeCutoff.setMinutes(timeCutoff.getMinutes() - 1);
  OAuth._pendingCredentials.remove({ createdAt: { $lt: timeCutoff } });
};
const _cleanupHandle = Meteor.setInterval(_cleanStaleResults, 60 * 1000);

// Stores the key and credential in the _pendingCredentials collection.
// Will throw an exception if `key` is not a string.
//
// @param key {string}
// @param credential {Object}   The credential to store
// @param credentialSecret {string} A secret that must be presented in
//   addition to the `key` to retrieve the credential
//
OAuth._storePendingCredential = (key, credential, credentialSecret = null) => {
  check(key, String);
  check(credentialSecret, Match.Maybe(String));

  if (credential instanceof Error) {
    credential = storableError(credential);
  } else {
    credential = OAuth.sealSecret(credential);
  }

  // We do an upsert here instead of an insert in case the user happens
  // to somehow send the same `state` parameter twice during an OAuth
  // login; we don't want a duplicate key error.
  OAuth._pendingCredentials.upsert({
    key,
  }, {
    key,
    credential,
    credentialSecret,
    createdAt: new Date()
  });
};

// Retrieves and removes a credential from the _pendingCredentials collection
//
// @param key {string}
// @param credentialSecret {string}
//
OAuth._retrievePendingCredential = (key, credentialSecret = null) => {
  check(key, String);

  const pendingCredential = OAuth._pendingCredentials.findOne({
    key,
    credentialSecret,
  });

  if (pendingCredential) {
    OAuth._pendingCredentials.remove({ _id: pendingCredential._id });
    if (pendingCredential.credential.error)
      return recreateError(pendingCredential.credential.error);
    else
      return OAuth.openSecret(pendingCredential.credential);
  } else {
    return undefined;
  }
};

// Convert an Error into an object that can be stored in mongo
// Note: A Meteor.Error is reconstructed as a Meteor.Error
// All other error classes are reconstructed as a plain Error.
// TODO: Can we do this more simply with EJSON?
const storableError = error => {
  const plainObject = {};
  Object.getOwnPropertyNames(error).forEach(
    key => plainObject[key] = error[key]
  );

  // Keep track of whether it's a Meteor.Error
  if(error instanceof Meteor.Error) {
    plainObject['meteorError'] = true;
  }

  return { error: plainObject };
};

// Create an error from the error format stored in mongo
const recreateError = errorDoc => {
  let error;

  if (errorDoc.meteorError) {
    error = new Meteor.Error();
    delete errorDoc.meteorError;
  } else {
    error = new Error();
  }

  Object.getOwnPropertyNames(errorDoc).forEach(key =>
    error[key] = errorDoc[key]
  );

  return error;
};


var assert = require("assert");
var files = require('../fs/files.js');
var _ = require("underscore");

// This class encapsulates a structured specification of files and
// directories that should be stripped from the node_modules directories
// of Meteor packages during `meteor build`, as requested by calling
// `Npm.discard` in package.js files.
function NpmDiscards() {
  assert.ok(this instanceof NpmDiscards);
  this.discards = {};
}

var NDp = NpmDiscards.prototype;

// Update the current specification of discarded files with additional
// patterns that should be discarded. See the comment in package-source.js
// about `Npm.strip` for an explanation of what should be passed for the
// `discards` parameter.
NDp.merge = function(discards) {
  merge(this.discards, discards);
};

function merge(into, from) {
  _.each(from, function(fromValue, packageName) {
    var intoValue = _.has(into, packageName) && into[packageName];
    if (_.isString(fromValue) ||
        _.isRegExp(fromValue)) {
      if (intoValue) {
        intoValue.push(fromValue);
      } else {
        into[packageName] = [fromValue];
      }
    } else if (_.isArray(fromValue)) {
      if (intoValue) {
        intoValue.push.apply(intoValue, fromValue);
      } else {
        // Make a defensive copy of any arrays passed to `Npm.strip`.
        into[packageName] = fromValue.slice(0);
      }
    }
  });
}

NDp.shouldDiscard = function shouldDiscard(candidatePath, isDirectory) {
  if (typeof isDirectory === "undefined") {
    isDirectory = files.lstat(candidatePath).isDirectory();
  }

  for (var currentPath = candidatePath, parentPath;
       (parentPath = files.pathDirname(currentPath)) !== currentPath;
       currentPath = parentPath) {
    if (files.pathBasename(parentPath) === "node_modules") {
      var packageName = files.pathBasename(currentPath);

      if (_.has(this.discards, packageName)) {
        var relPath = files.pathRelative(currentPath, candidatePath);

        if (isDirectory) {
          relPath = files.pathJoin(relPath, files.pathSep);
        }

        return this.discards[packageName].some(function(pattern) {
          return matches(pattern, relPath);
        });
      }

      // Stop at the first ancestor node_modules directory we find.
      break;
    }
  }

  return false;
};

// TODO Improve this. For example we don't currently support wildcard
// string patterns (just use a RegExp if you need that flexibility).
function matches(pattern, relPath) {
  if (_.isRegExp(pattern)) {
    return relPath.match(pattern);
  }

  assert.ok(_.isString(pattern));

  if (pattern.charAt(0) === files.pathSep) {
    return relPath.indexOf(pattern.slice(1)) === 0;
  }

  return relPath.indexOf(pattern) !== -1;
}

module.exports = NpmDiscards;


* The `reify` npm package has been updated to version 0.20.4.

* The `core-js` npm package used by `ecmascript-runtime-client` and

`ecmascript-runtime-server` has been updated to version 3.1.4.

* The `reify` npm package has been updated to version 0.20.5.


Package.describe({
  summary: 'CSS minifier',
  version: '1.4.2'
});

Npm.depends({
  postcss: '7.0.14',
  cssnano: '4.1.9'
});

Package.onUse(function (api) {
  api.use('ecmascript');
  api.mainModule('minifier.js', 'server');
  api.export('CssTools');
});

Package.onTest(function (api) {
  api.use('ecmascript');
  api.use('tinytest');
  api.addFiles([
    'minifier-tests.js',
    'urlrewriting-tests.js'
  ], 'server');
});


keep keep keep keep replace replace replace keep keep keep


const selftest = require("../tool-testing/selftest.js");
const Sandbox = selftest.Sandbox;

selftest.define(".meteorignore", function () {
  const s = new Sandbox();

  s.createApp("myapp", "meteor-ignore");
  s.cd("myapp");

  let run = s.run();
  run.waitSecs(30);
  run.match("/a.js");
  run.match("/b.js");
  run.match("/lib/e.js");
  run.match("/lib/f.js");
  run.match("/main.js");
  run.match("/server/c.js");
  run.match("/server/d.js");
  run.match("App running at");

  s.write("server/.meteorignore", "c.*");
  run.waitSecs(10);
  run.match("/a.js");
  run.match("/b.js");
  run.match("/lib/e.js");
  run.match("/lib/f.js");
  run.match("/main.js");
  run.match("/server/d.js");
  run.match("restarted");

  s.write(".meteorignore", "server/d.js");
  run.waitSecs(10);
  run.match("/a.js");
  run.match("/b.js");
  run.match("/lib/e.js");
  run.match("/lib/f.js");
  run.match("/main.js");
  run.match("restarted");

  s.write("lib/.meteorignore", "*.js\n!e.*");
  run.waitSecs(10);
  run.match("/a.js");
  run.match("/b.js");
  run.match("/lib/e.js");
  run.match("/main.js");
  run.match("restarted");

  s.write(".meteorignore", "lib/**");
  run.waitSecs(10);
  run.match("/a.js");
  run.match("/b.js");
  run.match("/main.js");
  run.match("/server/d.js");
  run.match("restarted");

  s.write(".meteorignore", "/*.js\nlib");
  run.waitSecs(10);
  run.match("/server/d.js");
  run.match("restarted");

  s.unlink(".meteorignore");
  s.unlink("lib/.meteorignore");
  s.unlink("server/.meteorignore");
  run.waitSecs(10);
  run.match("/a.js");
  run.match("/b.js");
  run.match("/lib/e.js");
  run.match("/lib/f.js");
  run.match("/main.js");
  run.match("/server/c.js");
  run.match("/server/d.js");
  run.match("restarted");

  run.stop();
});


This package exists to test dynamic imports from packages that are
prefixed by a username, and thus have a colon between the username and the
package name.


keep keep keep keep replace replace replace keep keep

Package.describe({
  name: "babel-compiler",
  summary: "Parser/transpiler for ECMAScript 2015+ syntax",
  // Tracks the npm version below.  Use wrap numbers to increment
  // without incrementing the npm version.  Hmm-- Apparently this
  // isn't possible because you can't publish a non-recommended
  // release with package versions that don't have a pre-release
  // identifier at the end (eg, -dev)
  version: '7.4.0'
});

Npm.depends({
  'meteor-babel': '7.4.12',
  'json5': '2.1.0'
});

Package.onUse(function (api) {
  api.use('ecmascript-runtime', 'server');
  api.use('modern-browsers');

  api.addFiles([
    'babel.js',
    'babel-compiler.js',
    'versions.js',
  ], 'server');

  api.export('Babel', 'server');
  api.export('BabelCompiler', 'server');
});


# ddp-server
[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/ddp-server) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/ddp-server)
***