Update X11 RANDR monitors on ConfigureNotify event.

According to the RANDR 1.5 spec:
https://cgit.freedesktop.org/xorg/proto/randrproto/tree/randrproto.txt

RRSetMonitor and RRDeleteMonitor requests will generate a
ConfigureNotify event on the root window of the screen.

They do not appear to generate any RRScreenChangeNotify or other
similar event. So this CL causes ScreenCapturerX11's monitor list to be
updated on ConfigureNotify events. It is needed, for example, when
using a commandline such as "xrandr --setmonitor ..." to add monitors.

Bug: None
Change-Id: I1948a8b96800721409472ac6264c935abe169ec3
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/230882
Commit-Queue: Joe Downing <joedow@chromium.org>
Reviewed-by: Joe Downing <joedow@chromium.org>
Cr-Commit-Position: refs/heads/main@{#34919}
diff --git a/modules/desktop_capture/linux/screen_capturer_x11.cc b/modules/desktop_capture/linux/screen_capturer_x11.cc
index 33e3326..ab1bd7f 100644
--- a/modules/desktop_capture/linux/screen_capturer_x11.cc
+++ b/modules/desktop_capture/linux/screen_capturer_x11.cc
@@ -205,6 +205,16 @@
         RTC_LOG(LS_INFO) << "XRandR monitor " << m.name << " rect updated.";
         selected_monitor_rect_ =
             DesktopRect::MakeXYWH(m.x, m.y, m.width, m.height);
+        const auto& pixel_buffer_rect = x_server_pixel_buffer_.window_rect();
+        if (!pixel_buffer_rect.ContainsRect(selected_monitor_rect_)) {
+          // This is never expected to happen, but crop the rectangle anyway
+          // just in case the server returns inconsistent information.
+          // CaptureScreen() expects `selected_monitor_rect_` to lie within
+          // the pixel-buffer's rectangle.
+          RTC_LOG(LS_WARNING)
+              << "Cropping selected monitor rect to fit the pixel-buffer.";
+          selected_monitor_rect_.IntersectWith(pixel_buffer_rect);
+        }
         return;
       }
     }
@@ -408,7 +418,12 @@
                          "configuration change.";
   }
 
-  if (!use_randr_) {
+  if (use_randr_) {
+    // Adding/removing RANDR monitors can generate a ConfigureNotify event
+    // without generating any RRScreenChangeNotify event. So it is important to
+    // update the monitors here even if the screen resolution hasn't changed.
+    UpdateMonitors();
+  } else {
     selected_monitor_rect_ =
         DesktopRect::MakeSize(x_server_pixel_buffer_.window_size());
   }