b5e480dfc9d32ac63e2949043b0a509c64c36e76
[platform/framework/web/crosswalk.git] / src / remoting / client / plugin / chromoting_instance.h
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 // TODO(ajwong): We need to come up with a better description of the
6 // responsibilities for each thread.
7
8 #ifndef REMOTING_CLIENT_PLUGIN_CHROMOTING_INSTANCE_H_
9 #define REMOTING_CLIENT_PLUGIN_CHROMOTING_INSTANCE_H_
10
11 #include <string>
12
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/weak_ptr.h"
16 #include "ppapi/c/pp_instance.h"
17 #include "ppapi/c/pp_rect.h"
18 #include "ppapi/c/pp_resource.h"
19 #include "ppapi/cpp/instance.h"
20 #include "ppapi/cpp/var.h"
21 #include "remoting/client/client_context.h"
22 #include "remoting/client/client_user_interface.h"
23 #include "remoting/client/key_event_mapper.h"
24 #include "remoting/client/plugin/media_source_video_renderer.h"
25 #include "remoting/client/plugin/normalizing_input_filter.h"
26 #include "remoting/client/plugin/pepper_input_handler.h"
27 #include "remoting/client/plugin/pepper_plugin_thread_delegate.h"
28 #include "remoting/proto/event.pb.h"
29 #include "remoting/protocol/client_stub.h"
30 #include "remoting/protocol/clipboard_stub.h"
31 #include "remoting/protocol/connection_to_host.h"
32 #include "remoting/protocol/cursor_shape_stub.h"
33 #include "remoting/protocol/input_event_tracker.h"
34 #include "remoting/protocol/mouse_input_filter.h"
35 #include "remoting/protocol/negotiating_client_authenticator.h"
36 #include "remoting/protocol/third_party_client_authenticator.h"
37
38 namespace base {
39 class DictionaryValue;
40 }  // namespace base
41
42 namespace pp {
43 class InputEvent;
44 class Module;
45 }  // namespace pp
46
47 namespace webrtc {
48 class DesktopRegion;
49 class DesktopSize;
50 class DesktopVector;
51 }  // namespace webrtc
52
53 namespace remoting {
54
55 class ChromotingClient;
56 class ChromotingStats;
57 class ClientContext;
58 class DelegatingSignalStrategy;
59 class FrameConsumer;
60 class FrameConsumerProxy;
61 class PepperAudioPlayer;
62 class PepperTokenFetcher;
63 class PepperView;
64 class RectangleUpdateDecoder;
65 class SignalStrategy;
66 class VideoRenderer;
67
68 struct ClientConfig;
69
70 class ChromotingInstance :
71       public ClientUserInterface,
72       public MediaSourceVideoRenderer::Delegate,
73       public protocol::ClipboardStub,
74       public protocol::CursorShapeStub,
75       public pp::Instance {
76  public:
77   // Plugin API version. This should be incremented whenever the API
78   // interface changes.
79   static const int kApiVersion = 7;
80
81   // Plugin API features. This allows orthogonal features to be supported
82   // without bumping the API version.
83   static const char kApiFeatures[];
84
85   // Capabilities supported by the plugin that should also be supported by the
86   // webapp to be enabled.
87   static const char kRequestedCapabilities[];
88
89   // Capabilities supported by the plugin that do not need to be supported by
90   // the webapp to be enabled.
91   static const char kSupportedCapabilities[];
92
93   // Backward-compatibility version used by for the messaging
94   // interface. Should be updated whenever we remove support for
95   // an older version of the API.
96   static const int kApiMinMessagingVersion = 5;
97
98   // Backward-compatibility version used by for the ScriptableObject
99   // interface. Should be updated whenever we remove support for
100   // an older version of the API.
101   static const int kApiMinScriptableVersion = 5;
102
103   // Helper method to parse authentication_methods parameter.
104   static bool ParseAuthMethods(const std::string& auth_methods,
105                                ClientConfig* config);
106
107   explicit ChromotingInstance(PP_Instance instance);
108   virtual ~ChromotingInstance();
109
110   // pp::Instance interface.
111   virtual void DidChangeFocus(bool has_focus) OVERRIDE;
112   virtual void DidChangeView(const pp::View& view) OVERRIDE;
113   virtual bool Init(uint32_t argc, const char* argn[],
114                     const char* argv[]) OVERRIDE;
115   virtual void HandleMessage(const pp::Var& message) OVERRIDE;
116   virtual bool HandleInputEvent(const pp::InputEvent& event) OVERRIDE;
117
118   // ClientUserInterface interface.
119   virtual void OnConnectionState(protocol::ConnectionToHost::State state,
120                                  protocol::ErrorCode error) OVERRIDE;
121   virtual void OnConnectionReady(bool ready) OVERRIDE;
122   virtual void OnRouteChanged(const std::string& channel_name,
123                               const protocol::TransportRoute& route) OVERRIDE;
124   virtual void SetCapabilities(const std::string& capabilities) OVERRIDE;
125   virtual void SetPairingResponse(
126       const protocol::PairingResponse& pairing_response) OVERRIDE;
127   virtual void DeliverHostMessage(
128       const protocol::ExtensionMessage& message) OVERRIDE;
129   virtual protocol::ClipboardStub* GetClipboardStub() OVERRIDE;
130   virtual protocol::CursorShapeStub* GetCursorShapeStub() OVERRIDE;
131   virtual scoped_ptr<protocol::ThirdPartyClientAuthenticator::TokenFetcher>
132   GetTokenFetcher(const std::string& host_public_key) OVERRIDE;
133
134   // protocol::ClipboardStub interface.
135   virtual void InjectClipboardEvent(
136       const protocol::ClipboardEvent& event) OVERRIDE;
137
138   // protocol::CursorShapeStub interface.
139   virtual void SetCursorShape(
140       const protocol::CursorShapeInfo& cursor_shape) OVERRIDE;
141
142   // Called by PepperView.
143   void SetDesktopSize(const webrtc::DesktopSize& size,
144                       const webrtc::DesktopVector& dpi);
145   void SetDesktopShape(const webrtc::DesktopRegion& shape);
146   void OnFirstFrameReceived();
147
148   // Return statistics record by ChromotingClient.
149   // If no connection is currently active then NULL will be returned.
150   ChromotingStats* GetStats();
151
152   // Registers a global log message handler that redirects the log output to
153   // our plugin instance.
154   // This is called by the plugin's PPP_InitializeModule.
155   // Note that no logging will be processed unless a ChromotingInstance has been
156   // registered for logging (see RegisterLoggingInstance).
157   static void RegisterLogMessageHandler();
158
159   // Registers this instance so it processes messages sent by the global log
160   // message handler. This overwrites any previously registered instance.
161   void RegisterLoggingInstance();
162
163   // Unregisters this instance so that debug log messages will no longer be sent
164   // to it. If this instance is not the currently registered logging instance,
165   // then the currently registered instance will stay in effect.
166   void UnregisterLoggingInstance();
167
168   // A Log Message Handler that is called after each LOG message has been
169   // processed. This must be of type LogMessageHandlerFunction defined in
170   // base/logging.h.
171   static bool LogToUI(int severity, const char* file, int line,
172                       size_t message_start, const std::string& str);
173
174   // Requests the webapp to fetch a third-party token.
175   void FetchThirdPartyToken(
176       const GURL& token_url,
177       const std::string& host_public_key,
178       const std::string& scope,
179       const base::WeakPtr<PepperTokenFetcher> pepper_token_fetcher);
180
181  private:
182   FRIEND_TEST_ALL_PREFIXES(ChromotingInstanceTest, TestCaseSetup);
183
184   // Used as the |FetchSecretCallback| for IT2Me (or Me2Me from old webapps).
185   // Immediately calls |secret_fetched_callback| with |shared_secret|.
186   static void FetchSecretFromString(
187       const std::string& shared_secret,
188       bool pairing_supported,
189       const protocol::SecretFetchedCallback& secret_fetched_callback);
190
191   // Message handlers for messages that come from JavaScript. Called
192   // from HandleMessage().
193   void HandleConnect(const base::DictionaryValue& data);
194   void HandleDisconnect(const base::DictionaryValue& data);
195   void HandleOnIncomingIq(const base::DictionaryValue& data);
196   void HandleReleaseAllKeys(const base::DictionaryValue& data);
197   void HandleInjectKeyEvent(const base::DictionaryValue& data);
198   void HandleRemapKey(const base::DictionaryValue& data);
199   void HandleTrapKey(const base::DictionaryValue& data);
200   void HandleSendClipboardItem(const base::DictionaryValue& data);
201   void HandleNotifyClientResolution(const base::DictionaryValue& data);
202   void HandlePauseVideo(const base::DictionaryValue& data);
203   void HandlePauseAudio(const base::DictionaryValue& data);
204   void HandleOnPinFetched(const base::DictionaryValue& data);
205   void HandleOnThirdPartyTokenFetched(const base::DictionaryValue& data);
206   void HandleRequestPairing(const base::DictionaryValue& data);
207   void HandleExtensionMessage(const base::DictionaryValue& data);
208   void HandleAllowMouseLockMessage();
209   void HandleEnableMediaSourceRendering();
210
211   // Helper method called from Connect() to connect with parsed config.
212   void ConnectWithConfig(const ClientConfig& config,
213                          const std::string& local_jid);
214
215   // Helper method to post messages to the webapp.
216   void PostChromotingMessage(const std::string& method,
217                              const pp::VarDictionary& data);
218
219   // Same as above, but serializes messages to JSON before sending them.  This
220   // method is used for backward compatibility with older version of the webapp
221   // that expect to received most messages formatted using JSON.
222   //
223   // TODO(sergeyu): When all current versions of the webapp support raw messages
224   // remove this method and use PostChromotingMessage() instead.
225   void PostLegacyJsonMessage(const std::string& method,
226                        scoped_ptr<base::DictionaryValue> data);
227
228   // Posts trapped keys to the web-app to handle.
229   void SendTrappedKey(uint32 usb_keycode, bool pressed);
230
231   // Callback for DelegatingSignalStrategy.
232   void SendOutgoingIq(const std::string& iq);
233
234   void SendPerfStats();
235
236   void ProcessLogToUI(const std::string& message);
237
238   // Returns true if the hosting content has the chrome-extension:// scheme.
239   bool IsCallerAppOrExtension();
240
241   // Returns true if there is a ConnectionToHost and it is connected.
242   bool IsConnected();
243
244   // Used as the |FetchSecretCallback| for Me2Me connections.
245   // Uses the PIN request dialog in the webapp to obtain the shared secret.
246   void FetchSecretFromDialog(
247       bool pairing_supported,
248       const protocol::SecretFetchedCallback& secret_fetched_callback);
249
250   // MediaSourceVideoRenderer::Delegate implementation.
251   virtual void OnMediaSourceSize(const webrtc::DesktopSize& size,
252                                  const webrtc::DesktopVector& dpi) OVERRIDE;
253   virtual void OnMediaSourceShape(const webrtc::DesktopRegion& shape) OVERRIDE;
254   virtual void OnMediaSourceReset(const std::string& format) OVERRIDE;
255   virtual void OnMediaSourceData(uint8_t* buffer, size_t buffer_size) OVERRIDE;
256
257   bool initialized_;
258
259   PepperPluginThreadDelegate plugin_thread_delegate_;
260   scoped_refptr<PluginThreadTaskRunner> plugin_task_runner_;
261   ClientContext context_;
262   scoped_ptr<VideoRenderer> video_renderer_;
263   scoped_ptr<PepperView> view_;
264   scoped_ptr<base::WeakPtrFactory<FrameConsumer> > view_weak_factory_;
265   pp::View plugin_view_;
266
267   // Contains the most-recently-reported desktop shape, if any.
268   scoped_ptr<webrtc::DesktopRegion> desktop_shape_;
269
270   scoped_ptr<DelegatingSignalStrategy> signal_strategy_;
271
272   scoped_ptr<protocol::ConnectionToHost> host_connection_;
273   scoped_ptr<ChromotingClient> client_;
274
275   // Input pipeline components, in reverse order of distance from input source.
276   protocol::MouseInputFilter mouse_input_filter_;
277   protocol::InputEventTracker input_tracker_;
278   KeyEventMapper key_mapper_;
279   scoped_ptr<protocol::InputFilter> normalizing_input_filter_;
280   PepperInputHandler input_handler_;
281
282   // PIN Fetcher.
283   bool use_async_pin_dialog_;
284   protocol::SecretFetchedCallback secret_fetched_callback_;
285
286   // Set to true if the webapp has requested to use MediaSource API for
287   // rendering. In that case all the encoded video will be passed to the
288   // webapp for decoding.
289   bool use_media_source_rendering_;
290
291   base::WeakPtr<PepperTokenFetcher> pepper_token_fetcher_;
292
293   // Weak reference to this instance, used for global logging and task posting.
294   base::WeakPtrFactory<ChromotingInstance> weak_factory_;
295
296   DISALLOW_COPY_AND_ASSIGN(ChromotingInstance);
297 };
298
299 }  // namespace remoting
300
301 #endif  // REMOTING_CLIENT_PLUGIN_CHROMOTING_INSTANCE_H_