1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::client::Client;
use crate::compositor::{
    PlaceSubsurfaceParams, Surface, SurfaceCommand, SurfaceRelation, SurfaceRole,
};
use crate::display::Callback;
use crate::object::{NewObjectExt, ObjectRef, RequestReceiver};
use anyhow::{format_err, Error};
use fuchsia_wayland_core as wl;
use std::mem;
use wayland_server_protocol::{
    WlSubcompositor, WlSubcompositorRequest, WlSubsurface, WlSubsurfaceRequest,
};

/// An implementation of the wl_subcompositor global.
///
/// wl_subcompositor provides an interface for clients to defer some composition
/// to the server. For example, a media player application may provide the
/// compositor with one surface that contains the video frames and another
/// surface that contains playback controls. Deferring this composition to the
/// server allows for the server to make certain optimizations, such as mapping
/// these surfaces to hardware layers on the display controller, if available.
///
/// Implementation Note: We currently implement the wl_subcompositor by creating
/// new scenic ShapeNodes and placing them as children of the parent node. This
/// makes for a simple implementation, but we don't support any alpha blending
/// of subsurfaces (due to limitations in how Scenic handles these use cases).
/// Scenic may be extended to handle these 2D composition use-cases, but without
/// that we'll need to do some of our own blending here.
pub struct Subcompositor;

impl Subcompositor {
    /// Creates a new `Subcompositor`.
    pub fn new() -> Self {
        Subcompositor
    }
}

impl RequestReceiver<WlSubcompositor> for Subcompositor {
    fn receive(
        this: ObjectRef<Self>,
        request: WlSubcompositorRequest,
        client: &mut Client,
    ) -> Result<(), Error> {
        match request {
            WlSubcompositorRequest::Destroy => {
                client.delete_id(this.id())?;
            }
            WlSubcompositorRequest::GetSubsurface { id, surface, parent } => {
                let subsurface = Subsurface::new(surface, parent);
                let surface_ref = subsurface.surface_ref;
                let parent_ref = subsurface.parent_ref;
                subsurface.attach_to_parent(client)?;
                let subsurface_ref = id.implement(client, subsurface)?;
                surface_ref.get_mut(client)?.set_role(SurfaceRole::Subsurface(subsurface_ref))?;
                parent_ref
                    .get_mut(client)?
                    .enqueue(SurfaceCommand::AddSubsurface(surface_ref, subsurface_ref));
            }
        }
        Ok(())
    }
}

/// Wayland subsurfaces may be in one of two modes, Sync (the default) or Desync.
/// When a wl_subsurface is in sync mode, a wl_surface::commit will simply
/// snapshot the set of pending state. This state will be applied (and changes
/// will appear on screen) when its parent's surface is committed.
///
/// In contrast, a surface in Desync mode will schedule an update to pixels on
/// screen in response to wl_surface::commit.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum SubsurfaceMode {
    Sync,
    Desync,
}

pub struct Subsurface {
    /// A reference to the backing wl_surface for the subsurface.
    surface_ref: ObjectRef<Surface>,

    /// A reference to the backing wl_surface for the parents surface.
    parent_ref: ObjectRef<Surface>,

    /// The current mode of the surface.
    ///
    /// See `SubsurfaceMode` for more details.
    mode: SubsurfaceMode,

    /// When in sync mode, this is the set of commands that are pending our
    /// parents commit.
    ///
    /// When in desync mode, this must be empty.
    pending_commands: Vec<SurfaceCommand>,

    /// When in sync mode, this is the set of wl_surface::frame callbacks that
    /// are pending our parents commit.
    ///
    /// When in desync mode, this must be empty.
    pending_callbacks: Vec<ObjectRef<Callback>>,
}

impl Subsurface {
    pub fn new(surface: wl::ObjectId, parent: wl::ObjectId) -> Self {
        Self {
            surface_ref: surface.into(),
            parent_ref: parent.into(),
            mode: SubsurfaceMode::Sync,
            pending_commands: Vec::new(),
            pending_callbacks: Vec::new(),
        }
    }

    /// Gets the associated wl_surface for this subsurface.
    pub fn surface(&self) -> ObjectRef<Surface> {
        self.surface_ref
    }

    /// Returns true iff this subsurface is running in synchronized mode.
    pub fn is_sync(&self) -> bool {
        self.mode == SubsurfaceMode::Sync
    }

    /// Adds some `SurfaceCommand`s to this surfaces pending state.
    ///
    /// This `pending state` is a set of operations that were committed with a
    /// wl_surface::commit request, but are waiting for our parents state to
    /// be committed.
    ///
    /// Subsurfaces in desync mode have no pending state, as their state is
    /// applied immediately upon wl_surface::commit.
    pub fn add_pending_commands(&mut self, mut commands: Vec<SurfaceCommand>) {
        assert!(self.is_sync(), "Desync subsurfaces have no pending state");
        self.pending_commands.append(&mut commands);
    }

    /// Extracts the set of pending `SurfaceCommand`s and frame Callbacks for
    /// this subsurface, resetting both to empty vectors.
    pub fn take_pending_state(&mut self) -> (Vec<SurfaceCommand>, Vec<ObjectRef<Callback>>) {
        let commands = mem::replace(&mut self.pending_commands, Vec::new());
        let callbacks = mem::replace(&mut self.pending_callbacks, Vec::new());
        (commands, callbacks)
    }

    pub fn finalize_commit(&mut self, callbacks: &mut Vec<ObjectRef<Callback>>) -> bool {
        if self.is_sync() {
            // If we're in sync mode, we just defer the callbacks until our
            // parents state is applied.
            self.pending_callbacks.append(callbacks);
            false
        } else {
            true
        }
    }

    fn attach_to_parent(&self, client: &mut Client) -> Result<(), Error> {
        let flatland = match self.parent_ref.get(client)?.flatland() {
            Some(s) => s.clone(),
            None => return Err(format_err!("Parent surface has no flatland instance!")),
        };
        self.surface_ref.get_mut(client)?.set_flatland(flatland.clone())?;

        // Unwrap here since we have just determined both surfaces have a
        // flatland instance, which is the only prerequisite for having a transform.
        let parent_transform = self.parent_ref.get(client)?.transform().unwrap();
        let child_transform = self.surface_ref.get(client)?.transform().unwrap();
        flatland
            .borrow()
            .proxy()
            .add_child(&parent_transform, &child_transform)
            .expect("fidl error");

        Ok(())
    }

    fn detach_from_parent(&self, client: &Client) -> Result<(), Error> {
        if let Some(flatland) = self.parent_ref.get(client)?.flatland() {
            // Unwrap here since we have just determined parent surface has a
            // flatland instance, which is the only prerequisite for having a
            // transform.
            let parent_transform = *self.parent_ref.get(client)?.transform().unwrap();
            if let Some(child_transform) = self.surface_ref.get(client)?.transform() {
                flatland
                    .borrow()
                    .proxy()
                    .remove_child(&parent_transform, &child_transform)
                    .expect("fidl error");
            }
        }
        Ok(())
    }
}

impl RequestReceiver<WlSubsurface> for Subsurface {
    fn receive(
        this: ObjectRef<Self>,
        request: WlSubsurfaceRequest,
        client: &mut Client,
    ) -> Result<(), Error> {
        match request {
            WlSubsurfaceRequest::Destroy => {
                let parent_ref = {
                    let subsurface = this.get(client)?;
                    subsurface.detach_from_parent(client)?;
                    subsurface.parent_ref
                };
                parent_ref.get_mut(client)?.detach_subsurface(this);
                client.delete_id(this.id())?;
            }
            WlSubsurfaceRequest::SetPosition { x, y } => {
                let surface_ref = this.get(client)?.surface_ref;
                surface_ref.get_mut(client)?.enqueue(SurfaceCommand::SetPosition(x, y));
            }
            WlSubsurfaceRequest::PlaceAbove { sibling } => {
                let parent_ref = this.get(client)?.parent_ref;
                parent_ref.get_mut(client)?.enqueue(SurfaceCommand::PlaceSubsurface(
                    PlaceSubsurfaceParams {
                        subsurface: this,
                        sibling: sibling.into(),
                        relation: SurfaceRelation::Above,
                    },
                ));
            }
            WlSubsurfaceRequest::PlaceBelow { sibling } => {
                let parent_ref = this.get(client)?.parent_ref;
                parent_ref.get_mut(client)?.enqueue(SurfaceCommand::PlaceSubsurface(
                    PlaceSubsurfaceParams {
                        subsurface: this,
                        sibling: sibling.into(),
                        relation: SurfaceRelation::Below,
                    },
                ));
            }
            // Note that SetSync and SetDesync are not double buffered as is
            // most state:
            //
            //   This state is applied when the parent surface's wl_surface
            //   state is applied, regardless of the sub-surface's mode. As the
            //   exception, set_sync and set_desync are effective immediately.
            WlSubsurfaceRequest::SetSync => {
                this.get_mut(client)?.mode = SubsurfaceMode::Sync;
            }
            WlSubsurfaceRequest::SetDesync => {
                let (commands, callbacks, surface_ref) = {
                    let this = this.get_mut(client)?;
                    let (commands, callbacks) = this.take_pending_state();
                    (commands, callbacks, this.surface_ref)
                };
                // TODO(tjdetwiler): We should instead schedule these callbacks
                // on the wl_surface immediately. This needs a small refactor of
                // wl_surface to make this possible.
                assert!(callbacks.is_empty());
                let surface = surface_ref.get_mut(client)?;
                for command in commands {
                    surface.enqueue(command);
                }
                this.get_mut(client)?.mode = SubsurfaceMode::Desync;
            }
        }
        Ok(())
    }
}