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