summaryrefslogtreecommitdiffstats
path: root/components/mus/ws/window_tree.cc
blob: 938fbd4c4a0fe43498aa4d66630784ba6cdc83e0 (plain)
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
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
// Copyright 2014 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 "components/mus/ws/window_tree.h"

#include <stddef.h>
#include <utility>

#include "base/bind.h"
#include "base/macros.h"
#include "base/stl_util.h"
#include "components/mus/ws/default_access_policy.h"
#include "components/mus/ws/display.h"
#include "components/mus/ws/display_manager.h"
#include "components/mus/ws/focus_controller.h"
#include "components/mus/ws/operation.h"
#include "components/mus/ws/platform_display.h"
#include "components/mus/ws/server_window.h"
#include "components/mus/ws/server_window_observer.h"
#include "components/mus/ws/window_manager_state.h"
#include "components/mus/ws/window_server.h"
#include "components/mus/ws/window_tree_binding.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/converters/ime/ime_type_converters.h"
#include "mojo/converters/input_events/input_events_type_converters.h"
#include "mojo/converters/surfaces/surfaces_type_converters.h"
#include "ui/platform_window/text_input_state.h"

using mojo::Array;
using mojo::Callback;
using mojo::InterfaceRequest;
using mojo::Rect;
using mojo::String;

namespace mus {
namespace ws {

class TargetedEvent : public ServerWindowObserver {
 public:
  TargetedEvent(ServerWindow* target, const ui::Event& event)
      : target_(target), event_(ui::Event::Clone(event)) {
    target_->AddObserver(this);
  }
  ~TargetedEvent() override {
    if (target_)
      target_->RemoveObserver(this);
  }

  ServerWindow* target() { return target_; }
  ui::Event* event() { return event_.get(); }

 private:
  // ServerWindowObserver:
  void OnWindowDestroyed(ServerWindow* window) override {
    DCHECK_EQ(target_, window);
    target_->RemoveObserver(this);
    target_ = nullptr;
  }

  ServerWindow* target_;
  scoped_ptr<ui::Event> event_;

  DISALLOW_COPY_AND_ASSIGN(TargetedEvent);
};

WindowTree::WindowTree(WindowServer* window_server,
                       const UserId& user_id,
                       ServerWindow* root,
                       scoped_ptr<AccessPolicy> access_policy)
    : window_server_(window_server),
      user_id_(user_id),
      id_(window_server_->GetAndAdvanceNextConnectionId()),
      next_window_id_(1),
      access_policy_(std::move(access_policy)),
      event_ack_id_(0),
      window_manager_internal_(nullptr) {
  if (root)
    roots_.insert(root);
  access_policy_->Init(id_, this);
}

WindowTree::~WindowTree() {
  DestroyWindows();
}

void WindowTree::Init(scoped_ptr<WindowTreeBinding> binding,
                      mojom::WindowTreePtr tree) {
  DCHECK(!binding_);
  binding_ = std::move(binding);

  if (roots_.empty())
    return;

  std::vector<const ServerWindow*> to_send;
  CHECK_EQ(1u, roots_.size());
  GetUnknownWindowsFrom(*roots_.begin(), &to_send);

  Display* display = GetDisplay(*roots_.begin());
  const ServerWindow* focused_window =
      display ? display->GetFocusedWindow() : nullptr;
  if (focused_window)
    focused_window = access_policy_->GetWindowForFocusChange(focused_window);
  ClientWindowId focused_window_id;
  if (focused_window)
    IsWindowKnown(focused_window, &focused_window_id);

  client()->OnEmbed(id_, WindowToWindowData(to_send.front()), std::move(tree),
                    focused_window_id.id);
}

void WindowTree::ConfigureWindowManager() {
  DCHECK(!window_manager_internal_);
  window_manager_internal_ = binding_->GetWindowManager();
}

const ServerWindow* WindowTree::GetWindow(const WindowId& id) const {
  if (id_ == id.connection_id) {
    auto iter = created_window_map_.find(id);
    return iter == created_window_map_.end() ? nullptr : iter->second;
  }
  return window_server_->GetWindow(id);
}

bool WindowTree::IsWindowKnown(const ServerWindow* window,
                               ClientWindowId* id) const {
  if (!window)
    return false;
  auto iter = window_id_to_client_id_map_.find(window->id());
  if (iter == window_id_to_client_id_map_.end())
    return false;
  if (id)
    *id = iter->second;
  return true;
}

bool WindowTree::HasRoot(const ServerWindow* window) const {
  return roots_.count(window) > 0;
}

const ServerWindow* WindowTree::GetWindowByClientId(
    const ClientWindowId& id) const {
  auto iter = client_id_to_window_id_map_.find(id);
  return iter == client_id_to_window_id_map_.end() ? nullptr
                                                   : GetWindow(iter->second);
}

const Display* WindowTree::GetDisplay(const ServerWindow* window) const {
  return window ? display_manager()->GetDisplayContaining(window) : nullptr;
}

const WindowManagerState* WindowTree::GetWindowManagerState(
    const ServerWindow* window) const {
  return window
             ? display_manager()
                   ->GetWindowManagerAndDisplay(window)
                   .window_manager_state
             : nullptr;
}

void WindowTree::OnWindowDestroyingTreeImpl(WindowTree* tree) {
  if (event_source_wms_ && event_source_wms_->tree() == tree)
    event_source_wms_ = nullptr;

  // Notify our client if |tree| was embedded in any of our views.
  for (const auto* tree_root : tree->roots_) {
    const bool owns_tree_root = tree_root->id().connection_id == id_;
    if (owns_tree_root) {
      client()->OnEmbeddedAppDisconnected(
          ClientWindowIdForWindow(tree_root).id);
    }
  }
}

void WindowTree::NotifyChangeCompleted(
    uint32_t change_id,
    mojom::WindowManagerErrorCode error_code) {
  client()->OnChangeCompleted(
      change_id, error_code == mojom::WindowManagerErrorCode::SUCCESS);
}

bool WindowTree::SetCapture(const ClientWindowId& client_window_id) {
  ServerWindow* window = GetWindowByClientId(client_window_id);
  WindowManagerState* wms = GetWindowManagerState(window);
  ServerWindow* current_capture_window = wms ? wms->capture_window() : nullptr;
  if (window && window->IsDrawn() && wms && wms->IsActive() &&
      access_policy_->CanSetCapture(window) &&
      (!current_capture_window ||
       access_policy_->CanSetCapture(current_capture_window)) &&
      event_ack_id_) {
    return wms->SetCapture(window, !HasRoot(window));
  }
  return false;
}

bool WindowTree::NewWindow(
    const ClientWindowId& client_window_id,
    const std::map<std::string, std::vector<uint8_t>>& properties) {
  if (!IsValidIdForNewWindow(client_window_id))
    return false;
  const WindowId window_id = GenerateNewWindowId();
  DCHECK(!GetWindow(window_id));
  ServerWindow* window =
      window_server_->CreateServerWindow(window_id, properties);
  created_window_map_[window_id] = window;
  client_id_to_window_id_map_[client_window_id] = window_id;
  window_id_to_client_id_map_[window_id] = client_window_id;
  return true;
}

bool WindowTree::AddWindow(const ClientWindowId& parent_id,
                           const ClientWindowId& child_id) {
  ServerWindow* parent = GetWindowByClientId(parent_id);
  ServerWindow* child = GetWindowByClientId(child_id);
  if (parent && child && child->parent() != parent &&
      !child->Contains(parent) && access_policy_->CanAddWindow(parent, child)) {
    Operation op(this, window_server_, OperationType::ADD_WINDOW);
    parent->Add(child);
    return true;
  }
  return false;
}

bool WindowTree::AddTransientWindow(const ClientWindowId& window_id,
                                    const ClientWindowId& transient_window_id) {
  ServerWindow* window = GetWindowByClientId(window_id);
  ServerWindow* transient_window = GetWindowByClientId(transient_window_id);
  if (window && transient_window && !transient_window->Contains(window) &&
      access_policy_->CanAddTransientWindow(window, transient_window)) {
    Operation op(this, window_server_, OperationType::ADD_TRANSIENT_WINDOW);
    window->AddTransientWindow(transient_window);
    return true;
  }
  return false;
}

bool WindowTree::SetModal(const ClientWindowId& window_id) {
  ServerWindow* window = GetWindowByClientId(window_id);
  if (window && access_policy_->CanSetModal(window)) {
    window->SetModal();
    WindowManagerState* wms = GetWindowManagerState(window);
    if (wms)
      wms->ReleaseCaptureBlockedByModalWindow(window);
    return true;
  }
  return false;
}

std::vector<const ServerWindow*> WindowTree::GetWindowTree(
    const ClientWindowId& window_id) const {
  const ServerWindow* window = GetWindowByClientId(window_id);
  std::vector<const ServerWindow*> windows;
  if (window)
    GetWindowTreeImpl(window, &windows);
  return windows;
}

bool WindowTree::SetWindowVisibility(const ClientWindowId& window_id,
                                     bool visible) {
  ServerWindow* window = GetWindowByClientId(window_id);
  if (!window || window->visible() == visible ||
      !access_policy_->CanChangeWindowVisibility(window)) {
    return false;
  }
  Operation op(this, window_server_, OperationType::SET_WINDOW_VISIBILITY);
  window->SetVisible(visible);
  return true;
}

bool WindowTree::SetFocus(const ClientWindowId& window_id) {
  ServerWindow* window = GetWindowByClientId(window_id);
  // TODO(beng): consider shifting non-policy drawn check logic to VTH's
  //             FocusController.
  // TODO(sky): this doesn't work to clear focus. That is because if window is
  // null, then |host| is null and we fail.
  Display* display = GetDisplay(window);
  if (!window || !display || !window->IsDrawn() || !window->can_focus() ||
      !access_policy_->CanSetFocus(window)) {
    return false;
  }

  Operation op(this, window_server_, OperationType::SET_FOCUS);
  window_server_->SetFocusedWindow(window);
  return true;
}

bool WindowTree::Embed(const ClientWindowId& window_id,
                       mojom::WindowTreeClientPtr client) {
  if (!client || !CanEmbed(window_id))
    return false;
  ServerWindow* window = GetWindowByClientId(window_id);
  PrepareForEmbed(window);
  // When embedding we don't know the user id of where the TreeClient came
  // from. Use an invalid id, which limits what the client is able to do.
  window_server_->EmbedAtWindow(window, InvalidUserId(), std::move(client),
                                make_scoped_ptr(new DefaultAccessPolicy));
  return true;
}

void WindowTree::DispatchInputEvent(ServerWindow* target,
                                    const ui::Event& event) {
  if (event_ack_id_) {
    // This is currently waiting for an event ack. Add it to the queue.
    event_queue_.push(make_scoped_ptr(new TargetedEvent(target, event)));
    // TODO(sad): If the |event_queue_| grows too large, then this should notify
    // Display, so that it can stop sending events.
    return;
  }

  // If there are events in the queue, then store this new event in the queue,
  // and dispatch the latest event from the queue instead that still has a live
  // target.
  if (!event_queue_.empty()) {
    event_queue_.push(make_scoped_ptr(new TargetedEvent(target, event)));
    return;
  }

  DispatchInputEventImpl(target, event);
}

bool WindowTree::IsWaitingForNewTopLevelWindow(uint32_t wm_change_id) {
  return waiting_for_top_level_window_info_ &&
         waiting_for_top_level_window_info_->wm_change_id == wm_change_id;
}

void WindowTree::OnWindowManagerCreatedTopLevelWindow(
    uint32_t wm_change_id,
    uint32_t client_change_id,
    const ServerWindow* window) {
  DCHECK(IsWaitingForNewTopLevelWindow(wm_change_id));
  scoped_ptr<WaitingForTopLevelWindowInfo> waiting_for_top_level_window_info(
      std::move(waiting_for_top_level_window_info_));
  binding_->SetIncomingMethodCallProcessingPaused(false);
  // We were paused, so the id should still be valid.
  DCHECK(IsValidIdForNewWindow(
      waiting_for_top_level_window_info->client_window_id));
  client_id_to_window_id_map_[waiting_for_top_level_window_info
                                  ->client_window_id] = window->id();
  window_id_to_client_id_map_[window->id()] =
      waiting_for_top_level_window_info->client_window_id;
  roots_.insert(window);
  client()->OnTopLevelCreated(client_change_id, WindowToWindowData(window));
}

void WindowTree::OnChangeCompleted(uint32_t change_id, bool success) {
  client()->OnChangeCompleted(change_id, success);
}

void WindowTree::OnAccelerator(uint32_t accelerator_id,
                               const ui::Event& event) {
  DCHECK(window_manager_internal_);
  window_manager_internal_->OnAccelerator(accelerator_id,
                                          mojom::Event::From(event));
}

void WindowTree::ProcessWindowBoundsChanged(const ServerWindow* window,
                                            const gfx::Rect& old_bounds,
                                            const gfx::Rect& new_bounds,
                                            bool originated_change) {
  ClientWindowId client_window_id;
  if (originated_change || !IsWindowKnown(window, &client_window_id))
    return;
  client()->OnWindowBoundsChanged(client_window_id.id, Rect::From(old_bounds),
                                  Rect::From(new_bounds));
}

void WindowTree::ProcessClientAreaChanged(
    const ServerWindow* window,
    const gfx::Insets& new_client_area,
    const std::vector<gfx::Rect>& new_additional_client_areas,
    bool originated_change) {
  ClientWindowId client_window_id;
  if (originated_change || !IsWindowKnown(window, &client_window_id))
    return;
  client()->OnClientAreaChanged(
      client_window_id.id, mojo::Insets::From(new_client_area),
      mojo::Array<mojo::RectPtr>::From(new_additional_client_areas));
}

void WindowTree::ProcessViewportMetricsChanged(
    Display* display,
    const mojom::ViewportMetrics& old_metrics,
    const mojom::ViewportMetrics& new_metrics,
    bool originated_change) {
  mojo::Array<Id> window_ids;
  for (const ServerWindow* root : roots_) {
    if (GetDisplay(root) == display) {
      ClientWindowId client_window_id;
      const bool known = IsWindowKnown(root, &client_window_id);
      DCHECK(known);
      window_ids.push_back(client_window_id.id);
    }
  }
  if (window_ids.size() == 0u)
    return;

  client()->OnWindowViewportMetricsChanged(
      std::move(window_ids), old_metrics.Clone(), new_metrics.Clone());
}

void WindowTree::ProcessWillChangeWindowHierarchy(
    const ServerWindow* window,
    const ServerWindow* new_parent,
    const ServerWindow* old_parent,
    bool originated_change) {
  if (originated_change)
    return;

  const bool old_drawn = window->IsDrawn();
  const bool new_drawn =
      window->visible() && new_parent && new_parent->IsDrawn();
  if (old_drawn == new_drawn)
    return;

  NotifyDrawnStateChanged(window, new_drawn);
}

void WindowTree::ProcessWindowPropertyChanged(
    const ServerWindow* window,
    const std::string& name,
    const std::vector<uint8_t>* new_data,
    bool originated_change) {
  if (originated_change)
    return;

  ClientWindowId client_window_id;
  if (!IsWindowKnown(window, &client_window_id))
    return;

  Array<uint8_t> data(nullptr);
  if (new_data)
    data = Array<uint8_t>::From(*new_data);

  client()->OnWindowSharedPropertyChanged(client_window_id.id, String(name),
                                          std::move(data));
}

void WindowTree::ProcessWindowHierarchyChanged(const ServerWindow* window,
                                               const ServerWindow* new_parent,
                                               const ServerWindow* old_parent,
                                               bool originated_change) {
  const bool knows_new = new_parent && IsWindowKnown(new_parent);
  if (originated_change && !IsWindowKnown(window) && knows_new) {
    std::vector<const ServerWindow*> unused;
    GetUnknownWindowsFrom(window, &unused);
  }
  if (originated_change || (window_server_->current_operation_type() ==
                            OperationType::DELETE_WINDOW) ||
      (window_server_->current_operation_type() == OperationType::EMBED) ||
      window_server_->DidTreeMessageClient(id_)) {
    return;
  }

  if (!access_policy_->ShouldNotifyOnHierarchyChange(window, &new_parent,
                                                     &old_parent)) {
    return;
  }
  // Inform the client of any new windows and update the set of windows we know
  // about.
  std::vector<const ServerWindow*> to_send;
  if (!IsWindowKnown(window))
    GetUnknownWindowsFrom(window, &to_send);
  const bool knows_old = old_parent && IsWindowKnown(old_parent);
  if (!knows_old && !knows_new)
    return;

  const ClientWindowId new_parent_client_window_id =
      knows_new ? ClientWindowIdForWindow(new_parent) : ClientWindowId();
  const ClientWindowId old_parent_client_window_id =
      knows_old ? ClientWindowIdForWindow(old_parent) : ClientWindowId();
  const ClientWindowId client_window_id =
      window ? ClientWindowIdForWindow(window) : ClientWindowId();
  client()->OnWindowHierarchyChanged(
      client_window_id.id, new_parent_client_window_id.id,
      old_parent_client_window_id.id, WindowsToWindowDatas(to_send));
  window_server_->OnTreeMessagedClient(id_);
}

void WindowTree::ProcessWindowReorder(const ServerWindow* window,
                                      const ServerWindow* relative_window,
                                      mojom::OrderDirection direction,
                                      bool originated_change) {
  DCHECK_EQ(window->parent(), relative_window->parent());
  ClientWindowId client_window_id, relative_client_window_id;
  if (originated_change || !IsWindowKnown(window, &client_window_id) ||
      !IsWindowKnown(relative_window, &relative_client_window_id) ||
      window_server_->DidTreeMessageClient(id_))
    return;

  // Do not notify ordering changes of the root windows, since the client
  // doesn't know about the ancestors of the roots, and so can't do anything
  // about this ordering change of the root.
  if (HasRoot(window) || HasRoot(relative_window))
    return;

  client()->OnWindowReordered(client_window_id.id, relative_client_window_id.id,
                              direction);
  window_server_->OnTreeMessagedClient(id_);
}

void WindowTree::ProcessWindowDeleted(const ServerWindow* window,
                                      bool originated_change) {
  if (window->id().connection_id == id_)
    created_window_map_.erase(window->id());

  ClientWindowId client_window_id;
  if (!IsWindowKnown(window, &client_window_id))
    return;

  if (HasRoot(window))
    RemoveRoot(window, RemoveRootReason::DELETED);
  else
    RemoveFromMaps(window);

  if (originated_change)
    return;

  client()->OnWindowDeleted(client_window_id.id);
  window_server_->OnTreeMessagedClient(id_);
}

void WindowTree::ProcessWillChangeWindowVisibility(const ServerWindow* window,
                                                   bool originated_change) {
  if (originated_change)
    return;

  ClientWindowId client_window_id;
  if (IsWindowKnown(window, &client_window_id)) {
    client()->OnWindowVisibilityChanged(client_window_id.id,
                                        !window->visible());
    return;
  }

  bool window_target_drawn_state;
  if (window->visible()) {
    // Window is being hidden, won't be drawn.
    window_target_drawn_state = false;
  } else {
    // Window is being shown. Window will be drawn if its parent is drawn.
    window_target_drawn_state = window->parent() && window->parent()->IsDrawn();
  }

  NotifyDrawnStateChanged(window, window_target_drawn_state);
}

void WindowTree::ProcessCursorChanged(const ServerWindow* window,
                                      int32_t cursor_id,
                                      bool originated_change) {
  if (originated_change)
    return;
  ClientWindowId client_window_id;
  if (!IsWindowKnown(window, &client_window_id))
    return;

  client()->OnWindowPredefinedCursorChanged(client_window_id.id,
                                            mojom::Cursor(cursor_id));
}

void WindowTree::ProcessFocusChanged(const ServerWindow* old_focused_window,
                                     const ServerWindow* new_focused_window) {
  if (window_server_->current_operation_type() == OperationType::SET_FOCUS &&
      window_server_->IsOperationSource(id_)) {
    return;
  }
  const ServerWindow* window =
      new_focused_window
          ? access_policy_->GetWindowForFocusChange(new_focused_window)
          : nullptr;
  ClientWindowId client_window_id;
  // If the window isn't known we'll supply null, which is ok.
  IsWindowKnown(window, &client_window_id);
  client()->OnWindowFocused(client_window_id.id);
}

void WindowTree::ProcessTransientWindowAdded(
    const ServerWindow* window,
    const ServerWindow* transient_window,
    bool originated_change) {
  if (originated_change)
    return;

  ClientWindowId client_window_id, transient_client_window_id;
  if (!IsWindowKnown(window, &client_window_id) ||
      !IsWindowKnown(transient_window, &transient_client_window_id)) {
    return;
  }
  client()->OnTransientWindowAdded(client_window_id.id,
                                   transient_client_window_id.id);
}

void WindowTree::ProcessTransientWindowRemoved(
    const ServerWindow* window,
    const ServerWindow* transient_window,
    bool originated_change) {
  if (originated_change)
    return;
  ClientWindowId client_window_id, transient_client_window_id;
  if (!IsWindowKnown(window, &client_window_id) ||
      !IsWindowKnown(transient_window, &transient_client_window_id)) {
    return;
  }
  client()->OnTransientWindowRemoved(client_window_id.id,
                                     transient_client_window_id.id);
}

DisplayManager* WindowTree::display_manager() {
  return window_server_->display_manager();
}

const DisplayManager* WindowTree::display_manager() const {
  return window_server_->display_manager();
}

Display* WindowTree::GetDisplayForWindowManager() {
  return GetWindowManagerStateForWindowManager()->display();
}

WindowManagerState* WindowTree::GetWindowManagerStateForWindowManager() {
  // The WindowTree for the wm has one and only one root.
  CHECK_EQ(1u, roots_.size());

  // Indicates this connection is for the wm.
  DCHECK(window_manager_internal_);

  WindowManagerState* wms = display_manager()
                                ->GetWindowManagerAndDisplay(*roots_.begin())
                                .window_manager_state;
  CHECK(wms);
  DCHECK_EQ(this, wms->tree());
  return wms;
}

bool WindowTree::ShouldRouteToWindowManager(const ServerWindow* window) const {
  // If the client created this window, then do not route it through the WM.
  if (window->id().connection_id == id_)
    return false;

  // If the client did not create the window, then it must be the root of the
  // client. If not, that means the client should not know about this window,
  // and so do not route the request to the WM.
  if (roots_.count(window) == 0)
    return false;

  // The WindowManager is attached to the root of the Display, if there isn't a
  // WindowManager attached no need to route to it.
  const WindowManagerState* wms = display_manager()
                                      ->GetWindowManagerAndDisplay(window)
                                      .window_manager_state;
  if (!wms || !wms->tree()->window_manager_internal_)
    return false;

  // Requests coming from the WM should not be routed through the WM again.
  const bool is_wm = wms->tree() == this;
  return is_wm ? false : true;
}

void WindowTree::ProcessLostCapture(const ServerWindow* old_capture_window,
                                    bool originated_change) {
  if ((originated_change &&
       window_server_->current_operation_type() ==
           OperationType::RELEASE_CAPTURE) ||
      !IsWindowKnown(old_capture_window)) {
    return;
  }
  client()->OnLostCapture(WindowIdToTransportId(old_capture_window->id()));
}

ClientWindowId WindowTree::ClientWindowIdForWindow(
    const ServerWindow* window) const {
  auto iter = window_id_to_client_id_map_.find(window->id());
  DCHECK(iter != window_id_to_client_id_map_.end());
  return iter->second;
}

bool WindowTree::IsValidIdForNewWindow(const ClientWindowId& id) const {
  return client_id_to_window_id_map_.count(id) == 0u &&
         access_policy_->IsValidIdForNewWindow(id);
}

WindowId WindowTree::GenerateNewWindowId() {
  // TODO(sky): deal with wrapping and uniqueness.
  return WindowId(id_, next_window_id_++);
}

bool WindowTree::CanReorderWindow(const ServerWindow* window,
                                  const ServerWindow* relative_window,
                                  mojom::OrderDirection direction) const {
  if (!window || !relative_window)
    return false;

  if (!window->parent() || window->parent() != relative_window->parent())
    return false;

  if (!access_policy_->CanReorderWindow(window, relative_window, direction))
    return false;

  std::vector<const ServerWindow*> children = window->parent()->GetChildren();
  const size_t child_i =
      std::find(children.begin(), children.end(), window) - children.begin();
  const size_t target_i =
      std::find(children.begin(), children.end(), relative_window) -
      children.begin();
  if ((direction == mojom::OrderDirection::ABOVE && child_i == target_i + 1) ||
      (direction == mojom::OrderDirection::BELOW && child_i + 1 == target_i)) {
    return false;
  }

  return true;
}

bool WindowTree::DeleteWindowImpl(WindowTree* source, ServerWindow* window) {
  DCHECK(window);
  DCHECK_EQ(window->id().connection_id, id_);
  Operation op(source, window_server_, OperationType::DELETE_WINDOW);
  delete window;
  return true;
}

void WindowTree::GetUnknownWindowsFrom(
    const ServerWindow* window,
    std::vector<const ServerWindow*>* windows) {
  if (IsWindowKnown(window) || !access_policy_->CanGetWindowTree(window))
    return;
  windows->push_back(window);
  // There are two cases where this gets hit:
  // . During init, in which case using the window id as the client id is
  //   fine.
  // . When a window is moved to a parent of a window we know about. This is
  //   only encountered for the WM or embed roots. We assume such clients want
  //   to see the real id of the window and are only created ClientWindowIds
  //   with the connection_id.
  const ClientWindowId client_window_id(WindowIdToTransportId(window->id()));
  DCHECK_EQ(0u, client_id_to_window_id_map_.count(client_window_id));
  client_id_to_window_id_map_[client_window_id] = window->id();
  window_id_to_client_id_map_[window->id()] = client_window_id;
  if (!access_policy_->CanDescendIntoWindowForWindowTree(window))
    return;
  std::vector<const ServerWindow*> children(window->GetChildren());
  for (size_t i = 0; i < children.size(); ++i)
    GetUnknownWindowsFrom(children[i], windows);
}

bool WindowTree::RemoveFromMaps(const ServerWindow* window) {
  auto iter = window_id_to_client_id_map_.find(window->id());
  if (iter == window_id_to_client_id_map_.end())
    return false;

  client_id_to_window_id_map_.erase(iter->second);
  window_id_to_client_id_map_.erase(iter);
  return true;
}

void WindowTree::RemoveFromKnown(const ServerWindow* window,
                                 std::vector<ServerWindow*>* local_windows) {
  if (window->id().connection_id == id_) {
    if (local_windows)
      local_windows->push_back(GetWindow(window->id()));
    return;
  }

  RemoveFromMaps(window);

  std::vector<const ServerWindow*> children = window->GetChildren();
  for (size_t i = 0; i < children.size(); ++i)
    RemoveFromKnown(children[i], local_windows);
}

void WindowTree::RemoveRoot(const ServerWindow* window,
                            RemoveRootReason reason) {
  DCHECK(roots_.count(window) > 0);
  roots_.erase(window);

  const ClientWindowId client_window_id(ClientWindowIdForWindow(window));

  // No need to do anything if we created the window.
  if (window->id().connection_id == id_)
    return;

  if (reason == RemoveRootReason::EMBED) {
    client()->OnUnembed(client_window_id.id);
    client()->OnWindowDeleted(client_window_id.id);
    window_server_->OnTreeMessagedClient(id_);
  }

  // This connection no longer knows about the window. Unparent any windows that
  // were parented to windows in the root.
  std::vector<ServerWindow*> local_windows;
  RemoveFromKnown(window, &local_windows);
  for (size_t i = 0; i < local_windows.size(); ++i)
    local_windows[i]->parent()->Remove(local_windows[i]);
}

Array<mojom::WindowDataPtr> WindowTree::WindowsToWindowDatas(
    const std::vector<const ServerWindow*>& windows) {
  Array<mojom::WindowDataPtr> array(windows.size());
  for (size_t i = 0; i < windows.size(); ++i)
    array[i] = WindowToWindowData(windows[i]);
  return array;
}

mojom::WindowDataPtr WindowTree::WindowToWindowData(
    const ServerWindow* window) {
  DCHECK(IsWindowKnown(window));
  const ServerWindow* parent = window->parent();
  // If the parent isn't known, it means the parent is not visible to us (not
  // in roots), and should not be sent over.
  if (parent && !IsWindowKnown(parent))
    parent = nullptr;
  mojom::WindowDataPtr window_data(mojom::WindowData::New());
  window_data->parent_id =
      parent ? ClientWindowIdForWindow(parent).id : ClientWindowId().id;
  window_data->window_id =
      window ? ClientWindowIdForWindow(window).id : ClientWindowId().id;
  window_data->bounds = Rect::From(window->bounds());
  window_data->properties =
      mojo::Map<String, Array<uint8_t>>::From(window->properties());
  window_data->visible = window->visible();
  window_data->drawn = window->IsDrawn();
  window_data->viewport_metrics =
      window_server_->GetViewportMetricsForWindow(window);
  return window_data;
}

void WindowTree::GetWindowTreeImpl(
    const ServerWindow* window,
    std::vector<const ServerWindow*>* windows) const {
  DCHECK(window);

  if (!access_policy_->CanGetWindowTree(window))
    return;

  windows->push_back(window);

  if (!access_policy_->CanDescendIntoWindowForWindowTree(window))
    return;

  std::vector<const ServerWindow*> children(window->GetChildren());
  for (size_t i = 0; i < children.size(); ++i)
    GetWindowTreeImpl(children[i], windows);
}

void WindowTree::NotifyDrawnStateChanged(const ServerWindow* window,
                                         bool new_drawn_value) {
  // Even though we don't know about window, it may be an ancestor of our root,
  // in which case the change may effect our roots drawn state.
  if (roots_.empty())
    return;

  for (auto* root : roots_) {
    if (window->Contains(root) && (new_drawn_value != root->IsDrawn())) {
      client()->OnWindowDrawnStateChanged(ClientWindowIdForWindow(root).id,
                                          new_drawn_value);
    }
  }
}

void WindowTree::DestroyWindows() {
  if (created_window_map_.empty())
    return;

  Operation op(this, window_server_, OperationType::DELETE_WINDOW);
  // If we get here from the destructor we're not going to get
  // ProcessWindowDeleted(). Copy the map and delete from the copy so that we
  // don't have to worry about whether |created_window_map_| changes or not.
  base::hash_map<WindowId, ServerWindow*> created_window_map_copy;
  created_window_map_.swap(created_window_map_copy);
  // A sibling can be a transient parent of another window so we detach windows
  // from their transient parents to avoid double deletes.
  for (auto& pair : created_window_map_copy) {
    ServerWindow* transient_parent = pair.second->transient_parent();
    if (transient_parent)
      transient_parent->RemoveTransientWindow(pair.second);
  }
  STLDeleteValues(&created_window_map_copy);
}

bool WindowTree::CanEmbed(const ClientWindowId& window_id) const {
  const ServerWindow* window = GetWindowByClientId(window_id);
  return window && access_policy_->CanEmbed(window);
}

void WindowTree::PrepareForEmbed(ServerWindow* window) {
  DCHECK(window);

  // Only allow a node to be the root for one connection.
  WindowTree* existing_owner = window_server_->GetTreeWithRoot(window);

  Operation op(this, window_server_, OperationType::EMBED);
  RemoveChildrenAsPartOfEmbed(window);
  if (existing_owner) {
    // Never message the originating connection.
    window_server_->OnTreeMessagedClient(id_);
    existing_owner->RemoveRoot(window, RemoveRootReason::EMBED);
  }
}

void WindowTree::RemoveChildrenAsPartOfEmbed(ServerWindow* window) {
  CHECK(window);
  std::vector<ServerWindow*> children = window->GetChildren();
  for (size_t i = 0; i < children.size(); ++i)
    window->Remove(children[i]);
}

void WindowTree::DispatchInputEventImpl(ServerWindow* target,
                                        const ui::Event& event) {
  DCHECK(!event_ack_id_);
  // We do not want to create a sequential id for each event, because that can
  // leak some information to the client. So instead, manufacture the id
  // randomly.
  // TODO(moshayedi): Find a faster way to generate ids.
  event_ack_id_ = 0x1000000 | (rand() & 0xffffff);
  event_source_wms_ = GetWindowManagerState(target);
  // Should only get events from windows attached to a host.
  DCHECK(event_source_wms_);
  client()->OnWindowInputEvent(event_ack_id_,
                               ClientWindowIdForWindow(target).id,
                               mojom::Event::From(event));
}

void WindowTree::NewWindow(
    uint32_t change_id,
    Id transport_window_id,
    mojo::Map<mojo::String, mojo::Array<uint8_t>> transport_properties) {
  std::map<std::string, std::vector<uint8_t>> properties;
  if (!transport_properties.is_null()) {
    properties =
        transport_properties.To<std::map<std::string, std::vector<uint8_t>>>();
  }
  client()->OnChangeCompleted(
      change_id, NewWindow(ClientWindowId(transport_window_id), properties));
}

void WindowTree::NewTopLevelWindow(
    uint32_t change_id,
    Id transport_window_id,
    mojo::Map<mojo::String, mojo::Array<uint8_t>> transport_properties) {
  DCHECK(!waiting_for_top_level_window_info_);
  const ClientWindowId client_window_id(transport_window_id);
  // TODO(sky): need a way for client to provide context to figure out display.
  Display* display = display_manager()->displays().empty()
                         ? nullptr
                         : *(display_manager()->displays().begin());
  // TODO(sky): move checks to accesspolicy.
  WindowManagerState* wms =
      display && user_id_ != InvalidUserId()
          ? display->GetWindowManagerStateForUser(user_id_)
          : nullptr;
  if (!wms || wms->tree() == this || !IsValidIdForNewWindow(client_window_id)) {
    client()->OnChangeCompleted(change_id, false);
    return;
  }

  // The server creates the real window. Any further messages from the client
  // may try to alter the window. Pause incoming messages so that we know we
  // can't get a message for a window before the window is created. Once the
  // window is created we'll resume processing.
  binding_->SetIncomingMethodCallProcessingPaused(true);

  const uint32_t wm_change_id =
      window_server_->GenerateWindowManagerChangeId(this, change_id);

  waiting_for_top_level_window_info_.reset(
      new WaitingForTopLevelWindowInfo(client_window_id, wm_change_id));

  wms->tree()->window_manager_internal_->WmCreateTopLevelWindow(
      wm_change_id, std::move(transport_properties));
}

void WindowTree::DeleteWindow(uint32_t change_id, Id transport_window_id) {
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  bool success = false;
  bool should_close = window && (access_policy_->CanDeleteWindow(window) ||
                                 ShouldRouteToWindowManager(window));
  if (should_close) {
    WindowTree* tree =
        window_server_->GetTreeWithId(window->id().connection_id);
    success = tree && tree->DeleteWindowImpl(this, window);
  }
  client()->OnChangeCompleted(change_id, success);
}

void WindowTree::AddWindow(uint32_t change_id, Id parent_id, Id child_id) {
  client()->OnChangeCompleted(change_id, AddWindow(ClientWindowId(parent_id),
                                                   ClientWindowId(child_id)));
}

void WindowTree::RemoveWindowFromParent(uint32_t change_id, Id window_id) {
  bool success = false;
  ServerWindow* window = GetWindowByClientId(ClientWindowId(window_id));
  if (window && window->parent() &&
      access_policy_->CanRemoveWindowFromParent(window)) {
    success = true;
    Operation op(this, window_server_,
                 OperationType::REMOVE_WINDOW_FROM_PARENT);
    window->parent()->Remove(window);
  }
  client()->OnChangeCompleted(change_id, success);
}

void WindowTree::AddTransientWindow(uint32_t change_id,
                                    Id window,
                                    Id transient_window) {
  client()->OnChangeCompleted(
      change_id, AddTransientWindow(ClientWindowId(window),
                                    ClientWindowId(transient_window)));
}

void WindowTree::RemoveTransientWindowFromParent(uint32_t change_id,
                                                 Id transient_window_id) {
  bool success = false;
  ServerWindow* transient_window =
      GetWindowByClientId(ClientWindowId(transient_window_id));
  if (transient_window && transient_window->transient_parent() &&
      access_policy_->CanRemoveTransientWindowFromParent(transient_window)) {
    success = true;
    Operation op(this, window_server_,
                 OperationType::REMOVE_TRANSIENT_WINDOW_FROM_PARENT);
    transient_window->transient_parent()->RemoveTransientWindow(
        transient_window);
  }
  client()->OnChangeCompleted(change_id, success);
}

void WindowTree::SetModal(uint32_t change_id, Id window_id) {
  client()->OnChangeCompleted(change_id, SetModal(ClientWindowId(window_id)));
}

void WindowTree::ReorderWindow(uint32_t change_id,
                               Id window_id,
                               Id relative_window_id,
                               mojom::OrderDirection direction) {
  bool success = false;
  ServerWindow* window = GetWindowByClientId(ClientWindowId(window_id));
  ServerWindow* relative_window =
      GetWindowByClientId(ClientWindowId(relative_window_id));
  if (CanReorderWindow(window, relative_window, direction)) {
    success = true;
    Operation op(this, window_server_, OperationType::REORDER_WINDOW);
    window->Reorder(relative_window, direction);
    window_server_->ProcessWindowReorder(window, relative_window, direction);
  }
  client()->OnChangeCompleted(change_id, success);
}

void WindowTree::GetWindowTree(
    Id window_id,
    const Callback<void(Array<mojom::WindowDataPtr>)>& callback) {
  std::vector<const ServerWindow*> windows(
      GetWindowTree(ClientWindowId(window_id)));
  callback.Run(WindowsToWindowDatas(windows));
}

void WindowTree::SetCapture(uint32_t change_id, Id window_id) {
  client()->OnChangeCompleted(change_id, SetCapture(ClientWindowId(window_id)));
}

void WindowTree::ReleaseCapture(uint32_t change_id, Id window_id) {
  ServerWindow* window = GetWindowByClientId(ClientWindowId(window_id));
  WindowManagerState* wms = GetWindowManagerState(window);
  ServerWindow* current_capture_window = wms ? wms->capture_window() : nullptr;
  bool success = window && wms && wms->IsActive() &&
                 (!current_capture_window ||
                  access_policy_->CanSetCapture(current_capture_window)) &&
                 window == current_capture_window;
  if (success) {
    Operation op(this, window_server_, OperationType::RELEASE_CAPTURE);
    success = wms->SetCapture(nullptr, false);
  }
  client()->OnChangeCompleted(change_id, success);
}

void WindowTree::SetWindowBounds(uint32_t change_id,
                                 Id window_id,
                                 mojo::RectPtr bounds) {
  ServerWindow* window = GetWindowByClientId(ClientWindowId(window_id));
  if (window && ShouldRouteToWindowManager(window)) {
    const uint32_t wm_change_id =
        window_server_->GenerateWindowManagerChangeId(this, change_id);
    // |window_id| may be a client id, use the id from the window to ensure
    // the windowmanager doesn't get an id it doesn't know about.
    WindowManagerState* wms = display_manager()
                                  ->GetWindowManagerAndDisplay(window)
                                  .window_manager_state;
    wms->tree()->window_manager_internal_->WmSetBounds(
        wm_change_id, wms->tree()->ClientWindowIdForWindow(window).id,
        std::move(bounds));
    return;
  }

  // Only the owner of the window can change the bounds.
  bool success = window && access_policy_->CanSetWindowBounds(window);
  if (success) {
    Operation op(this, window_server_, OperationType::SET_WINDOW_BOUNDS);
    window->SetBounds(bounds.To<gfx::Rect>());
  }
  client()->OnChangeCompleted(change_id, success);
}

void WindowTree::SetWindowVisibility(uint32_t change_id,
                                     Id transport_window_id,
                                     bool visible) {
  client()->OnChangeCompleted(
      change_id,
      SetWindowVisibility(ClientWindowId(transport_window_id), visible));
}

void WindowTree::SetWindowProperty(uint32_t change_id,
                                   Id transport_window_id,
                                   const mojo::String& name,
                                   mojo::Array<uint8_t> value) {
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  if (window && ShouldRouteToWindowManager(window)) {
    const uint32_t wm_change_id =
        window_server_->GenerateWindowManagerChangeId(this, change_id);
    WindowManagerState* wms = display_manager()
                                  ->GetWindowManagerAndDisplay(window)
                                  .window_manager_state;
    wms->tree()->window_manager_internal_->WmSetProperty(
        wm_change_id, wms->tree()->ClientWindowIdForWindow(window).id, name,
        std::move(value));
    return;
  }
  const bool success = window && access_policy_->CanSetWindowProperties(window);
  if (success) {
    Operation op(this, window_server_, OperationType::SET_WINDOW_PROPERTY);
    if (value.is_null()) {
      window->SetProperty(name, nullptr);
    } else {
      std::vector<uint8_t> data = value.To<std::vector<uint8_t>>();
      window->SetProperty(name, &data);
    }
  }
  client()->OnChangeCompleted(change_id, success);
}

void WindowTree::AttachSurface(Id transport_window_id,
                               mojom::SurfaceType type,
                               mojo::InterfaceRequest<mojom::Surface> surface,
                               mojom::SurfaceClientPtr client) {
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  const bool success =
      window && access_policy_->CanSetWindowSurface(window, type);
  if (!success)
    return;
  window->CreateSurface(type, std::move(surface), std::move(client));
}

void WindowTree::SetWindowTextInputState(Id transport_window_id,
                                         mojo::TextInputStatePtr state) {
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  bool success = window && access_policy_->CanSetWindowTextInputState(window);
  if (success)
    window->SetTextInputState(state.To<ui::TextInputState>());
}

void WindowTree::SetImeVisibility(Id transport_window_id,
                                  bool visible,
                                  mojo::TextInputStatePtr state) {
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  bool success = window && access_policy_->CanSetWindowTextInputState(window);
  if (success) {
    if (!state.is_null())
      window->SetTextInputState(state.To<ui::TextInputState>());

    Display* display = GetDisplay(window);
    if (display)
      display->SetImeVisibility(window, visible);
  }
}

void WindowTree::OnWindowInputEventAck(uint32_t event_id, bool handled) {
  if (event_ack_id_ == 0 || event_id != event_ack_id_) {
    // TODO(sad): Something bad happened. Kill the client?
    NOTIMPLEMENTED() << "Wrong event acked.";
  }
  event_ack_id_ = 0;

  WindowManagerState* event_source_wms = event_source_wms_;
  event_source_wms_ = nullptr;
  if (event_source_wms)
    event_source_wms->OnEventAck(this, handled);

  if (!event_queue_.empty()) {
    DCHECK(!event_ack_id_);
    ServerWindow* target = nullptr;
    ui::Event* event = nullptr;
    do {
      scoped_ptr<TargetedEvent> targeted_event =
          std::move(event_queue_.front());
      event_queue_.pop();
      target = targeted_event->target();
      event = targeted_event->event();
    } while (!event_queue_.empty() && !GetDisplay(target));
    if (target)
      DispatchInputEventImpl(target, *event);
  }
}

void WindowTree::SetClientArea(
    Id transport_window_id,
    mojo::InsetsPtr insets,
    mojo::Array<mojo::RectPtr> transport_additional_client_areas) {
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  if (!window || !access_policy_->CanSetClientArea(window))
    return;

  std::vector<gfx::Rect> additional_client_areas =
      transport_additional_client_areas.To<std::vector<gfx::Rect>>();
  window->SetClientArea(insets.To<gfx::Insets>(), additional_client_areas);
}

void WindowTree::Embed(Id transport_window_id,
                       mojom::WindowTreeClientPtr client,
                       const EmbedCallback& callback) {
  callback.Run(Embed(ClientWindowId(transport_window_id), std::move(client)));
}

void WindowTree::SetFocus(uint32_t change_id, Id transport_window_id) {
  client()->OnChangeCompleted(change_id,
                              SetFocus(ClientWindowId(transport_window_id)));
}

void WindowTree::SetCanFocus(Id transport_window_id, bool can_focus) {
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  // TODO(sky): there should be an else case (it shouldn't route to wm and
  // policy allows, then set_can_focus).
  if (window && ShouldRouteToWindowManager(window))
    window->set_can_focus(can_focus);
}

void WindowTree::SetPredefinedCursor(uint32_t change_id,
                                     Id transport_window_id,
                                     mus::mojom::Cursor cursor_id) {
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));

  // Only the owner of the window can change the bounds.
  bool success = window && access_policy_->CanSetCursorProperties(window);
  if (success) {
    Operation op(this, window_server_,
                 OperationType::SET_WINDOW_PREDEFINED_CURSOR);
    window->SetPredefinedCursor(cursor_id);
  }
  client()->OnChangeCompleted(change_id, success);
}

void WindowTree::GetWindowManagerClient(
    mojo::AssociatedInterfaceRequest<mojom::WindowManagerClient> internal) {
  if (!access_policy_->CanSetWindowManager() || !window_manager_internal_ ||
      window_manager_internal_client_binding_) {
    return;
  }
  window_manager_internal_client_binding_.reset(
      new mojo::AssociatedBinding<mojom::WindowManagerClient>(
          this, std::move(internal)));
}

void WindowTree::AddAccelerator(uint32_t id,
                                mojom::EventMatcherPtr event_matcher,
                                const AddAcceleratorCallback& callback) {
  WindowManagerState* wms = GetWindowManagerStateForWindowManager();
  const bool success =
      wms->event_dispatcher()->AddAccelerator(id, std::move(event_matcher));
  callback.Run(success);
}

void WindowTree::RemoveAccelerator(uint32_t id) {
  WindowManagerState* wms = GetWindowManagerStateForWindowManager();
  wms->event_dispatcher()->RemoveAccelerator(id);
}

void WindowTree::AddActivationParent(Id transport_window_id) {
  Display* host = GetDisplayForWindowManager();
  if (!host)
    return;
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  if (window)
    host->AddActivationParent(window);
}

void WindowTree::RemoveActivationParent(Id transport_window_id) {
  Display* host = GetDisplayForWindowManager();
  if (!host)
    return;
  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  if (window)
    host->RemoveActivationParent(window);
}

void WindowTree::ActivateNextWindow() {
  Display* display = GetDisplayForWindowManager();
  if (!display)
    return;
  display->ActivateNextWindow();
}

void WindowTree::SetUnderlaySurfaceOffsetAndExtendedHitArea(
    Id window_id,
    int32_t x_offset,
    int32_t y_offset,
    mojo::InsetsPtr hit_area) {
  ServerWindow* window = GetWindowByClientId(ClientWindowId(window_id));
  if (!window)
    return;

  window->SetUnderlayOffset(gfx::Vector2d(x_offset, y_offset));
  window->set_extended_hit_test_region(hit_area.To<gfx::Insets>());
}

void WindowTree::WmResponse(uint32_t change_id, bool response) {
  // TODO(sky): think about what else case means.
  if (GetDisplayForWindowManager())
    window_server_->WindowManagerChangeCompleted(change_id, response);
}

void WindowTree::WmRequestClose(Id transport_window_id) {
  // Only the WindowManager should be using this.
  Display* host = GetDisplayForWindowManager();
  if (!host)
    return;

  ServerWindow* window =
      GetWindowByClientId(ClientWindowId(transport_window_id));
  WindowTree* tree = window_server_->GetTreeWithRoot(window);
  if (tree && tree != this) {
    tree->client()->RequestClose(tree->ClientWindowIdForWindow(window).id);
  }
  // TODO(sky): think about what else case means.
}

void WindowTree::WmSetFrameDecorationValues(
    mojom::FrameDecorationValuesPtr values) {
  WindowManagerState* wm_state = GetWindowManagerStateForWindowManager();
  if (wm_state)
    wm_state->SetFrameDecorationValues(std::move(values));
}

void WindowTree::OnWmCreatedTopLevelWindow(uint32_t change_id,
                                           Id transport_window_id) {
  if (GetDisplayForWindowManager()) {
    ServerWindow* window =
        GetWindowByClientId(ClientWindowId(transport_window_id));
    if (window && window->id().connection_id != id_) {
      window_server_->WindowManagerSentBogusMessage();
      window = nullptr;
    }
    window_server_->WindowManagerCreatedTopLevelWindow(this, change_id, window);
  }
  // TODO(sky): think about what else case means.
}

bool WindowTree::HasRootForAccessPolicy(const ServerWindow* window) const {
  return HasRoot(window);
}

bool WindowTree::IsWindowKnownForAccessPolicy(
    const ServerWindow* window) const {
  return IsWindowKnown(window);
}

bool WindowTree::IsWindowRootOfAnotherTreeForAccessPolicy(
    const ServerWindow* window) const {
  WindowTree* tree = window_server_->GetTreeWithRoot(window);
  return tree && tree != this;
}

}  // namespace ws
}  // namespace mus