web_worker_observer.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (c) 2017 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "atom/renderer/web_worker_observer.h"
  5. #include "atom/common/api/atom_bindings.h"
  6. #include "atom/common/api/event_emitter_caller.h"
  7. #include "atom/common/asar/asar_util.h"
  8. #include "atom/common/node_bindings.h"
  9. #include "base/lazy_instance.h"
  10. #include "base/threading/thread_local.h"
  11. #include "atom/common/node_includes.h"
  12. namespace atom {
  13. namespace {
  14. static base::LazyInstance<
  15. base::ThreadLocalPointer<WebWorkerObserver>>::DestructorAtExit lazy_tls =
  16. LAZY_INSTANCE_INITIALIZER;
  17. } // namespace
  18. // static
  19. WebWorkerObserver* WebWorkerObserver::GetCurrent() {
  20. WebWorkerObserver* self = lazy_tls.Pointer()->Get();
  21. return self ? self : new WebWorkerObserver;
  22. }
  23. WebWorkerObserver::WebWorkerObserver()
  24. : node_bindings_(NodeBindings::Create(NodeBindings::WORKER)),
  25. atom_bindings_(new AtomBindings(node_bindings_->uv_loop())) {
  26. lazy_tls.Pointer()->Set(this);
  27. }
  28. WebWorkerObserver::~WebWorkerObserver() {
  29. lazy_tls.Pointer()->Set(nullptr);
  30. node::FreeEnvironment(node_bindings_->uv_env());
  31. asar::ClearArchives();
  32. }
  33. void WebWorkerObserver::ContextCreated(v8::Local<v8::Context> context) {
  34. v8::Context::Scope context_scope(context);
  35. // Start the embed thread.
  36. node_bindings_->PrepareMessageLoop();
  37. // Setup node environment for each window.
  38. node::Environment* env = node_bindings_->CreateEnvironment(context);
  39. // Add Electron extended APIs.
  40. atom_bindings_->BindTo(env->isolate(), env->process_object());
  41. // Load everything.
  42. node_bindings_->LoadEnvironment(env);
  43. // Make uv loop being wrapped by window context.
  44. node_bindings_->set_uv_env(env);
  45. // Give the node loop a run to make sure everything is ready.
  46. node_bindings_->RunMessageLoop();
  47. }
  48. void WebWorkerObserver::ContextWillDestroy(v8::Local<v8::Context> context) {
  49. node::Environment* env = node::Environment::GetCurrent(context);
  50. if (env)
  51. mate::EmitEvent(env->isolate(), env->process_object(), "exit");
  52. delete this;
  53. }
  54. } // namespace atom