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

#include "base/file_util.h"
#include "content/public/renderer/render_thread.h"
#include "content/nw/src/api/api_messages.h"
#include "content/nw/src/api/dispatcher_bindings.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/support/gc_extension.h"
#include "third_party/node/src/node.h"
#include "third_party/node/src/req_wrap.h"
#include "v8/include/v8.h"

namespace content {

ShellRenderProcessObserver::ShellRenderProcessObserver() {
  RenderThread::Get()->AddObserver(this);
}

ShellRenderProcessObserver::~ShellRenderProcessObserver() {
}

bool ShellRenderProcessObserver::OnControlMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(ShellRenderProcessObserver, message)
    IPC_MESSAGE_HANDLER(ShellViewMsg_Open, OnOpen)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void ShellRenderProcessObserver::OnRenderProcessWillShutdown() {
  // process.emit('exit');
  node::EmitExit(node::process);
  node::RunAtExit();
}

void ShellRenderProcessObserver::WebKitInitialized() {
  webkit_glue::SetJavaScriptFlags(" --expose-gc");
  RenderThread::Get()->RegisterExtension(extensions_v8::GCExtension::Get());
  RenderThread::Get()->RegisterExtension(new api::DispatcherBindings());
}

void ShellRenderProcessObserver::OnOpen(const std::string& path) {
  v8::HandleScope handle_scope;

  // the App object is stored in process["_nw_app"].
  v8::Local<v8::Object> process = node::g_context->Global()->Get(
      node::process_symbol)->ToObject();
  v8::Local<v8::String> app_symbol = v8::String::NewSymbol("_nw_app");
  if (process->Has(app_symbol)) {
    // process["_nw_app"].emit(path).
    v8::Local<v8::Object> app = process->Get(app_symbol)->ToObject();
    v8::Local<v8::Function> emit = v8::Local<v8::Function>::Cast(
        app->Get(v8::String::New("emit")));
    v8::Local<v8::Value> argv[] = {
        v8::String::New("open"), v8::String::New(path.c_str())
    };
    emit->Call(app, 2, argv);
  }
}

}  // namespace content


DispatcherBindings::GetNextObjectId(const v8::Arguments& args) {

DispatcherBindings::GetAbsolutePath(const v8::Arguments& args) {

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

block-stream

a stream of blocks

# block-stream

A stream of blocks.

Write data into it, and it'll output data in buffer blocks the size you
specify, padding with zeroes if necessary.

```javascript
var block = new BlockStream(512)
fs.createReadStream("some-file").pipe(block)
block.pipe(fs.createWriteStream("block-file"))
```

When `.end()` or `.flush()` is called, it'll pad the block with zeroes.


static v8::Handle<v8::Value> RequireNwGui(const v8::Arguments& args);

static v8::Handle<v8::Value> GetNextObjectId(const v8::Arguments& args);

static v8::Handle<v8::Value> GetAbsolutePath(const v8::Arguments& args);

keep keep keep replace replace replace keep keep keep

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

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

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/values.h"
#include "base/command_line.h"
#include "chrome/renderer/static_v8_external_string_resource.h"
#include "content/nw/src/api/api_messages.h"
#include "content/nw/src/api/object_life_monitor.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/v8_value_converter.h"
#include "grit/nw_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/base/resource/resource_bundle.h"

using content::RenderView;
using content::V8ValueConverter;
using WebKit::WebFrame;
using WebKit::WebView;

namespace api {

namespace {

base::StringPiece GetStringResource(int resource_id) {
  return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id);
}

RenderView* GetCurrentRenderView() {
  WebFrame* frame = WebFrame::frameForCurrentContext();
  DCHECK(frame);
  if (!frame)
    return NULL;

  WebView* view = frame->view();
  if (!view)
    return NULL;  // can happen during closing.

  RenderView* render_view = RenderView::FromWebView(view);
  DCHECK(render_view);
  return render_view;
}

v8::Handle<v8::String> WrapSource(v8::Handle<v8::String> source) {
  v8::HandleScope handle_scope;
  v8::Handle<v8::String> left =
      v8::String::New("(function(nw, exports) {");
  v8::Handle<v8::String> right = v8::String::New("\n})");
  return handle_scope.Close(
      v8::String::Concat(left, v8::String::Concat(source, right)));
}

// Similar to node's `require` function, save functions in `exports`.
void RequireFromResource(v8::Handle<v8::Object> root,
                         v8::Handle<v8::Object> gui,
                         v8::Handle<v8::String> name,
                         int resource_id) {
  v8::HandleScope scope;

  v8::Handle<v8::String> source = v8::String::NewExternal(
      new StaticV8ExternalAsciiStringResource(
          GetStringResource(resource_id)));
  v8::Handle<v8::String> wrapped_source = WrapSource(source);

  v8::Handle<v8::Script> script(v8::Script::New(wrapped_source, name));
  v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(script->Run());
  v8::Handle<v8::Value> args[] = { root, gui };
  func->Call(root, 2, args);
}

bool MakePathAbsolute(FilePath* file_path) {
  DCHECK(file_path);

  FilePath current_directory;
  if (!file_util::GetCurrentDirectory(&current_directory))
    return false;

  if (file_path->IsAbsolute())
    return true;

  if (current_directory.empty())
    return file_util::AbsolutePath(file_path);

  if (!current_directory.IsAbsolute())
    return false;

  *file_path = current_directory.Append(*file_path);
  return true;
}

}  // namespace

DispatcherBindings::DispatcherBindings()
    : v8::Extension("dispatcher_bindings.js",
                    GetStringResource(
                        IDR_NW_API_DISPATCHER_BINDINGS_JS).data(),
                    0,     // num dependencies.
                    NULL,  // dependencies array.
                    GetStringResource(
                        IDR_NW_API_DISPATCHER_BINDINGS_JS).size()) {
}

DispatcherBindings::~DispatcherBindings() {
}

v8::Handle<v8::FunctionTemplate>
DispatcherBindings::GetNativeFunction(v8::Handle<v8::String> name) {
  if (name->Equals(v8::String::New("RequireNwGui")))
    return v8::FunctionTemplate::New(RequireNwGui);
  else if (name->Equals(v8::String::New("GetConstructorName")))
    return v8::FunctionTemplate::New(GetConstructorName);
  else if (name->Equals(v8::String::New("GetHiddenValue")))
    return v8::FunctionTemplate::New(GetHiddenValue);
  else if (name->Equals(v8::String::New("SetHiddenValue")))
    return v8::FunctionTemplate::New(SetHiddenValue);
  else if (name->Equals(v8::String::New("SetDestructor")))
    return v8::FunctionTemplate::New(SetDestructor);
  else if (name->Equals(v8::String::New("GetNextObjectId")))
    return v8::FunctionTemplate::New(GetNextObjectId);
  else if (name->Equals(v8::String::New("GetAbsolutePath")))
    return v8::FunctionTemplate::New(GetAbsolutePath);
  else if (name->Equals(v8::String::New("AllocateObject")))
    return v8::FunctionTemplate::New(AllocateObject);
  else if (name->Equals(v8::String::New("DeallocateObject")))
    return v8::FunctionTemplate::New(DeallocateObject);
  else if (name->Equals(v8::String::New("CallObjectMethod")))
    return v8::FunctionTemplate::New(CallObjectMethod);
  else if (name->Equals(v8::String::New("CallObjectMethodSync")))
    return v8::FunctionTemplate::New(CallObjectMethodSync);
  else if (name->Equals(v8::String::New("CallStaticMethod")))
    return v8::FunctionTemplate::New(CallStaticMethod);
  else if (name->Equals(v8::String::New("CallStaticMethodSync")))
    return v8::FunctionTemplate::New(CallStaticMethodSync);

  NOTREACHED() << "Trying to get an non-exist function in DispatcherBindings:"
               << *v8::String::Utf8Value(name);
  return v8::FunctionTemplate::New();
}

// static
v8::Handle<v8::Value>
DispatcherBindings::RequireNwGui(const v8::Arguments& args) {
  v8::HandleScope scope;

  // Initialize lazily
  v8::Local<v8::String> NwGuiSymbol = v8::String::NewSymbol("nwGui");
  v8::Local<v8::Value> NwGuiHidden = args.This()->Get(NwGuiSymbol);
  if (NwGuiHidden->IsObject())
    return scope.Close(NwGuiHidden);

  v8::Local<v8::Object> NwGui = v8::Object::New();
  args.This()->Set(NwGuiSymbol, NwGui);
  RequireFromResource(args.This(),
      NwGui, v8::String::New("base.js"), IDR_NW_API_BASE_JS);
  RequireFromResource(args.This(),
      NwGui, v8::String::New("menuitem.js"), IDR_NW_API_MENUITEM_JS);
  RequireFromResource(args.This(),
      NwGui, v8::String::New("menu.js"), IDR_NW_API_MENU_JS);
  RequireFromResource(args.This(),
      NwGui, v8::String::New("tray.js"), IDR_NW_API_TRAY_JS);
  RequireFromResource(args.This(),
      NwGui, v8::String::New("clipboard.js"), IDR_NW_API_CLIPBOARD_JS);
  RequireFromResource(args.This(),
      NwGui, v8::String::New("window.js"), IDR_NW_API_WINDOW_JS);
  RequireFromResource(args.This(),
      NwGui, v8::String::New("shell.js"), IDR_NW_API_SHELL_JS);
  RequireFromResource(args.This(),
      NwGui, v8::String::New("app.js"), IDR_NW_API_APP_JS);

  return scope.Close(NwGui);
}

// static
v8::Handle<v8::Value>
DispatcherBindings::GetNextObjectId(const v8::Arguments& args) {
  static int next_object_id = 1;
  return v8::Integer::New(next_object_id++);
}

// static
v8::Handle<v8::Value>
DispatcherBindings::GetAbsolutePath(const v8::Arguments& args) {
  FilePath path = FilePath::FromUTF8Unsafe(*v8::String::Utf8Value(args[0]));
  MakePathAbsolute(&path);
#if defined(OS_POSIX)
  return v8::String::New(path.value().c_str());
#else
  return v8::String::New(path.AsUTF8Unsafe().c_str());
#endif
}

// static
v8::Handle<v8::Value>
DispatcherBindings::GetHiddenValue(const v8::Arguments& args) {
  return args.This()->GetHiddenValue(args[0]->ToString());
}

// static
v8::Handle<v8::Value>
DispatcherBindings::SetHiddenValue(const v8::Arguments& args) {
  args.This()->SetHiddenValue(args[0]->ToString(), args[1]);
  return v8::Undefined();
}

// static
v8::Handle<v8::Value>
DispatcherBindings::GetConstructorName(const v8::Arguments& args) {
  if (args.Length() < 1 || !args[0]->IsObject())
    return v8::Undefined();

  return args[0]->ToObject()->GetConstructorName();
}

// static
v8::Handle<v8::Value>
DispatcherBindings::SetDestructor(const v8::Arguments& args) {
  ObjectLifeMonitor::BindTo(args.This(), args[0]);
  return v8::Undefined();
}

// static
v8::Handle<v8::Value>
DispatcherBindings::AllocateObject(const v8::Arguments& args) {
  if (args.Length() < 3) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "AllocateObject requries 3 arguments")));
  }

  int object_id = args[0]->Int32Value();
  std::string name = *v8::String::Utf8Value(args[1]);

  scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
  converter->SetStripNullFromObjects(true);

  scoped_ptr<base::Value> value_option(
      converter->FromV8Value(args[2], v8::Context::GetCurrent()));
  if (!value_option.get() ||
      !value_option->IsType(base::Value::TYPE_DICTIONARY)) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to convert 'option' passed to AllocateObject")));
  }

  RenderView* render_view = GetCurrentRenderView();
  if (!render_view) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to get render view in AllocateObject")));
  }

  render_view->Send(new ShellViewHostMsg_Allocate_Object(
        render_view->GetRoutingID(),
        object_id,
        name,
        *static_cast<base::DictionaryValue*>(value_option.get())));
  return v8::Undefined();
}

// static
v8::Handle<v8::Value>
DispatcherBindings::DeallocateObject(const v8::Arguments& args) {
  if (args.Length() < 1) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "DeallocateObject requries 1 arguments")));
  }

  int object_id = args[0]->Int32Value();

  RenderView* render_view = GetCurrentRenderView();
  if (!render_view) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to get render view in DeallocateObject")));
  }

  render_view->Send(new ShellViewHostMsg_Deallocate_Object(
        render_view->GetRoutingID(), object_id));
  return v8::Undefined();
}

// static
v8::Handle<v8::Value>
DispatcherBindings::CallObjectMethod(const v8::Arguments& args) {
  if (args.Length() < 4) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "CallObjectMethod requries 4 arguments")));
  }

  int object_id = args[0]->Int32Value();
  std::string type = *v8::String::Utf8Value(args[1]);
  std::string method = *v8::String::Utf8Value(args[2]);

  scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());

  scoped_ptr<base::Value> value_args(
      converter->FromV8Value(args[3], v8::Context::GetCurrent()));
  if (!value_args.get() ||
      !value_args->IsType(base::Value::TYPE_LIST)) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to convert 'args' passed to CallObjectMethod")));
  }

  RenderView* render_view = GetCurrentRenderView();
  if (!render_view) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to get render view in CallObjectMethod")));
  }

  render_view->Send(new ShellViewHostMsg_Call_Object_Method(
        render_view->GetRoutingID(),
        object_id,
        type,
        method,
        *static_cast<base::ListValue*>(value_args.get())));
  return v8::Undefined();
}

// static
v8::Handle<v8::Value> DispatcherBindings::CallObjectMethodSync(
    const v8::Arguments& args) {
  if (args.Length() < 4) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "CallObjectMethodSync requries 4 arguments")));
  }

  int object_id = args[0]->Int32Value();
  std::string type = *v8::String::Utf8Value(args[1]);
  std::string method = *v8::String::Utf8Value(args[2]);

  scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());

  scoped_ptr<base::Value> value_args(
      converter->FromV8Value(args[3], v8::Context::GetCurrent()));
  if (!value_args.get() ||
      !value_args->IsType(base::Value::TYPE_LIST)) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to convert 'args' passed to CallObjectMethodSync")));
  }

  RenderView* render_view = GetCurrentRenderView();
  if (!render_view) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to get render view in CallObjectMethodSync")));
  }

  base::ListValue result;
  render_view->Send(new ShellViewHostMsg_Call_Object_Method_Sync(
        MSG_ROUTING_NONE,
        object_id,
        type,
        method,
        *static_cast<base::ListValue*>(value_args.get()),
        &result));
  return converter->ToV8Value(&result, v8::Context::GetCurrent());
}

// static
v8::Handle<v8::Value> DispatcherBindings::CallStaticMethod(
    const v8::Arguments& args) {
  if (args.Length() < 3) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "CallStaticMethod requries 3 arguments")));
  }

  std::string type = *v8::String::Utf8Value(args[0]);
  std::string method = *v8::String::Utf8Value(args[1]);

  scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());

  scoped_ptr<base::Value> value_args(
      converter->FromV8Value(args[2], v8::Context::GetCurrent()));
  if (!value_args.get() ||
      !value_args->IsType(base::Value::TYPE_LIST)) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to convert 'args' passed to CallStaticMethod")));
  }

  RenderView* render_view = GetCurrentRenderView();
  if (!render_view) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to get render view in CallStaticMethod")));
  }

  render_view->Send(new ShellViewHostMsg_Call_Static_Method(
        render_view->GetRoutingID(),
        type,
        method,
        *static_cast<base::ListValue*>(value_args.get())));
  return v8::Undefined();
}

// static
v8::Handle<v8::Value> DispatcherBindings::CallStaticMethodSync(
    const v8::Arguments& args) {
  if (args.Length() < 3) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "CallStaticMethodSync requries 3 arguments")));
  }

  std::string type = *v8::String::Utf8Value(args[0]);
  std::string method = *v8::String::Utf8Value(args[1]);

  scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());

  scoped_ptr<base::Value> value_args(
      converter->FromV8Value(args[2], v8::Context::GetCurrent()));
  if (!value_args.get() ||
      !value_args->IsType(base::Value::TYPE_LIST)) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to convert 'args' passed to CallStaticMethodSync")));
  }

  RenderView* render_view = GetCurrentRenderView();
  if (!render_view) {
    return v8::ThrowException(v8::Exception::Error(v8::String::New(
            "Unable to get render view in CallStaticMethodSync")));
  }

  base::ListValue result;
  render_view->Send(new ShellViewHostMsg_Call_Static_Method_Sync(
        MSG_ROUTING_NONE,
        type,
        method,
        *static_cast<base::ListValue*>(value_args.get()),
        &result));
  return converter->ToV8Value(&result, v8::Context::GetCurrent());
}

}  // 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/media/media_stream_devices_controller.h"

#include "base/logging.h"
#include "base/values.h"

#include <algorithm>

namespace {

// A predicate that checks if a StreamDeviceInfo object has the same ID as the
// device ID specified at construction.
class DeviceIdEquals {
 public:
  explicit DeviceIdEquals(const std::string& device_id)
      : device_id_(device_id) {
  }

  bool operator() (const content::MediaStreamDevice& device) {
    return device.device_id == device_id_;
  }

 private:
  std::string device_id_;
};

// A predicate that checks if a StreamDeviceInfo object has the same device
// name as the device name specified at construction.
class DeviceNameEquals {
 public:
  explicit DeviceNameEquals(const std::string& device_name)
      : device_name_(device_name) {
  }

  bool operator() (const content::MediaStreamDevice& device) {
    return device.name == device_name_;
  }

 private:
  std::string device_name_;
};

// Whether |request| contains any device of given |type|.
bool HasDevice(const content::MediaStreamRequest& request,
               content::MediaStreamDeviceType type) {
  content::MediaStreamDeviceMap::const_iterator device_it =
      request.devices.find(type);
  return device_it != request.devices.end() && !device_it->second.empty();
}

const char kAudioKey[] = "audio";
const char kVideoKey[] = "video";

}  // namespace

MediaStreamDevicesController::MediaStreamDevicesController(
    const content::MediaStreamRequest* request,
    const content::MediaResponseCallback& callback)
    : request_(*request),
      callback_(callback) {
  for (content::MediaStreamDeviceMap::const_iterator it =
           request_.devices.begin();
       it != request_.devices.end(); ++it) {
    if (content::IsAudioMediaType(it->first)) {
      has_audio_ |= !it->second.empty();
    } else if (content::IsVideoMediaType(it->first)) {
      has_video_ |= !it->second.empty();
    }
  }
}

MediaStreamDevicesController::~MediaStreamDevicesController() {}

bool MediaStreamDevicesController::DismissInfoBarAndTakeActionOnSettings() {
  // Deny the request and don't show the infobar if there is no devices.
  if (!has_audio_ && !has_video_) {
    Deny();
    return true;
  }

  std::string audio, video;
  GetAlwaysAllowedDevices(&audio, &video);
  Accept(audio, video, true);
  return true;
}

void MediaStreamDevicesController::Accept(const std::string& audio_id,
                                          const std::string& video_id,
                                          bool always_allow) {
  content::MediaStreamDevices devices;
  std::string audio_device, video_device;
  if (has_audio_) {
    AddDeviceWithId(content::MEDIA_DEVICE_AUDIO_CAPTURE,
                    audio_id, &devices, &audio_device);
  }
  if (has_video_) {
    AddDeviceWithId(content::MEDIA_DEVICE_VIDEO_CAPTURE,
                    video_id, &devices, &video_device);
  }
  DCHECK(!devices.empty());

  callback_.Run(devices);
}

void MediaStreamDevicesController::Deny() {
  callback_.Run(content::MediaStreamDevices());
}

void MediaStreamDevicesController::AddDeviceWithId(
    content::MediaStreamDeviceType type,
    const std::string& id,
    content::MediaStreamDevices* devices,
    std::string* device_name) {
  DCHECK(devices);
  content::MediaStreamDeviceMap::const_iterator device_it =
      request_.devices.find(type);
  if (device_it == request_.devices.end())
    return;

  content::MediaStreamDevices::const_iterator it = std::find_if(
      device_it->second.begin(), device_it->second.end(), DeviceIdEquals(id));
  if (it == device_it->second.end())
    return;

  devices->push_back(*it);
  *device_name = it->name;
}

void MediaStreamDevicesController::GetAlwaysAllowedDevices(
    std::string* audio_id, std::string* video_id) {
  DCHECK(audio_id->empty());
  DCHECK(video_id->empty());
  if (has_audio_) {
    *audio_id =
        GetFirstDeviceId(content::MEDIA_DEVICE_AUDIO_CAPTURE);
  }
  if (has_video_) {
    *video_id =
        GetFirstDeviceId(content::MEDIA_DEVICE_VIDEO_CAPTURE);
  }
}

std::string MediaStreamDevicesController::GetDeviceIdByName(
    content::MediaStreamDeviceType type,
    const std::string& name) {
  content::MediaStreamDeviceMap::const_iterator device_it =
      request_.devices.find(type);
  if (device_it != request_.devices.end()) {
    content::MediaStreamDevices::const_iterator it = std::find_if(
        device_it->second.begin(), device_it->second.end(),
        DeviceNameEquals(name));
    if (it != device_it->second.end())
      return it->device_id;
  }

  // Device is not available, return an empty string.
  return std::string();
}

std::string MediaStreamDevicesController::GetFirstDeviceId(
    content::MediaStreamDeviceType type) {
  content::MediaStreamDeviceMap::const_iterator device_it =
      request_.devices.find(type);
  if (device_it != request_.devices.end())
    return device_it->second.begin()->device_id;

  return std::string();
}


var common = require('../common');
var assert = common.assert;
var fake = common.fake.create();
var DelayedStream = common.DelayedStream;
var Stream = require('stream').Stream;

(function testMaxDataSize() {
  var source = new Stream();
  var delayedStream = DelayedStream.create(source, {maxDataSize: 1024, pauseStream: false});

  source.emit('data', new Buffer(1024));

  fake
    .expect(delayedStream, 'emit')
    .withArg(1, 'error');
  source.emit('data', new Buffer(1));
  fake.verify();
})();


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

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

#include "base/values.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/api/menuitem/menuitem.h"
#include "content/nw/src/nw_shell.h"

namespace api {

Menu::Menu(int id,
           DispatcherHost* dispatcher_host,
           const base::DictionaryValue& option)
    : Base(id, dispatcher_host, option) {
  Create(option);
}

Menu::~Menu() {
  Destroy();
}

void Menu::Call(const std::string& method,
                const base::ListValue& arguments) {
  if (method == "Append") {
    int object_id = 0;
    arguments.GetInteger(0, &object_id);
    Append(dispatcher_host()->GetObject<MenuItem>(object_id));
  } else if (method == "Insert") {
    int object_id = 0;
    arguments.GetInteger(0, &object_id);
    int pos = 0;
    arguments.GetInteger(1, &pos);
    Insert(dispatcher_host()->GetObject<MenuItem>(object_id), pos);
  } else if (method == "Remove") {
    int object_id = 0;
    arguments.GetInteger(0, &object_id);
    int pos = 0;
    arguments.GetInteger(1, &pos);
    Remove(dispatcher_host()->GetObject<MenuItem>(object_id), pos);
  } else if (method == "Popup") {
    int x = 0;
    arguments.GetInteger(0, &x);
    int y = 0;
    arguments.GetInteger(1, &y);
    Popup(x, y, content::Shell::FromRenderViewHost(
          dispatcher_host()->render_view_host()));
  } else {
    NOTREACHED() << "Invalid call to Menu method:" << method
                 << " arguments:" << arguments;
  }
}

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

var nwDispatcher = nwDispatcher || {};

(function() {
  native function RequireNwGui();
  native function GetNextObjectId();
  native function GetAbsolutePath();

  native function AllocateObject();
  native function DeallocateObject();
  native function CallObjectMethod();
  native function CallObjectMethodSync();
  native function CallStaticMethod();
  native function CallStaticMethodSync();

  native function GetConstructorName();
  native function GetHiddenValue();
  native function SetHiddenValue();
  native function SetDestructor();

  nwDispatcher.requireNwGui = RequireNwGui;

  // Request a new object from browser
  nwDispatcher.allocateObject = function(object, option) {
    var id = GetNextObjectId();
    AllocateObject(id, GetConstructorName(object), option);

    // Store object id and make it readonly
    Object.defineProperty(object, 'id', {
      value: id,
      writable: false
    });

    // Deallcoate on destroy
    object.setDestructor(nwDispatcher.deallocateObject);

    // Store id to object relations, there is no delete in deallocateObject
    // since this is a weak map.
    global.__nwObjectsRegistry.set(id, object);
  }

  // Free a object in browser
  nwDispatcher.deallocateObject = function(object) {
    DeallocateObject(object.id);
  };

  // Call method of a object in browser.
  nwDispatcher.callObjectMethod = function(object, method, args) {
    CallObjectMethod(object.id, GetConstructorName(object), method, args);
  };

  // Call sync method of a object in browser and return results.
  nwDispatcher.callObjectMethodSync = function(object, method, args) {
    return CallObjectMethodSync(
        object.id, GetConstructorName(object), method, args);
  };

  // Call a static method.
  nwDispatcher.callStaticMethod = CallStaticMethod;

  // Call a sync method of static class in browse and return.
  nwDispatcher.callStaticMethodSync = CallStaticMethodSync;

  nwDispatcher.handleEvent = function(object_id, ev, args) {
    var object = global.__nwObjectsRegistry.get(object_id);
    args.splice(0, 0, ev);
    object.handleEvent.apply(object, args);
  }

  nwDispatcher.getAbsolutePath = GetAbsolutePath;
  nwDispatcher.getConstructorName = GetConstructorName;

  // Extended prototype of objects.
  nwDispatcher.getHiddenValue = GetHiddenValue;
  nwDispatcher.setHiddenValue = SetHiddenValue;
  nwDispatcher.setDestructor = SetDestructor;
  nwDispatcher.inherits = function(ctor, superCtor) {
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  };
})();


// 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_STREAM_DEVICES_CONTROLLER_H_
#define CONTENT_NW_SRC_MEDIA_MEDIA_STREAM_DEVICES_CONTROLLER_H_

#include <string>

#include "content/public/browser/web_contents_delegate.h"

class GURL;

class MediaStreamDevicesController {
 public:
  // TODO(xians): Use const content::MediaStreamRequest& instead of *.
  MediaStreamDevicesController(const content::MediaStreamRequest* request,
                               const content::MediaResponseCallback& callback);

  virtual ~MediaStreamDevicesController();

  // Public method to be called before creating the MediaStreamInfoBarDelegate.
  // This function will check the content settings exceptions and take the
  // corresponding action on exception which matches the request.
  bool DismissInfoBarAndTakeActionOnSettings();

  // Public methods to be called by MediaStreamInfoBarDelegate;
  bool has_audio() const { return has_audio_; }
  bool has_video() const { return has_video_; }
  void Accept(const std::string& audio_id,
              const std::string& video_id,
              bool always_allow);
  void Deny();

 private:
  // Used by the various helper methods below to filter an operation on devices
  // of a particular type.
  typedef bool (*FilterByDeviceTypeFunc)(content::MediaStreamDeviceType);

  // Finds a device in the current request with the specified |id| and |type|,
  // adds it to the |devices| array and also return the name of the device.
  void AddDeviceWithId(content::MediaStreamDeviceType type,
                       const std::string& id,
                       content::MediaStreamDevices* devices,
                       std::string* device_name);

  // Gets the respective "always allowed" devices for the origin in |request_|.
  // |audio_id| and |video_id| will be empty if there is no "always allowed"
  // device for the origin, or any of the devices is not listed on the devices
  // list in |request_|.
  void GetAlwaysAllowedDevices(std::string* audio_id,
                               std::string* video_id);

  std::string GetDeviceIdByName(content::MediaStreamDeviceType type,
                                const std::string& name);

  std::string GetFirstDeviceId(content::MediaStreamDeviceType type);

  bool has_audio_;
  bool has_video_;

  // The original request for access to devices.
  const content::MediaStreamRequest request_;

  // The callback that needs to be Run to notify WebRTC of whether access to
  // audio/video devices was granted or not.
  content::MediaResponseCallback callback_;
  DISALLOW_COPY_AND_ASSIGN(MediaStreamDevicesController);
};

#endif  // CONTENT_NW_SRC_MEDIA_MEDIA_STREAM_DEVICES_CONTROLLER_H_


var common = module.exports;

var path = require('path');
var root = path.join(__dirname, '..');

common.dir = {
  fixture: root + '/test/fixture',
  tmp: root + '/test/tmp',
};

common.CombinedStream = require(root);
common.assert = require('assert');


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

#ifndef CONTENT_NW_SRC_API_DISPATCHER_HOST_H_
#define CONTENT_NW_SRC_API_DISPATCHER_HOST_H_

#include "base/basictypes.h"
#include "base/id_map.h"
#include "content/public/browser/render_view_host_observer.h"

#include <string>

namespace base {
class DictionaryValue;
class ListValue;
}

namespace WebKit {
class WebFrame;
}

namespace api {

class Base;

class DispatcherHost : public content::RenderViewHostObserver {
 public:
  explicit DispatcherHost(content::RenderViewHost* render_view_host);
  virtual ~DispatcherHost();

  // Get C++ object from its id.
  Base* GetObject(int id);

  // Helper function to convert type.
  template<class T>
  T* GetObject(int id) {
    return static_cast<T*>(GetObject(id));
  }

  // Send event to C++ object's corresponding js object.
  void SendEvent(Base* object,
                 const std::string& event,
                 const base::ListValue& arguments);

  virtual bool Send(IPC::Message* message) OVERRIDE;
  content::RenderViewHost* render_view_host() const {
    return content::RenderViewHostObserver::render_view_host();
  }

 private:
  IDMap<Base, IDMapOwnPointer> objects_registry_;

  // RenderViewHostObserver implementation.
  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;

  void OnAllocateObject(int object_id,
                        const std::string& type,
                        const base::DictionaryValue& option);
  void OnDeallocateObject(int object_id);
  void OnCallObjectMethod(int object_id,
                          const std::string& type,
                          const std::string& method,
                          const base::ListValue& arguments);
  void OnCallObjectMethodSync(int object_id,
                              const std::string& type,
                              const std::string& method,
                              const base::ListValue& arguments,
                              base::ListValue* result);
  void OnCallStaticMethod(const std::string& type,
                          const std::string& method,
                          const base::ListValue& arguments);
  void OnCallStaticMethodSync(const std::string& type,
                              const std::string& method,
                              const base::ListValue& arguments,
                              base::ListValue* result);
  void OnUncaughtException(const std::string& err);

  DISALLOW_COPY_AND_ASSIGN(DispatcherHost);
};

}  // namespace api

#endif  // CONTENT_NW_SRC_API_DISPATCHER_HOST_H_


nwDispatcher.allocateObject = function(object, option) {

keep keep keep keep replace keep keep keep

var id = global.__nwObjectsRegistry.allocateId();

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

#ifndef CONTENT_NW_SRC_API_DISPATCHER_BINDINGS_H_
#define CONTENT_NW_SRC_API_DISPATCHER_BINDINGS_H_

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "v8/include/v8.h"

namespace api {

class DispatcherBindings : public v8::Extension {
 public:
  DispatcherBindings();
  virtual ~DispatcherBindings();

  // v8::Extension implementation.
  virtual v8::Handle<v8::FunctionTemplate>
      GetNativeFunction(v8::Handle<v8::String> name) OVERRIDE;

 private:
  // Helper functions for bindings.
  static v8::Handle<v8::Value> RequireNwGui(const v8::Arguments& args);
  static v8::Handle<v8::Value> GetIDWeakMapConstructor(
      const v8::Arguments& args);
  static v8::Handle<v8::Value> GetNextObjectId(const v8::Arguments& args);
  static v8::Handle<v8::Value> GetAbsolutePath(const v8::Arguments& args);

  // Extended prototype of objects.
  static v8::Handle<v8::Value> GetHiddenValue(const v8::Arguments& args);
  static v8::Handle<v8::Value> SetHiddenValue(const v8::Arguments& args);
  static v8::Handle<v8::Value> GetConstructorName(const v8::Arguments& args);
  static v8::Handle<v8::Value> SetDestructor(const v8::Arguments& args);

  // Remote objects.
  static v8::Handle<v8::Value> AllocateObject(const v8::Arguments& args);
  static v8::Handle<v8::Value> DeallocateObject(const v8::Arguments& args);
  static v8::Handle<v8::Value> CallObjectMethod(const v8::Arguments& args);
  static v8::Handle<v8::Value> CallObjectMethodSync(const v8::Arguments& args);
  static v8::Handle<v8::Value> CallStaticMethod(const v8::Arguments& args);
  static v8::Handle<v8::Value> CallStaticMethodSync(const v8::Arguments& args);

  DISALLOW_COPY_AND_ASSIGN(DispatcherBindings);
};

}  // namespace api

#endif  // CONTENT_NW_SRC_API_DISPATCHER_BINDINGS_H_


form-data

A module to create readable `"multipart/form-data"` streams.  Can be used to submit forms and file uploads to other web applications.


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

#include "base/memory/scoped_ptr.h"
#include "base/string16.h"
#include "base/stringprintf.h"
#include "media/base/media_log.h"
#include "media/base/media_log_event.h"

MediaInternals* MediaInternals::GetInstance() {
  return Singleton<MediaInternals>::get();
}

MediaInternals::~MediaInternals() {}

void MediaInternals::OnDeleteAudioStream(void* host, int stream_id) {
}

void MediaInternals::OnSetAudioStreamPlaying(
    void* host, int stream_id, bool playing) {
}

void MediaInternals::OnSetAudioStreamStatus(
    void* host, int stream_id, const std::string& status) {
}

void MediaInternals::OnSetAudioStreamVolume(
    void* host, int stream_id, double volume) {
}

void MediaInternals::OnMediaEvent(
    int render_process_id, const media::MediaLogEvent& event) {
}

void MediaInternals::OnCaptureDevicesOpened(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
}

void MediaInternals::OnCaptureDevicesClosed(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevices& devices) {
}

void MediaInternals::OnMediaRequestStateChanged(
    int render_process_id,
    int render_view_id,
    const content::MediaStreamDevice& device,
    content::MediaRequestState state) {
}

MediaInternals::MediaInternals() {}


var common = require('../common');
var assert = common.assert;
var CombinedStream = common.CombinedStream;
var fs = require('fs');

var FILE1 = common.dir.fixture + '/file1.txt';
var FILE2 = common.dir.fixture + '/file2.txt';
var EXPECTED = fs.readFileSync(FILE1) + fs.readFileSync(FILE2);

(function testDelayedStreams() {
  var combinedStream = CombinedStream.create({pauseStreams: false});
  combinedStream.append(fs.createReadStream(FILE1));
  combinedStream.append(fs.createReadStream(FILE2));

  var stream1 = combinedStream._streams[0];
  var stream2 = combinedStream._streams[1];

  stream1.on('end', function() {
    assert.ok(stream2.dataSize > 0);
  });

  var tmpFile = common.dir.tmp + '/combined.txt';
  var dest = fs.createWriteStream(tmpFile);
  combinedStream.pipe(dest);

  dest.on('end', function() {
    var written = fs.readFileSync(tmpFile, 'utf8');
    assert.strictEqual(written, EXPECTED);
  });
})();


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

keep keep replace replace keep keep keep keep

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

#ifndef CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_
#define CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_

#include <string>
#include <map>

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

namespace printing {
class PrintJobManager;
}

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 WebContentsViewPort* OverrideCreateWebContentsView(
      WebContents* web_contents,
      RenderViewHostDelegateView** render_view_host_delegate_view) OVERRIDE;
  virtual std::string GetApplicationLocale() OVERRIDE;
  virtual void AppendExtraCommandLineSwitches(CommandLine* command_line,
                                              int child_process_id) OVERRIDE;
  virtual void ResourceDispatcherHostCreated() OVERRIDE;
  virtual AccessTokenStore* CreateAccessTokenStore() OVERRIDE;
  virtual void OverrideWebkitPrefs(
      RenderViewHost* render_view_host,
      const GURL& url,
      webkit_glue::WebPreferences* prefs) OVERRIDE;
  virtual std::string GetDefaultDownloadName() OVERRIDE;
  virtual MediaObserver* GetMediaObserver() OVERRIDE;
  virtual void BrowserURLHandlerCreated(BrowserURLHandler* handler) OVERRIDE;
  virtual bool ShouldTryToUseExistingProcessHost(
      BrowserContext* browser_context, const GURL& url) OVERRIDE;
  virtual bool IsSuitableHost(RenderProcessHost* process_host,
                              const GURL& site_url) OVERRIDE;
  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_;
  }
  virtual printing::PrintJobManager* print_job_manager();
  virtual void RenderProcessHostCreated(RenderProcessHost* host) OVERRIDE;
  virtual net::URLRequestContextGetter* CreateRequestContext(
      BrowserContext* browser_context,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          blob_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          file_system_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          developer_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          chrome_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          chrome_devtools_protocol_handler) OVERRIDE;
  virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
      BrowserContext* browser_context,
      const base::FilePath& partition_path,
      bool in_memory,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          blob_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          file_system_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          developer_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          chrome_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          chrome_devtools_protocol_handler) OVERRIDE;

 private:
  ShellBrowserContext* ShellBrowserContextForBrowserContext(
      BrowserContext* content_browser_context);
  scoped_ptr<ShellResourceDispatcherHostDelegate>
      resource_dispatcher_host_delegate_;

  ShellBrowserMainParts* shell_browser_main_parts_;
};

}  // namespace content

#endif  // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_


function assert() {
  var str = '';
  str += ('' + arguments[arguments.length - 1] + ': ');

  var result = true;
  for (var i = 0; i < arguments.length - 1; ++i) {
    if (!arguments[i]) {
      result = false;
      str += ('FAILED');
      str += (' at condition ' + (i + 1) + ' ');
    }
  }

  if (result) {
    str = '
' + str + 'PASSED';
  } else {
    str = '
' + str;
  }

  str += '
';

  $(document.body).append(str);
}


// 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_NET_SHELL_NETWORK_DELEGATE_H_
#define CONTENT_NW_SRC_NET_SHELL_NETWORK_DELEGATE_H_

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "net/base/network_delegate.h"

namespace content {

class ShellNetworkDelegate : public net::NetworkDelegate {
 public:
  ShellNetworkDelegate();
  virtual ~ShellNetworkDelegate();

 private:
  // net::NetworkDelegate implementation.
  virtual int OnBeforeURLRequest(net::URLRequest* request,
                                 const net::CompletionCallback& callback,
                                 GURL* new_url) OVERRIDE;
  virtual int OnBeforeSendHeaders(net::URLRequest* request,
                                  const net::CompletionCallback& callback,
                                  net::HttpRequestHeaders* headers) OVERRIDE;
  virtual void OnSendHeaders(net::URLRequest* request,
                             const net::HttpRequestHeaders& headers) OVERRIDE;
  virtual int OnHeadersReceived(
      net::URLRequest* request,
      const net::CompletionCallback& callback,
      const net::HttpResponseHeaders* original_response_headers,
      scoped_refptr<net::HttpResponseHeaders>*
          override_response_headers) OVERRIDE;
  virtual void OnBeforeRedirect(net::URLRequest* request,
                                const GURL& new_location) OVERRIDE;
  virtual void OnResponseStarted(net::URLRequest* request) OVERRIDE;
  virtual void OnRawBytesRead(const net::URLRequest& request,
                              int bytes_read) OVERRIDE;
  virtual void OnCompleted(net::URLRequest* request, bool started) OVERRIDE;
  virtual void OnURLRequestDestroyed(net::URLRequest* request) OVERRIDE;
  virtual void OnPACScriptError(int line_number,
                                const string16& error) OVERRIDE;
  virtual AuthRequiredResponse OnAuthRequired(
      net::URLRequest* request,
      const net::AuthChallengeInfo& auth_info,
      const AuthCallback& callback,
      net::AuthCredentials* credentials) OVERRIDE;
  virtual bool OnCanGetCookies(const net::URLRequest& request,
                               const net::CookieList& cookie_list) OVERRIDE;
  virtual bool OnCanSetCookie(const net::URLRequest& request,
                              const std::string& cookie_line,
                              net::CookieOptions* options) OVERRIDE;
  virtual bool OnCanAccessFile(const net::URLRequest& request,
                               const base::FilePath& path) const OVERRIDE;
  virtual bool OnCanThrottleRequest(
      const net::URLRequest& request) const OVERRIDE;
  virtual int OnBeforeSocketStreamConnect(
      net::SocketStream* stream,
      const net::CompletionCallback& callback) OVERRIDE;
  virtual void OnRequestWaitStateChange(const net::URLRequest& request,
                                        RequestWaitState state) OVERRIDE;

  DISALLOW_COPY_AND_ASSIGN(ShellNetworkDelegate);
};

}  // namespace content

#endif  // CONTENT_NW_SRC_NET_SHELL_NETWORK_DELEGATE_H_


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


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

#include "base/logging.h"
#include "base/values.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/nw/src/api/api_messages.h"
#include "content/nw/src/api/app/app.h"
#include "content/nw/src/api/base/base.h"
#include "content/nw/src/api/clipboard/clipboard.h"
#include "content/nw/src/api/menu/menu.h"
#include "content/nw/src/api/menuitem/menuitem.h"
#include "content/nw/src/api/shell/shell.h"
#include "content/nw/src/api/tray/tray.h"
#include "content/nw/src/api/window/window.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/nw/src/nw_shell.h"
#include "content/public/browser/render_process_host.h"

using content::WebContents;
using content::ShellBrowserContext;

namespace api {

DispatcherHost::DispatcherHost(content::RenderViewHost* render_view_host)
    : content::RenderViewHostObserver(render_view_host) {
}

DispatcherHost::~DispatcherHost() {
}

Base* DispatcherHost::GetApiObject(int id) {
  return objects_registry_.Lookup(id);
}

void DispatcherHost::SendEvent(Base* object,
                               const std::string& event,
                               const base::ListValue& arguments) {
  Send(new ShellViewMsg_Object_On_Event(
       routing_id(), object->id(), event, arguments));
}

bool DispatcherHost::Send(IPC::Message* message) {
  return content::RenderViewHostObserver::Send(message);
}

bool DispatcherHost::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(DispatcherHost, message)
    IPC_MESSAGE_HANDLER(ShellViewHostMsg_Allocate_Object, OnAllocateObject)
    IPC_MESSAGE_HANDLER(ShellViewHostMsg_Deallocate_Object, OnDeallocateObject)
    IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method, OnCallObjectMethod)
    IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Object_Method_Sync,
                        OnCallObjectMethodSync)
    IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method, OnCallStaticMethod)
    IPC_MESSAGE_HANDLER(ShellViewHostMsg_Call_Static_Method_Sync,
                        OnCallStaticMethodSync)
    IPC_MESSAGE_HANDLER(ShellViewHostMsg_UncaughtException,
                        OnUncaughtException);
    IPC_MESSAGE_HANDLER(ShellViewHostMsg_GetShellId, OnGetShellId);
    IPC_MESSAGE_HANDLER(ShellViewHostMsg_CreateShell, OnCreateShell);
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void DispatcherHost::OnAllocateObject(int object_id,
                                      const std::string& type,
                                      const base::DictionaryValue& option) {
  DVLOG(1) << "OnAllocateObject: object_id:" << object_id
             << " type:" << type
             << " option:" << option;

  if (type == "Menu") {
    objects_registry_.AddWithID(new Menu(object_id, this, option), object_id);
  } else if (type == "MenuItem") {
    objects_registry_.AddWithID(
        new MenuItem(object_id, this, option), object_id);
  } else if (type == "Tray") {
    objects_registry_.AddWithID(new Tray(object_id, this, option), object_id);
  } else if (type == "Clipboard") {
    objects_registry_.AddWithID(
        new Clipboard(object_id, this, option), object_id);
  } else if (type == "Window") {
    objects_registry_.AddWithID(new Window(object_id, this, option), object_id);
  } else {
    LOG(ERROR) << "Allocate an object of unknow type: " << type;
    objects_registry_.AddWithID(new Base(object_id, this, option), object_id);
  }
}

void DispatcherHost::OnDeallocateObject(int object_id) {
  DLOG(INFO) << "OnDeallocateObject: object_id:" << object_id;
  objects_registry_.Remove(object_id);
}

void DispatcherHost::OnCallObjectMethod(
    int object_id,
    const std::string& type,
    const std::string& method,
    const base::ListValue& arguments) {
  DLOG(INFO) << "OnCallObjectMethod: object_id:" << object_id
             << " type:" << type
             << " method:" << method
             << " arguments:" << arguments;

  Base* object = GetApiObject(object_id);
  DCHECK(object) << "Unknown object: " << object_id;
  object->Call(method, arguments);
}

void DispatcherHost::OnCallObjectMethodSync(
    int object_id,
    const std::string& type,
    const std::string& method,
    const base::ListValue& arguments,
    base::ListValue* result) {
  DLOG(INFO) << "OnCallObjectMethodSync: object_id:" << object_id
             << " type:" << type
             << " method:" << method
             << " arguments:" << arguments;

  Base* object = GetApiObject(object_id);
  DCHECK(object) << "Unknown object: " << object_id;
  object->CallSync(method, arguments, result);
}

void DispatcherHost::OnCallStaticMethod(
    const std::string& type,
    const std::string& method,
    const base::ListValue& arguments) {
  DLOG(INFO) << "OnCallStaticMethod: "
             << " type:" << type
             << " method:" << method
             << " arguments:" << arguments;

  if (type == "Shell") {
    api::Shell::Call(method, arguments);
    return;
  } else if (type == "App") {
    api::App::Call(method, arguments);
    return;
  }

  NOTREACHED() << "Calling unknown method " << method << " of class " << type;
}

void DispatcherHost::OnCallStaticMethodSync(
    const std::string& type,
    const std::string& method,
    const base::ListValue& arguments,
    base::ListValue* result) {
  DLOG(INFO) << "OnCallStaticMethodSync: "
             << " type:" << type
             << " method:" << method
             << " arguments:" << arguments;

  if (type == "App") {
    content::Shell* shell =
        content::Shell::FromRenderViewHost(render_view_host());
    api::App::Call(shell, method, arguments, result);
    return;
  }

  NOTREACHED() << "Calling unknown method " << method << " of class " << type;
}

void DispatcherHost::OnUncaughtException(const std::string& err) {
  content::Shell* shell =
      content::Shell::FromRenderViewHost(render_view_host());
  shell->PrintCriticalError("Uncaught node.js Error", err);
}

void DispatcherHost::OnGetShellId(int* id) {
  content::Shell* shell =
      content::Shell::FromRenderViewHost(render_view_host());
  *id = shell->id();
}

void DispatcherHost::OnCreateShell(const std::string& url,
                                   const base::DictionaryValue& manifest,
                                   int* routing_id) {
  WebContents* base_web_contents =
      content::Shell::FromRenderViewHost(render_view_host())->web_contents();
  ShellBrowserContext* browser_context =
      static_cast<ShellBrowserContext*>(base_web_contents->GetBrowserContext());
  scoped_ptr<base::DictionaryValue> new_manifest(manifest.DeepCopy());
  bool new_renderer = false;
  if (new_manifest->GetBoolean(switches::kmNewInstance,
                               &new_renderer) && new_renderer)
    browser_context->set_pinning_renderer(false);

  WebContents::CreateParams create_params(browser_context,
                                          new_renderer ? NULL : base_web_contents->GetSiteInstance());

  WebContents* web_contents = content::WebContentsImpl::CreateWithOpener(
      create_params,
      static_cast<content::WebContentsImpl*>(base_web_contents));
  new content::Shell(web_contents, new_manifest.get());
  web_contents->GetController().LoadURL(
      GURL(url),
      content::Referrer(),
      content::PAGE_TRANSITION_TYPED,
      std::string());

  if (new_renderer)
    browser_context->set_pinning_renderer(true);

  *routing_id = web_contents->GetRoutingID();
}

}  // namespace api


import sys,os,re

nw_version_h = os.path.join(os.path.dirname(__file__), '..', 'src',
    'nw_version.h')

f = open(nw_version_h)

for line in f:
  if re.match('#define NW_VERSION_IS_RELEASE', line):
    release = int(line.split()[2])
    #print release


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

// Get basic type definitions.
#define IPC_MESSAGE_IMPL
#include "content/nw/src/common/common_message_generator.h"

// Generate constructors.
#include "ipc/struct_constructor_macros.h"
#include "content/nw/src/common/common_message_generator.h"

// Generate destructors.
#include "ipc/struct_destructor_macros.h"
#include "content/nw/src/common/common_message_generator.h"

// Generate param traits write methods.
#include "ipc/param_traits_write_macros.h"
namespace IPC {
#include "content/nw/src/common/common_message_generator.h"
}  // namespace IPC

// Generate param traits read methods.
#include "ipc/param_traits_read_macros.h"
namespace IPC {
#include "content/nw/src/common/common_message_generator.h"
}  // namespace IPC

// Generate param traits log methods.
#include "ipc/param_traits_log_macros.h"
namespace IPC {
#include "content/nw/src/common/common_message_generator.h"
}  // namespace IPC


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

#include "base/string_piece.h"
#include "content/nw/src/api/api_messages.h"
#include "content/nw/src/renderer/common/render_messages.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/user_agent/user_agent_util.h"

namespace content {

ShellContentClient::~ShellContentClient() {
}

std::string ShellContentClient::GetUserAgent() const {
  return webkit_glue::BuildUserAgentFromProduct("Chrome/27.0.1430.0");
}

string16 ShellContentClient::GetLocalizedString(int message_id) const {
  return l10n_util::GetStringUTF16(message_id);
}

base::StringPiece ShellContentClient::GetDataResource(
    int resource_id,
    ui::ScaleFactor scale_factor) const {
  return ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
      resource_id, scale_factor);
}

base::RefCountedStaticMemory* ShellContentClient::GetDataResourceBytes(
    int resource_id) const {
  return ResourceBundle::GetSharedInstance().LoadDataResourceBytes(resource_id);
}

gfx::Image& ShellContentClient::GetNativeImageNamed(int resource_id) const {
  return ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}

// This is for message handling after the rvh is swapped out
// FIXME: move dispatcher_host to WebContentsObserver

bool ShellContentClient::CanHandleWhileSwappedOut(
    const IPC::Message& msg) {
  switch (msg.type()) {
    case ShellViewHostMsg_Allocate_Object::ID:
    case ShellViewHostMsg_Deallocate_Object::ID:
    case ShellViewHostMsg_Call_Object_Method::ID:
    case ShellViewHostMsg_Call_Object_Method_Sync::ID:
    case ShellViewHostMsg_Call_Static_Method::ID:
    case ShellViewHostMsg_Call_Static_Method_Sync::ID:
    case ShellViewHostMsg_UncaughtException::ID:
    case ShellViewHostMsg_GetShellId::ID:
    case ShellViewHostMsg_CreateShell::ID:
      return true;
    default:
      break;
  }
  return false;
}

}  // namespace content


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


  <title> Hello World </title>

this is node-webkit


// 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 "base/bind.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "net/base/auth.h"
#include "net/url_request/url_request.h"
#include "ui/base/text/text_elider.h"

namespace content {

ShellLoginDialog::ShellLoginDialog(
    net::AuthChallengeInfo* auth_info,
    net::URLRequest* request) : auth_info_(auth_info),
                                request_(request) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ShellLoginDialog::PrepDialog, this,
                 ASCIIToUTF16(auth_info->challenger.ToString()),
                 UTF8ToUTF16(auth_info->realm)));
}

void ShellLoginDialog::OnRequestCancelled() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ShellLoginDialog::PlatformRequestCancelled, this));
}

void ShellLoginDialog::UserAcceptedAuth(const string16& username,
                                        const string16& password) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&ShellLoginDialog::SendAuthToRequester, this,
                 true, username, password));
}

void ShellLoginDialog::UserCancelledAuth() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&ShellLoginDialog::SendAuthToRequester, this,
                 false, string16(), string16()));
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ShellLoginDialog::PlatformCleanUp, this));
}

ShellLoginDialog::~ShellLoginDialog() {
  // Cannot post any tasks here; this object is going away and cannot be
  // referenced/dereferenced.
}

void ShellLoginDialog::PrepDialog(const string16& host,
                                  const string16& realm) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // The realm is controlled by the remote server, so there is no reason to
  // believe it is of a reasonable length.
  string16 elided_realm;
  ui::ElideString(realm, 120, &elided_realm);

  string16 explanation =
      ASCIIToUTF16("The server ") + host +
      ASCIIToUTF16(" requires a username and password.");

  if (!elided_realm.empty()) {
    explanation += ASCIIToUTF16(" The server says: ");
    explanation += elided_realm;
    explanation += ASCIIToUTF16(".");
  }

  PlatformCreateDialog(explanation);
}

void ShellLoginDialog::SendAuthToRequester(bool success,
                                           const string16& username,
                                           const string16& password) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  if (success)
    request_->SetAuth(net::AuthCredentials(username, password));
  else
    request_->CancelAuth();
  ResourceDispatcherHost::Get()->ClearLoginDelegateForRequest(request_);

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ShellLoginDialog::PlatformCleanUp, this));
}

}  // namespace content