blob: 6bd3c7096239dc65bde1dde8f69c070265adcf2e [file] [log] [blame]
commit-bot@chromium.org0fc0dea2013-12-18 04:45:37 +00001/*
2 * Copyright 2013 Google Inc.
3 *
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 *
8 */
9
10#ifndef SkV8Example_Global_DEFINED
11#define SkV8Example_Global_DEFINED
12
commit-bot@chromium.org872796b2013-12-20 15:56:52 +000013#include <map>
14
commit-bot@chromium.org0fc0dea2013-12-18 04:45:37 +000015#include <v8.h>
16
17using namespace v8;
18
19#include "SkTypes.h"
20#include "SkEvent.h"
21
22class SkOSWindow;
23
commit-bot@chromium.org872796b2013-12-20 15:56:52 +000024typedef Persistent<Function, CopyablePersistentTraits<Function> > CopyablePersistentFn;
25
commit-bot@chromium.org0fc0dea2013-12-18 04:45:37 +000026// Provides the global isolate and context for our V8 instance.
27// Also implements all the global level functions.
28class Global : SkNoncopyable {
29public:
30 Global(Isolate* isolate)
31 : fIsolate(isolate)
32 , fWindow(NULL)
commit-bot@chromium.org872796b2013-12-20 15:56:52 +000033 , fLastTimerID(0)
commit-bot@chromium.org0fc0dea2013-12-18 04:45:37 +000034 {
35 gGlobal = this;
commit-bot@chromium.orgc8d73282014-01-06 18:17:24 +000036 this->initialize();
commit-bot@chromium.org0fc0dea2013-12-18 04:45:37 +000037 }
38 virtual ~Global() {}
39
40 // The script will be parsed into the context this Global contains.
41 bool parseScript(const char script[]);
42
43 Local<Context> getContext() {
44 return Local<Context>::New(fIsolate, fContext);
45 }
46
47 Isolate* getIsolate() {
48 return fIsolate;
49 }
50
51 void setWindow(SkOSWindow* win) {
52 fWindow = win;
53 }
54 SkOSWindow* getWindow() {
55 return fWindow;
56 }
57
58 void reportException(TryCatch* tryCatch);
59
60private:
commit-bot@chromium.orgc8d73282014-01-06 18:17:24 +000061 void initialize();
commit-bot@chromium.org0fc0dea2013-12-18 04:45:37 +000062 Handle<Context> createRootContext();
commit-bot@chromium.org872796b2013-12-20 15:56:52 +000063 int32_t getNextTimerID();
commit-bot@chromium.org0fc0dea2013-12-18 04:45:37 +000064
65 static bool TimeOutProc(const SkEvent& evt);
66
67 // Static functions that implement the global JS functions we add to
68 // the context.
69 static void SetTimeout(const v8::FunctionCallbackInfo<v8::Value>& args);
70 static void Print(const v8::FunctionCallbackInfo<v8::Value>& args);
71 static void Inval(const v8::FunctionCallbackInfo<Value>& args);
72
73 Persistent<Context> fContext;
74 Isolate* fIsolate;
75 SkOSWindow* fWindow;
76 static Global* gGlobal;
77
commit-bot@chromium.org872796b2013-12-20 15:56:52 +000078 // Handle to the functions to call when a timeout triggers as indexed by id.
79 std::map<int32_t, CopyablePersistentFn > fTimeouts;
80
81 // Last timer ID generated.
82 int32_t fLastTimerID;
commit-bot@chromium.org0fc0dea2013-12-18 04:45:37 +000083};
84
85#endif