1 /* 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 13 #include <map> 14 15 #include <v8.h> 16 17 18 #include "SkTypes.h" 19 #include "SkEvent.h" 20 21 class SkOSWindow; 22 23 typedef v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > CopyablePersistentFn; 24 25 // Provides the global isolate and context for our V8 instance. 26 // Also implements all the global level functions. 27 class Global : SkNoncopyable { 28 public: 29 Global(v8::Isolate* isolate) 30 : fIsolate(isolate) 31 , fWindow(NULL) 32 , fLastTimerID(0) 33 { 34 gGlobal = this; 35 this->initialize(); 36 } 37 virtual ~Global() {} 38 39 // The script will be parsed into the context this Global contains. 40 bool parseScript(const char script[]); 41 42 v8::Local<v8::Context> getContext() { 43 return v8::Local<v8::Context>::New(fIsolate, fContext); 44 } 45 46 v8::Isolate* getIsolate() { 47 return fIsolate; 48 } 49 50 void setWindow(SkOSWindow* win) { 51 fWindow = win; 52 } 53 SkOSWindow* getWindow() { 54 return fWindow; 55 } 56 57 void reportException(v8::TryCatch* tryCatch); 58 59 private: 60 void initialize(); 61 v8::Handle<v8::Context> createRootContext(); 62 int32_t getNextTimerID(); 63 64 static bool TimeOutProc(const SkEvent& evt); 65 66 // Static functions that implement the global JS functions we add to 67 // the context. 68 static void SetTimeout(const v8::FunctionCallbackInfo<v8::Value>& args); 69 static void Print(const v8::FunctionCallbackInfo<v8::Value>& args); 70 static void Inval(const v8::FunctionCallbackInfo<v8::Value>& args); 71 72 v8::Persistent<v8::Context> fContext; 73 v8::Isolate* fIsolate; 74 SkOSWindow* fWindow; 75 static Global* gGlobal; 76 77 // Handle to the functions to call when a timeout triggers as indexed by id. 78 std::map<int32_t, CopyablePersistentFn > fTimeouts; 79 80 // Last timer ID generated. 81 int32_t fLastTimerID; 82 }; 83 84 #endif 85