File: x11_software_bitmap_presenter.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (294 lines) | stat: -rw-r--r-- 9,984 bytes parent folder | download | duplicates (7)
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "ui/base/x/x11_software_bitmap_presenter.h"

#include <stddef.h>
#include <stdint.h>
#include <string.h>

#include <cstring>
#include <memory>
#include <utility>

#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted_memory.h"
#include "skia/ext/legacy_display_globals.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "ui/base/x/x11_shm_image_pool.h"
#include "ui/base/x/x11_util.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/x/atom_cache.h"
#include "ui/gfx/x/connection.h"
#include "ui/gfx/x/xproto.h"
#include "ui/gfx/x/xproto_types.h"

namespace ui {

namespace {

constexpr int kMaxFramesPending = 2;

class ScopedPixmap {
 public:
  ScopedPixmap(x11::Connection* connection, x11::Pixmap pixmap)
      : connection_(connection), pixmap_(pixmap) {}

  ScopedPixmap(const ScopedPixmap&) = delete;
  ScopedPixmap& operator=(const ScopedPixmap&) = delete;

  ~ScopedPixmap() {
    if (pixmap_ != x11::Pixmap::None) {
      connection_->FreePixmap({pixmap_});
    }
  }

 private:
  const raw_ptr<x11::Connection> connection_;
  x11::Pixmap pixmap_;
};

}  // namespace

// static
bool X11SoftwareBitmapPresenter::CompositeBitmap(x11::Connection* connection,
                                                 x11::Drawable widget,
                                                 int x,
                                                 int y,
                                                 int width,
                                                 int height,
                                                 int depth,
                                                 x11::GraphicsContext gc,
                                                 const void* data) {
  int16_t x_i16 = x;
  int16_t y_i16 = y;
  uint16_t w_u16 = width;
  uint16_t h_u16 = height;
  uint8_t d_u8 = depth;
  connection->ClearArea({false, widget, x_i16, y_i16, w_u16, h_u16});

  constexpr auto kAllPlanes =
      std::numeric_limits<decltype(x11::GetImageRequest::plane_mask)>::max();

  scoped_refptr<x11::UnsizedRefCountedMemory> bg;
  auto req = connection->GetImage({x11::ImageFormat::ZPixmap, widget, x_i16,
                                   y_i16, w_u16, h_u16, kAllPlanes});
  if (auto reply = req.Sync()) {
    bg = reply->data;
  } else {
    auto pixmap_id = connection->GenerateId<x11::Pixmap>();
    connection->CreatePixmap({d_u8, pixmap_id, widget, w_u16, h_u16});
    ScopedPixmap pixmap(connection, pixmap_id);

    connection->ChangeGC(x11::ChangeGCRequest{
        .gc = gc, .subwindow_mode = x11::SubwindowMode::IncludeInferiors});
    connection->CopyArea(
        {widget, pixmap_id, gc, x_i16, y_i16, 0, 0, w_u16, h_u16});
    connection->ChangeGC(x11::ChangeGCRequest{
        .gc = gc, .subwindow_mode = x11::SubwindowMode::ClipByChildren});

    auto pix_req = connection->GetImage(
        {x11::ImageFormat::ZPixmap, pixmap_id, 0, 0, w_u16, h_u16, kAllPlanes});
    auto pix_reply = pix_req.Sync();
    if (!pix_reply) {
      return false;
    }
    bg = pix_reply->data;
  }

  SkBitmap bg_bitmap;
  SkImageInfo image_info = SkImageInfo::Make(
      w_u16, h_u16, kBGRA_8888_SkColorType, kPremul_SkAlphaType);
  if (!bg_bitmap.installPixels(image_info, bg->bytes(),
                               image_info.minRowBytes())) {
    return false;
  }
  SkCanvas canvas(bg_bitmap);

  SkBitmap fg_bitmap;
  image_info = SkImageInfo::Make(width, height, kBGRA_8888_SkColorType,
                                 kPremul_SkAlphaType);
  if (!fg_bitmap.installPixels(image_info, const_cast<void*>(data),
                               4 * width)) {
    return false;
  }
  canvas.drawImage(fg_bitmap.asImage(), 0, 0);

  connection->PutImage(
      {x11::ImageFormat::ZPixmap, widget, gc, w_u16, h_u16, x_i16, y_i16, 0,
       d_u8, x11::SizedRefCountedMemory::From(bg, size_t{w_u16} * h_u16)});

  return true;
}

X11SoftwareBitmapPresenter::X11SoftwareBitmapPresenter(
    x11::Connection& connection,
    gfx::AcceleratedWidget widget,
    bool enable_multibuffering)
    : widget_(static_cast<x11::Window>(widget)),
      connection_(connection),
      enable_multibuffering_(enable_multibuffering) {
  DCHECK_NE(widget_, x11::Window::None);

  gc_ = connection_->GenerateId<x11::GraphicsContext>();
  connection_->CreateGC({gc_, widget_});

  if (auto response = connection_->GetWindowAttributes({widget_}).Sync()) {
    visual_ = response->visual;
    depth_ = connection_->GetVisualInfoFromId(visual_)->format->depth;
  } else {
    LOG(ERROR) << "XGetWindowAttributes failed for window "
               << static_cast<uint32_t>(widget_);
    return;
  }

  shm_pool_ = std::make_unique<ui::XShmImagePool>(
      &connection_.get(), widget_, visual_, depth_, MaxFramesPending(),
      enable_multibuffering_);

  // TODO(thomasanderson): Avoid going through the X11 server to plumb this
  // property in.
  connection_->GetPropertyAs(widget_, x11::GetAtom("CHROMIUM_COMPOSITE_WINDOW"),
                             &composite_);
}

X11SoftwareBitmapPresenter::~X11SoftwareBitmapPresenter() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (gc_ != x11::GraphicsContext{}) {
    connection_->FreeGC({gc_});
  }
}

bool X11SoftwareBitmapPresenter::ShmPoolReady() const {
  return shm_pool_ && shm_pool_->Ready();
}

void X11SoftwareBitmapPresenter::Resize(const gfx::Size& pixel_size) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (pixel_size == viewport_pixel_size_) {
    return;
  }
  viewport_pixel_size_ = pixel_size;
  // Fallback to the non-shm codepath when |composite_| is true, which only
  // happens for status icon windows that are typically 16x16px.  It's possible
  // to add a shm codepath, but it wouldn't be buying much since it would only
  // affect windows that are tiny and infrequently updated.
  if (!composite_ && shm_pool_ && shm_pool_->Resize(pixel_size)) {
    needs_swap_ = false;
    surface_ = nullptr;
  } else {
    SkColorType color_type = ColorTypeForVisual(visual_);
    if (color_type == kUnknown_SkColorType) {
      return;
    }
    SkImageInfo info = SkImageInfo::Make(viewport_pixel_size_.width(),
                                         viewport_pixel_size_.height(),
                                         color_type, kOpaque_SkAlphaType);
    SkSurfaceProps props = skia::LegacyDisplayGlobals::GetSkSurfaceProps();
    surface_ = SkSurfaces::Raster(info, &props);
  }
}

SkCanvas* X11SoftwareBitmapPresenter::GetSkCanvas() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (ShmPoolReady()) {
    return shm_pool_->CurrentCanvas();
  } else if (surface_) {
    return surface_->getCanvas();
  }
  return nullptr;
}

void X11SoftwareBitmapPresenter::EndPaint(const gfx::Rect& damage_rect) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  gfx::Rect rect = damage_rect;
  rect.Intersect(gfx::Rect(viewport_pixel_size_));
  if (rect.IsEmpty()) {
    return;
  }

  SkPixmap skia_pixmap;

  if (ShmPoolReady()) {
    // TODO(thomasanderson): Investigate direct rendering with DRI3 to avoid any
    // unnecessary X11 IPC or buffer copying.
    x11::Shm::PutImageRequest put_image_request{
        .drawable = widget_,
        .gc = gc_,
        .total_width =
            static_cast<uint16_t>(shm_pool_->CurrentBitmap().width()),
        .total_height =
            static_cast<uint16_t>(shm_pool_->CurrentBitmap().height()),
        .src_x = static_cast<uint16_t>(rect.x()),
        .src_y = static_cast<uint16_t>(rect.y()),
        .src_width = static_cast<uint16_t>(rect.width()),
        .src_height = static_cast<uint16_t>(rect.height()),
        .dst_x = static_cast<int16_t>(rect.x()),
        .dst_y = static_cast<int16_t>(rect.y()),
        .depth = static_cast<uint8_t>(depth_),
        .format = x11::ImageFormat::ZPixmap,
        .send_event = enable_multibuffering_,
        .shmseg = shm_pool_->CurrentSegment(),
        .offset = 0,
    };
    connection_->shm().PutImage(put_image_request);
    needs_swap_ = true;
    // Flush now to ensure the X server gets the request as early as
    // possible to reduce frame-to-frame latency.
    connection_->Flush();
    return;
  }
  if (surface_) {
    surface_->peekPixels(&skia_pixmap);
  }

  if (!skia_pixmap.addr()) {
    return;
  }

  if (composite_ && CompositeBitmap(&connection_.get(), widget_, rect.x(),
                                    rect.y(), rect.width(), rect.height(),
                                    depth_, gc_, skia_pixmap.addr())) {
    // Flush now to ensure the X server gets the request as early as
    // possible to reduce frame-to-frame latency.

    connection_->Flush();
    return;
  }

  auto* connection = x11::Connection::Get();
  DrawPixmap(connection, visual_, widget_, gc_, skia_pixmap, rect.x(), rect.y(),
             rect.x(), rect.y(), rect.width(), rect.height());

  // Flush now to ensure the X server gets the request as early as
  // possible to reduce frame-to-frame latency.
  connection_->Flush();
}

void X11SoftwareBitmapPresenter::OnSwapBuffers(
    SwapBuffersCallback swap_ack_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (enable_multibuffering_ && ShmPoolReady() && needs_swap_) {
    shm_pool_->SwapBuffers(std::move(swap_ack_callback));
  } else {
    std::move(swap_ack_callback).Run(viewport_pixel_size_);
  }
  needs_swap_ = false;
}

int X11SoftwareBitmapPresenter::MaxFramesPending() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return enable_multibuffering_ ? kMaxFramesPending : 1;
}

}  // namespace ui