summaryrefslogtreecommitdiffstats
path: root/ash/display/display_controller.cc
blob: cba80e2ee88d969f6b44928f0ed1d192976ba628 (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
// 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 "ash/display/display_controller.h"

#include <algorithm>
#include <cmath>
#include <map>

#include "ash/ash_root_window_transformer.h"
#include "ash/ash_switches.h"
#include "ash/display/display_manager.h"
#include "ash/display/display_pref_util.h"
#include "ash/host/root_window_host_factory.h"
#include "ash/root_window_controller.h"
#include "ash/screen_ash.h"
#include "ash/shell.h"
#include "ash/wm/coordinate_conversion.h"
#include "ash/wm/property_util.h"
#include "ash/wm/window_util.h"
#include "base/command_line.h"
#include "base/json/json_value_converter.h"
#include "base/stringprintf.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/values.h"
#include "third_party/skia/include/utils/SkMatrix44.h"
#include "ui/aura/client/activation_client.h"
#include "ui/aura/client/capture_client.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/env.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#include "ui/aura/window_property.h"
#include "ui/aura/window_tracker.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/dip_util.h"
#include "ui/gfx/display.h"
#include "ui/gfx/screen.h"

#if defined(OS_CHROMEOS)
#include "ash/display/output_configurator_animation.h"
#include "base/chromeos/chromeos_version.h"
#include "base/time.h"
#include "chromeos/display/output_configurator.h"
#include "ui/base/x/x11_util.h"

// Including this at the bottom to avoid other
// potential conflict with chrome headers.
#include <X11/extensions/Xrandr.h>
#undef RootWindow
#endif  // defined(OS_CHROMEOS)

DECLARE_WINDOW_PROPERTY_TYPE(gfx::Display::Rotation);

namespace ash {
namespace {

DEFINE_WINDOW_PROPERTY_KEY(gfx::Display::Rotation, kRotationPropertyKey,
                           gfx::Display::ROTATE_0);

// Primary display stored in global object as it can be
// accessed after Shell is deleted. A separate display instance is created
// during the shutdown instead of always keeping two display instances
// (one here and another one in display_manager) in sync, which is error prone.
int64 primary_display_id = gfx::Display::kInvalidDisplayID;
gfx::Display* primary_display_for_shutdown = NULL;
// Keeps the number of displays during the shutdown after
// ash::Shell:: is deleted.
int num_displays_for_shutdown = -1;

// The maximum value for 'offset' in DisplayLayout in case of outliers.  Need
// to change this value in case to support even larger displays.
const int kMaxValidOffset = 10000;

// The number of pixels to overlap between the primary and secondary displays,
// in case that the offset value is too large.
const int kMinimumOverlapForInvalidOffset = 100;

// Specifies how long the display change should have been disabled
// after each display change operations.
// |kCycleDisplayThrottleTimeoutMs| is set to be longer to avoid
// changing the settings while the system is still configurating
// displays. It will be overriden by |kAfterDisplayChangeThrottleTimeoutMs|
// when the display change happens, so the actual timeout is much shorter.
const int64 kAfterDisplayChangeThrottleTimeoutMs = 500;
const int64 kCycleDisplayThrottleTimeoutMs = 4000;
const int64 kSwapDisplayThrottleTimeoutMs = 500;

// Persistent key names
const char kPositionKey[] = "position";
const char kOffsetKey[] = "offset";
const char kMirroredKey[] = "mirrored";
const char kPrimaryIdKey[] = "primary-id";

typedef std::map<DisplayLayout::Position, std::string> PositionToStringMap;

const PositionToStringMap* GetPositionToStringMap() {
  static const PositionToStringMap* map = CreateToStringMap(
      DisplayLayout::TOP, "top",
      DisplayLayout::BOTTOM, "bottom",
      DisplayLayout::RIGHT, "right",
      DisplayLayout::LEFT, "left");
  return map;
}

bool GetPositionFromString(const base::StringPiece& position,
                           DisplayLayout::Position* field) {
  if (ReverseFind(GetPositionToStringMap(), position, field))
    return true;
  LOG(ERROR) << "Invalid position value:" << position;
  return false;
}

std::string GetStringFromPosition(DisplayLayout::Position position) {
  const PositionToStringMap* map = GetPositionToStringMap();
  PositionToStringMap::const_iterator iter = map->find(position);
  return iter != map->end() ? iter->second : std::string("unknown");
}

bool GetDisplayIdFromString(const base::StringPiece& position, int64* field) {
  return base::StringToInt64(position, field);
}

internal::DisplayManager* GetDisplayManager() {
  return Shell::GetInstance()->display_manager();
}

// Round near zero value to zero.
void RoundNearZero(gfx::Transform* transform) {
  const float kEpsilon = 0.001f;
  SkMatrix44& matrix = transform->matrix();
  for (int x = 0; x < 4; ++x) {
    for (int y = 0; y < 4; ++y) {
      if (std::abs(SkMScalarToFloat(matrix.get(x, y))) < kEpsilon)
        matrix.set(x, y, SkFloatToMScalar(0.0f));
    }
  }
}

void RotateRootWindow(aura::RootWindow* root_window,
                      const gfx::Display& display,
                      const internal::DisplayInfo& info) {
  // TODO(oshima): Add animation. (crossfade+rotation, or just cross-fade)
#if defined(OS_WIN)
  // Windows 8 bots refused to resize the host window, and
  // updating the transform results in incorrectly resizing
  // the root window. Don't apply the transform unless
  // necessary so that unit tests pass on win8 bots.
  if (info.rotation() == root_window->GetProperty(kRotationPropertyKey))
    return;
  root_window->SetProperty(kRotationPropertyKey, info.rotation());
#endif
  gfx::Transform rotate;
  // The origin is (0, 0), so the translate width/height must be reduced by
  // 1 pixel.
  float one_pixel = 1.0f / display.device_scale_factor();
  switch (info.rotation()) {
    case gfx::Display::ROTATE_0:
      break;
    case gfx::Display::ROTATE_90:
      rotate.Translate(display.bounds().height() - one_pixel, 0);
      rotate.Rotate(90);
      break;
    case gfx::Display::ROTATE_270:
      rotate.Translate(0, display.bounds().width() - one_pixel);
      rotate.Rotate(270);
      break;
    case gfx::Display::ROTATE_180:
      rotate.Translate(display.bounds().width() - one_pixel,
                       display.bounds().height() - one_pixel);
      rotate.Rotate(180);
      break;
  }
  RoundNearZero(&rotate);

  scoped_ptr<aura::RootWindowTransformer> transformer(
      new AshRootWindowTransformer(root_window,
                                   rotate,
                                   info.GetOverscanInsetsInPixel(),
                                   info.ui_scale()));
  root_window->SetRootWindowTransformer(transformer.Pass());
}

void SetDisplayPropertiesOnHostWindow(aura::RootWindow* root,
                                      const gfx::Display& display) {
  internal::DisplayInfo info =
      GetDisplayManager()->GetDisplayInfo(display.id());
#if defined(OS_CHROMEOS)
  // Native window property (Atom in X11) that specifies the display's
  // rotation, scale factor and if it's internal display.  They are
  // read and used by touchpad/mouse driver directly on X (contact
  // adlr@ for more details on touchpad/mouse driver side). The value
  // of the rotation is one of 0 (normal), 1 (90 degrees clockwise), 2
  // (180 degree) or 3 (270 degrees clockwise).  The value of the
  // scale factor is in percent (100, 140, 200 etc).
  const char kRotationProp[] = "_CHROME_DISPLAY_ROTATION";
  const char kScaleFactorProp[] = "_CHROME_DISPLAY_SCALE_FACTOR";
  const char kInternalProp[] = "_CHROME_DISPLAY_INTERNAL";
  const char kCARDINAL[] = "CARDINAL";
  int xrandr_rotation = RR_Rotate_0;
  switch (info.rotation()) {
    case gfx::Display::ROTATE_0:
      xrandr_rotation = RR_Rotate_0;
      break;
    case gfx::Display::ROTATE_90:
      xrandr_rotation = RR_Rotate_90;
      break;
    case gfx::Display::ROTATE_180:
      xrandr_rotation = RR_Rotate_180;
      break;
    case gfx::Display::ROTATE_270:
      xrandr_rotation = RR_Rotate_270;
      break;
  }

  int internal = display.IsInternal() ? 1 : 0;
  gfx::AcceleratedWidget xwindow = root->GetAcceleratedWidget();
  ui::SetIntProperty(xwindow, kInternalProp, kCARDINAL, internal);
  ui::SetIntProperty(xwindow, kRotationProp, kCARDINAL, xrandr_rotation);
  ui::SetIntProperty(xwindow,
                     kScaleFactorProp,
                     kCARDINAL,
                     100 * display.device_scale_factor());
#endif
  RotateRootWindow(root, display, info);
}

}  // namespace

namespace internal {

// A utility class to store/restore focused/active window
// when the display configuration has changed.
class FocusActivationStore {
 public:
  FocusActivationStore()
      : activation_client_(NULL),
        capture_client_(NULL),
        focus_client_(NULL),
        focused_(NULL),
        active_(NULL) {
  }

  void Store() {
    if (!activation_client_) {
      aura::RootWindow* root = Shell::GetPrimaryRootWindow();
      activation_client_ = aura::client::GetActivationClient(root);
      capture_client_ = aura::client::GetCaptureClient(root);
      focus_client_ = aura::client::GetFocusClient(root);
    }
    focused_ = focus_client_->GetFocusedWindow();
    if (focused_)
      tracker_.Add(focused_);
    active_ = activation_client_->GetActiveWindow();
    if (active_ && focused_ != active_)
      tracker_.Add(active_);

    // Deactivate the window to close menu / bubble windows.
    activation_client_->DeactivateWindow(active_);
    // Release capture if any.
    capture_client_->SetCapture(NULL);
    // Clear the focused window if any. This is necessary because a
    // window may be deleted when losing focus (fullscreen flash for
    // example).  If the focused window is still alive after move, it'll
    // be re-focused below.
    focus_client_->FocusWindow(NULL);
  }

  void Restore() {
    // Restore focused or active window if it's still alive.
    if (focused_ && tracker_.Contains(focused_)) {
      focus_client_->FocusWindow(focused_);
    } else if (active_ && tracker_.Contains(active_)) {
      activation_client_->ActivateWindow(active_);
    }
    if (focused_)
      tracker_.Remove(focused_);
    if (active_)
      tracker_.Remove(active_);
    focused_ = NULL;
    active_ = NULL;
  }

 private:
  aura::client::ActivationClient* activation_client_;
  aura::client::CaptureClient* capture_client_;
  aura::client::FocusClient* focus_client_;
  aura::WindowTracker tracker_;
  aura::Window* focused_;
  aura::Window* active_;

  DISALLOW_COPY_AND_ASSIGN(FocusActivationStore);
};

}  // namespace internal

////////////////////////////////////////////////////////////////////////////////
// DisplayLayout

// static
DisplayLayout DisplayLayout::FromInts(int position, int offsets) {
  return DisplayLayout(static_cast<Position>(position), offsets);
}

DisplayLayout::DisplayLayout()
    : position(RIGHT),
      offset(0),
      mirrored(false),
      primary_id(gfx::Display::kInvalidDisplayID) {
}

DisplayLayout::DisplayLayout(DisplayLayout::Position position, int offset)
    : position(position),
      offset(offset),
      mirrored(false),
      primary_id(gfx::Display::kInvalidDisplayID) {
  DCHECK_LE(TOP, position);
  DCHECK_GE(LEFT, position);

  // Set the default value to |position| in case position is invalid.  DCHECKs
  // above doesn't stop in Release builds.
  if (TOP > position || LEFT < position)
    this->position = RIGHT;

  DCHECK_GE(kMaxValidOffset, abs(offset));
}

DisplayLayout DisplayLayout::Invert() const {
  Position inverted_position = RIGHT;
  switch (position) {
    case TOP:
      inverted_position = BOTTOM;
      break;
    case BOTTOM:
      inverted_position = TOP;
      break;
    case RIGHT:
      inverted_position = LEFT;
      break;
    case LEFT:
      inverted_position = RIGHT;
      break;
  }
  DisplayLayout ret = DisplayLayout(inverted_position, -offset);
  ret.primary_id = primary_id;
  return ret;
}

// static
bool DisplayLayout::ConvertFromValue(const base::Value& value,
                                     DisplayLayout* layout) {
  base::JSONValueConverter<DisplayLayout> converter;
  return converter.Convert(value, layout);
}

// static
bool DisplayLayout::ConvertToValue(const DisplayLayout& layout,
                                   base::Value* value) {
  base::DictionaryValue* dict_value = NULL;
  if (!value->GetAsDictionary(&dict_value) || dict_value == NULL)
    return false;

  const std::string position_str = GetStringFromPosition(layout.position);
  dict_value->SetString(kPositionKey, position_str);
  dict_value->SetInteger(kOffsetKey, layout.offset);
  dict_value->SetBoolean(kMirroredKey, layout.mirrored);
  dict_value->SetString(kPrimaryIdKey, base::Int64ToString(layout.primary_id));
  return true;
}

std::string DisplayLayout::ToString() const {
  const std::string position_str = GetStringFromPosition(position);
  return base::StringPrintf(
      "%s, %d%s",
      position_str.c_str(), offset, mirrored ? ", mirrored" : "");
}

// static
void DisplayLayout::RegisterJSONConverter(
    base::JSONValueConverter<DisplayLayout>* converter) {
  converter->RegisterCustomField<Position>(
      kPositionKey, &DisplayLayout::position, &GetPositionFromString);
  converter->RegisterIntField(kOffsetKey, &DisplayLayout::offset);
  converter->RegisterBoolField(kMirroredKey, &DisplayLayout::mirrored);
  converter->RegisterCustomField<int64>(
      kPrimaryIdKey, &DisplayLayout::primary_id, &GetDisplayIdFromString);
}

////////////////////////////////////////////////////////////////////////////////
// DisplayChangeLimiter

DisplayController::DisplayChangeLimiter::DisplayChangeLimiter()
    : throttle_timeout_(base::Time::Now()) {
}

void DisplayController::DisplayChangeLimiter::SetThrottleTimeout(
    int64 throttle_ms) {
  throttle_timeout_ =
      base::Time::Now() + base::TimeDelta::FromMilliseconds(throttle_ms);
}

bool DisplayController::DisplayChangeLimiter::IsThrottled() const {
  return base::Time::Now() < throttle_timeout_;
}

////////////////////////////////////////////////////////////////////////////////
// DisplayController

DisplayController::DisplayController()
    : primary_root_window_for_replace_(NULL),
      in_bootstrap_(true),
      focus_activation_store_(new internal::FocusActivationStore()) {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
#if defined(OS_CHROMEOS)
  if (!command_line->HasSwitch(switches::kAshDisableDisplayChangeLimiter) &&
      base::chromeos::IsRunningOnChromeOS())
    limiter_.reset(new DisplayChangeLimiter);
#endif
  if (command_line->HasSwitch(switches::kAshSecondaryDisplayLayout)) {
    std::string value = command_line->GetSwitchValueASCII(
        switches::kAshSecondaryDisplayLayout);
    char layout;
    int offset = 0;
    if (sscanf(value.c_str(), "%c,%d", &layout, &offset) == 2) {
      if (layout == 't')
        default_display_layout_.position = DisplayLayout::TOP;
      else if (layout == 'b')
        default_display_layout_.position = DisplayLayout::BOTTOM;
      else if (layout == 'r')
        default_display_layout_.position = DisplayLayout::RIGHT;
      else if (layout == 'l')
        default_display_layout_.position = DisplayLayout::LEFT;
      default_display_layout_.offset = offset;
    }
  }
  // Reset primary display to make sure that tests don't use
  // stale display info from previous tests.
  primary_display_id = gfx::Display::kInvalidDisplayID;
  delete primary_display_for_shutdown;
  primary_display_for_shutdown = NULL;
  num_displays_for_shutdown = -1;
}

DisplayController::~DisplayController() {
  DCHECK(primary_display_for_shutdown);
}

void DisplayController::Start() {
  Shell::GetScreen()->AddObserver(this);
  in_bootstrap_ = false;
}

void DisplayController::Shutdown() {
  DCHECK(!primary_display_for_shutdown);
  primary_display_for_shutdown = new gfx::Display(
      GetDisplayManager()->GetDisplayForId(primary_display_id));
  num_displays_for_shutdown = GetDisplayManager()->GetNumDisplays();

  Shell::GetScreen()->RemoveObserver(this);
  // Delete all root window controllers, which deletes root window
  // from the last so that the primary root window gets deleted last.
  for (std::map<int64, aura::RootWindow*>::const_reverse_iterator it =
           root_windows_.rbegin(); it != root_windows_.rend(); ++it) {
    internal::RootWindowController* controller =
        GetRootWindowController(it->second);
    DCHECK(controller);
    delete controller;
  }
}

// static
const gfx::Display& DisplayController::GetPrimaryDisplay() {
  DCHECK_NE(primary_display_id, gfx::Display::kInvalidDisplayID);
  if (primary_display_for_shutdown)
    return *primary_display_for_shutdown;
  return GetDisplayManager()->GetDisplayForId(primary_display_id);
}

// static
int DisplayController::GetNumDisplays() {
  if (num_displays_for_shutdown >= 0)
    return num_displays_for_shutdown;
  return GetDisplayManager()->GetNumDisplays();
}

// static
bool DisplayController::HasPrimaryDisplay() {
  return primary_display_id != gfx::Display::kInvalidDisplayID;
}

void DisplayController::InitPrimaryDisplay() {
  const gfx::Display* primary_candidate =
      GetDisplayManager()->GetPrimaryDisplayCandidate();
  primary_display_id = primary_candidate->id();
  AddRootWindowForDisplay(*primary_candidate);
  UpdateDisplayBoundsForLayout();
}

void DisplayController::InitSecondaryDisplays() {
  internal::DisplayManager* display_manager = GetDisplayManager();
  for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
    const gfx::Display* display = display_manager->GetDisplayAt(i);
    if (primary_display_id != display->id()) {
      aura::RootWindow* root = AddRootWindowForDisplay(*display);
      Shell::GetInstance()->InitRootWindowForSecondaryDisplay(root);
    }
  }
  if (display_manager->GetNumDisplays() > 1) {
    UpdateDisplayBoundsForLayout();
    DisplayIdPair pair = GetCurrentDisplayIdPair();
    DisplayLayout layout = GetCurrentDisplayLayout();
    SetPrimaryDisplayId(
        layout.primary_id == gfx::Display::kInvalidDisplayID ?
        pair.first : layout.primary_id);
  }
}

void DisplayController::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void DisplayController::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

aura::RootWindow* DisplayController::GetPrimaryRootWindow() {
  DCHECK(!root_windows_.empty());
  return root_windows_[primary_display_id];
}

aura::RootWindow* DisplayController::GetRootWindowForDisplayId(int64 id) {
  return root_windows_[id];
}

void DisplayController::CloseChildWindows() {
  for (std::map<int64, aura::RootWindow*>::const_iterator it =
           root_windows_.begin(); it != root_windows_.end(); ++it) {
    aura::RootWindow* root_window = it->second;
    internal::RootWindowController* controller =
        GetRootWindowController(root_window);
    if (controller) {
      controller->CloseChildWindows();
    } else {
      while (!root_window->children().empty()) {
        aura::Window* child = root_window->children()[0];
        delete child;
      }
    }
  }
}

std::vector<aura::RootWindow*> DisplayController::GetAllRootWindows() {
  std::vector<aura::RootWindow*> windows;
  for (std::map<int64, aura::RootWindow*>::const_iterator it =
           root_windows_.begin(); it != root_windows_.end(); ++it) {
    DCHECK(it->second);
    if (GetRootWindowController(it->second))
      windows.push_back(it->second);
  }
  return windows;
}

gfx::Insets DisplayController::GetOverscanInsets(int64 display_id) const {
  return GetDisplayManager()->GetOverscanInsets(display_id);
}

void DisplayController::SetOverscanInsets(int64 display_id,
                                          const gfx::Insets& insets_in_dip) {
  GetDisplayManager()->SetOverscanInsets(display_id, insets_in_dip);
}

void DisplayController::ClearCustomOverscanInsets(int64 display_id) {
  GetDisplayManager()->ClearCustomOverscanInsets(display_id);
}

std::vector<internal::RootWindowController*>
DisplayController::GetAllRootWindowControllers() {
  std::vector<internal::RootWindowController*> controllers;
  for (std::map<int64, aura::RootWindow*>::const_iterator it =
           root_windows_.begin(); it != root_windows_.end(); ++it) {
    internal::RootWindowController* controller =
        GetRootWindowController(it->second);
    if (controller)
      controllers.push_back(controller);
  }
  return controllers;
}

void DisplayController::SetDefaultDisplayLayout(const DisplayLayout& layout) {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (!command_line->HasSwitch(switches::kAshSecondaryDisplayLayout))
    default_display_layout_ = layout;
}

void DisplayController::RegisterLayoutForDisplayIdPair(
    int64 id1,
    int64 id2,
    const DisplayLayout& layout) {
  RegisterLayoutForDisplayIdPairInternal(id1, id2, layout, true);
}

void DisplayController::RegisterLayoutForDisplayId(
    int64 id,
    const DisplayLayout& layout) {
  int64 first_id = gfx::Display::InternalDisplayId();
  if (first_id == gfx::Display::kInvalidDisplayID)
    first_id = GetDisplayManager()->first_display_id();
  // Caveat: This doesn't work if the machine booted with
  // no display.
  // Ignore if the layout was registered for the internal or
  // 1st display.
  if (first_id != id)
    RegisterLayoutForDisplayIdPairInternal(first_id, id, layout, false);
}

void DisplayController::SetLayoutForCurrentDisplays(
    const DisplayLayout& layout_relative_to_primary) {
  DCHECK_EQ(2U, GetDisplayManager()->GetNumDisplays());
  if (GetDisplayManager()->GetNumDisplays() < 2)
    return;
  const gfx::Display& primary = GetPrimaryDisplay();
  const DisplayIdPair pair = GetCurrentDisplayIdPair();
  // Invert if the primary was swapped.
  DisplayLayout to_set = pair.first == primary.id() ?
      layout_relative_to_primary : layout_relative_to_primary.Invert();

  const DisplayLayout& current_layout = paired_layouts_[pair];
  if (to_set.position != current_layout.position ||
      to_set.offset != current_layout.offset) {
    to_set.primary_id = primary.id();
    paired_layouts_[pair] = to_set;
    NotifyDisplayConfigurationChanging();
    UpdateDisplayBoundsForLayout();
    NotifyDisplayConfigurationChanged();
  }
}

DisplayLayout DisplayController::GetCurrentDisplayLayout() const {
  DCHECK_EQ(2U, GetDisplayManager()->num_connected_displays());
  // Invert if the primary was swapped.
  if (GetDisplayManager()->num_connected_displays() > 1) {
    DisplayIdPair pair = GetCurrentDisplayIdPair();
    DisplayLayout layout = GetRegisteredDisplayLayout(pair);
    const gfx::Display& primary = GetPrimaryDisplay();
    // Invert if the primary was swapped. If mirrored, first is always
    // primary.
    return pair.first == primary.id() ? layout : layout.Invert();
  }
  // On release build, just fallback to default instead of blowing up.
  return default_display_layout_;
}

DisplayIdPair DisplayController::GetCurrentDisplayIdPair() const {
  internal::DisplayManager* display_manager = GetDisplayManager();
  const gfx::Display& primary = GetPrimaryDisplay();
  if (display_manager->IsMirrored())
    return std::make_pair(primary.id(), display_manager->mirrored_display_id());

  const gfx::Display& secondary = ScreenAsh::GetSecondaryDisplay();
  if (primary.IsInternal() ||
      GetDisplayManager()->first_display_id() == primary.id()) {
    return std::make_pair(primary.id(), secondary.id());
  } else {
    // Display has been Swapped.
    return std::make_pair(secondary.id(), primary.id());
  }
}

DisplayLayout DisplayController::GetRegisteredDisplayLayout(
    const DisplayIdPair& pair) const {
  std::map<DisplayIdPair, DisplayLayout>::const_iterator iter =
      paired_layouts_.find(pair);
  return iter != paired_layouts_.end() ? iter->second : default_display_layout_;
}

void DisplayController::CycleDisplayMode() {
  if (limiter_) {
    if  (limiter_->IsThrottled())
      return;
    limiter_->SetThrottleTimeout(kCycleDisplayThrottleTimeoutMs);
  }
#if defined(OS_CHROMEOS)
  Shell* shell = Shell::GetInstance();
  internal::DisplayManager* display_manager = GetDisplayManager();
  if (!base::chromeos::IsRunningOnChromeOS()) {
    internal::DisplayManager::CycleDisplay();
  } else if (display_manager->num_connected_displays() > 1) {
    chromeos::OutputState new_state = display_manager->IsMirrored() ?
       chromeos::STATE_DUAL_EXTENDED : chromeos::STATE_DUAL_MIRROR;
    internal::OutputConfiguratorAnimation* animation =
        shell->output_configurator_animation();
    animation->StartFadeOutAnimation(base::Bind(
        base::IgnoreResult(&chromeos::OutputConfigurator::SetDisplayMode),
        base::Unretained(shell->output_configurator()),
        new_state));
  }
#endif
}

void DisplayController::SwapPrimaryDisplay() {
  if (limiter_) {
    if  (limiter_->IsThrottled())
      return;
    limiter_->SetThrottleTimeout(kSwapDisplayThrottleTimeoutMs);
  }

  if (Shell::GetScreen()->GetNumDisplays() > 1) {
#if defined(OS_CHROMEOS)
    internal::OutputConfiguratorAnimation* animation =
        Shell::GetInstance()->output_configurator_animation();
    if (animation) {
      animation->StartFadeOutAnimation(base::Bind(
          &DisplayController::OnFadeOutForSwapDisplayFinished,
          base::Unretained(this)));
    } else {
      SetPrimaryDisplay(ScreenAsh::GetSecondaryDisplay());
    }
#else
    SetPrimaryDisplay(ScreenAsh::GetSecondaryDisplay());
#endif
  }
}

void DisplayController::SetPrimaryDisplayId(int64 id) {
  DCHECK_NE(gfx::Display::kInvalidDisplayID, id);
  if (id == gfx::Display::kInvalidDisplayID || primary_display_id == id)
    return;

  const gfx::Display& display = GetDisplayManager()->GetDisplayForId(id);
  if (display.is_valid())
    SetPrimaryDisplay(display);
}

void DisplayController::SetPrimaryDisplay(
    const gfx::Display& new_primary_display) {
  internal::DisplayManager* display_manager = GetDisplayManager();
  DCHECK(new_primary_display.is_valid());
  DCHECK(display_manager->IsActiveDisplay(new_primary_display));

  if (!new_primary_display.is_valid() ||
      !display_manager->IsActiveDisplay(new_primary_display)) {
    LOG(ERROR) << "Invalid or non-existent display is requested:"
               << new_primary_display.ToString();
    return;
  }

  if (primary_display_id == new_primary_display.id() ||
      root_windows_.size() < 2) {
    return;
  }

  aura::RootWindow* non_primary_root = root_windows_[new_primary_display.id()];
  LOG_IF(ERROR, !non_primary_root)
      << "Unknown display is requested in SetPrimaryDisplay: id="
      << new_primary_display.id();
  if (!non_primary_root)
    return;

  gfx::Display old_primary_display = GetPrimaryDisplay();

  // Swap root windows between current and new primary display.
  aura::RootWindow* primary_root = root_windows_[primary_display_id];
  DCHECK(primary_root);
  DCHECK_NE(primary_root, non_primary_root);

  root_windows_[new_primary_display.id()] = primary_root;
  primary_root->SetProperty(internal::kDisplayIdKey, new_primary_display.id());

  root_windows_[old_primary_display.id()] = non_primary_root;
  non_primary_root->SetProperty(internal::kDisplayIdKey,
                                old_primary_display.id());

  primary_display_id = new_primary_display.id();
  paired_layouts_[GetCurrentDisplayIdPair()].primary_id = primary_display_id;

  display_manager->UpdateWorkAreaOfDisplayNearestWindow(
      primary_root, old_primary_display.GetWorkAreaInsets());
  display_manager->UpdateWorkAreaOfDisplayNearestWindow(
      non_primary_root, new_primary_display.GetWorkAreaInsets());

  // Update the dispay manager with new display info.
  std::vector<internal::DisplayInfo> display_info_list;
  display_info_list.push_back(display_manager->GetDisplayInfo(
      primary_display_id));
  display_info_list.push_back(display_manager->GetDisplayInfo(
      GetSecondaryDisplay()->id()));
  GetDisplayManager()->set_force_bounds_changed(true);
  GetDisplayManager()->UpdateDisplays(display_info_list);
  GetDisplayManager()->set_force_bounds_changed(false);
}

gfx::Display* DisplayController::GetSecondaryDisplay() {
  internal::DisplayManager* display_manager = GetDisplayManager();
  CHECK_EQ(2U, display_manager->GetNumDisplays());
  return display_manager->GetDisplayAt(0)->id() == primary_display_id ?
      display_manager->GetDisplayAt(1) : display_manager->GetDisplayAt(0);
}

void DisplayController::EnsurePointerInDisplays() {
  // Don't try to move the pointer during the boot/startup.
  if (!HasPrimaryDisplay())
    return;
  gfx::Point location_in_screen = Shell::GetScreen()->GetCursorScreenPoint();
  gfx::Point target_location;
  int64 closest_distance_squared = -1;
  internal::DisplayManager* display_manager = GetDisplayManager();

  aura::RootWindow* dst_root_window = NULL;
  for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
    const gfx::Display* display = display_manager->GetDisplayAt(i);
    aura::RootWindow* root_window = GetRootWindowForDisplayId(display->id());
    if (display->bounds().Contains(location_in_screen)) {
      dst_root_window = root_window;
      target_location = location_in_screen;
      break;
    }
    gfx::Point center = display->bounds().CenterPoint();
    // Use the distance squared from the center of the dislay. This is not
    // exactly "closest" display, but good enough to pick one
    // appropriate (and there are at most two displays).
    // We don't care about actual distance, only relative to other displays, so
    // using the LengthSquared() is cheaper than Length().

    int64 distance_squared = (center - location_in_screen).LengthSquared();
    if (closest_distance_squared < 0 ||
        closest_distance_squared > distance_squared) {
      dst_root_window = root_window;
      target_location = center;
      closest_distance_squared = distance_squared;
    }
  }
  DCHECK(dst_root_window);
  aura::client::ScreenPositionClient* client =
      aura::client::GetScreenPositionClient(dst_root_window);
  client->ConvertPointFromScreen(dst_root_window, &target_location);
  dst_root_window->MoveCursorTo(target_location);
}

gfx::Point DisplayController::GetNativeMouseCursorLocation() const {
  if (in_bootstrap())
    return gfx::Point();

  gfx::Point location = Shell::GetScreen()->GetCursorScreenPoint();
  const gfx::Display& display =
      Shell::GetScreen()->GetDisplayNearestPoint(location);
  const aura::RootWindow* root_window =
      root_windows_.find(display.id())->second;
  aura::client::ScreenPositionClient* client =
      aura::client::GetScreenPositionClient(root_window);
  client->ConvertPointFromScreen(root_window, &location);
  root_window->ConvertPointToNativeScreen(&location);
  return location;
}

void DisplayController::UpdateMouseCursor(const gfx::Point& point_in_native) {
  if (in_bootstrap())
    return;

  std::vector<aura::RootWindow*> root_windows = GetAllRootWindows();
  for (std::vector<aura::RootWindow*>::iterator iter = root_windows.begin();
       iter != root_windows.end();
       ++iter) {
    aura::RootWindow* root_window = *iter;
    gfx::Rect bounds_in_native(root_window->GetHostOrigin(),
                               root_window->GetHostSize());
    if (bounds_in_native.Contains(point_in_native)) {
      gfx::Point point(point_in_native);
      root_window->ConvertPointFromNativeScreen(&point);
      root_window->MoveCursorTo(point);
      break;
    }
  }
}

void DisplayController::OnDisplayBoundsChanged(const gfx::Display& display) {
  if (limiter_)
    limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);
  const internal::DisplayInfo& display_info =
      GetDisplayManager()->GetDisplayInfo(display.id());
  DCHECK(!display_info.bounds_in_pixel().IsEmpty());

  UpdateDisplayBoundsForLayout();
  aura::RootWindow* root = root_windows_[display.id()];
  SetDisplayPropertiesOnHostWindow(root, display);
  root->SetHostBounds(display_info.bounds_in_pixel());
}

void DisplayController::OnDisplayAdded(const gfx::Display& display) {
  if (limiter_)
    limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);

  if (primary_root_window_for_replace_) {
    DCHECK(root_windows_.empty());
    primary_display_id = display.id();
    root_windows_[display.id()] = primary_root_window_for_replace_;
    primary_root_window_for_replace_->SetProperty(
        internal::kDisplayIdKey, display.id());
    primary_root_window_for_replace_ = NULL;
    UpdateDisplayBoundsForLayout();
    const internal::DisplayInfo& display_info =
        GetDisplayManager()->GetDisplayInfo(display.id());
    root_windows_[display.id()]->SetHostBounds(
        display_info.bounds_in_pixel());
  } else {
    if (primary_display_id == gfx::Display::kInvalidDisplayID)
      primary_display_id = display.id();
    DCHECK(!root_windows_.empty());
    aura::RootWindow* root = AddRootWindowForDisplay(display);
    UpdateDisplayBoundsForLayout();
    Shell::GetInstance()->InitRootWindowForSecondaryDisplay(root);
  }
}

void DisplayController::OnDisplayRemoved(const gfx::Display& display) {
  if (limiter_)
    limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);

  aura::RootWindow* root_to_delete = root_windows_[display.id()];
  DCHECK(root_to_delete) << display.ToString();

  // Display for root window will be deleted when the Primary RootWindow
  // is deleted by the Shell.
  root_windows_.erase(display.id());

  // When the primary root window's display is removed, move the primary
  // root to the other display.
  if (primary_display_id == display.id()) {
    // Temporarily store the primary root window in
    // |primary_root_window_for_replace_| when replacing the display.
    if (root_windows_.size() == 0) {
      primary_display_id = gfx::Display::kInvalidDisplayID;
      primary_root_window_for_replace_ = root_to_delete;
      return;
    }
    DCHECK_EQ(1U, root_windows_.size());
    primary_display_id = GetSecondaryDisplay()->id();
    aura::RootWindow* primary_root = root_to_delete;

    // Delete the other root instead.
    root_to_delete = root_windows_[primary_display_id];
    root_to_delete->SetProperty(internal::kDisplayIdKey, display.id());

    // Setup primary root.
    root_windows_[primary_display_id] = primary_root;
    primary_root->SetProperty(internal::kDisplayIdKey, primary_display_id);

    OnDisplayBoundsChanged(
        GetDisplayManager()->GetDisplayForId(primary_display_id));
  }
  internal::RootWindowController* controller =
      GetRootWindowController(root_to_delete);
  DCHECK(controller);
  controller->MoveWindowsTo(GetPrimaryRootWindow());
  // Delete most of root window related objects, but don't delete
  // root window itself yet because the stack may be using it.
  controller->Shutdown();
  MessageLoop::current()->DeleteSoon(FROM_HERE, controller);
}

aura::RootWindow* DisplayController::CreateRootWindowForDisplay(
    const gfx::Display& display) {
  static int root_window_count = 0;
  const internal::DisplayInfo& display_info =
      GetDisplayManager()->GetDisplayInfo(display.id());
  const gfx::Rect& bounds_in_pixel = display_info.bounds_in_pixel();
  aura::RootWindow::CreateParams params(bounds_in_pixel);
  params.host = Shell::GetInstance()->root_window_host_factory()->
      CreateRootWindowHost(bounds_in_pixel);
  aura::RootWindow* root_window = new aura::RootWindow(params);
  root_window->SetName(
      base::StringPrintf("RootWindow-%d", root_window_count++));
  root_window->compositor()->SetBackgroundColor(SK_ColorBLACK);
  // No need to remove RootWindowObserver because
  // the DisplayManager object outlives RootWindow objects.
  root_window->AddRootWindowObserver(GetDisplayManager());
  root_window->SetProperty(internal::kDisplayIdKey, display.id());
  root_window->Init();
  return root_window;
}

aura::RootWindow* DisplayController::AddRootWindowForDisplay(
    const gfx::Display& display) {
  aura::RootWindow* root = CreateRootWindowForDisplay(display);
  root_windows_[display.id()] = root;
  SetDisplayPropertiesOnHostWindow(root, display);

#if defined(OS_CHROMEOS)
  static bool force_constrain_pointer_to_root =
      CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kAshConstrainPointerToRoot);
  if (base::chromeos::IsRunningOnChromeOS() || force_constrain_pointer_to_root)
    root->ConfineCursorToWindow();
#endif
  return root;
}

void DisplayController::UpdateDisplayBoundsForLayout() {
  if (Shell::GetScreen()->GetNumDisplays() < 2 ||
      GetDisplayManager()->num_connected_displays() < 2) {
    return;
  }

  DCHECK_EQ(2, Shell::GetScreen()->GetNumDisplays());
  const gfx::Rect& primary_bounds = GetPrimaryDisplay().bounds();

  gfx::Display* secondary_display = GetSecondaryDisplay();
  const gfx::Rect& secondary_bounds = secondary_display->bounds();
  gfx::Point new_secondary_origin = primary_bounds.origin();

  const DisplayLayout layout = GetCurrentDisplayLayout();
  DisplayLayout::Position position = layout.position;

  // Ignore the offset in case the secondary display doesn't share edges with
  // the primary display.
  int offset = layout.offset;
  if (position == DisplayLayout::TOP || position == DisplayLayout::BOTTOM) {
    offset = std::min(
        offset, primary_bounds.width() - kMinimumOverlapForInvalidOffset);
    offset = std::max(
        offset, -secondary_bounds.width() + kMinimumOverlapForInvalidOffset);
  } else {
    offset = std::min(
        offset, primary_bounds.height() - kMinimumOverlapForInvalidOffset);
    offset = std::max(
        offset, -secondary_bounds.height() + kMinimumOverlapForInvalidOffset);
  }
  switch (position) {
    case DisplayLayout::TOP:
      new_secondary_origin.Offset(offset, -secondary_bounds.height());
      break;
    case DisplayLayout::RIGHT:
      new_secondary_origin.Offset(primary_bounds.width(), offset);
      break;
    case DisplayLayout::BOTTOM:
      new_secondary_origin.Offset(offset, primary_bounds.height());
      break;
    case DisplayLayout::LEFT:
      new_secondary_origin.Offset(-secondary_bounds.width(), offset);
      break;
  }
  gfx::Insets insets = secondary_display->GetWorkAreaInsets();
  secondary_display->set_bounds(
      gfx::Rect(new_secondary_origin, secondary_bounds.size()));
  secondary_display->UpdateWorkAreaFromInsets(insets);
}

void DisplayController::NotifyDisplayConfigurationChanging() {
  if (in_bootstrap())
    return;
  FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanging());
  focus_activation_store_->Store();
}

void DisplayController::NotifyDisplayConfigurationChanged() {
  if (in_bootstrap())
    return;
  focus_activation_store_->Restore();

  internal::DisplayManager* display_manager = GetDisplayManager();
  if (display_manager->num_connected_displays() > 1) {
    DisplayIdPair pair = GetCurrentDisplayIdPair();
    if (paired_layouts_.find(pair) == paired_layouts_.end())
      paired_layouts_[pair] = default_display_layout_;
    paired_layouts_[pair].mirrored = display_manager->IsMirrored();
    if (Shell::GetScreen()->GetNumDisplays() > 1 ) {
      int64 primary_id = paired_layouts_[pair].primary_id;
      SetPrimaryDisplayId(
          primary_id == gfx::Display::kInvalidDisplayID ?
          pair.first : primary_id);
      // Update the primary_id in case the above call is
      // ignored. Happens when a) default layout's primary id
      // doesn't exist, or b) the primary_id has already been
      // set to the same and didn't update it.
      paired_layouts_[pair].primary_id = GetPrimaryDisplay().id();
    }
  }
  FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanged());
}

void DisplayController::RegisterLayoutForDisplayIdPairInternal(
    int64 id1,
    int64 id2,
    const DisplayLayout& layout,
    bool override) {
  DisplayIdPair pair = std::make_pair(id1, id2);
  if (override || paired_layouts_.find(pair) == paired_layouts_.end())
    paired_layouts_[pair] = layout;
}

void DisplayController::OnFadeOutForSwapDisplayFinished() {
#if defined(OS_CHROMEOS)
  SetPrimaryDisplay(ScreenAsh::GetSecondaryDisplay());
  Shell::GetInstance()->output_configurator_animation()->StartFadeInAnimation();
#endif
}

}  // namespace ash