File: wayland_util.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 (456 lines) | stat: -rw-r--r-- 15,325 bytes parent folder | download | duplicates (5)
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.


#include "ui/ozone/platform/wayland/common/wayland_util.h"

#include <sys/socket.h>
#include <xdg-shell-client-protocol.h>

#include "base/files/file_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "build/buildflag.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/base/hit_test.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/ozone/platform/wayland/host/wayland_connection.h"
#include "ui/ozone/platform/wayland/host/wayland_shm_buffer.h"
#include "ui/ozone/platform/wayland/host/wayland_surface.h"
#include "ui/ozone/platform/wayland/host/wayland_window.h"

namespace wl {

namespace {

const SkColorType kColorType = kBGRA_8888_SkColorType;

}  // namespace

uint32_t IdentifyDirection(int hittest) {
  uint32_t direction = 0;
  switch (hittest) {
    case HTBOTTOM:
      direction = xdg_toplevel_resize_edge::XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM;
      break;
    case HTBOTTOMLEFT:
      direction =
          xdg_toplevel_resize_edge::XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT;
      break;
    case HTBOTTOMRIGHT:
      direction =
          xdg_toplevel_resize_edge::XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT;
      break;
    case HTLEFT:
      direction = xdg_toplevel_resize_edge::XDG_TOPLEVEL_RESIZE_EDGE_LEFT;
      break;
    case HTRIGHT:
      direction = xdg_toplevel_resize_edge::XDG_TOPLEVEL_RESIZE_EDGE_RIGHT;
      break;
    case HTTOP:
      direction = xdg_toplevel_resize_edge::XDG_TOPLEVEL_RESIZE_EDGE_TOP;
      break;
    case HTTOPLEFT:
      direction = xdg_toplevel_resize_edge::XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT;
      break;
    case HTTOPRIGHT:
      direction = xdg_toplevel_resize_edge::XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT;
      break;
    default:
      direction = xdg_toplevel_resize_edge::XDG_TOPLEVEL_RESIZE_EDGE_NONE;
      break;
  }
  return direction;
}

bool DrawBitmap(const SkBitmap& bitmap, ui::WaylandShmBuffer* out_buffer) {
  DCHECK(out_buffer);
  DCHECK(out_buffer->GetMemory());
  DCHECK(gfx::Rect(out_buffer->size())
             .Contains(gfx::Rect(bitmap.width(), bitmap.height())));

  auto* mapped_memory = out_buffer->GetMemory();
  auto size = out_buffer->size();
  sk_sp<SkSurface> sk_surface =
      SkSurfaces::WrapPixels(SkImageInfo::Make(size.width(), size.height(),
                                               kColorType, kOpaque_SkAlphaType),
                             mapped_memory, out_buffer->stride());

  if (!sk_surface)
    return false;

  // The |bitmap| contains ARGB image, so update our wl_buffer, which is
  // backed by a SkSurface.
  SkRect damage;
  bitmap.getBounds(&damage);

  // Clear to transparent in case |bitmap| is smaller than the canvas.
  auto* canvas = sk_surface->getCanvas();
  canvas->clear(SK_ColorTRANSPARENT);
  canvas->drawImageRect(bitmap.asImage(), damage, SkSamplingOptions());
  return true;
}

void ReadDataFromFD(base::ScopedFD fd, std::vector<uint8_t>* contents) {
  DCHECK(contents);
  std::array<uint8_t, 1 << 10> buffer;  // 1 kB in bytes.
  ssize_t length;
  while ((length = read(fd.get(), buffer.data(), buffer.size())) > 0) {
    contents->insert(contents->end(), buffer.begin(), buffer.begin() + length);
  }
}

gfx::Rect TranslateBoundsToParentCoordinates(const gfx::Rect& child_bounds,
                                             const gfx::Rect& parent_bounds) {
  return gfx::Rect(
      (child_bounds.origin() - parent_bounds.origin().OffsetFromOrigin()),
      child_bounds.size());
}

gfx::RectF TranslateBoundsToParentCoordinatesF(
    const gfx::RectF& child_bounds,
    const gfx::RectF& parent_bounds) {
  return gfx::RectF(
      (child_bounds.origin() - parent_bounds.origin().OffsetFromOrigin()),
      child_bounds.size());
}

gfx::Rect TranslateBoundsToTopLevelCoordinates(const gfx::Rect& child_bounds,
                                               const gfx::Rect& parent_bounds) {
  return gfx::Rect(
      (child_bounds.origin() + parent_bounds.origin().OffsetFromOrigin()),
      child_bounds.size());
}

wl_output_transform ToWaylandTransform(gfx::OverlayTransform transform) {
  switch (transform) {
    case gfx::OVERLAY_TRANSFORM_NONE:
      return WL_OUTPUT_TRANSFORM_NORMAL;
    case gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL:
      return WL_OUTPUT_TRANSFORM_FLIPPED;
    case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL:
      return WL_OUTPUT_TRANSFORM_FLIPPED_180;
    // gfx::OverlayTransform and Wayland buffer transforms rotate in opposite
    // directions relative to each other, so swap 90 and 270.
    // TODO(rivr): Currently all wl_buffers are created without y inverted, so
    // this may need to be revisited if that changes.
    case gfx::OVERLAY_TRANSFORM_ROTATE_CLOCKWISE_90:
      return WL_OUTPUT_TRANSFORM_270;
    case gfx::OVERLAY_TRANSFORM_ROTATE_CLOCKWISE_180:
      return WL_OUTPUT_TRANSFORM_180;
    case gfx::OVERLAY_TRANSFORM_ROTATE_CLOCKWISE_270:
      return WL_OUTPUT_TRANSFORM_90;
    case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL_CLOCKWISE_90:
    case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL_CLOCKWISE_270:
    default:
      break;
  }
  NOTREACHED();
}

gfx::RectF ApplyWaylandTransform(const gfx::RectF& rect,
                                 const gfx::SizeF& bounds,
                                 wl_output_transform transform) {
  gfx::RectF result = rect;
  switch (transform) {
    case WL_OUTPUT_TRANSFORM_NORMAL:
      break;
    case WL_OUTPUT_TRANSFORM_FLIPPED:
      result.set_x(bounds.width() - rect.x() - rect.width());
      break;
    case WL_OUTPUT_TRANSFORM_FLIPPED_90:
      result.set_x(rect.y());
      result.set_y(rect.x());
      result.set_width(rect.height());
      result.set_height(rect.width());
      break;
    case WL_OUTPUT_TRANSFORM_FLIPPED_180:
      result.set_y(bounds.height() - rect.y() - rect.height());
      break;
    case WL_OUTPUT_TRANSFORM_FLIPPED_270:
      result.set_x(bounds.height() - rect.y() - rect.height());
      result.set_y(bounds.width() - rect.x() - rect.width());
      result.set_width(rect.height());
      result.set_height(rect.width());
      break;
    case WL_OUTPUT_TRANSFORM_90:
      result.set_x(rect.y());
      result.set_y(bounds.width() - rect.x() - rect.width());
      result.set_width(rect.height());
      result.set_height(rect.width());
      break;
    case WL_OUTPUT_TRANSFORM_180:
      result.set_x(bounds.width() - rect.x() - rect.width());
      result.set_y(bounds.height() - rect.y() - rect.height());
      break;
    case WL_OUTPUT_TRANSFORM_270:
      result.set_x(bounds.height() - rect.y() - rect.height());
      result.set_y(rect.x());
      result.set_width(rect.height());
      result.set_height(rect.width());
      break;
    default:
      NOTREACHED();
  }
  return result;
}

gfx::Rect ApplyWaylandTransform(const gfx::Rect& rect,
                                const gfx::Size& bounds,
                                wl_output_transform transform) {
  gfx::Rect result = rect;
  switch (transform) {
    case WL_OUTPUT_TRANSFORM_NORMAL:
      break;
    case WL_OUTPUT_TRANSFORM_FLIPPED:
      result.set_x(bounds.width() - rect.x() - rect.width());
      break;
    case WL_OUTPUT_TRANSFORM_FLIPPED_90:
      result.set_x(rect.y());
      result.set_y(rect.x());
      result.set_width(rect.height());
      result.set_height(rect.width());
      break;
    case WL_OUTPUT_TRANSFORM_FLIPPED_180:
      result.set_y(bounds.height() - rect.y() - rect.height());
      break;
    case WL_OUTPUT_TRANSFORM_FLIPPED_270:
      result.set_x(bounds.height() - rect.y() - rect.height());
      result.set_y(bounds.width() - rect.x() - rect.width());
      result.set_width(rect.height());
      result.set_height(rect.width());
      break;
    case WL_OUTPUT_TRANSFORM_90:
      result.set_x(rect.y());
      result.set_y(bounds.width() - rect.x() - rect.width());
      result.set_width(rect.height());
      result.set_height(rect.width());
      break;
    case WL_OUTPUT_TRANSFORM_180:
      result.set_x(bounds.width() - rect.x() - rect.width());
      result.set_y(bounds.height() - rect.y() - rect.height());
      break;
    case WL_OUTPUT_TRANSFORM_270:
      result.set_x(bounds.height() - rect.y() - rect.height());
      result.set_y(rect.x());
      result.set_width(rect.height());
      result.set_height(rect.width());
      break;
    default:
      NOTREACHED();
  }
  return result;
}

gfx::SizeF ApplyWaylandTransform(const gfx::SizeF& size,
                                 wl_output_transform transform) {
  gfx::SizeF result = size;
  switch (transform) {
    case WL_OUTPUT_TRANSFORM_NORMAL:
    case WL_OUTPUT_TRANSFORM_FLIPPED:
    case WL_OUTPUT_TRANSFORM_FLIPPED_180:
    case WL_OUTPUT_TRANSFORM_180:
      break;
    case WL_OUTPUT_TRANSFORM_FLIPPED_90:
    case WL_OUTPUT_TRANSFORM_FLIPPED_270:
    case WL_OUTPUT_TRANSFORM_90:
    case WL_OUTPUT_TRANSFORM_270:
      result.set_width(size.height());
      result.set_height(size.width());
      break;
    default:
      NOTREACHED();
  }
  return result;
}

ui::WaylandWindow* RootWindowFromWlSurface(wl_surface* surface) {
  if (!surface)
    return nullptr;
  auto* wayland_surface = static_cast<ui::WaylandSurface*>(
      wl_proxy_get_user_data(reinterpret_cast<wl_proxy*>(surface)));
  if (!wayland_surface)
    return nullptr;
  return wayland_surface->root_window();
}

gfx::Rect TranslateWindowBoundsToParentDIP(ui::WaylandWindow* window,
                                           ui::WaylandWindow* parent_window) {
  DCHECK(window);
  DCHECK(parent_window);
  DCHECK_EQ(window->applied_state().window_scale,
            parent_window->applied_state().window_scale);
  return wl::TranslateBoundsToParentCoordinates(
      window->GetBoundsInDIP(), parent_window->GetBoundsInDIP());
}

std::vector<gfx::Rect> CreateRectsFromSkPath(const SkPath& path) {
  SkRegion clip_region;
  clip_region.setRect(path.getBounds().round());
  SkRegion region;
  region.setPath(path, clip_region);

  std::vector<gfx::Rect> rects;
  for (SkRegion::Iterator it(region); !it.done(); it.next())
    rects.push_back(gfx::SkIRectToRect(it.rect()));

  return rects;
}

SkPath ConvertPathToDIP(const SkPath& path_in_pixels, float scale) {
  SkScalar sk_scale = SkFloatToScalar(1.0f / scale);
  SkPath path_in_dips;
  path_in_pixels.transform(SkMatrix::Scale(sk_scale, sk_scale), &path_in_dips);
  return path_in_dips;
}

void SkColorToWlArray(const SkColor& color, wl_array& array) {
  SkColor4f precise_color = SkColor4f::FromColor(color);
  SkColorToWlArray(precise_color, array);
}

void SkColorToWlArray(const SkColor4f& color, wl_array& array) {
  for (float component : color.array()) {
    float* ptr = static_cast<float*>(wl_array_add(&array, sizeof(float)));
    DCHECK(ptr);
    *ptr = component;
  }
}

base::TimeTicks EventMillisecondsToTimeTicks(uint32_t milliseconds) {
  // TODO(crbug.com/40287874): `milliseconds` comes from Weston that
  // uses timestamp from libinput, which is different from TimeTicks.
  // Use EventTimeForNow(), for now.
  return ui::EventTimeForNow();
}

float ClampScale(float scale) {
  return std::max(1.f, scale);
}

bool MaybeHandlePlatformEventForDrag(const ui::PlatformEvent& event,
                                     bool start_drag_ack_received,
                                     base::OnceClosure cancel_drag_cb) {
  // Two distinct problematic edge cases are handled here, where mouse button or
  // touch release events come in after start_drag has already been requested:
  //
  // 1. If it's received before the drag session effectively starts at
  //    compositor side, which is possible given the asynchronous nature of the
  //    Wayland protocol. In this case, to preventing UI from getting stuck on
  //    the drag nested loop, we just abort the drag session.
  //
  // 2. Otherwise, button release events may be received from buggy compositors
  //    in addition to the actual dnd drop events, in which case the event is
  //    suppressed, otherwise it leads to broken UI state, as observed for
  //    example in https://crbug.com/329703410.
  if (EventShouldCancelDrag(event)) {
    if (!start_drag_ack_received) {
      std::move(cancel_drag_cb).Run();
    } else {
      return true;
    }
  }
  return false;
}

bool EventShouldCancelDrag(const ui::PlatformEvent& event) {
  return !event->IsSynthesized() &&
         (event->type() == ui::EventType::kMouseReleased ||
          event->type() == ui::EventType::kTouchReleased);
}

void RecordConnectionMetrics(wl_display* display) {
  CHECK(display);

  // These values are logged to metrics so must not be changed.
  enum class WaylandCompositor {
    // Couldn't obtain compositor name.
    kUnknown = 0,
    // Obtained compositor name, but don't have an enum value for it.
    kOther = 1,

    kAnvil = 2,
    kCage = 3,
    kCosmic = 4,
    kDwl = 5,
    kGamescope = 6,
    kHyprland = 7,
    kKWin = 8,
    kLabwc = 9,
    kMiracle = 10,
    kMutter = 11,
    kNiri = 12,
    kQtile = 13,
    kRiver = 14,
    kSway = 15,
    kTheseus = 16,
    kWayfire = 17,
    kWeston = 18,

    kMaxValue = kWeston,
  };

  auto get_compositor = [&]() {
    struct {
      const char* name;
      WaylandCompositor compositor;
    } constexpr kCompositors[] = {
        {"anvil", WaylandCompositor::kAnvil},
        {"cage", WaylandCompositor::kCage},
        {"cosmic", WaylandCompositor::kCosmic},
        {"dwl", WaylandCompositor::kDwl},
        {"gamescope", WaylandCompositor::kGamescope},
        {"gnome", WaylandCompositor::kMutter},
        {"hyprland", WaylandCompositor::kHyprland},
        {"kwin", WaylandCompositor::kKWin},
        {"labwc", WaylandCompositor::kLabwc},
        {"miracle", WaylandCompositor::kMiracle},
        {"mutter", WaylandCompositor::kMutter},
        {"niri", WaylandCompositor::kNiri},
        {"qtile", WaylandCompositor::kQtile},
        {"river", WaylandCompositor::kRiver},
        {"sway", WaylandCompositor::kSway},
        {"theseus", WaylandCompositor::kTheseus},
        {"wayfire", WaylandCompositor::kWayfire},
        {"weston", WaylandCompositor::kWeston},
    };

    const int fd = wl_display_get_fd(display);
    if (fd == -1) {
      return WaylandCompositor::kUnknown;
    }

    ucred credentials{.pid = 0};
    socklen_t size = sizeof(ucred);
    if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &credentials, &size) == -1) {
      return WaylandCompositor::kUnknown;
    }

    std::string name;
    if (!base::ReadFileToStringNonBlocking(
            base::FilePath(
                base::StringPrintf("/proc/%d/comm", credentials.pid)),
            &name)) {
      return WaylandCompositor::kUnknown;
    }

    for (const auto& [name_key, compositor] : kCompositors) {
      if (base::StartsWith(name, name_key,
                           base::CompareCase::INSENSITIVE_ASCII)) {
        return compositor;
      }
    }

    return WaylandCompositor::kOther;
  };

  base::UmaHistogramEnumeration("Linux.Wayland.Compositor", get_compositor());
}

}  // namespace wl