1 // Copyright (c) 2012 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 
5 #ifndef CHROME_BROWSER_EXTENSIONS_API_MESSAGING_NATIVE_MESSAGE_PORT_H_
6 #define CHROME_BROWSER_EXTENSIONS_API_MESSAGING_NATIVE_MESSAGE_PORT_H_
7 
8 #include "base/memory/ref_counted.h"
9 #include "base/memory/weak_ptr.h"
10 #include "base/threading/thread_checker.h"
11 #include "extensions/browser/api/messaging/message_port.h"
12 #include "extensions/common/api/messaging/port_id.h"
13 
14 namespace base {
15 class SingleThreadTaskRunner;
16 }
17 
18 namespace extensions {
19 class NativeMessageHost;
20 
21 // A port that manages communication with a native application.
22 // All methods must be called on the UI Thread of the browser process.
23 class NativeMessagePort : public MessagePort {
24  public:
25   NativeMessagePort(base::WeakPtr<ChannelDelegate> channel_delegate,
26                     const PortId& port_id,
27                     std::unique_ptr<NativeMessageHost> native_message_host);
28   ~NativeMessagePort() override;
29 
30   // MessagePort implementation.
31   bool IsValidPort() override;
32   void DispatchOnMessage(const Message& message) override;
33 
34  private:
35   class Core;
36   void PostMessageFromNativeHost(const std::string& message);
37   void CloseChannel(const std::string& error_message);
38 
39   base::ThreadChecker thread_checker_;
40   base::WeakPtr<ChannelDelegate> weak_channel_delegate_;
41   scoped_refptr<base::SingleThreadTaskRunner> host_task_runner_;
42   const PortId port_id_;
43   std::unique_ptr<Core> core_;
44 
45   base::WeakPtrFactory<NativeMessagePort> weak_factory_{this};
46 };
47 
48 }  // namespace extensions
49 
50 #endif  // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_NATIVE_MESSAGE_PORT_H_
51