runner.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. #ifndef GIN_RUNNER_H_
  5. #define GIN_RUNNER_H_
  6. #include <string>
  7. #include "base/memory/weak_ptr.h"
  8. #include "gin/gin_export.h"
  9. #include "gin/public/context_holder.h"
  10. #include "v8/include/v8-forward.h"
  11. #include "v8/include/v8-isolate.h"
  12. namespace gin {
  13. // Runner is responsible for running code in a v8::Context.
  14. class GIN_EXPORT Runner {
  15. public:
  16. Runner();
  17. Runner(const Runner&) = delete;
  18. Runner& operator=(const Runner&) = delete;
  19. virtual ~Runner();
  20. // Before running script in this context, you'll need to enter the runner's
  21. // context by creating an instance of Runner::Scope on the stack.
  22. virtual v8::MaybeLocal<v8::Value> Run(const std::string& source,
  23. const std::string& resource_name) = 0;
  24. virtual ContextHolder* GetContextHolder() = 0;
  25. v8::Local<v8::Object> global() {
  26. return GetContextHolder()->context()->Global();
  27. }
  28. // Useful for running script in this context asynchronously. Rather than
  29. // holding a raw pointer to the runner, consider holding a WeakPtr.
  30. base::WeakPtr<Runner> GetWeakPtr() {
  31. return weak_factory_.GetWeakPtr();
  32. }
  33. class GIN_EXPORT Scope {
  34. public:
  35. explicit Scope(Runner* runner);
  36. Scope(const Scope&) = delete;
  37. Scope& operator=(const Scope&) = delete;
  38. ~Scope();
  39. private:
  40. v8::Isolate::Scope isolate_scope_;
  41. v8::HandleScope handle_scope_;
  42. v8::Context::Scope scope_;
  43. };
  44. private:
  45. friend class Scope;
  46. base::WeakPtrFactory<Runner> weak_factory_{this};
  47. };
  48. } // namespace gin
  49. #endif // GIN_RUNNER_H_