File: virtual_display_util_linux.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (217 lines) | stat: -rw-r--r-- 7,562 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/display/linux/test/virtual_display_util_linux.h"

#include <algorithm>
#include <limits>
#include <vector>

#include "base/environment.h"
#include "base/nix/xdg_util.h"
#include "ui/display/display.h"
#include "ui/display/display_list.h"
#include "ui/display/screen.h"
#include "ui/display/types/display_constants.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/x/connection.h"
#include "ui/gfx/x/randr.h"
#include "ui/gfx/x/randr_output_manager.h"

namespace {

// Appends a new screen with `resolution` and `dpi` to the specified desktop
// `layout`. Arranges horizontally left to right.
void AppendScreen(x11::RandRMonitorLayout& layout,
                  const gfx::Size& resolution,
                  const gfx::Vector2d& dpi) {
  // Find the rightmost screen layout.
  const x11::RandRMonitorConfig* rightmost_layout = nullptr;
  for (const auto& screen : layout.configs) {
    if (rightmost_layout == nullptr ||
        screen.rect().right() > rightmost_layout->rect().right()) {
      rightmost_layout = &screen;
    }
  }
  layout.configs.emplace_back(
      std::nullopt,
      gfx::Rect(rightmost_layout->rect().right() + 1,
                rightmost_layout->rect().y(), resolution.width(),
                resolution.height()),
      dpi);
}
}  // namespace

namespace display::test {

VirtualDisplayUtilLinux::VirtualDisplayUtilLinux(Screen* screen)
    : screen_(screen),
      randr_output_manager_(std::make_unique<x11::RandROutputManager>(
          /*output_name_prefix=*/"VDU_")),
      initial_layout_(randr_output_manager_->GetLayout()),
      current_layout_(initial_layout_) {
  CHECK(screen_);
  screen_->AddObserver(this);
}
VirtualDisplayUtilLinux::~VirtualDisplayUtilLinux() {
  ResetDisplays();
  screen_->RemoveObserver(this);
}

// static
bool VirtualDisplayUtilLinux::IsAPIAvailable() {
  // Check if XRandR is available with a sufficient number of connected outputs.
  // Skip base::nix::GetSessionType(...), which may return kTty instead of kX11
  // in SSH sessions with virtualized X11 environments.

  constexpr auto kConnected = static_cast<x11::RandR::RandRConnection>(0);
  constexpr auto kDisabled = static_cast<x11::RandR::Crtc>(0);
  x11::Connection* x11_connection = x11::Connection::Get();
  if (!x11_connection) {
    LOG(ERROR) << "X11 is not present.";
    return false;
  }
  x11::RandR& xrandr = x11_connection->randr();
  if (!xrandr.present()) {
    LOG(ERROR) << "XRandR is not present.";
    return false;
  }
  x11::Response<x11::RandR::GetScreenResourcesCurrentReply> screen_resources =
      xrandr.GetScreenResourcesCurrent({x11_connection->default_screen().root})
          .Sync();
  if (!screen_resources.reply) {
    LOG(ERROR) << "GetScreenResourcesCurrent failed.";
    return false;
  }
  int connected_and_disabled_outputs = 0;
  for (const auto& output : screen_resources.reply->outputs) {
    std::unique_ptr<x11::RandR::GetOutputInfoReply> output_reply =
        xrandr.GetOutputInfo(output, screen_resources.reply->config_timestamp)
            .Sync()
            .reply;
    if (output_reply && output_reply->connection == kConnected &&
        output_reply->crtc == kDisabled) {
      connected_and_disabled_outputs++;
    }
  }
  return connected_and_disabled_outputs >= kMaxDisplays;
}

int64_t VirtualDisplayUtilLinux::AddDisplay(
    const DisplayParams& display_params) {
  if (current_layout_.configs.size() - initial_layout_.configs.size() >
      kMaxDisplays) {
    LOG(ERROR) << "Cannot exceed " << kMaxDisplays << " virtual displays.";
    return kInvalidDisplayId;
  }
  CHECK(!current_layout_.configs.empty());
  last_requested_layout_ = current_layout_;
  AppendScreen(last_requested_layout_, display_params.resolution,
               display_params.dpi);
  randr_output_manager_->SetLayout(last_requested_layout_);
  size_t initial_detected_displays = detected_added_display_ids_.size();
  StartWaiting();
  CHECK_EQ(detected_added_display_ids_.size(), initial_detected_displays + 1u)
      << "Did not detect exactly one new display.";
  // Reconcile the added resizer display ID to the detected display::Display id.
  int64_t new_display_id = detected_added_display_ids_.back();
  x11::RandRMonitorLayout prev_layout = current_layout_;
  current_layout_ = randr_output_manager_->GetLayout();
  for (const auto& layout : current_layout_.configs) {
    auto was_added =
        std::find_if(prev_layout.configs.begin(), prev_layout.configs.end(),
                     [&](const x11::RandRMonitorConfig& prev) {
                       return prev.rect() == layout.rect();
                     });
    if (was_added == prev_layout.configs.end()) {
      display_id_to_randr_id_[new_display_id] = *layout.id();
    }
  }
  return new_display_id;
}

void VirtualDisplayUtilLinux::RemoveDisplay(int64_t display_id) {
  if (!display_id_to_randr_id_.contains(display_id)) {
    LOG(ERROR) << "Invalid display_id. Missing mapping for " << display_id
               << " to randr ID.";
    return;
  }
  last_requested_layout_ = current_layout_;
  x11::RandRMonitorConfig::ScreenId randr_id =
      display_id_to_randr_id_[display_id];
  std::erase_if(last_requested_layout_.configs,
                [&](const x11::RandRMonitorConfig& layout) {
                  return layout.id() == randr_id;
                });
  randr_output_manager_->SetLayout(last_requested_layout_);
  StartWaiting();
}

void VirtualDisplayUtilLinux::ResetDisplays() {
  last_requested_layout_ = initial_layout_;
  randr_output_manager_->SetLayout(last_requested_layout_);
  StartWaiting();
  current_layout_ = randr_output_manager_->GetLayout();
}

void VirtualDisplayUtilLinux::OnDisplayAdded(
    const display::Display& new_display) {
  detected_added_display_ids_.push_back(new_display.id());
  OnDisplayAddedOrRemoved(new_display.id());
}

void VirtualDisplayUtilLinux::OnDisplaysRemoved(
    const display::Displays& removed_displays) {
  for (const auto& display : removed_displays) {
    base::EraseIf(
        display_id_to_randr_id_,
        [&](std::pair<DisplayId, x11::RandRMonitorConfig::ScreenId>& pair) {
          return pair.first == display.id();
        });
    base::EraseIf(detected_added_display_ids_,
                  [&](DisplayId& id) { return id == display.id(); });
    OnDisplayAddedOrRemoved(display.id());
  }
}

void VirtualDisplayUtilLinux::OnDisplayAddedOrRemoved(int64_t id) {
  if (!RequestedLayoutIsSet()) {
    return;
  }
  StopWaiting();
}

bool VirtualDisplayUtilLinux::RequestedLayoutIsSet() {
  // Checks that the number of virtual displays (delta of last requested layout
  // minus initial layout) is equal to the number of detected virtual displays.
  return last_requested_layout_.configs.size() -
             initial_layout_.configs.size() ==
         detected_added_display_ids_.size();
}

void VirtualDisplayUtilLinux::StartWaiting() {
  CHECK(!run_loop_);
  if (RequestedLayoutIsSet()) {
    return;
  }
  run_loop_ = std::make_unique<base::RunLoop>();
  run_loop_->Run();
  run_loop_.reset();
}
void VirtualDisplayUtilLinux::StopWaiting() {
  CHECK(run_loop_);
  run_loop_->Quit();
}

// static
std::unique_ptr<VirtualDisplayUtil> VirtualDisplayUtil::TryCreate(
    Screen* screen) {
  if (!VirtualDisplayUtilLinux::IsAPIAvailable()) {
    return nullptr;
  }
  return std::make_unique<VirtualDisplayUtilLinux>(screen);
}

}  // namespace display::test