Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 1 | # Mojo C++ Bindings API |
Ken Rockot | 929282c | 2018-05-02 17:07:29 | [diff] [blame] | 2 | This document is a subset of the [Mojo documentation](/mojo/README.md). |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 3 | |
| 4 | [TOC] |
| 5 | |
| 6 | ## Overview |
| 7 | The Mojo C++ Bindings API leverages the |
Ken Rockot | 929282c | 2018-05-02 17:07:29 | [diff] [blame] | 8 | [C++ System API](/mojo/public/cpp/system/README.md) to provide a more natural |
| 9 | set of primitives for communicating over Mojo message pipes. Combined with |
| 10 | generated code from the |
| 11 | [Mojom IDL and bindings generator](/mojo/public/tools/bindings/README.md), users |
| 12 | can easily connect interface clients and implementations across arbitrary intra- |
David Benjamin | 0ff6182 | 2019-04-29 19:00:05 | [diff] [blame] | 13 | and inter-process boundaries. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 14 | |
| 15 | This document provides a detailed guide to bindings API usage with example code |
| 16 | snippets. For a detailed API references please consult the headers in |
Ken Rockot | 929282c | 2018-05-02 17:07:29 | [diff] [blame] | 17 | [//mojo/public/cpp/bindings](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/README.md). |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 18 | |
Oksana Zhuravlova | 70c47af | 2018-07-06 22:48:24 | [diff] [blame] | 19 | For a simplified guide targeted at Chromium developers, see [this |
Ken Rockot | ab03512 | 2019-02-06 00:35:24 | [diff] [blame] | 20 | link](/docs/mojo_and_services.md). |
Erik Chen | 3fdc02bc | 2018-06-28 03:13:48 | [diff] [blame] | 21 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 22 | ## Getting Started |
| 23 | |
| 24 | When a Mojom IDL file is processed by the bindings generator, C++ code is |
| 25 | emitted in a series of `.h` and `.cc` files with names based on the input |
| 26 | `.mojom` file. Suppose we create the following Mojom file at |
Oksana Zhuravlova | d5fea16d | 2018-08-15 00:02:17 | [diff] [blame] | 27 | `//services/db/public/mojom/db.mojom`: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 28 | |
| 29 | ``` |
| 30 | module db.mojom; |
| 31 | |
| 32 | interface Table { |
| 33 | AddRow(int32 key, string data); |
| 34 | }; |
| 35 | |
| 36 | interface Database { |
| 37 | CreateTable(Table& table); |
| 38 | }; |
| 39 | ``` |
| 40 | |
| 41 | And a GN target to generate the bindings in |
Oksana Zhuravlova | d5fea16d | 2018-08-15 00:02:17 | [diff] [blame] | 42 | `//services/db/public/mojom/BUILD.gn`: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 43 | |
| 44 | ``` |
| 45 | import("//mojo/public/tools/bindings/mojom.gni") |
| 46 | |
Oksana Zhuravlova | d5fea16d | 2018-08-15 00:02:17 | [diff] [blame] | 47 | mojom("mojom") { |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 48 | sources = [ |
| 49 | "db.mojom", |
| 50 | ] |
| 51 | } |
| 52 | ``` |
| 53 | |
David 'Digit' Turner | 743836f8 | 2017-10-27 13:04:15 | [diff] [blame] | 54 | Ensure that any target that needs this interface depends on it, e.g. with a line like: |
| 55 | |
| 56 | ``` |
Oksana Zhuravlova | d5fea16d | 2018-08-15 00:02:17 | [diff] [blame] | 57 | deps += [ '//services/db/public/mojom' ] |
David 'Digit' Turner | 743836f8 | 2017-10-27 13:04:15 | [diff] [blame] | 58 | ``` |
| 59 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 60 | If we then build this target: |
| 61 | |
| 62 | ``` |
Oksana Zhuravlova | d5fea16d | 2018-08-15 00:02:17 | [diff] [blame] | 63 | ninja -C out/r services/db/public/mojom |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 64 | ``` |
| 65 | |
| 66 | This will produce several generated source files, some of which are relevant to |
| 67 | C++ bindings. Two of these files are: |
| 68 | |
| 69 | ``` |
Oksana Zhuravlova | d5fea16d | 2018-08-15 00:02:17 | [diff] [blame] | 70 | out/gen/services/db/public/mojom/db.mojom.cc |
| 71 | out/gen/services/db/public/mojom/db.mojom.h |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 72 | ``` |
| 73 | |
| 74 | You can include the above generated header in your sources in order to use the |
| 75 | definitions therein: |
| 76 | |
| 77 | ``` cpp |
Oksana Zhuravlova | d5fea16d | 2018-08-15 00:02:17 | [diff] [blame] | 78 | #include "services/business/public/mojom/factory.mojom.h" |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 79 | |
| 80 | class TableImpl : public db::mojom::Table { |
| 81 | // ... |
| 82 | }; |
| 83 | ``` |
| 84 | |
| 85 | This document covers the different kinds of definitions generated by Mojom IDL |
| 86 | for C++ consumers and how they can effectively be used to communicate across |
| 87 | message pipes. |
| 88 | |
| 89 | *** note |
| 90 | **NOTE:** Using C++ bindings from within Blink code is typically subject to |
| 91 | special constraints which require the use of a different generated header. |
| 92 | For details, see [Blink Type Mapping](#Blink-Type-Mapping). |
| 93 | *** |
| 94 | |
| 95 | ## Interfaces |
| 96 | |
| 97 | Mojom IDL interfaces are translated to corresponding C++ (pure virtual) class |
| 98 | interface definitions in the generated header, consisting of a single generated |
| 99 | method signature for each request message on the interface. Internally there is |
| 100 | also generated code for serialization and deserialization of messages, but this |
| 101 | detail is hidden from bindings consumers. |
| 102 | |
| 103 | ### Basic Usage |
| 104 | |
| 105 | Let's consider a new `//sample/logger.mojom` to define a simple logging |
| 106 | interface which clients can use to log simple string messages: |
| 107 | |
| 108 | ``` cpp |
| 109 | module sample.mojom; |
| 110 | |
| 111 | interface Logger { |
| 112 | Log(string message); |
| 113 | }; |
| 114 | ``` |
| 115 | |
Mehran Mahmoudi | 0f7e56f3 | 2019-10-31 19:23:27 | [diff] [blame] | 116 | Running this through the bindings generator will produce a `logger.mojom.h` |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 117 | with the following definitions (modulo unimportant details): |
| 118 | |
| 119 | ``` cpp |
| 120 | namespace sample { |
| 121 | namespace mojom { |
| 122 | |
| 123 | class Logger { |
| 124 | virtual ~Logger() {} |
| 125 | |
| 126 | virtual void Log(const std::string& message) = 0; |
| 127 | }; |
| 128 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 129 | } // namespace mojom |
| 130 | } // namespace sample |
| 131 | ``` |
| 132 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 133 | ### Remote and PendingReceiver |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 134 | |
| 135 | In the world of Mojo bindings libraries these are effectively strongly-typed |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 136 | message pipe endpoints. If a `Remote<T>` is bound to a message pipe |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 137 | endpoint, it can be dereferenced to make calls on an opaque `T` interface. These |
| 138 | calls immediately serialize their arguments (using generated code) and write a |
| 139 | corresponding message to the pipe. |
| 140 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 141 | A `PendingReceiver<T>` is essentially just a typed container to hold the other |
| 142 | end of a `Remote<T>`'s pipe -- the receiving end -- until it can be |
| 143 | routed to some implementation which will **bind** it. The `PendingReceiver<T>` |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 144 | doesn't actually *do* anything other than hold onto a pipe endpoint and carry |
| 145 | useful compile-time type information. |
| 146 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 147 |  |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 148 | |
| 149 | So how do we create a strongly-typed message pipe? |
| 150 | |
| 151 | ### Creating Interface Pipes |
| 152 | |
Ken Rockot | f4d8a94 | 2017-05-13 00:10:37 | [diff] [blame] | 153 | One way to do this is by manually creating a pipe and wrapping each end with a |
| 154 | strongly-typed object: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 155 | |
| 156 | ``` cpp |
| 157 | #include "sample/logger.mojom.h" |
| 158 | |
| 159 | mojo::MessagePipe pipe; |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 160 | mojo::Remote<sample::mojom::Logger> logger( |
| 161 | mojo::PendingRemote<sample::mojom::Logger>(std::move(pipe.handle0), 0)); |
| 162 | mojo::PendingReceiver<sample::mojom::Logger> receiver(std::move(pipe.handle1)); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 163 | ``` |
| 164 | |
Ken Rockot | f4d8a94 | 2017-05-13 00:10:37 | [diff] [blame] | 165 | That's pretty verbose, but the C++ Bindings library provides a more convenient |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 166 | way to accomplish the same thing. [remote.h](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/remote.h) |
| 167 | defines a `BindNewPipeAndPassReceiver` method: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 168 | |
| 169 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 170 | mojo::Remote<sample::mojom::Logger> logger; |
Austin Sullivan | 03fb192 | 2020-10-02 14:27:45 | [diff] [blame] | 171 | auto receiver = logger.BindNewPipeAndPassReceiver(); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 172 | ``` |
| 173 | |
Ken Rockot | f4d8a94 | 2017-05-13 00:10:37 | [diff] [blame] | 174 | This second snippet is equivalent to the first one. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 175 | |
| 176 | *** note |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 177 | **NOTE:** In the first example above you may notice usage of the |
| 178 | `mojo::PendingRemote<Logger>`. This is similar to a `PendingReceiver<T>` |
| 179 | in that it merely holds onto a pipe handle and cannot actually read or |
| 180 | write messages on the pipe. Both this type and `PendingReceiver<T>` are safe |
| 181 | to move freely from sequence to sequence, whereas a bound `Remote<T>` is bound |
| 182 | to a single sequence. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 183 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 184 | A `Remote<T>` may be unbound by calling its `Unbind()` method, |
| 185 | which returns a new `PendingRemote<T>`. Conversely, an `Remote<T>` may |
| 186 | bind (and thus take ownership of) an `PendingRemote<T>` so that interface |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 187 | calls can be made on the pipe. |
| 188 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 189 | The sequence-bound nature of `Remote<T>` is necessary to support safe |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 190 | dispatch of its [message responses](#Receiving-Responses) and |
| 191 | [connection error notifications](#Connection-Errors). |
| 192 | *** |
| 193 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 194 | Once the `PendingRemote<Logger>` is bound we can immediately begin calling `Logger` |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 195 | interface methods on it, which will immediately write messages into the pipe. |
| 196 | These messages will stay queued on the receiving end of the pipe until someone |
| 197 | binds to it and starts reading them. |
| 198 | |
| 199 | ``` cpp |
| 200 | logger->Log("Hello!"); |
| 201 | ``` |
| 202 | |
| 203 | This actually writes a `Log` message to the pipe. |
| 204 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 205 |  |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 206 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 207 | But as mentioned above, `PendingReceiver` *doesn't actually do anything*, so |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 208 | that message will just sit on the pipe forever. We need a way to read messages |
| 209 | off the other end of the pipe and dispatch them. We have to |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 210 | **bind the pending receiver**. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 211 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 212 | ### Binding a Pending Receiver |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 213 | |
| 214 | There are many different helper classes in the bindings library for binding the |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 215 | receiving end of a message pipe. The most primitive among them is `mojo::Receiver<T>`. |
| 216 | A `mojo::Receiver<T>` bridges an implementation of `T` |
| 217 | with a single bound message pipe endpoint (via a `mojo::PendingReceiver<T>`), |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 218 | which it continuously watches for readability. |
| 219 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 220 | Any time the bound pipe becomes readable, the `Receiver` will schedule a task to |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 221 | read, deserialize (using generated code), and dispatch all available messages to |
| 222 | the bound `T` implementation. Below is a sample implementation of the `Logger` |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 223 | interface. Notice that the implementation itself owns a `mojo::Receiver`. This is |
| 224 | a common pattern, since a bound implementation must outlive any `mojo::Receiver` |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 225 | which binds it. |
| 226 | |
| 227 | ``` cpp |
| 228 | #include "base/logging.h" |
| 229 | #include "base/macros.h" |
| 230 | #include "sample/logger.mojom.h" |
| 231 | |
| 232 | class LoggerImpl : public sample::mojom::Logger { |
| 233 | public: |
| 234 | // NOTE: A common pattern for interface implementations which have one |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 235 | // instance per client is to take a PendingReceiver in the constructor. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 236 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 237 | explicit LoggerImpl(mojo::PendingReceiver<sample::mojom::Logger> receiver) |
| 238 | : receiver_(this, std::move(receiver)) {} |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 239 | ~Logger() override {} |
Johann | e6e768e9 | 2020-09-09 00:51:10 | [diff] [blame] | 240 | Logger(const Logger&) = delete; |
| 241 | Logger& operator=(const Logger&) = delete; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 242 | |
| 243 | // sample::mojom::Logger: |
| 244 | void Log(const std::string& message) override { |
| 245 | LOG(ERROR) << "[Logger] " << message; |
| 246 | } |
| 247 | |
| 248 | private: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 249 | mojo::Receiver<sample::mojom::Logger> receiver_; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 250 | }; |
| 251 | ``` |
| 252 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 253 | Now we can construct a `LoggerImpl` over our `PendingReceiver<Logger>`, and the |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 254 | previously queued `Log` message will be dispatched ASAP on the `LoggerImpl`'s |
Sam McNally | d482b4b | 2017-07-17 03:45:03 | [diff] [blame] | 255 | sequence: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 256 | |
| 257 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 258 | LoggerImpl impl(std::move(receiver)); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 259 | ``` |
| 260 | |
| 261 | The diagram below illustrates the following sequence of events, all set in |
| 262 | motion by the above line of code: |
| 263 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 264 | 1. The `LoggerImpl` constructor is called, passing the `PendingReceiver<Logger>` along |
| 265 | to the `Receiver`. |
| 266 | 2. The `Receiver` takes ownership of the `PendingReceiver<Logger>`'s pipe endpoint and |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 267 | begins watching it for readability. The pipe is readable immediately, so a |
| 268 | task is scheduled to read the pending `Log` message from the pipe ASAP. |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 269 | 3. The `Log` message is read and deserialized, causing the `Receiver` to invoke |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 270 | the `Logger::Log` implementation on its bound `LoggerImpl`. |
| 271 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 272 |  |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 273 | |
| 274 | As a result, our implementation will eventually log the client's `"Hello!"` |
| 275 | message via `LOG(ERROR)`. |
| 276 | |
| 277 | *** note |
| 278 | **NOTE:** Messages will only be read and dispatched from a pipe as long as the |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 279 | object which binds it (*i.e.* the `mojo::Receiver` in the above example) remains |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 280 | alive. |
| 281 | *** |
| 282 | |
| 283 | ### Receiving Responses |
| 284 | |
| 285 | Some Mojom interface methods expect a response. Suppose we modify our `Logger` |
| 286 | interface so that the last logged line can be queried like so: |
| 287 | |
| 288 | ``` cpp |
| 289 | module sample.mojom; |
| 290 | |
| 291 | interface Logger { |
| 292 | Log(string message); |
| 293 | GetTail() => (string message); |
| 294 | }; |
| 295 | ``` |
| 296 | |
| 297 | The generated C++ interface will now look like: |
| 298 | |
| 299 | ``` cpp |
| 300 | namespace sample { |
| 301 | namespace mojom { |
| 302 | |
| 303 | class Logger { |
| 304 | public: |
| 305 | virtual ~Logger() {} |
| 306 | |
| 307 | virtual void Log(const std::string& message) = 0; |
| 308 | |
David 'Digit' Turner | 743836f8 | 2017-10-27 13:04:15 | [diff] [blame] | 309 | using GetTailCallback = base::OnceCallback<void(const std::string& message)>; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 310 | |
David 'Digit' Turner | 743836f8 | 2017-10-27 13:04:15 | [diff] [blame] | 311 | virtual void GetTail(GetTailCallback callback) = 0; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 312 | } |
| 313 | |
| 314 | } // namespace mojom |
| 315 | } // namespace sample |
| 316 | ``` |
| 317 | |
| 318 | As before, both clients and implementations of this interface use the same |
| 319 | signature for the `GetTail` method: implementations use the `callback` argument |
| 320 | to *respond* to the request, while clients pass a `callback` argument to |
Erik Chen | 94936ef | 2020-09-11 20:41:12 | [diff] [blame] | 321 | asynchronously `receive` the response. The parameter `GetTailCallback` passed to |
| 322 | the implementation of `GetTail` is sequence-affine. It must be invoked on the |
| 323 | same sequence that `GetTail` is called on. A client's `callback` runs on the |
| 324 | same sequence on which they invoked `GetTail` (the sequence to which their |
| 325 | `logger` is bound). Here's an updated implementation: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 326 | |
| 327 | ```cpp |
| 328 | class LoggerImpl : public sample::mojom::Logger { |
| 329 | public: |
| 330 | // NOTE: A common pattern for interface implementations which have one |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 331 | // instance per client is to take a PendingReceiver in the constructor. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 332 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 333 | explicit LoggerImpl(mojo::PendingReceiver<sample::mojom::Logger> receiver) |
| 334 | : receiver_(this, std::move(receiver)) {} |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 335 | ~Logger() override {} |
Johann | e6e768e9 | 2020-09-09 00:51:10 | [diff] [blame] | 336 | Logger(const Logger&) = delete; |
| 337 | Logger& operator=(const Logger&) = delete; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 338 | |
| 339 | // sample::mojom::Logger: |
| 340 | void Log(const std::string& message) override { |
| 341 | LOG(ERROR) << "[Logger] " << message; |
| 342 | lines_.push_back(message); |
| 343 | } |
| 344 | |
David 'Digit' Turner | 743836f8 | 2017-10-27 13:04:15 | [diff] [blame] | 345 | void GetTail(GetTailCallback callback) override { |
| 346 | std::move(callback).Run(lines_.back()); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 347 | } |
| 348 | |
| 349 | private: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 350 | mojo::Receiver<sample::mojom::Logger> receiver_; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 351 | std::vector<std::string> lines_; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 352 | }; |
| 353 | ``` |
| 354 | |
| 355 | And an updated client call: |
| 356 | |
| 357 | ``` cpp |
| 358 | void OnGetTail(const std::string& message) { |
| 359 | LOG(ERROR) << "Tail was: " << message; |
| 360 | } |
| 361 | |
David 'Digit' Turner | 743836f8 | 2017-10-27 13:04:15 | [diff] [blame] | 362 | logger->GetTail(base::BindOnce(&OnGetTail)); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 363 | ``` |
| 364 | |
| 365 | Behind the scenes, the implementation-side callback is actually serializing the |
| 366 | response arguments and writing them onto the pipe for delivery back to the |
| 367 | client. Meanwhile the client-side callback is invoked by some internal logic |
| 368 | which watches the pipe for an incoming response message, reads and deserializes |
| 369 | it once it arrives, and then invokes the callback with the deserialized |
| 370 | parameters. |
| 371 | |
| 372 | ### Connection Errors |
| 373 | |
Yuzhu Shen | 92e791aa | 2017-06-20 20:39:31 | [diff] [blame] | 374 | If a pipe is disconnected, both endpoints will be able to observe the connection |
| 375 | error (unless the disconnection is caused by closing/destroying an endpoint, in |
| 376 | which case that endpoint won't get such a notification). If there are remaining |
| 377 | incoming messages for an endpoint on disconnection, the connection error won't |
| 378 | be triggered until the messages are drained. |
| 379 | |
David Benjamin | 0ff6182 | 2019-04-29 19:00:05 | [diff] [blame] | 380 | Pipe disconnection may be caused by: |
Yuzhu Shen | 92e791aa | 2017-06-20 20:39:31 | [diff] [blame] | 381 | * Mojo system-level causes: process terminated, resource exhausted, etc. |
| 382 | * The bindings close the pipe due to a validation error when processing a |
| 383 | received message. |
| 384 | * The peer endpoint is closed. For example, the remote side is a bound |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 385 | `mojo::Remote<T>` and it is destroyed. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 386 | |
| 387 | Regardless of the underlying cause, when a connection error is encountered on |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 388 | a receiver endpoint, that endpoint's **disconnect handler** (if set) is |
Anand K. Mistry | ff664b7 | 2019-11-08 00:50:10 | [diff] [blame] | 389 | invoked. This handler is a simple `base::OnceClosure` and may only be invoked |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 390 | *once* as long as the endpoint is bound to the same pipe. Typically clients and |
| 391 | implementations use this handler to do some kind of cleanup or -- particuarly if |
| 392 | the error was unexpected -- create a new pipe and attempt to establish a new |
| 393 | connection with it. |
| 394 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 395 | All message pipe-binding C++ objects (*e.g.*, `mojo::Receiver<T>`, |
| 396 | `mojo::Remote<T>`, *etc.*) support setting their disconnect handler |
| 397 | via a `set_disconnect_handler` method. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 398 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 399 | We can set up another end-to-end `Logger` example to demonstrate disconnect handler |
| 400 | invocation. Suppose that `LoggerImpl` had set up the following disconnect |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 401 | handler within its constructor: |
| 402 | |
| 403 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 404 | LoggerImpl::LoggerImpl(mojo::PendingReceiver<sample::mojom::Logger> receiver) |
| 405 | : receiver_(this, std::move(receiver)) { |
| 406 | receiver_.set_disconnect_handler( |
jameswest | 14ae013 | 2017-06-12 22:52:00 | [diff] [blame] | 407 | base::BindOnce(&LoggerImpl::OnError, base::Unretained(this))); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 408 | } |
| 409 | |
| 410 | void LoggerImpl::OnError() { |
| 411 | LOG(ERROR) << "Client disconnected! Purging log lines."; |
| 412 | lines_.clear(); |
| 413 | } |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 414 | |
| 415 | mojo::Remote<sample::mojom::Logger> logger; |
| 416 | LoggerImpl impl(logger.BindNewPipeAndPassReceiver()); |
| 417 | logger->Log("OK cool"); |
| 418 | logger.reset(); // Closes the client end. |
| 419 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 420 | ``` |
| 421 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 422 | As long as `impl` stays alive here, it will eventually receive the `Log` message |
| 423 | followed immediately by an invocation of the bound callback which outputs |
| 424 | `"Client disconnected! Purging log lines."`. Like all other receiver callbacks, a disconnect handler will |
| 425 | **never** be invoked once its corresponding receiver object has been destroyed. |
| 426 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 427 | The use of `base::Unretained` is *safe* because the error handler will never be |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 428 | invoked beyond the lifetime of `receiver_`, and `this` owns `receiver_`. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 429 | |
Yuzhu Shen | 7afd726 | 2017-11-16 22:30:26 | [diff] [blame] | 430 | ### A Note About Endpoint Lifetime and Callbacks |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 431 | Once a `mojo::Remote<T>` is destroyed, it is guaranteed that pending |
Yuzhu Shen | 7afd726 | 2017-11-16 22:30:26 | [diff] [blame] | 432 | callbacks as well as the connection error handler (if registered) won't be |
| 433 | called. |
| 434 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 435 | Once a `mojo::Receiver<T>` is destroyed, it is guaranteed that no more method |
Yuzhu Shen | 7afd726 | 2017-11-16 22:30:26 | [diff] [blame] | 436 | calls are dispatched to the implementation and the connection error handler (if |
| 437 | registered) won't be called. |
| 438 | |
John Abd-El-Malek | a915485 | 2017-12-21 23:39:48 | [diff] [blame] | 439 | ### Best practices for dealing with process crashes and callbacks |
| 440 | A common situation when calling mojo interface methods that take a callback is |
| 441 | that the caller wants to know if the other endpoint is torn down (e.g. because |
| 442 | of a crash). In that case, the consumer usually wants to know if the response |
| 443 | callback won't be run. There are different solutions for this problem, depending |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 444 | on how the `Remote<T>` is held: |
| 445 | 1. The consumer owns the `Remote<T>`: `set_disconnect_handler` |
John Abd-El-Malek | a915485 | 2017-12-21 23:39:48 | [diff] [blame] | 446 | should be used. |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 447 | 2. The consumer doesn't own the `Remote<T>`: there are two helpers |
John Abd-El-Malek | a915485 | 2017-12-21 23:39:48 | [diff] [blame] | 448 | depending on the behavior that the caller wants. If the caller wants to |
| 449 | ensure that an error handler is run, then |
| 450 | [**`mojo::WrapCallbackWithDropHandler`**](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/callback_helpers.h?l=46) |
| 451 | should be used. If the caller wants the callback to always be run, then |
| 452 | [**`mojo::WrapCallbackWithDefaultInvokeIfNotRun`**](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/callback_helpers.h?l=40) |
| 453 | helper should be used. With both of these helpers, usual callback care should |
| 454 | be followed to ensure that the callbacks don't run after the consumer is |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 455 | destructed (e.g. because the owner of the `Remote<T>` outlives the |
John Abd-El-Malek | a915485 | 2017-12-21 23:39:48 | [diff] [blame] | 456 | consumer). This includes using |
| 457 | [**`base::WeakPtr`**](https://cs.chromium.org/chromium/src/base/memory/weak_ptr.h?l=5) |
| 458 | or |
| 459 | [**`base::RefCounted`**](https://cs.chromium.org/chromium/src/base/memory/ref_counted.h?l=246). |
| 460 | It should also be noted that with these helpers, the callbacks could be run |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 461 | synchronously while the Remote<T> is reset or destroyed. |
John Abd-El-Malek | a915485 | 2017-12-21 23:39:48 | [diff] [blame] | 462 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 463 | ### A Note About Ordering |
| 464 | |
| 465 | As mentioned in the previous section, closing one end of a pipe will eventually |
| 466 | trigger a connection error on the other end. However it's important to note that |
| 467 | this event is itself ordered with respect to any other event (*e.g.* writing a |
| 468 | message) on the pipe. |
| 469 | |
| 470 | This means that it's safe to write something contrived like: |
| 471 | |
| 472 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 473 | LoggerImpl::LoggerImpl(mojo::PendingReceiver<sample::mojom::Logger> receiver, |
| 474 | base::OnceClosure disconnect_handler) |
| 475 | : receiver_(this, std::move(receiver)) { |
| 476 | receiver_.set_disconnect_handler(std::move(disconnect_handler)); |
| 477 | } |
| 478 | |
| 479 | void GoBindALogger(mojo::PendingReceiver<sample::mojom::Logger> receiver) { |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 480 | base::RunLoop loop; |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 481 | LoggerImpl impl(std::move(receiver), loop.QuitClosure()); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 482 | loop.Run(); |
| 483 | } |
| 484 | |
| 485 | void LogSomething() { |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 486 | mojo::Remote<sample::mojom::Logger> logger; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 487 | bg_thread->task_runner()->PostTask( |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 488 | FROM_HERE, base::BindOnce(&GoBindALogger, logger.BindNewPipeAndPassReceiver())); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 489 | logger->Log("OK Computer"); |
| 490 | } |
| 491 | ``` |
| 492 | |
| 493 | When `logger` goes out of scope it immediately closes its end of the message |
| 494 | pipe, but the impl-side won't notice this until it receives the sent `Log` |
| 495 | message. Thus the `impl` above will first log our message and *then* see a |
| 496 | connection error and break out of the run loop. |
| 497 | |
Sasha Bermeister | 995adc6 | 2017-12-07 02:36:43 | [diff] [blame] | 498 | ## Types |
| 499 | |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 500 | ### Enums |
| 501 | |
Ken Rockot | 929282c | 2018-05-02 17:07:29 | [diff] [blame] | 502 | [Mojom enums](/mojo/public/tools/bindings/README.md#Enumeration-Types) translate |
| 503 | directly to equivalent strongly-typed C++11 enum classes with `int32_t` as the |
| 504 | underlying type. The typename and value names are identical between Mojom and |
| 505 | C++. Mojo also always defines a special enumerator `kMaxValue` that shares the |
| 506 | value of the highest enumerator: this makes it easy to record Mojo enums in |
| 507 | histograms and interoperate with legacy IPC. |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 508 | |
| 509 | For example, consider the following Mojom definition: |
| 510 | |
| 511 | ```cpp |
| 512 | module business.mojom; |
| 513 | |
| 514 | enum Department { |
| 515 | kEngineering, |
Andrew Moylan | 341cece7 | 2017-06-22 22:03:02 | [diff] [blame] | 516 | kMarketing, |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 517 | kSales, |
| 518 | }; |
| 519 | ``` |
| 520 | |
| 521 | This translates to the following C++ definition: |
| 522 | |
| 523 | ```cpp |
| 524 | namespace business { |
| 525 | namespace mojom { |
| 526 | |
| 527 | enum class Department : int32_t { |
| 528 | kEngineering, |
| 529 | kMarketing, |
| 530 | kSales, |
Daniel Cheng | cda1df5b | 2018-03-30 21:30:16 | [diff] [blame] | 531 | kMaxValue = kSales, |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 532 | }; |
| 533 | |
| 534 | } // namespace mojom |
| 535 | } // namespace business |
| 536 | ``` |
| 537 | |
| 538 | ### Structs |
| 539 | |
Ken Rockot | 929282c | 2018-05-02 17:07:29 | [diff] [blame] | 540 | [Mojom structs](mojo/public/tools/bindings/README.md#Structs) can be used to |
| 541 | define logical groupings of fields into a new composite type. Every Mojom struct |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 542 | elicits the generation of an identically named, representative C++ class, with |
| 543 | identically named public fields of corresponding C++ types, and several helpful |
| 544 | public methods. |
| 545 | |
| 546 | For example, consider the following Mojom struct: |
| 547 | |
| 548 | ```cpp |
| 549 | module business.mojom; |
| 550 | |
| 551 | struct Employee { |
| 552 | int64 id; |
| 553 | string username; |
| 554 | Department department; |
| 555 | }; |
| 556 | ``` |
| 557 | |
| 558 | This would generate a C++ class like so: |
| 559 | |
| 560 | ```cpp |
| 561 | namespace business { |
| 562 | namespace mojom { |
| 563 | |
| 564 | class Employee; |
| 565 | |
| 566 | using EmployeePtr = mojo::StructPtr<Employee>; |
| 567 | |
| 568 | class Employee { |
| 569 | public: |
| 570 | // Default constructor - applies default values, potentially ones specified |
| 571 | // explicitly within the Mojom. |
| 572 | Employee(); |
| 573 | |
| 574 | // Value constructor - an explicit argument for every field in the struct, in |
| 575 | // lexical Mojom definition order. |
| 576 | Employee(int64_t id, const std::string& username, Department department); |
| 577 | |
| 578 | // Creates a new copy of this struct value |
| 579 | EmployeePtr Clone(); |
| 580 | |
| 581 | // Tests for equality with another struct value of the same type. |
| 582 | bool Equals(const Employee& other); |
| 583 | |
| 584 | // Equivalent public fields with names identical to the Mojom. |
| 585 | int64_t id; |
| 586 | std::string username; |
| 587 | Department department; |
| 588 | }; |
| 589 | |
| 590 | } // namespace mojom |
| 591 | } // namespace business |
| 592 | ``` |
| 593 | |
| 594 | Note when used as a message parameter or as a field within another Mojom struct, |
| 595 | a `struct` type is wrapped by the move-only `mojo::StructPtr` helper, which is |
| 596 | roughly equivalent to a `std::unique_ptr` with some additional utility methods. |
| 597 | This allows struct values to be nullable and struct types to be potentially |
| 598 | self-referential. |
| 599 | |
David Benjamin | 0ff6182 | 2019-04-29 19:00:05 | [diff] [blame] | 600 | Every generated struct class has a static `New()` method which returns a new |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 601 | `mojo::StructPtr<T>` wrapping a new instance of the class constructed by |
| 602 | forwarding the arguments from `New`. For example: |
| 603 | |
| 604 | ```cpp |
| 605 | mojom::EmployeePtr e1 = mojom::Employee::New(); |
| 606 | e1->id = 42; |
| 607 | e1->username = "mojo"; |
| 608 | e1->department = mojom::Department::kEngineering; |
| 609 | ``` |
| 610 | |
| 611 | is equivalent to |
| 612 | |
| 613 | ```cpp |
| 614 | auto e1 = mojom::Employee::New(42, "mojo", mojom::Department::kEngineering); |
| 615 | ``` |
| 616 | |
| 617 | Now if we define an interface like: |
| 618 | |
| 619 | ```cpp |
| 620 | interface EmployeeManager { |
| 621 | AddEmployee(Employee e); |
| 622 | }; |
| 623 | ``` |
| 624 | |
| 625 | We'll get this C++ interface to implement: |
| 626 | |
| 627 | ```cpp |
| 628 | class EmployeeManager { |
| 629 | public: |
| 630 | virtual ~EmployeManager() {} |
| 631 | |
| 632 | virtual void AddEmployee(EmployeePtr e) = 0; |
| 633 | }; |
| 634 | ``` |
| 635 | |
| 636 | And we can send this message from C++ code as follows: |
| 637 | |
| 638 | ```cpp |
| 639 | mojom::EmployeManagerPtr manager = ...; |
| 640 | manager->AddEmployee( |
| 641 | Employee::New(42, "mojo", mojom::Department::kEngineering)); |
| 642 | |
| 643 | // or |
| 644 | auto e = Employee::New(42, "mojo", mojom::Department::kEngineering); |
| 645 | manager->AddEmployee(std::move(e)); |
| 646 | ``` |
| 647 | |
| 648 | ### Unions |
| 649 | |
| 650 | Similarly to [structs](#Structs), tagged unions generate an identically named, |
| 651 | representative C++ class which is typically wrapped in a `mojo::StructPtr<T>`. |
| 652 | |
| 653 | Unlike structs, all generated union fields are private and must be retrieved and |
Oksana Zhuravlova | a4da21f | 2019-03-20 20:41:58 | [diff] [blame] | 654 | manipulated using accessors. A field `foo` is accessible by `get_foo()` and |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 655 | settable by `set_foo()`. There is also a boolean `is_foo()` for each field which |
| 656 | indicates whether the union is currently taking on the value of field `foo` in |
| 657 | exclusion to all other union fields. |
| 658 | |
| 659 | Finally, every generated union class also has a nested `Tag` enum class which |
| 660 | enumerates all of the named union fields. A Mojom union value's current type can |
| 661 | be determined by calling the `which()` method which returns a `Tag`. |
| 662 | |
| 663 | For example, consider the following Mojom definitions: |
| 664 | |
| 665 | ```cpp |
| 666 | union Value { |
| 667 | int64 int_value; |
Tom McKee | 1a5032f | 2018-08-02 17:14:55 | [diff] [blame] | 668 | float float_value; |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 669 | string string_value; |
| 670 | }; |
| 671 | |
| 672 | interface Dictionary { |
| 673 | AddValue(string key, Value value); |
| 674 | }; |
| 675 | ``` |
| 676 | |
Tom McKee | 1a5032f | 2018-08-02 17:14:55 | [diff] [blame] | 677 | This generates the following C++ interface: |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 678 | |
| 679 | ```cpp |
| 680 | class Value { |
| 681 | public: |
Tom McKee | 1a5032f | 2018-08-02 17:14:55 | [diff] [blame] | 682 | ~Value() {} |
| 683 | }; |
| 684 | |
| 685 | class Dictionary { |
| 686 | public: |
| 687 | virtual ~Dictionary() {} |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 688 | |
| 689 | virtual void AddValue(const std::string& key, ValuePtr value) = 0; |
| 690 | }; |
| 691 | ``` |
| 692 | |
| 693 | And we can use it like so: |
| 694 | |
| 695 | ```cpp |
| 696 | ValuePtr value = Value::New(); |
| 697 | value->set_int_value(42); |
| 698 | CHECK(value->is_int_value()); |
| 699 | CHECK_EQ(value->which(), Value::Tag::INT_VALUE); |
| 700 | |
| 701 | value->set_float_value(42); |
| 702 | CHECK(value->is_float_value()); |
| 703 | CHECK_EQ(value->which(), Value::Tag::FLOAT_VALUE); |
| 704 | |
| 705 | value->set_string_value("bananas"); |
| 706 | CHECK(value->is_string_value()); |
| 707 | CHECK_EQ(value->which(), Value::Tag::STRING_VALUE); |
| 708 | ``` |
| 709 | |
| 710 | Finally, note that if a union value is not currently occupied by a given field, |
| 711 | attempts to access that field will DCHECK: |
| 712 | |
| 713 | ```cpp |
| 714 | ValuePtr value = Value::New(); |
| 715 | value->set_int_value(42); |
| 716 | LOG(INFO) << "Value is " << value->string_value(); // DCHECK! |
| 717 | ``` |
| 718 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 719 | ### Sending Interfaces Over Interfaces |
| 720 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 721 | We know how to create interface pipes and use their Remote and PendingReceiver endpoints |
Ken Rockot | 686e413 | 2017-04-26 00:03:31 | [diff] [blame] | 722 | in some interesting ways. This still doesn't add up to interesting IPC! The |
| 723 | bread and butter of Mojo IPC is the ability to transfer interface endpoints |
| 724 | across other interfaces, so let's take a look at how to accomplish that. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 725 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 726 | #### Sending Pending Receivers |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 727 | |
| 728 | Consider a new example Mojom in `//sample/db.mojom`: |
| 729 | |
| 730 | ``` cpp |
| 731 | module db.mojom; |
| 732 | |
| 733 | interface Table { |
| 734 | void AddRow(int32 key, string data); |
| 735 | }; |
| 736 | |
| 737 | interface Database { |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 738 | AddTable(pending_receiver<Table> table); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 739 | }; |
| 740 | ``` |
| 741 | |
| 742 | As noted in the |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 743 | [Mojom IDL documentation](/mojo/public/tools/bindings/README.md#Primitive-Types), |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 744 | the `pending_receiver<Table>` syntax corresponds |
| 745 | precisely to the `PendingReceiver<T>` type discussed in the sections above, and |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 746 | in fact the generated code for these interfaces is approximately: |
| 747 | |
| 748 | ``` cpp |
| 749 | namespace db { |
| 750 | namespace mojom { |
| 751 | |
| 752 | class Table { |
| 753 | public: |
| 754 | virtual ~Table() {} |
| 755 | |
| 756 | virtual void AddRow(int32_t key, const std::string& data) = 0; |
| 757 | } |
| 758 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 759 | class Database { |
| 760 | public: |
| 761 | virtual ~Database() {} |
| 762 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 763 | virtual void AddTable(mojo::PendingReceiver<Table> table); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 764 | }; |
| 765 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 766 | } // namespace mojom |
| 767 | } // namespace db |
| 768 | ``` |
| 769 | |
| 770 | We can put this all together now with an implementation of `Table` and |
| 771 | `Database`: |
| 772 | |
| 773 | ``` cpp |
| 774 | #include "sample/db.mojom.h" |
| 775 | |
| 776 | class TableImpl : public db::mojom:Table { |
| 777 | public: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 778 | explicit TableImpl(mojo::PendingReceiver<db::mojom::Table> receiver) |
| 779 | : receiver_(this, std::move(receiver)) {} |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 780 | ~TableImpl() override {} |
| 781 | |
| 782 | // db::mojom::Table: |
| 783 | void AddRow(int32_t key, const std::string& data) override { |
| 784 | rows_.insert({key, data}); |
| 785 | } |
| 786 | |
| 787 | private: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 788 | mojo::Receiver<db::mojom::Table> receiver_; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 789 | std::map<int32_t, std::string> rows_; |
| 790 | }; |
| 791 | |
| 792 | class DatabaseImpl : public db::mojom::Database { |
| 793 | public: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 794 | explicit DatabaseImpl(mojo::PendingReceiver<db::mojom::Database> receiver) |
| 795 | : receiver_(this, std::move(receiver)) {} |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 796 | ~DatabaseImpl() override {} |
| 797 | |
| 798 | // db::mojom::Database: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 799 | void AddTable(mojo::PendingReceiver<db::mojom::Table> table) { |
Jeremy Roman | cf9ae2f | 2017-08-24 17:06:37 | [diff] [blame] | 800 | tables_.emplace_back(std::make_unique<TableImpl>(std::move(table))); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 801 | } |
| 802 | |
| 803 | private: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 804 | mojo::Receiver<db::mojom::Database> receiver_; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 805 | std::vector<std::unique_ptr<TableImpl>> tables_; |
| 806 | }; |
| 807 | ``` |
| 808 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 809 | Pretty straightforward. The `pending_receiver<Table>` Mojom parameter to `AddTable` translates to |
| 810 | a C++ `mojo::PendingReceiver<db::mojom::Table>`, which we know is just a |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 811 | strongly-typed message pipe handle. When `DatabaseImpl` gets an `AddTable` call, |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 812 | it constructs a new `TableImpl` and binds it to the received `mojo::PendingReceiver<db::mojom::Table>`. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 813 | |
| 814 | Let's see how this can be used. |
| 815 | |
| 816 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 817 | mojo::Remote<db::mojom::Database> database; |
| 818 | DatabaseImpl db_impl(database.BindNewPipeAndPassReceiver()); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 819 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 820 | mojo::Remote<db::mojom::Table> table1, table2; |
| 821 | database->AddTable(table1.BindNewPipeAndPassReceiver()); |
| 822 | database->AddTable(table2.BindNewPipeAndPassReceiver()); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 823 | |
| 824 | table1->AddRow(1, "hiiiiiiii"); |
| 825 | table2->AddRow(2, "heyyyyyy"); |
| 826 | ``` |
| 827 | |
| 828 | Notice that we can again start using the new `Table` pipes immediately, even |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 829 | while their `mojo::PendingReceiver<db::mojom::Table>` endpoints are still in transit. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 830 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 831 | #### Sending Remotes |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 832 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 833 | Of course we can also send `Remote`s: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 834 | |
| 835 | ``` cpp |
| 836 | interface TableListener { |
| 837 | OnRowAdded(int32 key, string data); |
| 838 | }; |
| 839 | |
| 840 | interface Table { |
| 841 | AddRow(int32 key, string data); |
| 842 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 843 | AddListener(pending_remote<TableListener> listener); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 844 | }; |
| 845 | ``` |
| 846 | |
| 847 | This would generate a `Table::AddListener` signature like so: |
| 848 | |
| 849 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 850 | virtual void AddListener(mojo::PendingRemote<TableListener> listener) = 0; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 851 | ``` |
| 852 | |
| 853 | and this could be used like so: |
| 854 | |
| 855 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 856 | mojo::PendingRemote<db::mojom::TableListener> listener; |
| 857 | TableListenerImpl impl(listener.InitWithNewPipeAndPassReceiver()); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 858 | table->AddListener(std::move(listener)); |
| 859 | ``` |
| 860 | |
| 861 | ## Other Interface Binding Types |
| 862 | |
| 863 | The [Interfaces](#Interfaces) section above covers basic usage of the most |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 864 | common bindings object types: `Remote`, `PendingReceiver`, and `Receiver`. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 865 | While these types are probably the most commonly used in practice, there are |
| 866 | several other ways of binding both client- and implementation-side interface |
| 867 | pipes. |
| 868 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 869 | ### Self-owned Receivers |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 870 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 871 | A **self-owned receiver** exists as a standalone object which owns its interface |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 872 | implementation and automatically cleans itself up when its bound interface |
| 873 | endpoint detects an error. The |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 874 | [**`MakeSelfOwnedReceiver`**](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/self_owned_receiver.h) |
| 875 | function is used to create such a receiver. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 876 | . |
| 877 | |
| 878 | ``` cpp |
| 879 | class LoggerImpl : public sample::mojom::Logger { |
| 880 | public: |
| 881 | LoggerImpl() {} |
| 882 | ~LoggerImpl() override {} |
| 883 | |
| 884 | // sample::mojom::Logger: |
| 885 | void Log(const std::string& message) override { |
| 886 | LOG(ERROR) << "[Logger] " << message; |
| 887 | } |
| 888 | |
| 889 | private: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 890 | // NOTE: This doesn't own any Receiver object! |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 891 | }; |
| 892 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 893 | mojo::Remote<db::mojom::Logger> logger; |
| 894 | mojo::MakeSelfOwnedReceiver(std::make_unique<LoggerImpl>(), |
| 895 | logger.BindNewPipeAndPassReceiver()); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 896 | |
| 897 | logger->Log("NOM NOM NOM MESSAGES"); |
| 898 | ``` |
| 899 | |
| 900 | Now as long as `logger` remains open somewhere in the system, the bound |
scottmg | 6613920 | 2017-05-04 18:56:35 | [diff] [blame] | 901 | `LoggerImpl` on the other end will remain alive. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 902 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 903 | ### Receiver Sets |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 904 | |
| 905 | Sometimes it's useful to share a single implementation instance with multiple |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 906 | clients. [**`ReceiverSet`**](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/receiver_set.h) |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 907 | makes this easy. Consider the Mojom: |
| 908 | |
| 909 | ``` cpp |
| 910 | module system.mojom; |
| 911 | |
| 912 | interface Logger { |
| 913 | Log(string message); |
| 914 | }; |
| 915 | |
| 916 | interface LoggerProvider { |
| 917 | GetLogger(Logger& logger); |
| 918 | }; |
| 919 | ``` |
| 920 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 921 | We can use `ReceiverSet` to bind multiple `Logger` pending receivers to a single |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 922 | implementation instance: |
| 923 | |
| 924 | ``` cpp |
| 925 | class LogManager : public system::mojom::LoggerProvider, |
| 926 | public system::mojom::Logger { |
| 927 | public: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 928 | explicit LogManager(mojo::PendingReceiver<system::mojom::LoggerProvider> receiver) |
| 929 | : provider_receiver_(this, std::move(receiver)) {} |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 930 | ~LogManager() {} |
| 931 | |
| 932 | // system::mojom::LoggerProvider: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 933 | void GetLogger(mojo::PendingReceiver<Logger> receiver) override { |
| 934 | logger_receivers_.Add(this, std::move(receiver)); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 935 | } |
| 936 | |
| 937 | // system::mojom::Logger: |
| 938 | void Log(const std::string& message) override { |
| 939 | LOG(ERROR) << "[Logger] " << message; |
| 940 | } |
| 941 | |
| 942 | private: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 943 | mojo::Receiver<system::mojom::LoggerProvider> provider_receiver_; |
| 944 | mojo::ReceiverSet<system::mojom::Logger> logger_receivers_; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 945 | }; |
| 946 | |
| 947 | ``` |
| 948 | |
| 949 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 950 | ### Remote Sets |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 951 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 952 | Similar to the `ReceiverSet` above, sometimes it's useful to maintain a set of |
| 953 | `Remote`s for *e.g.* a set of clients observing some event. |
| 954 | [**`RemoteSet`**](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/remote_set.h) |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 955 | is here to help. Take the Mojom: |
| 956 | |
| 957 | ``` cpp |
| 958 | module db.mojom; |
| 959 | |
| 960 | interface TableListener { |
| 961 | OnRowAdded(int32 key, string data); |
| 962 | }; |
| 963 | |
| 964 | interface Table { |
| 965 | AddRow(int32 key, string data); |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 966 | AddListener(pending_remote<TableListener> listener); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 967 | }; |
| 968 | ``` |
| 969 | |
| 970 | An implementation of `Table` might look something like like this: |
| 971 | |
| 972 | ``` cpp |
| 973 | class TableImpl : public db::mojom::Table { |
| 974 | public: |
| 975 | TableImpl() {} |
| 976 | ~TableImpl() override {} |
| 977 | |
| 978 | // db::mojom::Table: |
| 979 | void AddRow(int32_t key, const std::string& data) override { |
| 980 | rows_.insert({key, data}); |
| 981 | listeners_.ForEach([key, &data](db::mojom::TableListener* listener) { |
| 982 | listener->OnRowAdded(key, data); |
| 983 | }); |
| 984 | } |
| 985 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 986 | void AddListener(mojo::PendingRemote<db::mojom::TableListener> listener) { |
| 987 | listeners_.Add(std::move(listener)); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 988 | } |
| 989 | |
| 990 | private: |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 991 | mojo::RemoteSet<db::mojom::Table> listeners_; |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 992 | std::map<int32_t, std::string> rows_; |
| 993 | }; |
| 994 | ``` |
| 995 | |
| 996 | ## Associated Interfaces |
| 997 | |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 998 | Associated interfaces are interfaces which: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 999 | |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1000 | * enable running multiple interfaces over a single message pipe while |
| 1001 | preserving message ordering. |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1002 | * make it possible for the receiver to access a single message pipe from |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1003 | multiple sequences. |
| 1004 | |
| 1005 | ### Mojom |
| 1006 | |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1007 | New types `pending_associated_remote` and `pending_associated_receiver` are |
| 1008 | introduced for remote/receiver fields. For example: |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1009 | |
| 1010 | ``` cpp |
| 1011 | interface Bar {}; |
| 1012 | |
| 1013 | struct Qux { |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1014 | pending_associated_remote<Bar> bar; |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1015 | }; |
| 1016 | |
| 1017 | interface Foo { |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1018 | // Uses associated remote. |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1019 | PassBarRemote(pending_associated_remote<Bar> bar); |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1020 | // Uses associated receiver. |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1021 | PassBarReceiver(pending_associated_receiver<Bar> bar); |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1022 | // Passes a struct with associated interface pointer. |
| 1023 | PassQux(Qux qux); |
| 1024 | // Uses associated interface pointer in callback. |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1025 | AsyncGetBar() => (pending_associated_remote<Bar> bar); |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1026 | }; |
| 1027 | ``` |
| 1028 | |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1029 | In each case the interface impl/client will communicate using the same message |
| 1030 | pipe over which the associated remote/receiver is passed. |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1031 | |
| 1032 | ### Using associated interfaces in C++ |
| 1033 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1034 | When generating C++ bindings, the pending_associated_remote of `Bar` is |
| 1035 | mapped to `mojo::PendingAssociatedRemote<Bar>`; pending_associated_receiver to |
| 1036 | `mojo::PendingAssociatedReceiver<Bar>`. |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1037 | |
| 1038 | ``` cpp |
| 1039 | // In mojom: |
| 1040 | interface Foo { |
| 1041 | ... |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1042 | PassBarRemote(pending_associated_remote<Bar> bar); |
| 1043 | PassBarReceiver(pending_associated_receiver<Bar> bar); |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1044 | ... |
| 1045 | }; |
| 1046 | |
| 1047 | // In C++: |
| 1048 | class Foo { |
| 1049 | ... |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1050 | virtual void PassBarRemote(mojo::PendingAssociatedRemote<Bar> bar) = 0; |
| 1051 | virtual void PassBarReceiver(mojo::PendingAssociatedReceiver<Bar> bar) = 0; |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1052 | ... |
| 1053 | }; |
| 1054 | ``` |
| 1055 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1056 | #### Passing pending associated receivers |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1057 | |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1058 | Assume you already have a `Remote<Foo> foo`, and you would like to call |
| 1059 | `PassBarReceiver()` on it. You can do: |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1060 | |
| 1061 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1062 | mojo::PendingAssociatedRemote<Bar> pending_bar; |
| 1063 | mojo::PendingAssociatedReceiver<Bar> bar_receiver = pending_bar.InitWithNewEndpointAndPassReceiver(); |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1064 | foo->PassBarReceiver(std::move(bar_receiver)); |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1065 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1066 | mojo::AssociatedRemote<Bar> bar; |
| 1067 | bar.Bind(std::move(pending_bar)); |
| 1068 | bar->DoSomething(); |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1069 | ``` |
| 1070 | |
| 1071 | First, the code creates an associated interface of type `Bar`. It looks very |
| 1072 | similar to what you would do to setup a non-associated interface. An |
| 1073 | important difference is that one of the two associated endpoints (either |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1074 | `bar_receiver` or `pending_bar`) must be sent over another interface. That is |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1075 | how the interface is associated with an existing message pipe. |
| 1076 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1077 | It should be noted that you cannot call `bar->DoSomething()` before passing |
| 1078 | `bar_receiver`. This is required by the FIFO-ness guarantee: at the receiver |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1079 | side, when the message of `DoSomething` call arrives, we want to dispatch it to |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1080 | the corresponding `AssociatedReceiver<Bar>` before processing any subsequent |
| 1081 | messages. If `bar_receiver` is in a subsequent message, message dispatching gets |
| 1082 | into a deadlock. On the other hand, as soon as `bar_receiver` is sent, `bar` |
| 1083 | is usable. There is no need to wait until `bar_receiver` is bound to an |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1084 | implementation at the remote side. |
| 1085 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1086 | `AssociatedRemote` provides a `BindNewEndpointAndPassReceiver` method |
| 1087 | to make the code a little shorter. The following code achieves the same purpose: |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1088 | |
| 1089 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1090 | mojo::AssociatedRemote<Bar> bar; |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1091 | foo->PassBarReceiver(bar.BindNewEndpointAndPassReceiver()); |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1092 | bar->DoSomething(); |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1093 | ``` |
| 1094 | |
| 1095 | The implementation of `Foo` looks like this: |
| 1096 | |
| 1097 | ``` cpp |
| 1098 | class FooImpl : public Foo { |
| 1099 | ... |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1100 | void PassBarReceiver(mojo::AssociatedReceiver<Bar> bar) override { |
| 1101 | bar_receiver_.Bind(std::move(bar)); |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1102 | ... |
| 1103 | } |
| 1104 | ... |
| 1105 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1106 | Receiver<Foo> foo_receiver_; |
| 1107 | AssociatedReceiver<Bar> bar_receiver_; |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1108 | }; |
| 1109 | ``` |
| 1110 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1111 | In this example, `bar_receiver_`'s lifespan is tied to that of `FooImpl`. But you |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1112 | don't have to do that. You can, for example, pass `bar2` to another sequence to |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1113 | bind to an `AssociatedReceiver<Bar>` there. |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1114 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1115 | When the underlying message pipe is disconnected (e.g., `foo` or |
| 1116 | `foo_receiver_` is destroyed), all associated interface endpoints (e.g., |
| 1117 | `bar` and `bar_receiver_`) will receive a disconnect error. |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1118 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1119 | #### Passing associated remotes |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1120 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1121 | Similarly, assume you have already got an `Remote<Foo> foo`, and you |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1122 | would like to call `PassBarRemote()` on it. You can do: |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1123 | |
| 1124 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1125 | mojo::AssociatedReceiver<Bar> bar_receiver(some_bar_impl); |
| 1126 | mojo::PendingAssociatedRemote<Bar> bar; |
| 1127 | mojo::PendingAssociatedReceiver<Bar> bar_pending_receiver = bar.InitWithNewEndpointAndPassReceiver(); |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1128 | foo->PassBarRemote(std::move(bar)); |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1129 | bar_receiver.Bind(std::move(bar_pending_receiver)); |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1130 | ``` |
| 1131 | |
| 1132 | The following code achieves the same purpose: |
| 1133 | |
| 1134 | ``` cpp |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1135 | mojo::AssociatedReceiver<Bar> bar_receiver(some_bar_impl); |
| 1136 | mojo::PendingAssociatedRemote<Bar> bar; |
| 1137 | bar_receiver.Bind(bar.InitWithNewPipeAndPassReceiver()); |
David Bokan | e59ea1f4 | 2020-08-04 14:40:21 | [diff] [blame] | 1138 | foo->PassBarRemote(std::move(bar)); |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1139 | ``` |
| 1140 | |
| 1141 | ### Performance considerations |
| 1142 | |
Ken Rockot | cd23f75 | 2020-06-20 01:22:31 | [diff] [blame] | 1143 | When using associated interfaces on different sequences than the primary |
| 1144 | sequence (where the primary interface lives): |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1145 | |
| 1146 | * Sending messages: send happens directly on the calling sequence. So there |
| 1147 | isn't sequence hopping. |
| 1148 | * Receiving messages: associated interfaces bound on a different sequence from |
Ken Rockot | cd23f75 | 2020-06-20 01:22:31 | [diff] [blame] | 1149 | the primary interface incur an extra sequence hop during dispatch. |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1150 | |
| 1151 | Therefore, performance-wise associated interfaces are better suited for |
Ken Rockot | cd23f75 | 2020-06-20 01:22:31 | [diff] [blame] | 1152 | scenarios where message receiving happens on the primary sequence. |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1153 | |
| 1154 | ### Testing |
| 1155 | |
Ken Rockot | cd23f75 | 2020-06-20 01:22:31 | [diff] [blame] | 1156 | Associated interfaces need to be associated with a primary interface before |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1157 | they can be used. This means one end of the associated interface must be sent |
Ken Rockot | cd23f75 | 2020-06-20 01:22:31 | [diff] [blame] | 1158 | over one end of the primary interface, or over one end of another associated |
| 1159 | interface which itself already has a primary interface. |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1160 | |
| 1161 | If you want to test an associated interface endpoint without first |
Gyuyoung Kim | 7dd486c | 2020-09-15 01:47:18 | [diff] [blame] | 1162 | associating it, you can use `AssociatedRemote::BindNewEndpointAndPassDedicatedReceiver`. |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1163 | This will create working associated interface endpoints which are not actually |
Adithya Srinivasan | 4b6c608 | 2018-11-14 16:56:46 | [diff] [blame] | 1164 | associated with anything else. |
Chase Phillips | 3f76e15 | 2018-07-18 20:45:26 | [diff] [blame] | 1165 | |
| 1166 | ### Read more |
| 1167 | |
| 1168 | * [Design: Mojo Associated Interfaces](https://docs.google.com/document/d/1nq3J_HbS-gvVfIoEhcVyxm1uY-9G_7lhD-4Kyxb1WIY/edit) |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1169 | |
| 1170 | ## Synchronous Calls |
| 1171 | |
Oksana Zhuravlova | 50bac90 | 2019-01-15 00:17:59 | [diff] [blame] | 1172 | ### Think carefully before you decide to use sync calls |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1173 | |
Oksana Zhuravlova | 50bac90 | 2019-01-15 00:17:59 | [diff] [blame] | 1174 | Although sync calls are convenient, you should avoid them whenever they |
| 1175 | are not absolutely necessary: |
| 1176 | |
| 1177 | * Sync calls hurt parallelism and therefore hurt performance. |
| 1178 | * Re-entrancy changes message order and produces call stacks that you |
| 1179 | probably never think about while you are coding. It has always been a |
| 1180 | huge pain. |
| 1181 | * Sync calls may lead to deadlocks. |
| 1182 | |
| 1183 | ### Mojom changes |
| 1184 | |
| 1185 | A new attribute `[Sync]` (or `[Sync=true]`) is introduced for methods. |
| 1186 | For example: |
| 1187 | |
| 1188 | ``` cpp |
| 1189 | interface Foo { |
| 1190 | [Sync] |
| 1191 | SomeSyncCall() => (Bar result); |
| 1192 | }; |
| 1193 | ``` |
| 1194 | |
| 1195 | It indicates that when `SomeSyncCall()` is called, the control flow of |
| 1196 | the calling thread is blocked until the response is received. |
| 1197 | |
| 1198 | It is not allowed to use this attribute with functions that don’t have |
| 1199 | responses. If you just need to wait until the service side finishes |
| 1200 | processing the call, you can use an empty response parameter list: |
| 1201 | |
| 1202 | ``` cpp |
| 1203 | [Sync] |
| 1204 | SomeSyncCallWithNoResult() => (); |
| 1205 | ``` |
| 1206 | |
| 1207 | ### Generated bindings (C++) |
| 1208 | |
| 1209 | The generated C++ interface of the Foo interface above is: |
| 1210 | |
| 1211 | ``` cpp |
| 1212 | class Foo { |
| 1213 | public: |
| 1214 | // The service side implements this signature. The client side can |
| 1215 | // also use this signature if it wants to call the method asynchronously. |
| 1216 | virtual void SomeSyncCall(SomeSyncCallCallback callback) = 0; |
| 1217 | |
| 1218 | // The client side uses this signature to call the method synchronously. |
| 1219 | virtual bool SomeSyncCall(BarPtr* result); |
| 1220 | }; |
| 1221 | ``` |
| 1222 | |
| 1223 | As you can see, the client side and the service side use different |
| 1224 | signatures. At the client side, response is mapped to output parameters |
| 1225 | and the boolean return value indicates whether the operation is |
| 1226 | successful. (Returning false usually means a connection error has |
| 1227 | occurred.) |
| 1228 | |
| 1229 | At the service side, a signature with callback is used. The reason is |
| 1230 | that in some cases the implementation may need to do some asynchronous |
| 1231 | work which the sync method’s result depends on. |
| 1232 | |
| 1233 | *** note |
| 1234 | **NOTE:** you can also use the signature with callback at the client side to |
| 1235 | call the method asynchronously. |
| 1236 | *** |
| 1237 | |
| 1238 | ### Re-entrancy |
| 1239 | |
| 1240 | What happens on the calling thread while waiting for the response of a |
| 1241 | sync method call? It continues to process incoming sync request messages |
| 1242 | (i.e., sync method calls); block other messages, including async |
| 1243 | messages and sync response messages that don’t match the ongoing sync |
| 1244 | call. |
| 1245 | |
Ken Rockot | ab03512 | 2019-02-06 00:35:24 | [diff] [blame] | 1246 |  |
Oksana Zhuravlova | 50bac90 | 2019-01-15 00:17:59 | [diff] [blame] | 1247 | |
| 1248 | Please note that sync response messages that don’t match the ongoing |
| 1249 | sync call cannot re-enter. That is because they correspond to sync calls |
| 1250 | down in the call stack. Therefore, they need to be queued and processed |
| 1251 | while the stack unwinds. |
| 1252 | |
| 1253 | ### Avoid deadlocks |
| 1254 | |
| 1255 | Please note that the re-entrancy behavior doesn’t prevent deadlocks |
| 1256 | involving async calls. You need to avoid call sequences such as: |
| 1257 | |
Ken Rockot | ab03512 | 2019-02-06 00:35:24 | [diff] [blame] | 1258 |  |
Oksana Zhuravlova | 50bac90 | 2019-01-15 00:17:59 | [diff] [blame] | 1259 | |
| 1260 | ### Read more |
| 1261 | |
| 1262 | * [Design Proposal: Mojo Sync Methods]( |
| 1263 | https://docs.google.com/document/d/1dixzFzZQW8e3ldjdM8Adbo8klXDDE4pVekwo5aLgUsE) |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1264 | |
| 1265 | ## Type Mapping |
| 1266 | |
| 1267 | In many instances you might prefer that your generated C++ bindings use a more |
| 1268 | natural type to represent certain Mojom types in your interface methods. For one |
| 1269 | example consider a Mojom struct such as the `Rect` below: |
| 1270 | |
| 1271 | ``` cpp |
| 1272 | module gfx.mojom; |
| 1273 | |
| 1274 | struct Rect { |
| 1275 | int32 x; |
| 1276 | int32 y; |
| 1277 | int32 width; |
| 1278 | int32 height; |
| 1279 | }; |
| 1280 | |
| 1281 | interface Canvas { |
| 1282 | void FillRect(Rect rect); |
| 1283 | }; |
| 1284 | ``` |
| 1285 | |
| 1286 | The `Canvas` Mojom interface would normally generate a C++ interface like: |
| 1287 | |
| 1288 | ``` cpp |
| 1289 | class Canvas { |
| 1290 | public: |
| 1291 | virtual void FillRect(RectPtr rect) = 0; |
| 1292 | }; |
| 1293 | ``` |
| 1294 | |
| 1295 | However, the Chromium tree already defines a native |
| 1296 | [`gfx::Rect`](https://cs.chromium.org/chromium/src/ui/gfx/geometry/rect.h) which |
| 1297 | is equivalent in meaning but which also has useful helper methods. Instead of |
| 1298 | manually converting between a `gfx::Rect` and the Mojom-generated `RectPtr` at |
| 1299 | every message boundary, wouldn't it be nice if the Mojom bindings generator |
| 1300 | could instead generate: |
| 1301 | |
| 1302 | ``` cpp |
| 1303 | class Canvas { |
| 1304 | public: |
| 1305 | virtual void FillRect(const gfx::Rect& rect) = 0; |
| 1306 | } |
| 1307 | ``` |
| 1308 | |
| 1309 | The correct answer is, "Yes! That would be nice!" And fortunately, it can! |
| 1310 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1311 | ### Defining `StructTraits` |
| 1312 | |
| 1313 | In order to teach generated bindings code how to serialize an arbitrary native |
| 1314 | type `T` as an arbitrary Mojom type `mojom::U`, we need to define an appropriate |
| 1315 | specialization of the |
| 1316 | [`mojo::StructTraits`](https://cs.chromium.org/chromium/src/mojo/public/cpp/bindings/struct_traits.h) |
| 1317 | template. |
| 1318 | |
| 1319 | A valid specialization of `StructTraits` MUST define the following static |
| 1320 | methods: |
| 1321 | |
| 1322 | * A single static accessor for every field of the Mojom struct, with the exact |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1323 | same name as the struct field. These accessors must all take a (preferably |
| 1324 | const) ref to an object of the native type, and must return a value compatible |
| 1325 | with the Mojom struct field's type. This is used to safely and consistently |
| 1326 | extract data from the native type during message serialization without |
| 1327 | incurring extra copying costs. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1328 | |
| 1329 | * A single static `Read` method which initializes an instance of the the native |
| 1330 | type given a serialized representation of the Mojom struct. The `Read` method |
| 1331 | must return a `bool` to indicate whether the incoming data is accepted |
| 1332 | (`true`) or rejected (`false`). |
| 1333 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1334 | In order to define the mapping for `gfx::Rect`, we want the following |
| 1335 | `StructTraits` specialization, which we'll define in |
Stephen Nusko | 0ea37f3d | 2019-02-17 01:45:19 | [diff] [blame] | 1336 | `//ui/gfx/geometry/mojo/geometry_mojom_traits.h`: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1337 | |
| 1338 | ``` cpp |
Stephen Nusko | 0ea37f3d | 2019-02-17 01:45:19 | [diff] [blame] | 1339 | #include "mojo/public/cpp/bindings/mojom_traits.h" |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1340 | #include "ui/gfx/geometry/rect.h" |
| 1341 | #include "ui/gfx/geometry/mojo/geometry.mojom.h" |
| 1342 | |
| 1343 | namespace mojo { |
| 1344 | |
| 1345 | template <> |
| 1346 | class StructTraits<gfx::mojom::RectDataView, gfx::Rect> { |
| 1347 | public: |
| 1348 | static int32_t x(const gfx::Rect& r) { return r.x(); } |
| 1349 | static int32_t y(const gfx::Rect& r) { return r.y(); } |
| 1350 | static int32_t width(const gfx::Rect& r) { return r.width(); } |
| 1351 | static int32_t height(const gfx::Rect& r) { return r.height(); } |
| 1352 | |
| 1353 | static bool Read(gfx::mojom::RectDataView data, gfx::Rect* out_rect); |
| 1354 | }; |
| 1355 | |
| 1356 | } // namespace mojo |
| 1357 | ``` |
| 1358 | |
Stephen Nusko | 0ea37f3d | 2019-02-17 01:45:19 | [diff] [blame] | 1359 | And in `//ui/gfx/geometry/mojo/geometry_mojom_traits.cc`: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1360 | |
| 1361 | ``` cpp |
Stephen Nusko | 0ea37f3d | 2019-02-17 01:45:19 | [diff] [blame] | 1362 | #include "ui/gfx/geometry/mojo/geometry_mojom_traits.h" |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1363 | |
| 1364 | namespace mojo { |
| 1365 | |
| 1366 | // static |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1367 | bool StructTraits<gfx::mojom::RectDataView, gfx::Rect>::Read( |
| 1368 | gfx::mojom::RectDataView data, |
| 1369 | gfx::Rect* out_rect) { |
| 1370 | if (data.width() < 0 || data.height() < 0) |
| 1371 | return false; |
| 1372 | |
| 1373 | out_rect->SetRect(data.x(), data.y(), data.width(), data.height()); |
| 1374 | return true; |
| 1375 | }; |
| 1376 | |
| 1377 | } // namespace mojo |
| 1378 | ``` |
| 1379 | |
| 1380 | Note that the `Read()` method returns `false` if either the incoming `width` or |
| 1381 | `height` fields are negative. This acts as a validation step during |
| 1382 | deserialization: if a client sends a `gfx::Rect` with a negative width or |
| 1383 | height, its message will be rejected and the pipe will be closed. In this way, |
| 1384 | type mapping can serve to enable custom validation logic in addition to making |
| 1385 | callsites and interface implemention more convenient. |
| 1386 | |
Oksana Zhuravlova | 4b59467 | 2018-11-06 21:58:25 | [diff] [blame] | 1387 | When the struct fields have non-primitive types, e.g. string or array, |
| 1388 | returning a read-only view of the data in the accessor is recommended to |
| 1389 | avoid copying. It is safe because the input object is guaranteed to |
| 1390 | outlive the usage of the result returned by the accessor method. |
| 1391 | |
| 1392 | The following example uses `StringPiece` to return a view of the GURL's |
| 1393 | data (`//url/mojom/url_gurl_mojom_traits.h`): |
| 1394 | |
| 1395 | ``` cpp |
| 1396 | #include "base/strings/string_piece.h" |
| 1397 | #include "url/gurl.h" |
| 1398 | #include "url/mojom/url.mojom.h" |
| 1399 | #include "url/url_constants.h" |
| 1400 | |
| 1401 | namespace mojo { |
| 1402 | |
| 1403 | template <> |
| 1404 | struct StructTraits<url::mojom::UrlDataView, GURL> { |
| 1405 | static base::StringPiece url(const GURL& r) { |
| 1406 | if (r.possibly_invalid_spec().length() > url::kMaxURLChars || |
| 1407 | !r.is_valid()) { |
| 1408 | return base::StringPiece(); |
| 1409 | } |
| 1410 | return base::StringPiece(r.possibly_invalid_spec().c_str(), |
| 1411 | r.possibly_invalid_spec().length()); |
| 1412 | } |
| 1413 | } // namespace mojo |
| 1414 | ``` |
| 1415 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1416 | ### Enabling a New Type Mapping |
| 1417 | |
| 1418 | We've defined the `StructTraits` necessary, but we still need to teach the |
| 1419 | bindings generator (and hence the build system) about the mapping. To do this we |
Ken Rockot | 6ddaf0e | 2020-03-18 19:49:19 | [diff] [blame] | 1420 | must add some more information to our `mojom` target in GN: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1421 | |
| 1422 | ``` |
Ken Rockot | 6ddaf0e | 2020-03-18 19:49:19 | [diff] [blame] | 1423 | # Without a typemap |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1424 | mojom("mojom") { |
| 1425 | sources = [ |
| 1426 | "rect.mojom", |
Ken Rockot | 6ddaf0e | 2020-03-18 19:49:19 | [diff] [blame] | 1427 | ] |
| 1428 | } |
| 1429 | |
| 1430 | # With a typemap. |
| 1431 | mojom("mojom") { |
| 1432 | sources = [ |
| 1433 | "rect.mojom", |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1434 | ] |
| 1435 | |
Ken Rockot | 6ddaf0e | 2020-03-18 19:49:19 | [diff] [blame] | 1436 | cpp_typemaps = [ |
| 1437 | { |
| 1438 | # NOTE: A single typemap entry can list multiple individual type mappings. |
| 1439 | # Each mapping assumes the same values for |traits_headers| etc below. |
| 1440 | # |
| 1441 | # To typemap a type with separate |traits_headers| etc, add a separate |
| 1442 | # entry to |cpp_typemaps|. |
| 1443 | types = [ |
| 1444 | { |
| 1445 | mojom = "gfx.mojom.Rect" |
| 1446 | cpp = "::gfx::Rect" |
| 1447 | }, |
| 1448 | ] |
| 1449 | traits_headers = [ "//ui/gfx/geometry/mojo/geometry_mojom_traits.h" ] |
| 1450 | traits_sources = [ "//ui/gfx/geometry/mojo/geometry_mojom_traits.cc" ] |
| 1451 | traits_public_deps = [ "//ui/gfx/geometry" ] |
| 1452 | }, |
| 1453 | ] |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1454 | } |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1455 | ``` |
| 1456 | |
Ken Rockot | 6ddaf0e | 2020-03-18 19:49:19 | [diff] [blame] | 1457 | See typemap documentation in |
| 1458 | [mojom.gni](https://cs.chromium.org/chromium/src/mojo/public/tools/bindings/mojom.gni) |
| 1459 | for details on the above definition and other supported parameters. |
| 1460 | |
| 1461 | With this extra configuration present, any mojom references to `gfx.mojom.Rect` |
| 1462 | (e.g. for method parameters or struct fields) will be `gfx::Rect` references in |
| 1463 | generated C++ code. |
Ken Rockot | 6ddaf0e | 2020-03-18 19:49:19 | [diff] [blame] | 1464 | |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1465 | For the Blink variant of bindings, add to the `blink_cpp_typemaps` list instead. |
| 1466 | |
| 1467 | ### Type Mapping Without `traits_sources` |
| 1468 | |
Ken Rockot | 6ddaf0e | 2020-03-18 19:49:19 | [diff] [blame] | 1469 | Using `traits_sources` in a typemap configuration means that the listed sources |
| 1470 | will be baked directly into the corresponding `mojom` target's own sources. This |
| 1471 | can be problematic if you want to use the same typemap for both Blink and |
| 1472 | non-Blink bindings. |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1473 | |
| 1474 | For such cases, it is recommended that you define a separate `component` target |
Ken Rockot | 6ddaf0e | 2020-03-18 19:49:19 | [diff] [blame] | 1475 | for your typemap traits, and reference this in the `traits_public_deps` of the |
| 1476 | typemap: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1477 | |
| 1478 | ``` |
Ken Rockot | 6ddaf0e | 2020-03-18 19:49:19 | [diff] [blame] | 1479 | mojom("mojom") { |
| 1480 | sources = [ |
| 1481 | "rect.mojom", |
| 1482 | ] |
| 1483 | |
| 1484 | cpp_typemaps = [ |
| 1485 | { |
| 1486 | types = [ |
| 1487 | { |
| 1488 | mojom = "gfx.mojom.Rect" |
| 1489 | cpp = "::gfx::Rect" |
| 1490 | }, |
| 1491 | ] |
| 1492 | traits_headers = [ "//ui/gfx/geometry/mojo/geometry_mojom_traits.h" ] |
| 1493 | traits_public_deps = [ ":geometry_mojom_traits" ] |
| 1494 | }, |
| 1495 | ] |
| 1496 | } |
| 1497 | |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1498 | component("geometry_mojom_traits") { |
| 1499 | sources = [ |
| 1500 | "//ui/gfx/geometry/mojo/geometry_mojom_traits.cc", |
| 1501 | "//ui/gfx/geometry/mojo/geometry_mojom_traits.h", |
| 1502 | ] |
| 1503 | |
| 1504 | # The header of course needs corresponding COMPONENT_EXPORT() tags. |
| 1505 | defines = [ "IS_GEOMETRY_MOJOM_TRAITS_IMPL" ] |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1506 | } |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1507 | ``` |
| 1508 | |
| 1509 | ### StructTraits Reference |
| 1510 | |
| 1511 | Each of a `StructTraits` specialization's static getter methods -- one per |
| 1512 | struct field -- must return a type which can be used as a data source for the |
| 1513 | field during serialization. This is a quick reference mapping Mojom field type |
| 1514 | to valid getter return types: |
| 1515 | |
| 1516 | | Mojom Field Type | C++ Getter Return Type | |
| 1517 | |------------------------------|------------------------| |
| 1518 | | `bool` | `bool` |
| 1519 | | `int8` | `int8_t` |
| 1520 | | `uint8` | `uint8_t` |
| 1521 | | `int16` | `int16_t` |
| 1522 | | `uint16` | `uint16_t` |
| 1523 | | `int32` | `int32_t` |
| 1524 | | `uint32` | `uint32_t` |
| 1525 | | `int64` | `int64_t` |
| 1526 | | `uint64` | `uint64_t` |
| 1527 | | `float` | `float` |
| 1528 | | `double` | `double` |
| 1529 | | `handle` | `mojo::ScopedHandle` |
| 1530 | | `handle<message_pipe>` | `mojo::ScopedMessagePipeHandle` |
| 1531 | | `handle<data_pipe_consumer>` | `mojo::ScopedDataPipeConsumerHandle` |
| 1532 | | `handle<data_pipe_producer>` | `mojo::ScopedDataPipeProducerHandle` |
| 1533 | | `handle<shared_buffer>` | `mojo::ScopedSharedBufferHandle` |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1534 | | `pending_remote<Foo>` | `mojo::PendingRemote<Foo>` |
| 1535 | | `pending_receiver<Foo>` | `mojo::PendingReceiver<Foo>` |
| 1536 | | `pending_associated_remote<Foo>` | `mojo::PendingAssociatedRemote<Foo>` |
| 1537 | | `pending_associated_receiver<Foo>` | `mojo::PendingAssociatedReceiver<Foo>` |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1538 | | `string` | Value or reference to any type `T` that has a `mojo::StringTraits` specialization defined. By default this includes `std::string`, `base::StringPiece`, and `WTF::String` (Blink). |
| 1539 | | `array<T>` | Value or reference to any type `T` that has a `mojo::ArrayTraits` specialization defined. By default this includes `std::vector<T>`, `mojo::CArray<T>`, and `WTF::Vector<T>` (Blink). |
| 1540 | | `map<K, V>` | Value or reference to any type `T` that has a `mojo::MapTraits` specialization defined. By default this includes `std::map<T>`, `mojo::unordered_map<T>`, and `WTF::HashMap<T>` (Blink). |
| 1541 | | `FooEnum` | Value of any type that has an appropriate `EnumTraits` specialization defined. By default this inlcudes only the generated `FooEnum` type. |
| 1542 | | `FooStruct` | Value or reference to any type that has an appropriate `StructTraits` specialization defined. By default this includes only the generated `FooStructPtr` type. |
| 1543 | | `FooUnion` | Value of reference to any type that has an appropriate `UnionTraits` specialization defined. By default this includes only the generated `FooUnionPtr` type. |
Ryan Sleevi | 9353d6dc | 2019-08-29 16:47:34 | [diff] [blame] | 1544 | | `Foo?` | `base::Optional<CppType>`, where `CppType` is the value type defined by the appropriate traits class specialization (e.g. `StructTraits`, `mojo::MapTraits`, etc.). This may be customized by the [typemapping](#Enabling-a-New-Type-Mapping). |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1545 | |
| 1546 | ### Using Generated DataView Types |
| 1547 | |
| 1548 | Static `Read` methods on `StructTraits` specializations get a generated |
| 1549 | `FooDataView` argument (such as the `RectDataView` in the example above) which |
| 1550 | exposes a direct view of the serialized Mojom structure within an incoming |
| 1551 | message's contents. In order to make this as easy to work with as possible, the |
| 1552 | generated `FooDataView` types have a generated method corresponding to every |
| 1553 | struct field: |
| 1554 | |
| 1555 | * For POD field types (*e.g.* bools, floats, integers) these are simple accessor |
| 1556 | methods with names identical to the field name. Hence in the `Rect` example we |
| 1557 | can access things like `data.x()` and `data.width()`. The return types |
| 1558 | correspond exactly to the mappings listed in the table above, under |
| 1559 | [StructTraits Reference](#StructTraits-Reference). |
| 1560 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1561 | * For handle and interface types (*e.g* `handle` or `pending_remote<Foo>`) these |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1562 | are named `TakeFieldName` (for a field named `field_name`) and they return an |
| 1563 | appropriate move-only handle type by value. The return types correspond |
| 1564 | exactly to the mappings listed in the table above, under |
| 1565 | [StructTraits Reference](#StructTraits-Reference). |
| 1566 | |
| 1567 | * For all other field types (*e.g.*, enums, strings, arrays, maps, structs) |
| 1568 | these are named `ReadFieldName` (for a field named `field_name`) and they |
| 1569 | return a `bool` (to indicate success or failure in reading). On success they |
| 1570 | fill their output argument with the deserialized field value. The output |
| 1571 | argument may be a pointer to any type with an appropriate `StructTraits` |
| 1572 | specialization defined, as mentioned in the table above, under |
| 1573 | [StructTraits Reference](#StructTraits-Reference). |
| 1574 | |
| 1575 | An example would be useful here. Suppose we introduced a new Mojom struct: |
| 1576 | |
| 1577 | ``` cpp |
| 1578 | struct RectPair { |
| 1579 | Rect left; |
| 1580 | Rect right; |
| 1581 | }; |
| 1582 | ``` |
| 1583 | |
| 1584 | and a corresponding C++ type: |
| 1585 | |
| 1586 | ``` cpp |
| 1587 | class RectPair { |
| 1588 | public: |
| 1589 | RectPair() {} |
| 1590 | |
| 1591 | const gfx::Rect& left() const { return left_; } |
| 1592 | const gfx::Rect& right() const { return right_; } |
| 1593 | |
| 1594 | void Set(const gfx::Rect& left, const gfx::Rect& right) { |
| 1595 | left_ = left; |
| 1596 | right_ = right; |
| 1597 | } |
| 1598 | |
| 1599 | // ... some other stuff |
| 1600 | |
| 1601 | private: |
| 1602 | gfx::Rect left_; |
| 1603 | gfx::Rect right_; |
| 1604 | }; |
| 1605 | ``` |
| 1606 | |
| 1607 | Our traits to map `gfx::mojom::RectPair` to `gfx::RectPair` might look like |
| 1608 | this: |
| 1609 | |
| 1610 | ``` cpp |
| 1611 | namespace mojo { |
| 1612 | |
| 1613 | template <> |
| 1614 | class StructTraits |
| 1615 | public: |
| 1616 | static const gfx::Rect& left(const gfx::RectPair& pair) { |
| 1617 | return pair.left(); |
| 1618 | } |
| 1619 | |
| 1620 | static const gfx::Rect& right(const gfx::RectPair& pair) { |
| 1621 | return pair.right(); |
| 1622 | } |
| 1623 | |
| 1624 | static bool Read(gfx::mojom::RectPairDataView data, gfx::RectPair* out_pair) { |
| 1625 | gfx::Rect left, right; |
| 1626 | if (!data.ReadLeft(&left) || !data.ReadRight(&right)) |
| 1627 | return false; |
| 1628 | out_pair->Set(left, right); |
| 1629 | return true; |
| 1630 | } |
| 1631 | } // namespace mojo |
| 1632 | ``` |
| 1633 | |
| 1634 | Generated `ReadFoo` methods always convert `multi_word_field_name` fields to |
| 1635 | `ReadMultiWordFieldName` methods. |
| 1636 | |
Andrew Moylan | 341cece7 | 2017-06-22 22:03:02 | [diff] [blame] | 1637 | <a name="Blink-Type-Mapping"></a> |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1638 | ### Variants |
| 1639 | |
| 1640 | By now you may have noticed that additional C++ sources are generated when a |
| 1641 | Mojom is processed. These exist due to type mapping, and the source files we |
| 1642 | refer to throughout this docuemnt (namely `foo.mojom.cc` and `foo.mojom.h`) are |
| 1643 | really only one **variant** (the *default* or *chromium* variant) of the C++ |
| 1644 | bindings for a given Mojom file. |
| 1645 | |
| 1646 | The only other variant currently defined in the tree is the *blink* variant, |
| 1647 | which produces a few additional files: |
| 1648 | |
| 1649 | ``` |
| 1650 | out/gen/sample/db.mojom-blink.cc |
| 1651 | out/gen/sample/db.mojom-blink.h |
| 1652 | ``` |
| 1653 | |
| 1654 | These files mirror the definitions in the default variant but with different |
| 1655 | C++ types in place of certain builtin field and parameter types. For example, |
| 1656 | Mojom strings are represented by `WTF::String` instead of `std::string`. To |
| 1657 | avoid symbol collisions, the variant's symbols are nested in an extra inner |
| 1658 | namespace, so Blink consumer of the interface might write something like: |
| 1659 | |
| 1660 | ``` |
| 1661 | #include "sample/db.mojom-blink.h" |
| 1662 | |
| 1663 | class TableImpl : public db::mojom::blink::Table { |
| 1664 | public: |
| 1665 | void AddRow(int32_t key, const WTF::String& data) override { |
| 1666 | // ... |
| 1667 | } |
| 1668 | }; |
| 1669 | ``` |
| 1670 | |
| 1671 | In addition to using different C++ types for builtin strings, arrays, and maps, |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1672 | the custom typemaps applied to Blink bindings are managed separately from |
| 1673 | regular bindings. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1674 | |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1675 | `mojom` targets support a `blink_cpp_typemaps` parameter in addition to the |
| 1676 | regular `cpp_typemaps`. This lists the typemaps to apply to Blink bindings. |
| 1677 | |
| 1678 | To depend specifically on generated Blink bindings, reference |
| 1679 | `${target_name}_blink`. So for example, with the definition: |
| 1680 | |
| 1681 | ``` |
| 1682 | # In //foo/mojom |
| 1683 | mojom("mojom") { |
| 1684 | sources = [ |
| 1685 | "db.mojom", |
| 1686 | ] |
| 1687 | } |
| 1688 | ``` |
| 1689 | |
| 1690 | C++ sources can depend on the Blink bindings by depending on |
| 1691 | `"//foo/mojom:mojom_blink"`. |
| 1692 | |
| 1693 | Finally note that both bindings variants share some common definitions which are |
| 1694 | unaffected by differences in the type-mapping configuration (like enums, and |
| 1695 | structures describing serialized object formats). These definitions are |
| 1696 | generated in *shared* sources: |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1697 | |
| 1698 | ``` |
| 1699 | out/gen/sample/db.mojom-shared.cc |
| 1700 | out/gen/sample/db.mojom-shared.h |
| 1701 | out/gen/sample/db.mojom-shared-internal.h |
| 1702 | ``` |
| 1703 | |
| 1704 | Including either variant's header (`db.mojom.h` or `db.mojom-blink.h`) |
Andrew Moylan | 341cece7 | 2017-06-22 22:03:02 | [diff] [blame] | 1705 | implicitly includes the shared header, but may wish to include *only* the shared |
| 1706 | header in some instances. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1707 | |
Ken Rockot | 74de8b8 | 2020-03-10 00:50:20 | [diff] [blame] | 1708 | C++ sources can depend on shared sources only, by referencing the |
| 1709 | `"${target_name}_shared"` target, e.g. `"//foo/mojom:mojom_shared"` in the |
| 1710 | example above. |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1711 | |
| 1712 | ## Versioning Considerations |
| 1713 | |
| 1714 | For general documentation of versioning in the Mojom IDL see |
David Benjamin | 0ff6182 | 2019-04-29 19:00:05 | [diff] [blame] | 1715 | [Versioning](/mojo/public/tools/bindings/README.md#Versioning). |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1716 | |
| 1717 | This section briefly discusses some C++-specific considerations relevant to |
| 1718 | versioned Mojom types. |
| 1719 | |
| 1720 | ### Querying Interface Versions |
| 1721 | |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1722 | `Remote` defines the following methods to query or assert remote interface |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1723 | version: |
| 1724 | |
| 1725 | ```cpp |
Anand K. Mistry | ff664b7 | 2019-11-08 00:50:10 | [diff] [blame] | 1726 | void QueryVersion(base::OnceCallback<void(uint32_t)> callback); |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1727 | ``` |
| 1728 | |
| 1729 | This queries the remote endpoint for the version number of its binding. When a |
| 1730 | response is received `callback` is invoked with the remote version number. Note |
Oksana Zhuravlova | d5888c9 | 2019-08-23 19:43:06 | [diff] [blame] | 1731 | that this value is cached by the `Remote` instance to avoid redundant |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1732 | queries. |
| 1733 | |
| 1734 | ```cpp |
| 1735 | void RequireVersion(uint32_t version); |
| 1736 | ``` |
| 1737 | |
| 1738 | Informs the remote endpoint that a minimum version of `version` is required by |
| 1739 | the client. If the remote endpoint cannot support that version, it will close |
| 1740 | its end of the pipe immediately, preventing any other requests from being |
| 1741 | received. |
| 1742 | |
| 1743 | ### Versioned Enums |
| 1744 | |
| 1745 | For convenience, every extensible enum has a generated helper function to |
| 1746 | determine whether a received enum value is known by the implementation's current |
| 1747 | version of the enum definition. For example: |
| 1748 | |
| 1749 | ```cpp |
| 1750 | [Extensible] |
| 1751 | enum Department { |
| 1752 | SALES, |
| 1753 | DEV, |
| 1754 | RESEARCH, |
| 1755 | }; |
| 1756 | ``` |
| 1757 | |
| 1758 | generates the function in the same namespace as the generated C++ enum type: |
| 1759 | |
| 1760 | ```cpp |
| 1761 | inline bool IsKnownEnumValue(Department value); |
| 1762 | ``` |
| 1763 | |
Sasha Bermeister | 995adc6 | 2017-12-07 02:36:43 | [diff] [blame] | 1764 | ### Using Mojo Bindings in Chrome |
| 1765 | |
Oksana Zhuravlova | 87b225a | 2019-03-07 01:08:03 | [diff] [blame] | 1766 | See [Converting Legacy Chrome IPC To Mojo](/docs/mojo_ipc_conversion.md). |
Sasha Bermeister | 995adc6 | 2017-12-07 02:36:43 | [diff] [blame] | 1767 | |
rockot | f59d2d6 | 2017-04-01 02:49:08 | [diff] [blame] | 1768 | ### Additional Documentation |
| 1769 | |
Raphael Kubo da Costa | 8c6451ba | 2019-05-01 16:55:12 | [diff] [blame] | 1770 | [Calling Mojo From Blink](/docs/mojo_ipc_conversion.md#Blink_Specific-Advice): |
| 1771 | A brief overview of what it looks like to use Mojom C++ bindings from |
| 1772 | within Blink code. |