File: wayland_cursor_factory.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 (281 lines) | stat: -rw-r--r-- 10,006 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
// Copyright 2021 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/host/wayland_cursor_factory.h"

#include <wayland-cursor.h>

#include <cmath>

#include "base/numerics/safe_conversions.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "skia/ext/image_operations.h"
#include "ui/base/cursor/platform_cursor.h"
#include "ui/linux/linux_ui.h"
#include "ui/ozone/common/bitmap_cursor.h"
#include "ui/ozone/common/bitmap_cursor_factory.h"
#include "ui/ozone/platform/wayland/host/wayland_buffer_factory.h"
#include "ui/ozone/platform/wayland/host/wayland_connection.h"

namespace ui {

namespace {

// The threshold for rounding down the final scale of the cursor image
// that gets sent to the Wayland compositor. For instance, if the
// original cursor image scale is 1.2, we'll downscale it to 1.0. On
// the other hand, if it's something like 1.5 then we'll upscale it to 2.0.
const float kCursorScaleFlooringThreshold = 0.2;

float GetRoundedScale(float scale) {
  return std::ceil(scale - kCursorScaleFlooringThreshold);
}

}  // namespace

WaylandCursorFactory::ThemeData::ThemeData() = default;

WaylandCursorFactory::ThemeData::~ThemeData() = default;

void WaylandCursorFactory::ThemeData::AddThemeLoadedCallback(
    Callback callback) {
  if (loaded_) {
    std::move(callback).Run(theme_.get());
  } else {
    callbacks_.push_back(std::move(callback));
  }
}

void WaylandCursorFactory::ThemeData::SetLoadedTheme(wl_cursor_theme* theme) {
  DCHECK(!loaded_);
  theme_.reset(theme);
  loaded_ = true;
  for (auto& callback : callbacks_) {
    std::move(callback).Run(theme);
  }
  callbacks_.clear();
}

WaylandCursorFactory::WaylandCursorFactory(WaylandConnection* connection)
    : connection_(connection), theme_cache_(std::make_unique<ThemeCache>()) {
  connection_->SetCursorBufferListener(this);
}

WaylandCursorFactory::~WaylandCursorFactory() {
  connection_->SetCursorBufferListener(nullptr);
}

void WaylandCursorFactory::ObserveThemeChanges() {
  auto* linux_ui = LinuxUi::instance();
  DCHECK(linux_ui);
  cursor_theme_observer_.Observe(linux_ui);
}

scoped_refptr<PlatformCursor> WaylandCursorFactory::CreateImageCursor(
    mojom::CursorType type,
    const SkBitmap& bitmap,
    const gfx::Point& hotspot,
    float scale) {
  scoped_refptr<BitmapCursor> bitmap_cursor;

  // Wayland only supports cursor images with an integer scale, so we
  // must upscale cursor images with non-integer scales to integer scaled
  // images so that the cursor is displayed correctly.
  float rounded_scale = GetRoundedScale(scale);
  if (std::abs(rounded_scale - scale) > std::numeric_limits<float>::epsilon()) {
    const SkBitmap scaled_bitmap = skia::ImageOperations::Resize(
        bitmap, skia::ImageOperations::RESIZE_LANCZOS3,
        std::round(bitmap.width() * (rounded_scale / scale)),
        std::round(bitmap.height() * (rounded_scale / scale)));
    const gfx::Point scaled_hotspot =
        gfx::ScaleToRoundedPoint(hotspot, rounded_scale / scale);
    bitmap_cursor = base::MakeRefCounted<BitmapCursor>(
        type, scaled_bitmap, scaled_hotspot, rounded_scale);
  } else {
    bitmap_cursor =
        base::MakeRefCounted<BitmapCursor>(type, bitmap, hotspot, scale);
  }
  return base::MakeRefCounted<WaylandAsyncCursor>(bitmap_cursor);
}

scoped_refptr<PlatformCursor> WaylandCursorFactory::CreateAnimatedCursor(
    mojom::CursorType type,
    const std::vector<SkBitmap>& bitmaps,
    const gfx::Point& hotspot,
    float scale,
    base::TimeDelta frame_delay) {
  scoped_refptr<BitmapCursor> bitmap_cursor;

  float rounded_scale = GetRoundedScale(scale);
  if (std::abs(rounded_scale - scale) > std::numeric_limits<float>::epsilon()) {
    std::vector<SkBitmap> scaled_bitmaps;
    for (const auto& bitmap : bitmaps) {
      scaled_bitmaps.push_back(skia::ImageOperations::Resize(
          bitmap, skia::ImageOperations::RESIZE_LANCZOS3,
          std::round(bitmap.width() * (rounded_scale / scale)),
          std::round(bitmap.height() * (rounded_scale / scale))));
    }
    const gfx::Point scaled_hotspot =
        gfx::ScaleToRoundedPoint(hotspot, rounded_scale / scale);
    bitmap_cursor = base::MakeRefCounted<BitmapCursor>(
        type, scaled_bitmaps, scaled_hotspot, frame_delay, rounded_scale);
  } else {
    bitmap_cursor = base::MakeRefCounted<BitmapCursor>(type, bitmaps, hotspot,
                                                       frame_delay, scale);
  }
  return base::MakeRefCounted<WaylandAsyncCursor>(bitmap_cursor);
}

void WaylandCursorFactory::FinishCursorLoad(
    scoped_refptr<WaylandAsyncCursor> cursor,
    mojom::CursorType type,
    float scale,
    wl_cursor_theme* loaded_theme) {
  for (const auto& name : CursorNamesFromType(type)) {
    wl_cursor* theme_cursor = GetCursorFromTheme(loaded_theme, name);
    if (theme_cursor) {
      cursor->SetBitmapCursor(base::MakeRefCounted<BitmapCursor>(
          type, theme_cursor, GetRoundedScale(scale)));
      return;
    }
  }
  // Fall back to the BitmapCursorFactory implementation if the theme has't
  // provided a shape for the requested type.
  cursor->SetBitmapCursor(BitmapCursor::FromPlatformCursor(
      BitmapCursorFactory::GetDefaultCursor(type)));
}

scoped_refptr<PlatformCursor> WaylandCursorFactory::GetDefaultCursor(
    mojom::CursorType type) {
  // Fall back to 1x for scale if not provided.
  return GetDefaultCursor(type, 1.0);
}

scoped_refptr<PlatformCursor> WaylandCursorFactory::GetDefaultCursor(
    mojom::CursorType type,
    float scale) {
  auto* const current_theme = GetThemeForScale(scale);
  DCHECK(current_theme);
  if (current_theme->cache.count(type) == 0) {
    auto async_cursor = base::MakeRefCounted<WaylandAsyncCursor>();
    current_theme->cache[type] = async_cursor;
    current_theme->AddThemeLoadedCallback(
        base::BindOnce(&WaylandCursorFactory::FinishCursorLoad,
                       weak_factory_.GetWeakPtr(), async_cursor, type, scale));
  }
  return current_theme->cache[type];
}

wl_cursor* WaylandCursorFactory::GetCursorFromTheme(wl_cursor_theme* theme,
                                                    const std::string& name) {
  // Possible if the theme could not be loaded.
  if (!theme) {
    return nullptr;
  }

  return wl_cursor_theme_get_cursor(theme, name.c_str());
}

void WaylandCursorFactory::OnCursorThemeNameChanged(
    const std::string& cursor_theme_name) {
  CHECK(!cursor_theme_name.empty());

  if (name_ == cursor_theme_name)
    return;

  name_ = cursor_theme_name;
  FlushThemeCache(false);
}

void WaylandCursorFactory::OnCursorThemeSizeChanged(int cursor_theme_size) {
  size_ = cursor_theme_size;
}

void WaylandCursorFactory::OnCursorBufferAttached(wl_cursor* cursor_data) {
  if (!unloaded_theme_)
    return;
  if (!cursor_data) {
    unloaded_theme_.reset();
    return;
  }
  for (auto& item : *theme_cache_) {
    for (auto& subitem : item.second->cache) {
      auto bitmap_cursor = subitem.second->bitmap_cursor();
      if (bitmap_cursor && bitmap_cursor->platform_data() == cursor_data) {
        // The cursor that has been just attached is from the current theme.
        // That means that the theme that has been unloaded earlier can now be
        // deleted.
        unloaded_theme_.reset();
        return;
      }
    }
  }
}

WaylandCursorFactory::ThemeData* WaylandCursorFactory::GetThemeForScale(
    float scale) {
  auto item = theme_cache_->find(GetScaledSize(scale));
  if (item != theme_cache_->end()) {
    return item->second.get();
  }

  theme_cache_->insert_or_assign(GetScaledSize(scale),
                                 std::make_unique<ThemeData>());
  auto* cache_entry = theme_cache_->at(GetScaledSize(scale)).get();

  // The task environment is normally not created in tests.  As this factory is
  // part of the platform that is created always and early, posting a task to
  // the pool would fail in many many tests.
  if (!base::ThreadPoolInstance::Get())
    return cache_entry;

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(
          wl_cursor_theme_load, name_.empty() ? nullptr : name_.c_str(),
          GetScaledSize(scale), connection_->buffer_factory()->shm()),
      base::BindOnce(&WaylandCursorFactory::FinishThemeLoad,
                     weak_factory_.GetWeakPtr(), cache_entry->GetWeakPtr()));

  return cache_entry;
}

void WaylandCursorFactory::FlushThemeCache(bool force) {
  size_t num_cursor_objects = 0;
  for (auto& entry : *theme_cache_) {
    num_cursor_objects += entry.second->cache.size();
  }
  if (force) {
    unloaded_theme_.reset();
  } else {
    // If we use any cursor when the theme is reloaded, the one can be only from
    // the theme that is currently used.  As soon as we take the next cursor
    // from the next theme, we will destroy it (see OnCursorBufferAttached()
    // above). If more than one theme has been changed but we didn't take any
    // cursors from them (which is possible if the user played with settings but
    // didn't switch into Chromium), we don't need to track them all.
    if (!unloaded_theme_ && num_cursor_objects != 0) {
      unloaded_theme_ = std::move(theme_cache_);
    }
  }
  theme_cache_ = std::make_unique<ThemeCache>();
}

int WaylandCursorFactory::GetScaledSize(float scale) const {
  return base::checked_cast<int>(size_ * GetRoundedScale(scale));
}

void WaylandCursorFactory::FinishThemeLoad(base::WeakPtr<ThemeData> cache_entry,
                                           wl_cursor_theme* loaded_theme) {
  // wl_cursor_theme_load() can return nullptr.  We don't check that here but
  // have to be cautious when we actually load the shape.
  if (cache_entry) {
    cache_entry->SetLoadedTheme(loaded_theme);
  }
}

}  // namespace ui