Skip to main content

carnelian/view/strategies/
display_direct.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::app::strategies::framebuffer::{CoordinatorProxyPtr, DisplayId};
6use crate::app::{Config, MessageInternal};
7use crate::drawing::DisplayRotation;
8use crate::render::generic::{self, Backend};
9use crate::render::{Context as RenderContext, ContextInner};
10use crate::view::strategies::base::{ViewStrategy, ViewStrategyPtr};
11use crate::view::{
12    DisplayInfo, UserInputMessage, ViewAssistantContext, ViewAssistantPtr, ViewDetails,
13};
14use crate::{IntPoint, IntSize, Size, ViewKey, input};
15use anyhow::{Context, Error, bail, ensure};
16use async_trait::async_trait;
17use display_utils::{
18    BufferCollectionId, EventId, INVALID_LAYER_ID, ImageId as DisplayImageId, LayerId, PixelFormat,
19};
20use euclid::size2;
21use fidl_fuchsia_hardware_display::{
22    ConfigStamp, CoordinatorCommitConfigRequest, CoordinatorListenerRequest, CoordinatorProxy,
23    INVALID_CONFIG_STAMP_VALUE,
24};
25use fidl_fuchsia_hardware_display_types::{INVALID_DISP_ID, ImageBufferUsage, ImageMetadata};
26use fuchsia_async::{self as fasync};
27use fuchsia_framebuffer::sysmem::BufferCollectionAllocator;
28use fuchsia_framebuffer::{FrameSet, FrameUsage, ImageId};
29use fuchsia_trace::{duration, instant};
30use futures::channel::mpsc::UnboundedSender;
31use std::collections::{BTreeMap, BTreeSet, VecDeque};
32use std::sync::atomic::{AtomicU64, Ordering};
33use zx::{Event, MonotonicDuration, MonotonicInstant, Status};
34
35type WaitEvents = BTreeMap<ImageId, (Event, EventId)>;
36
37struct BusyImage {
38    stamp: ConfigStamp,
39    view_key: ViewKey,
40    image_id: DisplayImageId,
41    collection_id: BufferCollectionId,
42}
43
44#[derive(Default)]
45struct CollectionIdGenerator {}
46
47impl Iterator for CollectionIdGenerator {
48    type Item = BufferCollectionId;
49
50    fn next(&mut self) -> Option<BufferCollectionId> {
51        static NEXT_ID_VALUE: AtomicU64 = AtomicU64::new(100);
52        // NEXT_ID_VALUE only increments so it only requires atomicity, and we
53        // can use Relaxed order.
54        let value = NEXT_ID_VALUE.fetch_add(1, Ordering::Relaxed);
55        // fetch_add wraps on overflow, which we'll use as a signal
56        // that this generator is out of ids.
57        if value == 0 { None } else { Some(BufferCollectionId(value)) }
58    }
59}
60fn next_collection_id() -> BufferCollectionId {
61    CollectionIdGenerator::default().next().expect("collection_id")
62}
63
64#[derive(Default)]
65struct ImageIdGenerator {}
66
67impl Iterator for ImageIdGenerator {
68    type Item = u64;
69
70    fn next(&mut self) -> Option<u64> {
71        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
72        // NEXT_ID only increments so it only requires atomicity, and we can
73        // use Relaxed order.
74        let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
75        // fetch_add wraps on overflow, which we'll use as a signal
76        // that this generator is out of ids.
77        if id == 0 { None } else { Some(id) }
78    }
79}
80fn next_image_id() -> u64 {
81    ImageIdGenerator::default().next().expect("image_id")
82}
83
84#[derive(Default)]
85struct LayerIdGenerator {}
86
87impl Iterator for LayerIdGenerator {
88    type Item = LayerId;
89
90    fn next(&mut self) -> Option<LayerId> {
91        static NEXT_ID_VALUE: AtomicU64 = AtomicU64::new(1);
92        // NEXT_ID_VALUE only increments so it only requires atomicity, and we
93        // can use Relaxed order.
94        let value = NEXT_ID_VALUE.fetch_add(1, Ordering::Relaxed);
95        // fetch_add wraps on overflow, which we'll use as a signal
96        // that this generator is out of ids.
97        if value == 0 { None } else { Some(LayerId(value)) }
98    }
99}
100fn next_layer_id() -> LayerId {
101    LayerIdGenerator::default().next().expect("layer_id")
102}
103
104async fn create_and_import_event(
105    coordinator: &CoordinatorProxy,
106) -> Result<(Event, EventId), Error> {
107    let event = Event::create();
108
109    let their_event = event.duplicate_handle(zx::Rights::SAME_RIGHTS)?;
110    let event_id_value = event.koid()?.raw_koid();
111    let event_id = EventId(event_id_value);
112    coordinator.import_event(their_event, &event_id.into())?;
113    Ok((event, event_id))
114}
115
116fn size_from_info(info: &fidl_fuchsia_hardware_display::Info, mode_idx: usize) -> IntSize {
117    let mode = &info.modes[mode_idx];
118    size2(mode.active_area.width, mode.active_area.height).to_i32()
119}
120
121#[derive(Debug, Clone)]
122pub struct Display {
123    pub coordinator: CoordinatorProxyPtr,
124    pub display_id: DisplayId,
125    pub info: fidl_fuchsia_hardware_display::Info,
126    pub layer_id: LayerId,
127    pub mode_idx: usize,
128}
129
130impl Display {
131    pub async fn new(
132        coordinator: CoordinatorProxyPtr,
133        display_id: DisplayId,
134        info: fidl_fuchsia_hardware_display::Info,
135    ) -> Result<Self, Error> {
136        Ok(Self { coordinator, display_id, info, layer_id: INVALID_LAYER_ID, mode_idx: 0 })
137    }
138
139    pub fn set_mode(&mut self, mode_idx: usize) -> Result<(), Error> {
140        self.coordinator.set_display_mode(&self.info.id, &self.info.modes[mode_idx])?;
141        self.mode_idx = mode_idx;
142        Ok(())
143    }
144
145    pub async fn create_layer(&mut self) -> Result<(), Error> {
146        let layer_id = next_layer_id();
147        let result = self.coordinator.create_layer(&layer_id.into()).await?;
148        match result {
149            Ok(()) => {
150                self.layer_id = layer_id.into();
151                Ok(())
152            }
153            Err(status) => {
154                bail!("Display::new(): failed to create layer {}", Status::err_from_raw(status))
155            }
156        }
157    }
158
159    pub fn size(&self) -> IntSize {
160        size_from_info(&self.info, self.mode_idx)
161    }
162
163    pub fn pixel_format(&self) -> PixelFormat {
164        self.info.pixel_format[0].into()
165    }
166}
167
168struct DisplayResources {
169    pub frame_set: FrameSet,
170    pub image_indexes: BTreeMap<ImageId, u32>,
171    pub context: RenderContext,
172    pub wait_events: WaitEvents,
173    pub busy_images: VecDeque<BusyImage>,
174}
175
176const RENDER_FRAME_COUNT: usize = 2;
177
178pub(crate) struct DisplayDirectViewStrategy {
179    key: ViewKey,
180    display: Display,
181    app_sender: UnboundedSender<MessageInternal>,
182    display_rotation: DisplayRotation,
183    display_resources: Option<DisplayResources>,
184    drop_display_resources_task: Option<fasync::Task<()>>,
185    display_resource_release_delay: std::time::Duration,
186    vsync_phase: MonotonicInstant,
187    vsync_interval: MonotonicDuration,
188    mouse_cursor_position: Option<IntPoint>,
189    pub collection_id: BufferCollectionId,
190    render_frame_count: usize,
191    last_config_stamp: u64,
192
193    /// ID of the framebuffer that has been prepared for presentation.
194    prepared: Option<ImageId>,
195
196    /// ID of the framebuffer submitted in the most recent present call.
197    presented: Option<ImageId>,
198}
199
200impl DisplayDirectViewStrategy {
201    pub async fn new(
202        key: ViewKey,
203        coordinator: CoordinatorProxyPtr,
204        app_sender: UnboundedSender<MessageInternal>,
205        info: fidl_fuchsia_hardware_display::Info,
206        preferred_size: IntSize,
207    ) -> Result<ViewStrategyPtr, Error> {
208        let app_config = Config::get();
209        let collection_id = next_collection_id();
210        let render_frame_count = app_config.buffer_count.unwrap_or(RENDER_FRAME_COUNT);
211
212        // Find first mode with the preferred size. Use preferred mode if not found.
213        let mode_idx = info
214            .modes
215            .iter()
216            .position(|mode| {
217                let size = size2(mode.active_area.width, mode.active_area.height).to_i32();
218                size == preferred_size
219            })
220            .unwrap_or(0);
221
222        let mut display = Display::new(coordinator, info.id.into(), info).await?;
223
224        if mode_idx != 0 {
225            display.set_mode(mode_idx)?;
226        }
227        display.create_layer().await?;
228
229        let display_resources = Self::allocate_display_resources(
230            collection_id,
231            display.size(),
232            display.pixel_format(),
233            render_frame_count,
234            &display,
235        )
236        .await?;
237
238        app_sender.unbounded_send(MessageInternal::Render(key)).expect("unbounded_send");
239        app_sender.unbounded_send(MessageInternal::Focus(key, true)).expect("unbounded_send");
240
241        Ok(Box::new(Self {
242            key,
243            display,
244            app_sender,
245            display_rotation: app_config.display_rotation,
246            display_resources: Some(display_resources),
247            drop_display_resources_task: None,
248            display_resource_release_delay: app_config.display_resource_release_delay,
249            vsync_phase: MonotonicInstant::get(),
250            vsync_interval: MonotonicDuration::from_millis(16),
251            mouse_cursor_position: None,
252            collection_id,
253            render_frame_count,
254            last_config_stamp: INVALID_CONFIG_STAMP_VALUE,
255            prepared: None,
256            presented: None,
257        }))
258    }
259
260    fn make_context(
261        &mut self,
262        view_details: &ViewDetails,
263        image_id: Option<ImageId>,
264    ) -> ViewAssistantContext {
265        let time_now = MonotonicInstant::get();
266        // |interval_offset| is the offset from |time_now| to the next multiple
267        // of vsync interval after vsync phase, possibly negative if in the past.
268        let mut interval_offset = MonotonicDuration::from_nanos(
269            (self.vsync_phase.into_nanos() - time_now.into_nanos())
270                % self.vsync_interval.into_nanos(),
271        );
272        // Unless |time_now| is exactly on the interval, adjust forward to the next
273        // vsync after |time_now|.
274        if interval_offset != MonotonicDuration::from_nanos(0) && self.vsync_phase < time_now {
275            interval_offset += self.vsync_interval;
276        }
277
278        let display_rotation = self.display_rotation;
279        let app_sender = self.app_sender.clone();
280        let mouse_cursor_position = self.mouse_cursor_position.clone();
281        let (image_index, actual_image_id) = image_id
282            .and_then(|available| {
283                Some((
284                    *self.display_resources().image_indexes.get(&available).expect("image_index"),
285                    available,
286                ))
287            })
288            .unwrap_or_default();
289
290        ViewAssistantContext {
291            key: view_details.key,
292            size: match display_rotation {
293                DisplayRotation::Deg0 | DisplayRotation::Deg180 => view_details.physical_size,
294                DisplayRotation::Deg90 | DisplayRotation::Deg270 => {
295                    size2(view_details.physical_size.height, view_details.physical_size.width)
296                }
297            },
298            metrics: view_details.metrics,
299            presentation_time: time_now + interval_offset,
300            buffer_count: None,
301            image_id: actual_image_id,
302            image_index: image_index,
303            app_sender,
304            mouse_cursor_position,
305            display_info: Some(DisplayInfo::from(&self.display.info)),
306        }
307    }
308
309    async fn allocate_display_resources(
310        collection_id: BufferCollectionId,
311        size: IntSize,
312        pixel_format: display_utils::PixelFormat,
313        render_frame_count: usize,
314        display: &Display,
315    ) -> Result<DisplayResources, Error> {
316        let app_config = Config::get();
317
318        let display_rotation = app_config.display_rotation;
319        let unsize = size.floor().to_u32();
320
321        let mut buffer_allocator = BufferCollectionAllocator::new(
322            unsize.width,
323            unsize.height,
324            pixel_format.into(),
325            FrameUsage::Cpu,
326            render_frame_count,
327        )?;
328
329        buffer_allocator.set_name(100, "CarnelianDirect")?;
330
331        let context_token = buffer_allocator.duplicate_token().await?;
332        let context = RenderContext {
333            inner: ContextInner::Forma(generic::Forma::new_context(
334                context_token,
335                unsize,
336                display_rotation,
337            )),
338        };
339
340        let coordinator_token = buffer_allocator.duplicate_token().await?;
341        // Sysmem token channels serve both sysmem(1) and sysmem2, so we can convert here until
342        // display has an import_buffer_collection that takes a sysmem2 token.
343        display
344            .coordinator
345            .import_buffer_collection(&collection_id.into(), coordinator_token)
346            .await?
347            .map_err(zx::Status::err_from_raw)?;
348        display
349            .coordinator
350            .set_buffer_collection_constraints(
351                &collection_id.into(),
352                &ImageBufferUsage {
353                    tiling_type: fidl_fuchsia_hardware_display_types::IMAGE_TILING_TYPE_LINEAR,
354                },
355            )
356            .await?
357            .map_err(zx::Status::err_from_raw)?;
358
359        let buffers = buffer_allocator
360            .allocate_buffers(true)
361            .await
362            .context(format!("view: {:?} allocate_buffers", display.display_id))?;
363
364        ensure!(
365            buffers.settings.as_ref().unwrap().image_format_constraints.is_some(),
366            "No image format constraints"
367        );
368        ensure!(
369            buffers
370                .settings
371                .as_ref()
372                .unwrap()
373                .image_format_constraints
374                .as_ref()
375                .unwrap()
376                .pixel_format_modifier
377                .is_some(),
378            "Sysmem will always set pixel_format_modifier"
379        );
380        ensure!(
381            buffers.buffers.as_ref().unwrap().len() == render_frame_count,
382            "Buffers do not match frame count"
383        );
384
385        let image_tiling_type = match buffers
386            .settings
387            .as_ref()
388            .unwrap()
389            .image_format_constraints
390            .as_ref()
391            .unwrap()
392            .pixel_format_modifier
393            .as_ref()
394            .unwrap()
395        {
396            fidl_fuchsia_images2::PixelFormatModifier::IntelI915XTiled => 1,
397            fidl_fuchsia_images2::PixelFormatModifier::IntelI915YTiled => 2,
398            _ => fidl_fuchsia_hardware_display_types::IMAGE_TILING_TYPE_LINEAR,
399        };
400
401        let image_metadata = ImageMetadata {
402            dimensions: fidl_fuchsia_math::SizeU { width: unsize.width, height: unsize.height },
403            tiling_type: image_tiling_type,
404        };
405
406        let mut image_ids = BTreeSet::new();
407        let mut image_indexes = BTreeMap::new();
408        let mut wait_events = WaitEvents::new();
409        let buffer_count = buffers.buffers.as_ref().unwrap().len();
410        for index in 0..buffer_count as usize {
411            let uindex = index as u32;
412            let image_id = next_image_id();
413            let display_image_id = DisplayImageId(image_id);
414            display
415                .coordinator
416                .import_image(
417                    &image_metadata,
418                    &collection_id.into(),
419                    uindex,
420                    &display_image_id.into(),
421                )
422                .await
423                .context("FIDL coordinator import_image")?
424                .map_err(zx::Status::err_from_raw)
425                .context("import image error")?;
426
427            image_ids.insert(image_id as u64);
428            image_indexes.insert(image_id as u64, uindex);
429
430            let (event, event_id) = create_and_import_event(&display.coordinator).await?;
431            wait_events.insert(image_id as ImageId, (event, event_id));
432        }
433
434        let frame_set = FrameSet::new(image_ids);
435
436        display.coordinator.set_layer_primary_config(&display.layer_id.into(), &image_metadata)?;
437
438        Ok(DisplayResources {
439            frame_set,
440            image_indexes,
441            context,
442            wait_events,
443            busy_images: VecDeque::new(),
444        })
445    }
446
447    async fn maybe_reallocate_display_resources(&mut self) -> Result<(), Error> {
448        if self.display_resources.is_none() {
449            instant!(
450                c"gfx",
451                c"DisplayDirectViewStrategy::allocate_display_resources",
452                fuchsia_trace::Scope::Process,
453                "" => ""
454            );
455            self.collection_id = next_collection_id();
456            self.prepared = None;
457            self.presented = None;
458            self.display_resources = Some(
459                Self::allocate_display_resources(
460                    self.collection_id,
461                    self.display.size(),
462                    self.display.pixel_format(),
463                    self.render_frame_count,
464                    &self.display,
465                )
466                .await?,
467            );
468        }
469        Ok(())
470    }
471
472    fn display_resources(&mut self) -> &mut DisplayResources {
473        self.display_resources.as_mut().expect("display_resources")
474    }
475
476    fn update_image(
477        &mut self,
478        view_details: &ViewDetails,
479        view_assistant: &mut ViewAssistantPtr,
480        image: u64,
481    ) {
482        instant!(
483            c"gfx",
484            c"DisplayDirectViewStrategy::update_image",
485            fuchsia_trace::Scope::Process,
486            "image" => format!("{}", image).as_str()
487        );
488        let (event, _) = self.display_resources().wait_events.get(&image).expect("wait event");
489        let buffer_ready_event =
490            event.duplicate_handle(zx::Rights::SAME_RIGHTS).expect("duplicate_handle");
491        let direct_context = self.make_context(view_details, Some(image));
492
493        view_assistant
494            .render(&mut self.display_resources().context, buffer_ready_event, &direct_context)
495            .unwrap_or_else(|e| panic!("Update error: {:?}", e));
496    }
497
498    fn handle_vsync_parameters_changed(
499        &mut self,
500        phase: MonotonicInstant,
501        interval: MonotonicDuration,
502    ) {
503        self.vsync_phase = phase;
504        self.vsync_interval = interval;
505    }
506}
507
508#[async_trait(?Send)]
509impl ViewStrategy for DisplayDirectViewStrategy {
510    fn initial_metrics(&self) -> Size {
511        size2(1.0, 1.0)
512    }
513
514    fn initial_physical_size(&self) -> Size {
515        self.display.size().to_f32()
516    }
517
518    fn initial_logical_size(&self) -> Size {
519        self.display.size().to_f32()
520    }
521
522    fn create_view_assistant_context(&self, view_details: &ViewDetails) -> ViewAssistantContext {
523        ViewAssistantContext {
524            key: view_details.key,
525            size: match self.display_rotation {
526                DisplayRotation::Deg0 | DisplayRotation::Deg180 => view_details.physical_size,
527                DisplayRotation::Deg90 | DisplayRotation::Deg270 => {
528                    size2(view_details.physical_size.height, view_details.physical_size.width)
529                }
530            },
531            metrics: view_details.metrics,
532            presentation_time: Default::default(),
533            buffer_count: None,
534            image_id: Default::default(),
535            image_index: Default::default(),
536            app_sender: self.app_sender.clone(),
537            mouse_cursor_position: self.mouse_cursor_position.clone(),
538            display_info: Some(DisplayInfo::from(&self.display.info)),
539        }
540    }
541
542    fn setup(&mut self, view_details: &ViewDetails, view_assistant: &mut ViewAssistantPtr) {
543        if let Some(available) = self.display_resources().frame_set.take_image() {
544            let direct_context = self.make_context(view_details, Some(available));
545            view_assistant
546                .setup(&direct_context)
547                .unwrap_or_else(|e| panic!("Setup error: {:?}", e));
548            self.display_resources().frame_set.return_image(available);
549        }
550    }
551
552    async fn render(
553        &mut self,
554        view_details: &ViewDetails,
555        view_assistant: &mut ViewAssistantPtr,
556    ) -> bool {
557        duration!("gfx", "DisplayDirectViewStrategy::update");
558        self.maybe_reallocate_display_resources()
559            .await
560            .expect("maybe_reallocate_display_resources");
561
562        let prepared_image: Option<ImageId> =
563            self.display_resources().frame_set.take_image().or_else(|| {
564                // If there is only one render framebuffer, we always use that
565                // framebuffer, even if it's being presented.
566                if self.render_frame_count == 1 { self.presented } else { None }
567            });
568
569        if let Some(prepared_image) = prepared_image {
570            self.update_image(view_details, view_assistant, prepared_image);
571            self.prepared = Some(prepared_image);
572            true
573        } else {
574            false
575        }
576    }
577
578    fn present(&mut self, view_details: &ViewDetails) {
579        duration!("gfx", "DisplayDirectViewStrategy::present");
580
581        let image_to_present = self.prepared.take();
582        if let Some(image_to_present) = image_to_present {
583            instant!(
584                c"gfx",
585                c"DisplayDirectViewStrategy::present",
586                fuchsia_trace::Scope::Process,
587                "image_to_present" => format!("{}", image_to_present).as_str()
588            );
589            let collection_id = self.collection_id;
590            let view_key = view_details.key;
591
592            let layers = &[self.display.layer_id.into()];
593            if layers.len() as u32 > self.display.info.max_layer_count {
594                panic!(
595                    "Hardware layer limit ({}) is insufficient for Carnelian (requested {})",
596                    self.display.info.max_layer_count,
597                    layers.len()
598                );
599            }
600
601            self.display
602                .coordinator
603                .set_display_layers(&self.display.display_id.into(), layers)
604                .expect("set_display_layers");
605
606            let (_, wait_event_id) =
607                *self.display_resources().wait_events.get(&image_to_present).expect("wait event");
608
609            let image_id = DisplayImageId(image_to_present);
610            self.display
611                .coordinator
612                .set_layer_image2(
613                    &self.display.layer_id.into(),
614                    &image_id.into(),
615                    &wait_event_id.into(),
616                )
617                .expect("Frame::present() set_layer_image2");
618
619            self.last_config_stamp += 1;
620            let stamp = ConfigStamp { value: self.last_config_stamp };
621            let req = CoordinatorCommitConfigRequest { stamp: Some(stamp), ..Default::default() };
622
623            self.display.coordinator.commit_config(req).expect("Frame::present() commit_config");
624
625            if self.render_frame_count > 1 {
626                self.display_resources().busy_images.push_back(BusyImage {
627                    stamp,
628                    view_key,
629                    image_id,
630                    collection_id,
631                });
632            }
633            self.presented = Some(image_to_present);
634        }
635    }
636
637    fn handle_focus(
638        &mut self,
639        view_details: &ViewDetails,
640        view_assistant: &mut ViewAssistantPtr,
641        focus: bool,
642    ) {
643        let mut direct_context = self.make_context(view_details, None);
644        view_assistant
645            .handle_focus_event(&mut direct_context, focus)
646            .unwrap_or_else(|e| panic!("handle_focus error: {:?}", e));
647    }
648
649    fn convert_user_input_message(
650        &mut self,
651        _view_details: &ViewDetails,
652        _message: UserInputMessage,
653    ) -> Result<Vec<crate::input::Event>, Error> {
654        bail!("convert_user_input_message not used for display_direct.")
655    }
656
657    fn inspect_event(&mut self, view_details: &ViewDetails, event: &crate::input::Event) {
658        match &event.event_type {
659            input::EventType::Mouse(mouse_event) => {
660                self.mouse_cursor_position = Some(mouse_event.location);
661                self.app_sender
662                    .unbounded_send(MessageInternal::RequestRender(view_details.key))
663                    .expect("unbounded_send");
664            }
665            _ => (),
666        };
667    }
668
669    fn image_freed(&mut self, image_id: u64, collection_id: u32) {
670        if BufferCollectionId(collection_id as u64) == self.collection_id {
671            instant!(
672                c"gfx",
673                c"DisplayDirectViewStrategy::image_freed",
674                fuchsia_trace::Scope::Process,
675                "image_freed" => format!("{}", image_id).as_str()
676            );
677            if let Some(display_resources) = self.display_resources.as_mut() {
678                display_resources.frame_set.return_image(image_id);
679            }
680        }
681    }
682
683    fn ownership_changed(&mut self, owned: bool) {
684        if !owned {
685            let timer = fasync::Timer::new(fuchsia_async::MonotonicInstant::after(
686                self.display_resource_release_delay.into(),
687            ));
688            let timer_sender = self.app_sender.clone();
689            let task = fasync::Task::local(async move {
690                timer.await;
691                timer_sender
692                    .unbounded_send(MessageInternal::DropDisplayResources)
693                    .expect("unbounded_send");
694            });
695            self.drop_display_resources_task = Some(task);
696        } else {
697            self.drop_display_resources_task = None;
698        }
699    }
700
701    fn drop_display_resources(&mut self) {
702        let task = self.drop_display_resources_task.take();
703        if task.is_some() {
704            instant!(
705                c"gfx",
706                c"DisplayDirectViewStrategy::drop_display_resources",
707                fuchsia_trace::Scope::Process,
708                "" => ""
709            );
710            self.prepared = None;
711            self.presented = None;
712            self.display_resources = None;
713        }
714    }
715
716    async fn handle_display_coordinator_listener_request(
717        &mut self,
718        event: CoordinatorListenerRequest,
719    ) {
720        match event {
721            CoordinatorListenerRequest::OnVsync {
722                timestamp,
723                cookie,
724                displayed_config_stamp,
725                ..
726            } => {
727                duration!("gfx", "DisplayDirectViewStrategy::OnVsync");
728                let vsync_interval = MonotonicDuration::from_nanos(
729                    1_000_000_000_000 / self.display.info.modes[0].refresh_rate_millihertz as i64,
730                );
731                self.handle_vsync_parameters_changed(timestamp, vsync_interval);
732                if cookie.value != INVALID_DISP_ID {
733                    self.display
734                        .coordinator
735                        .acknowledge_vsync(cookie.value)
736                        .expect("acknowledge_vsync");
737                }
738
739                let signal_sender = self.app_sender.clone();
740
741                // Busy images are stamped with monotonically increasing values (because the last
742                // stamp added to the deque is always greater than the previous).  So when we see a
743                // vsync stamp, all images with a *strictly-lesser* stamp are now available for
744                // reuse (images with an *equal* stamp are the ones currently displayed on-screen,
745                // so can't be reused yet).
746                if let Some(display_resources) = self.display_resources.as_mut() {
747                    let busy_images = &mut display_resources.busy_images;
748                    while !busy_images.is_empty() {
749                        let front = &busy_images.front().unwrap();
750                        if displayed_config_stamp.value <= front.stamp.value {
751                            break;
752                        }
753
754                        signal_sender
755                            .unbounded_send(MessageInternal::ImageFreed(
756                                front.view_key,
757                                front.image_id.0,
758                                front.collection_id.0 as u32,
759                            ))
760                            .expect("unbounded_send");
761
762                        busy_images.pop_front();
763                    }
764                }
765
766                signal_sender
767                    .unbounded_send(MessageInternal::Render(self.key))
768                    .expect("unbounded_send");
769            }
770            CoordinatorListenerRequest::OnDisplaysChanged { .. } => {
771                eprintln!("Carnelian ignoring CoordinatorListenerRequest::OnDisplaysChanged");
772            }
773            CoordinatorListenerRequest::OnClientOwnershipChange { has_ownership, .. } => {
774                eprintln!(
775                    "Carnelian ignoring CoordinatorListenerRequest::OnClientOwnershipChange (value: {})",
776                    has_ownership
777                );
778            }
779            _ => (),
780        }
781    }
782
783    fn is_hosted_on_display(&self, display_id: DisplayId) -> bool {
784        self.display.display_id == display_id
785    }
786
787    fn close(&mut self) {
788        self.display
789            .coordinator
790            .release_buffer_collection(&self.collection_id.into())
791            .expect("release_buffer_collection");
792    }
793}