File: gtk_ui.cc

package info (click to toggle)
chromium-browser 70.0.3538.110-1~deb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,619,476 kB
  • sloc: cpp: 13,024,755; ansic: 1,349,823; python: 916,672; xml: 314,489; java: 280,047; asm: 276,936; perl: 75,771; objc: 66,634; sh: 45,860; cs: 28,354; php: 11,064; makefile: 10,911; yacc: 9,109; tcl: 8,403; ruby: 4,065; lex: 1,779; pascal: 1,411; lisp: 1,055; awk: 41; jsp: 39; sed: 17; sql: 3
file content (1351 lines) | stat: -rw-r--r-- 50,955 bytes parent folder | download
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/libgtkui/gtk_ui.h"

#include <dlfcn.h>
#include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h>
#include <math.h>
#include <pango/pango.h>

#include <cmath>
#include <set>
#include <utility>

#include "base/command_line.h"
#include "base/containers/flat_map.h"
#include "base/debug/leak_annotations.h"
#include "base/environment.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/protected_memory.h"
#include "base/memory/protected_memory_cfi.h"
#include "base/nix/mime_util_xdg.h"
#include "base/nix/xdg_util.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/browser/ui/libgtkui/app_indicator_icon.h"
#include "chrome/browser/ui/libgtkui/gtk_event_loop.h"
#include "chrome/browser/ui/libgtkui/gtk_key_bindings_handler.h"
#include "chrome/browser/ui/libgtkui/gtk_status_icon.h"
#include "chrome/browser/ui/libgtkui/gtk_util.h"
#include "chrome/browser/ui/libgtkui/native_theme_gtk.h"
#include "chrome/browser/ui/libgtkui/nav_button_provider_gtk.h"
#include "chrome/browser/ui/libgtkui/print_dialog_gtk.h"
#include "chrome/browser/ui/libgtkui/printing_gtk_util.h"
#include "chrome/browser/ui/libgtkui/select_file_dialog_impl.h"
#include "chrome/browser/ui/libgtkui/settings_provider_gtk.h"
#include "chrome/browser/ui/libgtkui/skia_utils_gtk.h"
#include "chrome/browser/ui/libgtkui/unity_service.h"
#include "chrome/browser/ui/libgtkui/x11_input_method_context_impl_gtk.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "printing/buildflags/buildflags.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkShader.h"
#include "ui/base/material_design/material_design_controller.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/display/display.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/dom_keyboard_layout_manager.h"
#include "ui/events/keycodes/dom/keycode_converter.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font_render_params.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia_source.h"
#include "ui/gfx/skbitmap_operations.h"
#include "ui/gfx/skia_util.h"
#include "ui/gfx/x/x11.h"
#include "ui/gfx/x/x11_types.h"
#include "ui/native_theme/native_theme.h"
#include "ui/shell_dialogs/select_file_policy.h"
#include "ui/views/controls/button/blue_button.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/button/label_button_border.h"
#include "ui/views/linux_ui/device_scale_factor_observer.h"
#include "ui/views/linux_ui/window_button_order_observer.h"
#include "ui/views/resources/grit/views_resources.h"

#if GTK_MAJOR_VERSION == 2
#include "chrome/browser/ui/libgtkui/gtk2/chrome_gtk_frame.h"
#include "chrome/browser/ui/libgtkui/gtk2/native_theme_gtk2.h"
#elif GTK_MAJOR_VERSION == 3
#include "chrome/browser/ui/libgtkui/native_theme_gtk.h"
#include "chrome/browser/ui/libgtkui/nav_button_provider_gtk.h"
#include "chrome/browser/ui/libgtkui/settings_provider_gtk.h"
#endif

#if defined(USE_GIO)
#include "chrome/browser/ui/libgtkui/settings_provider_gsettings.h"
#endif

#if BUILDFLAG(ENABLE_PRINTING)
#include "printing/printing_context_linux.h"
#endif

#if BUILDFLAG(ENABLE_NATIVE_WINDOW_NAV_BUTTONS)
#include "chrome/browser/ui/views/nav_button_provider.h"
#endif

// A minimized port of GtkThemeService into something that can provide colors
// and images for aura.
//
// TODO(erg): There's still a lot that needs ported or done for the first time:
//
// - Render and inject the omnibox background.
// - Make sure to test with a light on dark theme, too.

namespace libgtkui {

namespace {

const double kDefaultDPI = 96;

class GtkButtonImageSource : public gfx::ImageSkiaSource {
 public:
  GtkButtonImageSource(const char* idr_string, gfx::Size size)
      : width_(size.width()), height_(size.height()) {
    is_blue_ = !!strstr(idr_string, "IDR_BLUE");
    focus_ = !!strstr(idr_string, "_FOCUSED_");

    if (strstr(idr_string, "_DISABLED")) {
      state_ = ui::NativeTheme::kDisabled;
    } else if (strstr(idr_string, "_HOVER")) {
      state_ = ui::NativeTheme::kHovered;
    } else if (strstr(idr_string, "_PRESSED")) {
      state_ = ui::NativeTheme::kPressed;
    } else {
      state_ = ui::NativeTheme::kNormal;
    }
  }

  ~GtkButtonImageSource() override {}

  gfx::ImageSkiaRep GetImageForScale(float scale) override {
    int width = width_ * scale;
    int height = height_ * scale;

    SkBitmap border;
    border.allocN32Pixels(width, height);
    border.eraseColor(0);

    cairo_surface_t* surface = cairo_image_surface_create_for_data(
        static_cast<unsigned char*>(border.getAddr(0, 0)), CAIRO_FORMAT_ARGB32,
        width, height, width * 4);
    cairo_t* cr = cairo_create(surface);

#if GTK_MAJOR_VERSION == 2
    // Create a temporary GTK button to snapshot
    GtkWidget* window = gtk_offscreen_window_new();
    GtkWidget* button = gtk_toggle_button_new();

    if (state_ == ui::NativeTheme::kPressed)
      gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button), true);
    else if (state_ == ui::NativeTheme::kDisabled)
      gtk_widget_set_sensitive(button, false);

    gtk_widget_set_size_request(button, width, height);
    gtk_container_add(GTK_CONTAINER(window), button);

    if (is_blue_)
      TurnButtonBlue(button);

    gtk_widget_show_all(window);

    if (focus_)
      GTK_WIDGET_SET_FLAGS(button, GTK_HAS_FOCUS);

    int w, h;
    GdkPixmap* pixmap;

    {
      // http://crbug.com/346740
      ANNOTATE_SCOPED_MEMORY_LEAK;
      pixmap = gtk_widget_get_snapshot(button, nullptr);
    }

    gdk_drawable_get_size(GDK_DRAWABLE(pixmap), &w, &h);
    GdkColormap* colormap = gdk_drawable_get_colormap(pixmap);
    GdkPixbuf* pixbuf = gdk_pixbuf_get_from_drawable(
        nullptr, GDK_DRAWABLE(pixmap), colormap, 0, 0, 0, 0, w, h);

    gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0);
    cairo_paint(cr);

    g_object_unref(pixbuf);
    g_object_unref(pixmap);

    gtk_widget_destroy(window);
#else
    ScopedStyleContext context = GetStyleContextFromCss(
        is_blue_ ? "GtkButton#button.default.suggested-action"
                 : "GtkButton#button");
    GtkStateFlags state_flags = StateToStateFlags(state_);
    if (focus_) {
      state_flags =
          static_cast<GtkStateFlags>(state_flags | GTK_STATE_FLAG_FOCUSED);
    }
    gtk_style_context_set_state(context, state_flags);
    gtk_render_background(context, cr, 0, 0, width, height);
    gtk_render_frame(context, cr, 0, 0, width, height);
    if (focus_) {
      gfx::Rect focus_rect(width, height);

#if !GTK_CHECK_VERSION(3, 90, 0)
      if (!GtkVersionCheck(3, 14)) {
        gint focus_pad;
        gtk_style_context_get_style(context, "focus-padding", &focus_pad,
                                    nullptr);
        focus_rect.Inset(focus_pad, focus_pad);

        if (state_ == ui::NativeTheme::kPressed) {
          gint child_displacement_x, child_displacement_y;
          gboolean displace_focus;
          gtk_style_context_get_style(
              context, "child-displacement-x", &child_displacement_x,
              "child-displacement-y", &child_displacement_y, "displace-focus",
              &displace_focus, nullptr);
          if (displace_focus)
            focus_rect.Offset(child_displacement_x, child_displacement_y);
        }
      }
#endif

      if (!GtkVersionCheck(3, 20)) {
        GtkBorder border;
#if GTK_CHECK_VERSION(3, 90, 0)
        gtk_style_context_get_border(context, &border);
#else
        gtk_style_context_get_border(context, state_flags, &border);
#endif
        focus_rect.Inset(border.left, border.top, border.right, border.bottom);
      }

      gtk_render_focus(context, cr, focus_rect.x(), focus_rect.y(),
                       focus_rect.width(), focus_rect.height());
    }
#endif

    cairo_destroy(cr);
    cairo_surface_destroy(surface);

    return gfx::ImageSkiaRep(border, scale);
  }

 private:
  bool is_blue_;
  bool focus_;
  ui::NativeTheme::State state_;
  int width_;
  int height_;

  DISALLOW_COPY_AND_ASSIGN(GtkButtonImageSource);
};

class GtkButtonPainter : public views::Painter {
 public:
  explicit GtkButtonPainter(std::string idr) : idr_(idr) {}
  ~GtkButtonPainter() override {}

  gfx::Size GetMinimumSize() const override { return gfx::Size(); }
  void Paint(gfx::Canvas* canvas, const gfx::Size& size) override {
    gfx::ImageSkia image(
        std::make_unique<GtkButtonImageSource>(idr_.c_str(), size), 1);
    canvas->DrawImageInt(image, 0, 0);
  }

 private:
  std::string idr_;

  DISALLOW_COPY_AND_ASSIGN(GtkButtonPainter);
};

struct GObjectDeleter {
  void operator()(void* ptr) { g_object_unref(ptr); }
};
struct GtkIconInfoDeleter {
  void operator()(GtkIconInfo* ptr) {
#if GTK_CHECK_VERSION(3, 90, 0)
    g_object_unref(ptr);
#else
    G_GNUC_BEGIN_IGNORE_DEPRECATIONS
    gtk_icon_info_free(ptr);
    G_GNUC_END_IGNORE_DEPRECATIONS
#endif
  }
};
typedef std::unique_ptr<GIcon, GObjectDeleter> ScopedGIcon;
typedef std::unique_ptr<GtkIconInfo, GtkIconInfoDeleter> ScopedGtkIconInfo;
typedef std::unique_ptr<GdkPixbuf, GObjectDeleter> ScopedGdkPixbuf;

#if !GTK_CHECK_VERSION(3, 90, 0)
// Prefix for app indicator ids
const char kAppIndicatorIdPrefix[] = "chrome_app_indicator_";
#endif

// Number of app indicators used (used as part of app-indicator id).
int indicators_count;

// The unknown content type.
const char* kUnknownContentType = "application/octet-stream";

#if GTK_MAJOR_VERSION > 2
using GdkSetAllowedBackendsFn = void (*)(const gchar*);
// Place this function pointer in read-only memory after being resolved to
// prevent it being tampered with. See https://crbug.com/771365 for details.
PROTECTED_MEMORY_SECTION base::ProtectedMemory<GdkSetAllowedBackendsFn>
    g_gdk_set_allowed_backends;
#endif

std::unique_ptr<SettingsProvider> CreateSettingsProvider(GtkUi* gtk_ui) {
#if GTK_MAJOR_VERSION == 3
  if (GtkVersionCheck(3, 14))
    return std::make_unique<SettingsProviderGtk>(gtk_ui);
#endif
#if defined(USE_GIO)
  return std::make_unique<SettingsProviderGSettings>(gtk_ui);
#else
  return nullptr;
#endif
}

// Returns a gfx::FontRenderParams corresponding to GTK's configuration.
gfx::FontRenderParams GetGtkFontRenderParams() {
  GtkSettings* gtk_settings = gtk_settings_get_default();
  CHECK(gtk_settings);
  gint antialias = 0;
  gint hinting = 0;
  gchar* hint_style = nullptr;
  gchar* rgba = nullptr;
  g_object_get(gtk_settings, "gtk-xft-antialias", &antialias, "gtk-xft-hinting",
               &hinting, "gtk-xft-hintstyle", &hint_style, "gtk-xft-rgba",
               &rgba, nullptr);

  gfx::FontRenderParams params;
  params.antialiasing = antialias != 0;

  if (hinting == 0 || !hint_style || strcmp(hint_style, "hintnone") == 0) {
    params.hinting = gfx::FontRenderParams::HINTING_NONE;
  } else if (strcmp(hint_style, "hintslight") == 0) {
    params.hinting = gfx::FontRenderParams::HINTING_SLIGHT;
  } else if (strcmp(hint_style, "hintmedium") == 0) {
    params.hinting = gfx::FontRenderParams::HINTING_MEDIUM;
  } else if (strcmp(hint_style, "hintfull") == 0) {
    params.hinting = gfx::FontRenderParams::HINTING_FULL;
  } else {
    LOG(WARNING) << "Unexpected gtk-xft-hintstyle \"" << hint_style << "\"";
    params.hinting = gfx::FontRenderParams::HINTING_NONE;
  }

  if (!rgba || strcmp(rgba, "none") == 0) {
    params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
  } else if (strcmp(rgba, "rgb") == 0) {
    params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_RGB;
  } else if (strcmp(rgba, "bgr") == 0) {
    params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_BGR;
  } else if (strcmp(rgba, "vrgb") == 0) {
    params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VRGB;
  } else if (strcmp(rgba, "vbgr") == 0) {
    params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VBGR;
  } else {
    LOG(WARNING) << "Unexpected gtk-xft-rgba \"" << rgba << "\"";
    params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
  }

  g_free(hint_style);
  g_free(rgba);

  return params;
}

views::LinuxUI::NonClientWindowFrameAction GetDefaultMiddleClickAction() {
#if GTK_MAJOR_VERSION == 3
  if (GtkVersionCheck(3, 14))
    return views::LinuxUI::WINDOW_FRAME_ACTION_NONE;
#endif
  std::unique_ptr<base::Environment> env(base::Environment::Create());
  switch (base::nix::GetDesktopEnvironment(env.get())) {
    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
    case base::nix::DESKTOP_ENVIRONMENT_KDE5:
      // Starting with KDE 4.4, windows' titlebars can be dragged with the
      // middle mouse button to create tab groups. We don't support that in
      // Chrome, but at least avoid lowering windows in response to middle
      // clicks to avoid surprising users who expect the KDE behavior.
      return views::LinuxUI::WINDOW_FRAME_ACTION_NONE;
    default:
      return views::LinuxUI::WINDOW_FRAME_ACTION_LOWER;
  }
}

#if GTK_MAJOR_VERSION > 2
// COLOR_TOOLBAR_TOP_SEPARATOR represents the border between tabs and the
// frame, as well as the border between tabs and the toolbar.  For this
// reason, it is difficult to calculate the One True Color that works well on
// all themes and is opaque.  However, we can cheat to get a good color that
// works well for both borders.  The idea is we have two variables: alpha and
// lightness.  And we have two constraints (on lightness):
// 1. the border color, when painted on |header_bg|, should give |header_fg|
// 2. the border color, when painted on |tab_bg|, should give |tab_fg|
// This gives the equations:
// alpha*lightness + (1 - alpha)*header_bg = header_fg
// alpha*lightness + (1 - alpha)*tab_bg = tab_fg
// The algorithm below is just a result of solving those equations for alpha
// and lightness.  If a problem is encountered, like division by zero, or
// |a| or |l| not in [0, 1], then fallback on |header_fg| or |tab_fg|.
SkColor GetToolbarTopSeparatorColor(SkColor header_fg,
                                    SkColor header_bg,
                                    SkColor tab_fg,
                                    SkColor tab_bg) {
  using namespace color_utils;

  SkColor default_color = SkColorGetA(header_fg) ? header_fg : tab_fg;
  if (!SkColorGetA(default_color))
    return SK_ColorTRANSPARENT;

  auto get_lightness = [](SkColor color) {
    HSL hsl;
    SkColorToHSL(color, &hsl);
    return hsl.l;
  };

  double f1 = get_lightness(GetResultingPaintColor(header_fg, header_bg));
  double b1 = get_lightness(header_bg);
  double f2 = get_lightness(GetResultingPaintColor(tab_fg, tab_bg));
  double b2 = get_lightness(tab_bg);

  if (b1 == b2)
    return default_color;
  double a = (f1 - f2 - b1 + b2) / (b2 - b1);
  if (a == 0)
    return default_color;
  double l = (f1 - (1 - a) * b1) / a;
  if (a < 0 || a > 1 || l < 0 || l > 1)
    return default_color;
  // Take the hue and saturation from |default_color|, but use the
  // calculated lightness.
  HSL border;
  SkColorToHSL(default_color, &border);
  border.l = l;
  return HSLToSkColor(border, a * 0xff);
}
#endif

}  // namespace

GtkUi::GtkUi() {
  window_frame_actions_[WINDOW_FRAME_ACTION_SOURCE_DOUBLE_CLICK] =
      views::LinuxUI::WINDOW_FRAME_ACTION_TOGGLE_MAXIMIZE;
  window_frame_actions_[WINDOW_FRAME_ACTION_SOURCE_MIDDLE_CLICK] =
      GetDefaultMiddleClickAction();
  window_frame_actions_[WINDOW_FRAME_ACTION_SOURCE_RIGHT_CLICK] =
      views::LinuxUI::WINDOW_FRAME_ACTION_MENU;
#if GTK_MAJOR_VERSION > 2
  // Force Gtk to use Xwayland if it would have used wayland.  libgtkui assumes
  // the use of X11 (eg. X11InputMethodContextImplGtk) and will crash under
  // other backends.
  // TODO(thomasanderson): Change this logic once Wayland support is added.
  static base::ProtectedMemory<GdkSetAllowedBackendsFn>::Initializer init(
      &g_gdk_set_allowed_backends,
      reinterpret_cast<void (*)(const gchar*)>(
          dlsym(GetGdkSharedLibrary(), "gdk_set_allowed_backends")));
  if (GtkVersionCheck(3, 10))
    DCHECK(*g_gdk_set_allowed_backends);
  if (*g_gdk_set_allowed_backends)
    base::UnsanitizedCfiCall(g_gdk_set_allowed_backends)("x11");
#endif
#if GTK_MAJOR_VERSION >= 3
  // Avoid GTK initializing atk-bridge, and let AuraLinux implementation
  // do it once it is ready.
  std::unique_ptr<base::Environment> env(base::Environment::Create());
  env->SetVar("NO_AT_BRIDGE", "1");
#endif
  GtkInitFromCommandLine(*base::CommandLine::ForCurrentProcess());
#if GTK_MAJOR_VERSION == 2
  native_theme_ = NativeThemeGtk2::instance();
  fake_window_ = chrome_gtk_frame_new();
#elif GTK_MAJOR_VERSION == 3
  native_theme_ = NativeThemeGtk::instance();
  fake_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
#else
#error "Unsupported GTK version"
#endif
  gtk_widget_realize(fake_window_);
}

GtkUi::~GtkUi() {
  gtk_widget_destroy(fake_window_);
}

void OnThemeChanged(GObject* obj, GParamSpec* param, GtkUi* gtkui) {
  gtkui->ResetStyle();
}

void GtkUi::Initialize() {
  GtkSettings* settings = gtk_settings_get_default();
  g_signal_connect_after(settings, "notify::gtk-theme-name",
                         G_CALLBACK(OnThemeChanged), this);
  g_signal_connect_after(settings, "notify::gtk-icon-theme-name",
                         G_CALLBACK(OnThemeChanged), this);

  GdkScreen* screen = gdk_screen_get_default();
  // Listen for DPI changes.
  g_signal_connect_after(screen, "notify::resolution",
                         G_CALLBACK(OnDeviceScaleFactorMaybeChangedThunk),
                         this);
  // Listen for scale factor changes.  We would prefer to listen on
  // |screen|, but there is no scale-factor property, so use an
  // unmapped window instead.
  g_signal_connect(fake_window_, "notify::scale-factor",
                   G_CALLBACK(OnDeviceScaleFactorMaybeChangedThunk), this);

  LoadGtkValues();

#if BUILDFLAG(ENABLE_PRINTING)
  printing::PrintingContextLinux::SetCreatePrintDialogFunction(
      &PrintDialogGtk::CreatePrintDialog);
  printing::PrintingContextLinux::SetPdfPaperSizeFunction(
      &GetPdfPaperSizeDeviceUnitsGtk);
#endif

  // We must build this after GTK gets initialized.
  settings_provider_ = CreateSettingsProvider(this);

  indicators_count = 0;

  // Instantiate the singleton instance of GtkEventLoop.
  GtkEventLoop::GetInstance();
}

bool GtkUi::GetTint(int id, color_utils::HSL* tint) const {
  switch (id) {
    // Tints for which the cross-platform default is fine. Before adding new
    // values here, specifically verify they work well on Linux.
    case ThemeProperties::TINT_BACKGROUND_TAB:
    // TODO(estade): Return something useful for TINT_BUTTONS so that chrome://
    // page icons are colored appropriately.
    case ThemeProperties::TINT_BUTTONS:
      break;
    default:
      // Assume any tints not specifically verified on Linux aren't usable.
      // TODO(pkasting): Try to remove values from |colors_| that could just be
      // added to the group above instead.
      NOTREACHED();
  }
  return false;
}

bool GtkUi::GetColor(int id, SkColor* color, PrefService* pref_service) const {
  for (const ColorMap& color_map :
       {colors_, pref_service->GetBoolean(prefs::kUseCustomChromeFrame)
                     ? custom_frame_colors_
                     : native_frame_colors_}) {
    ColorMap::const_iterator it = color_map.find(id);
    if (it != color_map.end()) {
      *color = it->second;
      return true;
    }
  }

  return false;
}

SkColor GtkUi::GetFocusRingColor() const {
  return focus_ring_color_;
}

SkColor GtkUi::GetThumbActiveColor() const {
  return thumb_active_color_;
}

SkColor GtkUi::GetThumbInactiveColor() const {
  return thumb_inactive_color_;
}

SkColor GtkUi::GetTrackColor() const {
  return track_color_;
}

SkColor GtkUi::GetActiveSelectionBgColor() const {
  return active_selection_bg_color_;
}

SkColor GtkUi::GetActiveSelectionFgColor() const {
  return active_selection_fg_color_;
}

SkColor GtkUi::GetInactiveSelectionBgColor() const {
  return inactive_selection_bg_color_;
}

SkColor GtkUi::GetInactiveSelectionFgColor() const {
  return inactive_selection_fg_color_;
}

base::TimeDelta GtkUi::GetCursorBlinkInterval() const {
  // From http://library.gnome.org/devel/gtk/unstable/GtkSettings.html, this is
  // the default value for gtk-cursor-blink-time.
  static const gint kGtkDefaultCursorBlinkTime = 1200;

  // Dividing GTK's cursor blink cycle time (in milliseconds) by this value
  // yields an appropriate value for
  // content::RendererPreferences::caret_blink_interval.  This matches the
  // logic in the WebKit GTK port.
  static const double kGtkCursorBlinkCycleFactor = 2000.0;

  gint cursor_blink_time = kGtkDefaultCursorBlinkTime;
  gboolean cursor_blink = TRUE;
  g_object_get(gtk_settings_get_default(), "gtk-cursor-blink-time",
               &cursor_blink_time, "gtk-cursor-blink", &cursor_blink, nullptr);
  return cursor_blink ? base::TimeDelta::FromSecondsD(
                            cursor_blink_time / kGtkCursorBlinkCycleFactor)
                      : base::TimeDelta();
}

ui::NativeTheme* GtkUi::GetNativeTheme(aura::Window* window) const {
  ui::NativeTheme* native_theme_override = nullptr;
  if (!native_theme_overrider_.is_null())
    native_theme_override = native_theme_overrider_.Run(window);

  if (native_theme_override)
    return native_theme_override;

  return native_theme_;
}

void GtkUi::SetNativeThemeOverride(const NativeThemeGetter& callback) {
  native_theme_overrider_ = callback;
}

bool GtkUi::GetDefaultUsesSystemTheme() const {
  std::unique_ptr<base::Environment> env(base::Environment::Create());

  switch (base::nix::GetDesktopEnvironment(env.get())) {
    case base::nix::DESKTOP_ENVIRONMENT_CINNAMON:
    case base::nix::DESKTOP_ENVIRONMENT_GNOME:
    case base::nix::DESKTOP_ENVIRONMENT_PANTHEON:
    case base::nix::DESKTOP_ENVIRONMENT_UNITY:
    case base::nix::DESKTOP_ENVIRONMENT_XFCE:
      return true;
    case base::nix::DESKTOP_ENVIRONMENT_KDE3:
    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
    case base::nix::DESKTOP_ENVIRONMENT_KDE5:
    case base::nix::DESKTOP_ENVIRONMENT_OTHER:
      return false;
  }
  // Unless GetDesktopEnvironment() badly misbehaves, this should never happen.
  NOTREACHED();
  return false;
}

void GtkUi::SetDownloadCount(int count) const {
  if (unity::IsRunning())
    unity::SetDownloadCount(count);
}

void GtkUi::SetProgressFraction(float percentage) const {
  if (unity::IsRunning())
    unity::SetProgressFraction(percentage);
}

bool GtkUi::IsStatusIconSupported() const {
#if GTK_CHECK_VERSION(3, 90, 0)
  // TODO(thomasanderson): Provide some sort of status icon for GTK4.  The GTK3
  // config has two options.  The first is to use GTK status icons, but these
  // were removed in GTK4.  The second is to use libappindicator.  However, that
  // library has a dependency on GTK3, and loading multiple versions of GTK into
  // the same process is explicitly unsupported.
  NOTIMPLEMENTED();
  return false;
#else
  return true;
#endif
}

std::unique_ptr<views::StatusIconLinux> GtkUi::CreateLinuxStatusIcon(
    const gfx::ImageSkia& image,
    const base::string16& tool_tip) const {
#if GTK_CHECK_VERSION(3, 90, 0)
  NOTIMPLEMENTED();
  return nullptr;
#else
  if (AppIndicatorIcon::CouldOpen()) {
    ++indicators_count;
    return std::unique_ptr<views::StatusIconLinux>(new AppIndicatorIcon(
        base::StringPrintf("%s%d", kAppIndicatorIdPrefix, indicators_count),
        image, tool_tip));
  } else {
    return std::unique_ptr<views::StatusIconLinux>(
        new GtkStatusIcon(image, tool_tip));
  }
#endif
}

gfx::Image GtkUi::GetIconForContentType(const std::string& content_type,
                                        int size) const {
  // This call doesn't take a reference.
  GtkIconTheme* theme = gtk_icon_theme_get_default();

  std::string content_types[] = {content_type, kUnknownContentType};

  for (size_t i = 0; i < arraysize(content_types); ++i) {
    ScopedGIcon icon(g_content_type_get_icon(content_types[i].c_str()));
    ScopedGtkIconInfo icon_info(gtk_icon_theme_lookup_by_gicon(
        theme, icon.get(), size,
        static_cast<GtkIconLookupFlags>(GTK_ICON_LOOKUP_FORCE_SIZE)));
    if (!icon_info)
      continue;
    ScopedGdkPixbuf pixbuf(gtk_icon_info_load_icon(icon_info.get(), nullptr));
    if (!pixbuf)
      continue;

    SkBitmap bitmap = GdkPixbufToImageSkia(pixbuf.get());
    DCHECK_EQ(size, bitmap.width());
    DCHECK_EQ(size, bitmap.height());
    gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap);
    image_skia.MakeThreadSafe();
    return gfx::Image(image_skia);
  }
  return gfx::Image();
}

std::unique_ptr<views::Border> GtkUi::CreateNativeBorder(
    views::LabelButton* owning_button,
    std::unique_ptr<views::LabelButtonBorder> border) {
  if (owning_button->GetNativeTheme() != native_theme_)
    return std::move(border);

  std::unique_ptr<views::LabelButtonAssetBorder> gtk_border(
      new views::LabelButtonAssetBorder(owning_button->style()));

  gtk_border->set_insets(border->GetInsets());

  static struct {
    const char* idr;
    const char* idr_blue;
    bool focus;
    views::Button::ButtonState state;
  } const paintstate[] = {
      {
          "IDR_BUTTON_NORMAL", "IDR_BLUE_BUTTON_NORMAL", false,
          views::Button::STATE_NORMAL,
      },
      {
          "IDR_BUTTON_HOVER", "IDR_BLUE_BUTTON_HOVER", false,
          views::Button::STATE_HOVERED,
      },
      {
          "IDR_BUTTON_PRESSED", "IDR_BLUE_BUTTON_PRESSED", false,
          views::Button::STATE_PRESSED,
      },
      {
          "IDR_BUTTON_DISABLED", "IDR_BLUE_BUTTON_DISABLED", false,
          views::Button::STATE_DISABLED,
      },

      {
          "IDR_BUTTON_FOCUSED_NORMAL", "IDR_BLUE_BUTTON_FOCUSED_NORMAL", true,
          views::Button::STATE_NORMAL,
      },
      {
          "IDR_BUTTON_FOCUSED_HOVER", "IDR_BLUE_BUTTON_FOCUSED_HOVER", true,
          views::Button::STATE_HOVERED,
      },
      {
          "IDR_BUTTON_FOCUSED_PRESSED", "IDR_BLUE_BUTTON_FOCUSED_PRESSED", true,
          views::Button::STATE_PRESSED,
      },
      {
          "IDR_BUTTON_DISABLED", "IDR_BLUE_BUTTON_DISABLED", true,
          views::Button::STATE_DISABLED,
      },
  };

  bool is_blue =
      owning_button->GetClassName() == views::BlueButton::kViewClassName;

  for (unsigned i = 0; i < arraysize(paintstate); i++) {
    std::string idr = is_blue ? paintstate[i].idr_blue : paintstate[i].idr;
    gtk_border->SetPainter(
        paintstate[i].focus, paintstate[i].state,
        border->PaintsButtonState(paintstate[i].focus, paintstate[i].state)
            ? std::make_unique<GtkButtonPainter>(idr)
            : nullptr);
  }

  return std::move(gtk_border);
}

void GtkUi::AddWindowButtonOrderObserver(
    views::WindowButtonOrderObserver* observer) {
  if (nav_buttons_set_)
    observer->OnWindowButtonOrderingChange(leading_buttons_, trailing_buttons_);

  window_button_order_observer_list_.AddObserver(observer);
}

void GtkUi::RemoveWindowButtonOrderObserver(
    views::WindowButtonOrderObserver* observer) {
  window_button_order_observer_list_.RemoveObserver(observer);
}

void GtkUi::SetWindowButtonOrdering(
    const std::vector<views::FrameButton>& leading_buttons,
    const std::vector<views::FrameButton>& trailing_buttons) {
  leading_buttons_ = leading_buttons;
  trailing_buttons_ = trailing_buttons;
  nav_buttons_set_ = true;

  for (views::WindowButtonOrderObserver& observer :
       window_button_order_observer_list_) {
    observer.OnWindowButtonOrderingChange(leading_buttons_, trailing_buttons_);
  }
}

void GtkUi::SetNonClientWindowFrameAction(
    NonClientWindowFrameActionSourceType source,
    NonClientWindowFrameAction action) {
  window_frame_actions_[source] = action;
}

std::unique_ptr<ui::LinuxInputMethodContext> GtkUi::CreateInputMethodContext(
    ui::LinuxInputMethodContextDelegate* delegate,
    bool is_simple) const {
  return std::unique_ptr<ui::LinuxInputMethodContext>(
      new X11InputMethodContextImplGtk(delegate, is_simple));
}

gfx::FontRenderParams GtkUi::GetDefaultFontRenderParams() const {
  static gfx::FontRenderParams params = GetGtkFontRenderParams();
  return params;
}

void GtkUi::GetDefaultFontDescription(std::string* family_out,
                                      int* size_pixels_out,
                                      int* style_out,
                                      gfx::Font::Weight* weight_out,
                                      gfx::FontRenderParams* params_out) const {
  *family_out = default_font_family_;
  *size_pixels_out = default_font_size_pixels_;
  *style_out = default_font_style_;
  *weight_out = default_font_weight_;
  *params_out = default_font_render_params_;
}

ui::SelectFileDialog* GtkUi::CreateSelectFileDialog(
    ui::SelectFileDialog::Listener* listener,
    std::unique_ptr<ui::SelectFilePolicy> policy) const {
  return SelectFileDialogImpl::Create(listener, std::move(policy));
}

views::LinuxUI::NonClientWindowFrameAction GtkUi::GetNonClientWindowFrameAction(
    NonClientWindowFrameActionSourceType source) {
  return window_frame_actions_[source];
}

void GtkUi::NotifyWindowManagerStartupComplete() {
  // TODO(port) Implement this using _NET_STARTUP_INFO_BEGIN/_NET_STARTUP_INFO
  // from http://standards.freedesktop.org/startup-notification-spec/ instead.
  gdk_notify_startup_complete();
}

void GtkUi::AddDeviceScaleFactorObserver(
    views::DeviceScaleFactorObserver* observer) {
  device_scale_factor_observer_list_.AddObserver(observer);
}

void GtkUi::RemoveDeviceScaleFactorObserver(
    views::DeviceScaleFactorObserver* observer) {
  device_scale_factor_observer_list_.RemoveObserver(observer);
}

bool GtkUi::PreferDarkTheme() const {
  gboolean dark = false;
  g_object_get(gtk_settings_get_default(), "gtk-application-prefer-dark-theme",
               &dark, nullptr);
  return dark;
}

#if BUILDFLAG(ENABLE_NATIVE_WINDOW_NAV_BUTTONS)
std::unique_ptr<views::NavButtonProvider> GtkUi::CreateNavButtonProvider() {
#if GTK_MAJOR_VERSION == 3
  if (GtkVersionCheck(3, 14))
    return std::make_unique<libgtkui::NavButtonProviderGtk>();
#endif
  return nullptr;
}
#endif

// Mapping from GDK dead keys to corresponding printable character.
static struct {
  guint gdk_key;
  guint16 unicode;
} kDeadKeyMapping[] = {
    {GDK_KEY_dead_grave, 0x0060},      {GDK_KEY_dead_acute, 0x0027},
    {GDK_KEY_dead_circumflex, 0x005e}, {GDK_KEY_dead_tilde, 0x007e},
    {GDK_KEY_dead_diaeresis, 0x00a8},
};

base::flat_map<std::string, std::string> GtkUi::GetKeyboardLayoutMap() {
  GdkDisplay* display = gdk_display_get_default();
  GdkKeymap* keymap = gdk_keymap_get_for_display(display);
  if (!keymap)
    return {};

  ui::DomKeyboardLayoutManager* layouts = new ui::DomKeyboardLayoutManager();
  auto map = base::flat_map<std::string, std::string>();

  for (unsigned int i_domcode = 0;
       i_domcode < ui::kWritingSystemKeyDomCodeEntries; ++i_domcode) {
    ui::DomCode domcode = ui::writing_system_key_domcodes[i_domcode];
    guint16 keycode = ui::KeycodeConverter::DomCodeToNativeKeycode(domcode);
    GdkKeymapKey* keys = nullptr;
    guint* keyvals = nullptr;
    gint n_entries = 0;

    // The order of the layouts is based on the system default ordering in
    // Keyboard Settings. The currently active layout does not affect this
    // order.
    if (gdk_keymap_get_entries_for_keycode(keymap, keycode, &keys, &keyvals,
                                           &n_entries)) {
      for (gint i = 0; i < n_entries; ++i) {
        // There are 4 entries per layout group, one each for shift level 0..3.
        // We only care about the unshifted values (level = 0).
        if (keys[i].level == 0) {
          uint16_t unicode = gdk_keyval_to_unicode(keyvals[i]);
          if (unicode == 0) {
            for (unsigned int i_dead = 0; i_dead < base::size(kDeadKeyMapping);
                 ++i_dead) {
              if (keyvals[i] == kDeadKeyMapping[i_dead].gdk_key)
                unicode = kDeadKeyMapping[i_dead].unicode;
            }
          }
          if (unicode != 0)
            layouts->GetLayout(keys[i].group)->AddKeyMapping(domcode, unicode);
        }
      }
    }
    g_free(keys);
    keys = nullptr;
    g_free(keyvals);
    keyvals = nullptr;
  }
  return layouts->GetFirstAsciiCapableLayout()->GetMap();
}

bool GtkUi::MatchEvent(const ui::Event& event,
                       std::vector<ui::TextEditCommandAuraLinux>* commands) {
  // Ensure that we have a keyboard handler.
  if (!key_bindings_handler_)
    key_bindings_handler_.reset(new GtkKeyBindingsHandler);

  return key_bindings_handler_->MatchEvent(event, commands);
}

void GtkUi::OnDeviceScaleFactorMaybeChanged(void*, GParamSpec*) {
  UpdateDeviceScaleFactor();
}

void GtkUi::SetScrollbarColors() {
  // TODO(thomasanderson): Do not hardcode these values.  Get them from the
  // theme.
  thumb_active_color_ = SkColorSetRGB(244, 244, 244);
  thumb_inactive_color_ = SkColorSetRGB(234, 234, 234);
  track_color_ = SkColorSetRGB(211, 211, 211);
}

void GtkUi::LoadGtkValues() {
  // TODO(erg): GtkThemeService had a comment here about having to muck with
  // the raw Prefs object to remove prefs::kCurrentThemeImages or else we'd
  // regress startup time. Figure out how to do that when we can't access the
  // prefs system from here.

  UpdateDeviceScaleFactor();
  UpdateCursorTheme();

#if GTK_MAJOR_VERSION == 2
  const color_utils::HSL kDefaultFrameShift = {-1, -1, 0.4};
  SkColor frame_color =
      native_theme_->GetSystemColor(ui::NativeTheme::kColorId_WindowBackground);
  frame_color = color_utils::HSLShift(frame_color, kDefaultFrameShift);
  GetChromeStyleColor("frame-color", &frame_color);
  colors_[ThemeProperties::COLOR_FRAME] = frame_color;

  GtkStyle* style = gtk_rc_get_style(fake_window_);
  SkColor temp_color = color_utils::HSLShift(
      GdkColorToSkColor(style->bg[GTK_STATE_INSENSITIVE]), kDefaultFrameShift);
  GetChromeStyleColor("inactive-frame-color", &temp_color);
  colors_[ThemeProperties::COLOR_FRAME_INACTIVE] = temp_color;

  temp_color = color_utils::HSLShift(frame_color, kDefaultTintFrameIncognito);
  GetChromeStyleColor("incognito-frame-color", &temp_color);
  colors_[ThemeProperties::COLOR_FRAME_INCOGNITO] = temp_color;

  temp_color =
      color_utils::HSLShift(frame_color, kDefaultTintFrameIncognitoInactive);
  GetChromeStyleColor("incognito-inactive-frame-color", &temp_color);
  colors_[ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE] = temp_color;

  SkColor tab_color =
      native_theme_->GetSystemColor(ui::NativeTheme::kColorId_DialogBackground);
  SkColor label_color = native_theme_->GetSystemColor(
      ui::NativeTheme::kColorId_LabelEnabledColor);

  colors_[ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON] =
      color_utils::DeriveDefaultIconColor(label_color);

  colors_[ThemeProperties::COLOR_TAB_TEXT] = label_color;
  colors_[ThemeProperties::COLOR_BOOKMARK_TEXT] = label_color;
  colors_[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] =
      color_utils::BlendTowardOppositeLuma(label_color, 50);

  inactive_selection_bg_color_ = native_theme_->GetSystemColor(
      ui::NativeTheme::kColorId_TextfieldReadOnlyBackground);
  inactive_selection_fg_color_ = native_theme_->GetSystemColor(
      ui::NativeTheme::kColorId_TextfieldReadOnlyColor);

  // We pick the text and background colors for the NTP out of the
  // colors for a GtkEntry. We do this because GtkEntries background
  // color is never the same as |tab_color|, is usually a white,
  // and when it isn't a white, provides sufficient contrast to
  // |tab_color|. Try this out with Darklooks, HighContrastInverse
  // or ThinIce.
  colors_[ThemeProperties::COLOR_NTP_BACKGROUND] =
      native_theme_->GetSystemColor(
          ui::NativeTheme::kColorId_TextfieldDefaultBackground);
  colors_[ThemeProperties::COLOR_NTP_TEXT] = native_theme_->GetSystemColor(
      ui::NativeTheme::kColorId_TextfieldDefaultColor);
  // The NTP header is the color that surrounds the current active
  // thumbnail on the NTP, and acts as the border of the "Recent
  // Links" box. It would be awesome if they were separated so we
  // could use GetBorderColor() for the border around the "Recent
  // Links" section, but matching the frame color is more important.
  colors_[ThemeProperties::COLOR_NTP_HEADER] =
      colors_[ThemeProperties::COLOR_FRAME];
#else
  SkColor tab_color = GetBgColor("");
  SkColor tab_text_color = GetFgColor("GtkLabel");

  colors_[ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON] = tab_text_color;

  colors_[ThemeProperties::COLOR_TAB_TEXT] = tab_text_color;
  colors_[ThemeProperties::COLOR_BOOKMARK_TEXT] = tab_text_color;

  SkColor location_bar_border = GetBorderColor("GtkEntry#entry");
  if (SkColorGetA(location_bar_border))
    colors_[ThemeProperties::COLOR_LOCATION_BAR_BORDER] = location_bar_border;

  inactive_selection_bg_color_ = GetSelectionBgColor(
      GtkVersionCheck(3, 20) ? "GtkTextView#textview.view:backdrop "
                               "#text:backdrop #selection:backdrop"
                             : "GtkTextView.view:selected:backdrop");
  inactive_selection_fg_color_ =
      GetFgColor(GtkVersionCheck(3, 20) ? "GtkTextView#textview.view:backdrop "
                                          "#text:backdrop #selection:backdrop"
                                        : "GtkTextView.view:selected:backdrop");

  SkColor tab_border = GetBorderColor("GtkButton#button");
  colors_[ThemeProperties::COLOR_DETACHED_BOOKMARK_BAR_BACKGROUND] = tab_color;
  colors_[ThemeProperties::COLOR_BOOKMARK_BAR_INSTRUCTIONS_TEXT] =
      tab_text_color;
  // Separates the toolbar from the bookmark bar or butter bars.
  colors_[ThemeProperties::COLOR_TOOLBAR_CONTENT_AREA_SEPARATOR] = tab_border;
  // Separates entries in the downloads bar.
  colors_[ThemeProperties::COLOR_TOOLBAR_VERTICAL_SEPARATOR] = tab_border;
  // Separates the detached bookmark bar from the NTP.
  colors_[ThemeProperties::COLOR_DETACHED_BOOKMARK_BAR_SEPARATOR] = tab_border;

  colors_[ThemeProperties::COLOR_NTP_BACKGROUND] =
      native_theme_->GetSystemColor(
          ui::NativeTheme::kColorId_TextfieldDefaultBackground);
  colors_[ThemeProperties::COLOR_NTP_TEXT] = native_theme_->GetSystemColor(
      ui::NativeTheme::kColorId_TextfieldDefaultColor);
  colors_[ThemeProperties::COLOR_NTP_HEADER] =
      GetBorderColor("GtkButton#button");

  for (bool custom_frame : {false, true}) {
    ColorMap& color_map =
        custom_frame ? custom_frame_colors_ : native_frame_colors_;
    const std::string header_selector = custom_frame && GtkVersionCheck(3, 10)
                                            ? "#headerbar.header-bar.titlebar"
                                            : "GtkMenuBar#menubar";
    const std::string header_selector_inactive = header_selector + ":backdrop";
    const SkColor frame_color = GetBgColor(header_selector);
    const SkColor frame_color_incognito =
        color_utils::HSLShift(frame_color, kDefaultTintFrameIncognito);
    const SkColor frame_color_inactive = GetBgColor(header_selector_inactive);
    const SkColor frame_color_incognito_inactive =
        color_utils::HSLShift(frame_color_inactive, kDefaultTintFrameIncognito);

    color_map[ThemeProperties::COLOR_FRAME] = frame_color;
    color_map[ThemeProperties::COLOR_FRAME_INACTIVE] = frame_color_inactive;
    color_map[ThemeProperties::COLOR_FRAME_INCOGNITO] = frame_color_incognito;
    color_map[ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE] =
        frame_color_incognito_inactive;

    if (ui::MaterialDesignController::IsRefreshUi()) {
      colors_[ThemeProperties::COLOR_BACKGROUND_TAB] = SK_ColorTRANSPARENT;
      colors_[ThemeProperties::COLOR_BACKGROUND_TAB_INACTIVE] =
          SK_ColorTRANSPARENT;
      colors_[ThemeProperties::COLOR_BACKGROUND_TAB_INCOGNITO] =
          SK_ColorTRANSPARENT;
      colors_[ThemeProperties::COLOR_BACKGROUND_TAB_INCOGNITO_INACTIVE] =
          SK_ColorTRANSPARENT;

      const SkColor background_tab_text_color =
          GetFgColor(header_selector + " GtkLabel.title");
      const SkColor background_tab_text_color_inactive =
          GetFgColor(header_selector_inactive + " GtkLabel.title");

      color_map[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] =
          background_tab_text_color;
      color_map[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT_INCOGNITO] =
          color_utils::GetColorWithMinimumContrast(
              color_utils::HSLShift(background_tab_text_color,
                                    kDefaultTintFrameIncognito),
              frame_color_incognito);
      color_map[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT_INACTIVE] =
          background_tab_text_color_inactive;
      color_map[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT_INCOGNITO_INACTIVE] =
          color_utils::GetColorWithMinimumContrast(
              color_utils::HSLShift(background_tab_text_color_inactive,
                                    kDefaultTintFrameIncognito),
              frame_color_incognito_inactive);
    } else {
      color_utils::HSL frame_hsl;
      color_utils::SkColorToHSL(frame_color, &frame_hsl);
      color_utils::HSL frame_hsl_inactive;
      color_utils::SkColorToHSL(frame_color_inactive, &frame_hsl_inactive);
      const color_utils::HSL inactive_shift =
          color_utils::HSL{-1, (frame_hsl_inactive.s - frame_hsl.s + 1) / 2,
                           (frame_hsl_inactive.l - frame_hsl.l + 1) / 2};

      const SkColor background_tab_color =
          color_utils::HSLShift(tab_color, kDefaultTintBackgroundTab);
      const SkColor background_tab_color_inactive =
          color_utils::HSLShift(background_tab_color, inactive_shift);
      const SkColor background_tab_color_incognito =
          color_utils::HSLShift(tab_color, kDefaultTintBackgroundTabIncognito);
      const SkColor background_tab_color_incognito_inactive =
          color_utils::HSLShift(background_tab_color_incognito, inactive_shift);

      colors_[ThemeProperties::COLOR_BACKGROUND_TAB] = background_tab_color;
      colors_[ThemeProperties::COLOR_BACKGROUND_TAB_INACTIVE] =
          background_tab_color_inactive;
      colors_[ThemeProperties::COLOR_BACKGROUND_TAB_INCOGNITO] =
          background_tab_color_incognito;
      colors_[ThemeProperties::COLOR_BACKGROUND_TAB_INCOGNITO_INACTIVE] =
          background_tab_color_incognito_inactive;

      const SkColor background_tab_text_color =
          color_utils::BlendTowardOppositeLuma(tab_text_color, 50);
      const SkColor background_tab_text_color_incognito = color_utils::HSLShift(
          background_tab_text_color, kDefaultTintFrameIncognito);
      const SkColor background_tab_text_color_inactive =
          color_utils::HSLShift(background_tab_text_color, inactive_shift);
      const SkColor background_tab_text_color_incognito_inactive =
          color_utils::HSLShift(background_tab_text_color_incognito,
                                inactive_shift);

      color_map[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] =
          color_utils::GetColorWithMinimumContrast(background_tab_text_color,
                                                   background_tab_color);
      color_map[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT_INCOGNITO] =
          color_utils::GetColorWithMinimumContrast(
              background_tab_text_color_incognito,
              background_tab_color_incognito);
      color_map[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT_INACTIVE] =
          color_utils::GetColorWithMinimumContrast(
              background_tab_text_color_inactive,
              background_tab_color_inactive);
      color_map[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT_INCOGNITO_INACTIVE] =
          color_utils::GetColorWithMinimumContrast(
              background_tab_text_color_incognito_inactive,
              background_tab_color_incognito_inactive);
    }

    // These colors represent the border drawn around tabs and between
    // the tabstrip and toolbar.
    SkColor toolbar_top_separator =
        GetBorderColor(header_selector + " GtkButton#button");
    SkColor toolbar_top_separator_inactive =
        GetBorderColor(header_selector + ":backdrop GtkButton#button");
    if (!ui::MaterialDesignController::IsRefreshUi()) {
      toolbar_top_separator = GetToolbarTopSeparatorColor(
          toolbar_top_separator, frame_color, tab_border, tab_color);
      toolbar_top_separator_inactive = GetToolbarTopSeparatorColor(
          toolbar_top_separator_inactive, frame_color_inactive, tab_border,
          tab_color);
    }

    // Unlike with toolbars, we always want a border around tabs, so let
    // ThemeService choose the border color if the theme doesn't provide one.
    if (SkColorGetA(toolbar_top_separator) &&
        SkColorGetA(toolbar_top_separator_inactive)) {
      color_map[ThemeProperties::COLOR_TOOLBAR_TOP_SEPARATOR] =
          toolbar_top_separator;
      color_map[ThemeProperties::COLOR_TOOLBAR_TOP_SEPARATOR_INACTIVE] =
          toolbar_top_separator_inactive;
    }
  }
#endif

  colors_[ThemeProperties::COLOR_TOOLBAR] = tab_color;
  colors_[ThemeProperties::COLOR_CONTROL_BACKGROUND] = tab_color;

  colors_[ThemeProperties::COLOR_NTP_LINK] = native_theme_->GetSystemColor(
      ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused);

  // Generate the colors that we pass to WebKit.
  SetScrollbarColors();
  focus_ring_color_ = native_theme_->GetSystemColor(
      ui::NativeTheme::kColorId_FocusedBorderColor);

  // Some GTK themes only define the text selection colors on the GtkEntry
  // class, so we need to use that for getting selection colors.
  active_selection_bg_color_ = native_theme_->GetSystemColor(
      ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused);
  active_selection_fg_color_ = native_theme_->GetSystemColor(
      ui::NativeTheme::kColorId_TextfieldSelectionColor);

  colors_[ThemeProperties::COLOR_TAB_THROBBER_SPINNING] =
      native_theme_->GetSystemColor(
          ui::NativeTheme::kColorId_ThrobberSpinningColor);
  colors_[ThemeProperties::COLOR_TAB_THROBBER_WAITING] =
      native_theme_->GetSystemColor(
          ui::NativeTheme::kColorId_ThrobberWaitingColor);
}

void GtkUi::UpdateCursorTheme() {
  GtkSettings* settings = gtk_settings_get_default();

  gchar* theme = nullptr;
  gint size = 0;
  g_object_get(settings, "gtk-cursor-theme-name", &theme,
               "gtk-cursor-theme-size", &size, nullptr);

  if (theme)
    XcursorSetTheme(gfx::GetXDisplay(), theme);
  if (size)
    XcursorSetDefaultSize(gfx::GetXDisplay(), size);

  g_free(theme);
}

void GtkUi::UpdateDefaultFont() {
  gfx::SetFontRenderParamsDeviceScaleFactor(device_scale_factor_);

  GtkWidget* fake_label = gtk_label_new(nullptr);
  g_object_ref_sink(fake_label);  // Remove the floating reference.
  PangoContext* pc = gtk_widget_get_pango_context(fake_label);
  const PangoFontDescription* desc = pango_context_get_font_description(pc);

  // Use gfx::FontRenderParams to select a family and determine the rendering
  // settings.
  gfx::FontRenderParamsQuery query;
  query.families =
      base::SplitString(pango_font_description_get_family(desc), ",",
                        base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);

  if (pango_font_description_get_size_is_absolute(desc)) {
    // If the size is absolute, it's specified in Pango units. There are
    // PANGO_SCALE Pango units in a device unit (pixel).
    const int size_pixels = pango_font_description_get_size(desc) / PANGO_SCALE;
    default_font_size_pixels_ = size_pixels;
    query.pixel_size = size_pixels;
  } else {
    // Non-absolute sizes are in points (again scaled by PANGO_SIZE).
    // Round the value when converting to pixels to match GTK's logic.
    const double size_points = pango_font_description_get_size(desc) /
                               static_cast<double>(PANGO_SCALE);
    default_font_size_pixels_ =
        static_cast<int>(kDefaultDPI / 72.0 * size_points + 0.5);
    query.point_size = static_cast<int>(size_points);
  }

  query.style = gfx::Font::NORMAL;
  query.weight =
      static_cast<gfx::Font::Weight>(pango_font_description_get_weight(desc));
  // TODO(davemoore): What about PANGO_STYLE_OBLIQUE?
  if (pango_font_description_get_style(desc) == PANGO_STYLE_ITALIC)
    query.style |= gfx::Font::ITALIC;

  default_font_render_params_ =
      gfx::GetFontRenderParams(query, &default_font_family_);
  default_font_style_ = query.style;

  gtk_widget_destroy(fake_label);
  g_object_unref(fake_label);
}

bool GtkUi::GetChromeStyleColor(const char* style_property,
                                SkColor* ret_color) const {
#if GTK_MAJOR_VERSION == 2
  GdkColor* style_color = nullptr;
  gtk_widget_style_get(fake_window_, style_property, &style_color, nullptr);
  if (style_color) {
    *ret_color = GdkColorToSkColor(*style_color);
    gdk_color_free(style_color);
    return true;
  }
#endif
  return false;
}

void GtkUi::ResetStyle() {
  LoadGtkValues();
  native_theme_->NotifyObservers();
}

float GtkUi::GetRawDeviceScaleFactor() {
  if (display::Display::HasForceDeviceScaleFactor())
    return display::Display::GetForcedDeviceScaleFactor();

#if GTK_MAJOR_VERSION == 2
  GtkSettings* gtk_settings = gtk_settings_get_default();
  gint gtk_dpi = -1;
  g_object_get(gtk_settings, "gtk-xft-dpi", &gtk_dpi, nullptr);
  const float scale_factor = gtk_dpi / (1024 * kDefaultDPI);
#else
  GdkScreen* screen = gdk_screen_get_default();
  gint scale = gtk_widget_get_scale_factor(fake_window_);
  DCHECK_GT(scale, 0);
  gdouble resolution = gdk_screen_get_resolution(screen);
  const float scale_factor =
      resolution <= 0 ? scale : resolution * scale / kDefaultDPI;
#endif

  // Blacklist scaling factors <120% (crbug.com/484400) and round
  // to 1 decimal to prevent rendering problems (crbug.com/485183).
  return scale_factor < 1.2f ? 1.0f : roundf(scale_factor * 10) / 10;
}

void GtkUi::UpdateDeviceScaleFactor() {
  float old_device_scale_factor = device_scale_factor_;
  device_scale_factor_ = GetRawDeviceScaleFactor();
  if (device_scale_factor_ != old_device_scale_factor) {
    for (views::DeviceScaleFactorObserver& observer :
         device_scale_factor_observer_list_) {
      observer.OnDeviceScaleFactorChanged();
    }
  }
  UpdateDefaultFont();
}

float GtkUi::GetDeviceScaleFactor() const {
  return device_scale_factor_;
}

}  // namespace libgtkui

views::LinuxUI* BuildGtkUi() {
  return new libgtkui::GtkUi;
}