runner.h revision f2477e01787aa58f445919b809d89e252beef54f
1// Copyright 2013 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#ifndef GIN_RUNNER_H_
6#define GIN_RUNNER_H_
7
8#include <string>
9
10#include "base/memory/weak_ptr.h"
11#include "gin/context_holder.h"
12
13namespace gin {
14
15class Runner;
16class TryCatch;
17
18// Subclass RunnerDelegate to customize the behavior of |Runner|. Typical
19// embedders will want to subclass one of the specialized RunnerDelegates,
20// such as ModuleRunnerDelegate.
21class RunnerDelegate {
22 public:
23  RunnerDelegate();
24  virtual ~RunnerDelegate();
25
26  // Returns the template for the global object.
27  virtual v8::Handle<v8::ObjectTemplate> GetGlobalTemplate(Runner* runner);
28  virtual void DidCreateContext(Runner* runner);
29  virtual void WillRunScript(Runner* runner);
30  virtual void DidRunScript(Runner* runner);
31  virtual void UnhandledException(Runner* runner, TryCatch& try_catch);
32};
33
34// Runner lets you run code in a v8::Context. Upon construction, Runner will
35// create a v8::Context. Upon destruction, Runner will dispose the context.
36class Runner : public ContextHolder {
37 public:
38  Runner(RunnerDelegate* delegate, v8::Isolate* isolate);
39  ~Runner();
40
41  // Before running script in this context, you'll need to enter the runner's
42  // context by creating an instance of Runner::Scope on the stack.
43  void Run(const std::string& source, const std::string& resource_name);
44  void Run(v8::Handle<v8::Script> script);
45
46  v8::Handle<v8::Value> Call(v8::Handle<v8::Function> function,
47                             v8::Handle<v8::Value> receiver,
48                             int argc,
49                             v8::Handle<v8::Value> argv[]);
50
51  v8::Handle<v8::Object> global() const {
52    return context()->Global();
53  }
54
55  // Useful for running script in this context asynchronously. Rather than
56  // holding a raw pointer to the runner, consider holding a WeakPtr.
57  base::WeakPtr<Runner> GetWeakPtr() {
58    return weak_factory_.GetWeakPtr();
59  }
60
61  class Scope {
62   public:
63    explicit Scope(Runner* runner);
64    ~Scope();
65
66   private:
67    v8::Isolate::Scope isolate_scope_;
68    v8::HandleScope handle_scope_;
69    v8::Context::Scope scope_;
70
71    DISALLOW_COPY_AND_ASSIGN(Scope);
72  };
73
74 private:
75  friend class Scope;
76
77  RunnerDelegate* delegate_;
78
79  base::WeakPtrFactory<Runner> weak_factory_;
80
81  DISALLOW_COPY_AND_ASSIGN(Runner);
82};
83
84}  // namespace gin
85
86#endif  // GIN_RUNNER_H_
87