event.cc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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/render_frame_host.h"
  8. #include "content/public/browser/web_contents.h"
  9. #include "native_mate/object_template_builder.h"
  10. namespace mate {
  11. Event::Event(v8::Isolate* isolate) {
  12. Init(isolate);
  13. }
  14. Event::~Event() {}
  15. void Event::SetSenderAndMessage(content::RenderFrameHost* sender,
  16. IPC::Message* message) {
  17. DCHECK(!sender_);
  18. DCHECK(!message_);
  19. sender_ = sender;
  20. message_ = message;
  21. Observe(content::WebContents::FromRenderFrameHost(sender));
  22. }
  23. void Event::RenderFrameDeleted(content::RenderFrameHost* rfh) {
  24. if (sender_ != rfh)
  25. return;
  26. sender_ = nullptr;
  27. message_ = nullptr;
  28. }
  29. void Event::RenderFrameHostChanged(content::RenderFrameHost* old_rfh,
  30. content::RenderFrameHost* new_rfh) {
  31. if (sender_ && sender_ == old_rfh)
  32. sender_ = new_rfh;
  33. }
  34. void Event::FrameDeleted(content::RenderFrameHost* rfh) {
  35. if (sender_ != rfh)
  36. return;
  37. sender_ = nullptr;
  38. message_ = nullptr;
  39. }
  40. void Event::PreventDefault(v8::Isolate* isolate) {
  41. GetWrapper()->Set(StringToV8(isolate, "defaultPrevented"), v8::True(isolate));
  42. }
  43. bool Event::SendReply(const base::string16& json) {
  44. if (message_ == nullptr || sender_ == nullptr)
  45. return false;
  46. AtomFrameHostMsg_Message_Sync::WriteReplyParams(message_, json);
  47. bool success = sender_->Send(message_);
  48. message_ = nullptr;
  49. sender_ = nullptr;
  50. return success;
  51. }
  52. // static
  53. Handle<Event> Event::Create(v8::Isolate* isolate) {
  54. return mate::CreateHandle(isolate, new Event(isolate));
  55. }
  56. // static
  57. void Event::BuildPrototype(v8::Isolate* isolate,
  58. v8::Local<v8::FunctionTemplate> prototype) {
  59. prototype->SetClassName(mate::StringToV8(isolate, "Event"));
  60. mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
  61. .SetMethod("preventDefault", &Event::PreventDefault)
  62. .SetMethod("sendReply", &Event::SendReply);
  63. }
  64. } // namespace mate