1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "extensions/renderer/activity_log_converter_strategy.h"
6
7#include "base/logging.h"
8#include "base/values.h"
9#include "v8/include/v8.h"
10
11namespace extensions {
12
13namespace {
14
15// Summarize a V8 value. This performs a shallow conversion in all cases, and
16// returns only a string with a description of the value (e.g.,
17// "[HTMLElement]").
18scoped_ptr<base::Value> SummarizeV8Value(v8::Isolate* isolate,
19                                         v8::Handle<v8::Object> object) {
20  v8::TryCatch try_catch;
21  v8::Isolate::DisallowJavascriptExecutionScope scope(
22      isolate, v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
23  v8::Local<v8::String> name = v8::String::NewFromUtf8(isolate, "[");
24  if (object->IsFunction()) {
25    name =
26        v8::String::Concat(name, v8::String::NewFromUtf8(isolate, "Function"));
27    v8::Local<v8::Value> fname =
28        v8::Handle<v8::Function>::Cast(object)->GetName();
29    if (fname->IsString() && v8::Handle<v8::String>::Cast(fname)->Length()) {
30      name = v8::String::Concat(name, v8::String::NewFromUtf8(isolate, " "));
31      name = v8::String::Concat(name, v8::Handle<v8::String>::Cast(fname));
32      name = v8::String::Concat(name, v8::String::NewFromUtf8(isolate, "()"));
33    }
34  } else {
35    name = v8::String::Concat(name, object->GetConstructorName());
36  }
37  name = v8::String::Concat(name, v8::String::NewFromUtf8(isolate, "]"));
38
39  if (try_catch.HasCaught()) {
40    return scoped_ptr<base::Value>(
41        new base::StringValue("[JS Execution Exception]"));
42  }
43
44  return scoped_ptr<base::Value>(
45      new base::StringValue(std::string(*v8::String::Utf8Value(name))));
46}
47
48}  // namespace
49
50ActivityLogConverterStrategy::ActivityLogConverterStrategy() {}
51
52ActivityLogConverterStrategy::~ActivityLogConverterStrategy() {}
53
54bool ActivityLogConverterStrategy::FromV8Object(
55    v8::Handle<v8::Object> value,
56    base::Value** out,
57    v8::Isolate* isolate,
58    const FromV8ValueCallback& callback) const {
59  return FromV8Internal(value, out, isolate, callback);
60}
61
62bool ActivityLogConverterStrategy::FromV8Array(
63    v8::Handle<v8::Array> value,
64    base::Value** out,
65    v8::Isolate* isolate,
66    const FromV8ValueCallback& callback) const {
67  return FromV8Internal(value, out, isolate, callback);
68}
69
70bool ActivityLogConverterStrategy::FromV8Internal(
71    v8::Handle<v8::Object> value,
72    base::Value** out,
73    v8::Isolate* isolate,
74    const FromV8ValueCallback& callback) const {
75  scoped_ptr<base::Value> parsed_value;
76  parsed_value = SummarizeV8Value(isolate, value);
77  *out = parsed_value.release();
78
79  return true;
80}
81
82}  // namespace extensions
83