File: window_frame_provider_gtk.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 (413 lines) | stat: -rw-r--r-- 16,146 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
// 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/gtk/window_frame_provider_gtk.h"

#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/scoped_canvas.h"
#include "ui/gtk/gtk_compat.h"
#include "ui/gtk/gtk_util.h"
#include "ui/native_theme/native_theme.h"

namespace gtk {

namespace {

// The maximum reasonable size of the frame edges in DIPs.  If a GTK theme draws
// window decorations larger than this, they will be clipped.
constexpr int kMaxFrameSizeDip = 64;

// The maximum reasonable radius of the frame top corners in DIPs.  If this
// limit is exceeded, the corners will be drawn correctly, but the compositor
// will get an incorrect hint as to which pixels are fully opaque.
constexpr int kMaxCornerRadiusDip = 32;

GtkCssContext WindowContext(bool solid_frame,
                            bool tiled,
                            bool maximized,
                            bool focused) {
  std::string selector = "window.background.";
  selector += solid_frame ? "solid-csd" : "csd";
  if (tiled) {
    selector += ".tiled";
  }
  if (maximized) {
    selector += ".maximized";
  }
  if (!focused) {
    selector += ":inactive";
  }
  return AppendCssNodeToStyleContext({}, selector);
}

GtkCssContext DecorationContext(bool solid_frame,
                                bool tiled,
                                bool maximized,
                                bool focused) {
  auto context = WindowContext(solid_frame, tiled, maximized, focused);
  // GTK4 renders the decoration directly on the window.
  if (!GtkCheckVersion(4)) {
    context = AppendCssNodeToStyleContext(context, "decoration");
  }
  if (!focused) {
    gtk_style_context_set_state(context, GTK_STATE_FLAG_BACKDROP);
  }

  // The web contents is rendered after the frame border, so remove bottom
  // rounded corners otherwise their borders would get covered up.
  ApplyCssToContext(context, R"(* {
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
  })");

  return context;
}

GtkCssContext HeaderContext(bool solid_frame,
                            bool tiled,
                            bool maximized,
                            bool focused) {
  auto context = WindowContext(solid_frame, tiled, maximized, focused);
  context =
      AppendCssNodeToStyleContext(context, "headerbar.header-bar.titlebar");
  if (!focused) {
    gtk_style_context_set_state(context, GTK_STATE_FLAG_BACKDROP);
  }
  ApplyCssToContext(context, "* { border-bottom-style: none; }");
  return context;
}

SkBitmap PaintBitmap(const gfx::Size& bitmap_size,
                     const gfx::RectF& render_bounds,
                     GtkCssContext context,
                     float scale) {
  SkBitmap bitmap;
  bitmap.allocN32Pixels(bitmap_size.width(), bitmap_size.height());
  bitmap.eraseColor(SK_ColorTRANSPARENT);

  CairoSurface surface(bitmap);
  cairo_t* cr = surface.cairo();

  double opacity = GetOpacityFromContext(context);
  if (opacity < 1) {
    cairo_push_group(cr);
  }

  cairo_scale(cr, scale, scale);
  gtk_render_background(context, cr, render_bounds.x(), render_bounds.y(),
                        render_bounds.width(), render_bounds.height());
  gtk_render_frame(context, cr, render_bounds.x(), render_bounds.y(),
                   render_bounds.width(), render_bounds.height());

  if (opacity < 1) {
    cairo_pop_group_to_source(cr);
    cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
    cairo_paint_with_alpha(cr, opacity);
  }

  bitmap.setImmutable();
  return bitmap;
}

SkBitmap PaintHeaderbar(const gfx::Size& size,
                        GtkCssContext context,
                        float scale) {
  gfx::RectF tabstrip_bounds_dip(0, 0, size.width() / scale,
                                 size.height() / scale);
  return PaintBitmap(size, tabstrip_bounds_dip, context, scale);
}

int ComputeTopCornerRadius() {
  // In GTK4, there's no way to directly obtain CSS values for a context, so we
  // need to experimentally determine the corner radius by rendering a sample.
  // Additionally, in GTK4, the headerbar corners get clipped by the window
  // rather than the headerbar having its own rounded corners.
  auto context = GtkCheckVersion(4)
                     ? DecorationContext(false, false, false, false)
                     : HeaderContext(false, false, false, false);
  ApplyCssToContext(context, R"(window, headerbar {
    background-image: none;
    background-color: black;
    box-shadow: none;
    border: none;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
    border-top-right-radius: 0;
  })");
  gfx::Size size_dip{kMaxCornerRadiusDip, kMaxCornerRadiusDip};
  auto bitmap =
      GtkCheckVersion(4)
          ? PaintBitmap(size_dip, {{0, 0}, gfx::SizeF(size_dip)}, context, 1)
          : PaintHeaderbar(size_dip, context, 1);
  DCHECK_EQ(bitmap.width(), bitmap.height());
  for (int i = 0; i < bitmap.width(); ++i) {
    if (SkColorGetA(bitmap.getColor(0, i)) == 255 &&
        SkColorGetA(bitmap.getColor(i, 0)) == 255) {
      return i;
    }
  }
  return bitmap.width();
}

// Returns true iff any part of the header is transparent (even a single pixel).
// This is used as an optimization hint to the compositor so that it doesn't
// have to composite behind opaque regions.  The consequence of a false-negative
// is rendering artifacts, but the consequence of a false-positive is only a
// slight performance penalty, so this function is intentionally conservative
// in deciding if the header is translucent.
bool HeaderIsTranslucent() {
  // The arbitrary square size to render a sample header.
  constexpr int kHeaderSize = 32;
  auto context = HeaderContext(false, false, false, false);
  double opacity = GetOpacityFromContext(context);
  if (opacity < 1.0) {
    return true;
  }
  ApplyCssToContext(context, R"(window, headerbar {
    box-shadow: none;
    border: none;
    border-radius: 0;
  })");
  gfx::Size size_dip{kHeaderSize, kHeaderSize};
  auto bitmap = PaintHeaderbar(size_dip, context, 1);
  for (int x = 0; x < kHeaderSize; x++) {
    for (int y = 0; y < kHeaderSize; y++) {
      if (SkColorGetA(bitmap.getColor(x, y)) != SK_AlphaOPAQUE) {
        return true;
      }
    }
  }
  return false;
}

}  // namespace

WindowFrameProviderGtk::Asset::Asset() = default;

WindowFrameProviderGtk::Asset::Asset(const WindowFrameProviderGtk::Asset& src) =
    default;

WindowFrameProviderGtk::Asset& WindowFrameProviderGtk::Asset::operator=(
    const WindowFrameProviderGtk::Asset& src) = default;

WindowFrameProviderGtk::Asset::~Asset() = default;

WindowFrameProviderGtk::WindowFrameProviderGtk(bool solid_frame,
                                               bool tiled,
                                               bool maximized)
    : solid_frame_(solid_frame), tiled_(tiled), maximized_(maximized) {
  GtkSettings* settings = gtk_settings_get_default();
  // Unretained() is safe since WindowFrameProviderGtk will own the signals.
  auto callback = base::BindRepeating(&WindowFrameProviderGtk::OnThemeChanged,
                                      base::Unretained(this));
  theme_name_signal_ = ScopedGSignal(settings, "notify::gtk-theme-name",
                                     callback, G_CONNECT_AFTER);
  prefer_dark_signal_ =
      ScopedGSignal(settings, "notify::gtk-application-prefer-dark-theme",
                    callback, G_CONNECT_AFTER);
}

WindowFrameProviderGtk::~WindowFrameProviderGtk() = default;

int WindowFrameProviderGtk::GetTopCornerRadiusDip() {
  if (!top_corner_radius_dip_.has_value()) {
    top_corner_radius_dip_ = ComputeTopCornerRadius();
  }
  return *top_corner_radius_dip_;
}

bool WindowFrameProviderGtk::IsTopFrameTranslucent() {
  if (!top_frame_is_translucent_.has_value()) {
    top_frame_is_translucent_ = !solid_frame_ && HeaderIsTranslucent();
  }
  return *top_frame_is_translucent_;
}

gfx::Insets WindowFrameProviderGtk::GetFrameThicknessDip() {
  if (!frame_thickness_dip_.has_value()) {
    const auto& asset = GetOrCreateAsset(1.0f);

    // In GTK4, there's no way to obtain the frame thickness from CSS values
    // directly, so we must determine it experimentally based on the drawn
    // bitmaps.
    auto get_inset = [&](auto&& pixel_iterator) -> int {
      for (int i = 0; i < asset.frame_size_px; ++i) {
        if (SkColorGetA(pixel_iterator(i))) {
          return asset.frame_size_px - i;
        }
      }
      return 0;
    };

    frame_thickness_dip_ = gfx::Insets::TLBR(
        get_inset([&](int i) {
          return asset.focused_bitmap.getColor(2 * asset.frame_size_px, i);
        }),
        get_inset([&](int i) {
          return asset.focused_bitmap.getColor(i, 2 * asset.frame_size_px);
        }),
        get_inset([&](int i) {
          return asset.focused_bitmap.getColor(2 * asset.frame_size_px,
                                               BitmapSizePx(asset) - i - 1);
        }),
        get_inset([&](int i) {
          return asset.focused_bitmap.getColor(BitmapSizePx(asset) - i - 1,
                                               2 * asset.frame_size_px);
        }));
  }
  return *frame_thickness_dip_;
}

void WindowFrameProviderGtk::PaintWindowFrame(gfx::Canvas* canvas,
                                              const gfx::Rect& rect_dip,
                                              int top_area_height_dip,
                                              bool focused,
                                              const gfx::Insets& input_insets) {
  gfx::ScopedCanvas scoped_canvas(canvas);
  float scale = canvas->UndoDeviceScaleFactor();

  const auto& asset = GetOrCreateAsset(scale);

  const auto input_insets_px = gfx::ScaleToRoundedInsets(input_insets, scale);
  auto effective_frame_thickness_px =
      gfx::ScaleToRoundedInsets(GetFrameThicknessDip(), scale);
  effective_frame_thickness_px.SetToMax(input_insets_px);

  auto client_bounds_px = gfx::ScaleToRoundedRect(rect_dip, scale);
  client_bounds_px.Inset(effective_frame_thickness_px);

  gfx::Rect src_rect(gfx::Size(BitmapSizePx(asset), BitmapSizePx(asset)));
  src_rect.Inset(gfx::Insets(asset.frame_size_px) -
                 effective_frame_thickness_px);

  auto corner_w = std::min(asset.frame_size_px, client_bounds_px.width() / 2);
  auto corner_h = std::min(asset.frame_size_px, client_bounds_px.height() / 2);
  auto edge_w = client_bounds_px.width() - 2 * corner_w;
  auto edge_h = client_bounds_px.height() - 2 * corner_h;

  auto corner_insets =
      effective_frame_thickness_px + gfx::Insets::VH(corner_h, corner_w);

  auto image = gfx::ImageSkia::CreateFrom1xBitmap(
      focused ? asset.focused_bitmap : asset.unfocused_bitmap);

  auto draw_image = [&](int src_x, int src_y, int src_w, int src_h, int dst_x,
                        int dst_y, int dst_w, int dst_h) {
    if (src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0) {
      return;
    }
    canvas->DrawImageInt(image, src_x, src_y, src_w, src_h, dst_x, dst_y, dst_w,
                         dst_h, false);
  };

  // Top left corner
  draw_image(src_rect.x(), src_rect.y(), corner_insets.left(),
             corner_insets.top(), 0, 0, corner_insets.left(),
             corner_insets.top());
  // Top right corner
  draw_image(BitmapSizePx(asset) - asset.frame_size_px - corner_w, src_rect.y(),
             corner_insets.right(), corner_insets.top(),
             client_bounds_px.right() - corner_w, 0, corner_insets.right(),
             corner_insets.top());
  // Bottom left corner
  draw_image(src_rect.x(), BitmapSizePx(asset) - asset.frame_size_px - corner_h,
             corner_insets.left(), corner_insets.bottom(), 0,
             client_bounds_px.bottom() - corner_h, corner_insets.left(),
             corner_insets.bottom());
  // Bottom right corner
  draw_image(BitmapSizePx(asset) - asset.frame_size_px - corner_w,
             BitmapSizePx(asset) - asset.frame_size_px - corner_h,
             corner_insets.right(), corner_insets.bottom(),
             client_bounds_px.right() - corner_w,
             client_bounds_px.bottom() - corner_h, corner_insets.right(),
             corner_insets.bottom());
  // Top edge
  draw_image(2 * asset.frame_size_px, src_rect.y(), 1,
             effective_frame_thickness_px.top(), corner_insets.left(), 0,
             edge_w, effective_frame_thickness_px.top());
  // Left edge
  draw_image(src_rect.x(), 2 * asset.frame_size_px,
             effective_frame_thickness_px.left(), 1, 0, corner_insets.top(),
             effective_frame_thickness_px.left(), edge_h);
  // Bottom edge
  draw_image(2 * asset.frame_size_px, BitmapSizePx(asset) - asset.frame_size_px,
             1, effective_frame_thickness_px.bottom(), corner_insets.left(),
             client_bounds_px.bottom(), edge_w,
             effective_frame_thickness_px.bottom());
  // Right edge
  draw_image(BitmapSizePx(asset) - asset.frame_size_px, 2 * asset.frame_size_px,
             effective_frame_thickness_px.right(), 1, client_bounds_px.right(),
             corner_insets.top(), effective_frame_thickness_px.right(), edge_h);

  const int top_area_bottom_dip = rect_dip.y() + top_area_height_dip;
  const int top_area_bottom_px = base::ClampCeil(top_area_bottom_dip * scale);
  const int top_area_height_px = top_area_bottom_px - client_bounds_px.y();

  auto header = PaintHeaderbar(
      {client_bounds_px.width(), top_area_height_px},
      HeaderContext(solid_frame_, tiled_, maximized_, focused), scale);
  image = gfx::ImageSkia::CreateFrom1xBitmap(header);
  // In GTK4, the headerbar gets clipped by the window.
  if (GtkCheckVersion(4)) {
    gfx::RectF bounds_px =
        gfx::RectF(client_bounds_px.x(), client_bounds_px.y(), header.width(),
                   header.height());
    float radius_px = scale * GetTopCornerRadiusDip();
    SkVector radii[4]{{radius_px, radius_px}, {radius_px, radius_px}, {}, {}};
    SkRRect clip;
    clip.setRectRadii(gfx::RectFToSkRect(bounds_px), radii);
    canvas->sk_canvas()->clipRRect(clip, SkClipOp::kIntersect, true);
  }
  draw_image(0, 0, header.width(), header.height(), client_bounds_px.x(),
             client_bounds_px.y(), header.width(), header.height());
}

WindowFrameProviderGtk::Asset& WindowFrameProviderGtk::GetOrCreateAsset(
    float scale) {
  auto it = assets_.find(scale);
  if (it != assets_.end()) {
    return it->second;
  }
  auto& asset = assets_[scale];

  asset.frame_size_px = std::ceil(kMaxFrameSizeDip * scale);

  gfx::Rect frame_bounds_dip(kMaxFrameSizeDip, kMaxFrameSizeDip,
                             2 * kMaxFrameSizeDip, 2 * kMaxFrameSizeDip);
  auto focused_context =
      DecorationContext(solid_frame_, tiled_, maximized_, true);
  frame_bounds_dip.Inset(-GtkStyleContextGetPadding(focused_context));
  frame_bounds_dip.Inset(-GtkStyleContextGetBorder(focused_context));
  gfx::Size bitmap_size(BitmapSizePx(asset), BitmapSizePx(asset));
  asset.focused_bitmap = PaintBitmap(bitmap_size, gfx::RectF(frame_bounds_dip),
                                     focused_context, scale);
  asset.unfocused_bitmap = PaintBitmap(
      bitmap_size, gfx::RectF(frame_bounds_dip),
      DecorationContext(solid_frame_, tiled_, maximized_, false), scale);

  return asset;
}

int WindowFrameProviderGtk::BitmapSizePx(const Asset& asset) const {
  // The window decoration will be rendered into a square with this side length.
  // The left and right sides of the decoration add 2 * kMaxDecorationThickness,
  // and the window itself has size 2 * kMaxDecorationThickness.
  return 4 * asset.frame_size_px;
}

void WindowFrameProviderGtk::OnThemeChanged(GtkSettings* settings,
                                            GtkParamSpec* param) {
  assets_.clear();
  frame_thickness_dip_ = std::nullopt;
  top_corner_radius_dip_ = std::nullopt;
  top_frame_is_translucent_ = std::nullopt;
}

}  // namespace gtk