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 using namespace v8; 18 19 #include "SkTypes.h" 20 #include "SkEvent.h" 21 22 class SkOSWindow; 23 24 typedef Persistent<Function, CopyablePersistentTraits<Function> > CopyablePersistentFn; 25 26 // Provides the global isolate and context for our V8 instance. 27 // Also implements all the global level functions. 28 class Global : SkNoncopyable { 29 public: Global(Isolate * isolate)30 Global(Isolate* isolate) 31 : fIsolate(isolate) 32 , fWindow(NULL) 33 , fLastTimerID(0) 34 { 35 gGlobal = this; 36 this->initialize(); 37 } ~Global()38 virtual ~Global() {} 39 40 // The script will be parsed into the context this Global contains. 41 bool parseScript(const char script[]); 42 getContext()43 Local<Context> getContext() { 44 return Local<Context>::New(fIsolate, fContext); 45 } 46 getIsolate()47 Isolate* getIsolate() { 48 return fIsolate; 49 } 50 setWindow(SkOSWindow * win)51 void setWindow(SkOSWindow* win) { 52 fWindow = win; 53 } getWindow()54 SkOSWindow* getWindow() { 55 return fWindow; 56 } 57 58 void reportException(TryCatch* tryCatch); 59 60 private: 61 void initialize(); 62 Handle<Context> createRootContext(); 63 int32_t getNextTimerID(); 64 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 78 // 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; 83 }; 84 85 #endif 86