event.cc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) 2014 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/browser/api/event.h"
  5. #include "atom/common/api/api_messages.h"
  6. #include "atom/common/native_mate_converters/string16_converter.h"
  7. #include "content/public/browser/web_contents.h"
  8. #include "native_mate/object_template_builder.h"
  9. namespace mate {
  10. Event::Event(v8::Isolate* isolate)
  11. : sender_(nullptr),
  12. message_(nullptr) {
  13. Init(isolate);
  14. }
  15. Event::~Event() {
  16. }
  17. void Event::SetSenderAndMessage(content::WebContents* sender,
  18. IPC::Message* message) {
  19. DCHECK(!sender_);
  20. DCHECK(!message_);
  21. sender_ = sender;
  22. message_ = message;
  23. Observe(sender);
  24. }
  25. void Event::WebContentsDestroyed() {
  26. sender_ = nullptr;
  27. message_ = nullptr;
  28. }
  29. void Event::PreventDefault(v8::Isolate* isolate) {
  30. GetWrapper()->Set(StringToV8(isolate, "defaultPrevented"),
  31. v8::True(isolate));
  32. }
  33. bool Event::SendReply(const base::string16& json) {
  34. if (message_ == nullptr || sender_ == nullptr)
  35. return false;
  36. AtomViewHostMsg_Message_Sync::WriteReplyParams(message_, json);
  37. bool success = sender_->Send(message_);
  38. message_ = nullptr;
  39. sender_ = nullptr;
  40. return success;
  41. }
  42. // static
  43. Handle<Event> Event::Create(v8::Isolate* isolate) {
  44. return mate::CreateHandle(isolate, new Event(isolate));
  45. }
  46. // static
  47. void Event::BuildPrototype(
  48. v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) {
  49. prototype->SetClassName(mate::StringToV8(isolate, "Event"));
  50. mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
  51. .SetMethod("preventDefault", &Event::PreventDefault)
  52. .SetMethod("sendReply", &Event::SendReply);
  53. }
  54. } // namespace mate