mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-12-02 09:48:14 -05:00
Show context menus, dialogs and web views in macOS screenshots and recordings
Recording frames are also spaced as documented when capture is slow, and a drop-down that has left the screen is no longer drawn into macOS frames.
This commit is contained in:
1 parent
ae5ccfbaa0
commit
cd76a0ffdd
8 files changed
+599
-110
No files matched your search
+69
-23
@@ -2104,9 +2104,10 @@ dialog natively; cross-origin frames other than plugin configuration UIs are lis
|
||||
the first since a tool's change, yet it shows the change settled, since slider moves reach the
|
||||
toolpaths before they are drawn and the capture first draws any extra frames the change asked for:
|
||||
a capture right after `set_view` shows the layers its slider shows and the legend laid out.
|
||||
- `window`: the main window's own pixels, never the screen, from `capture_native_window()`, with
|
||||
every visible 3D canvas composited in from its canvas capture, since window capture loses OpenGL
|
||||
content on several platforms.
|
||||
- `window`: the main window's client area from `capture_native_window()`: its own pixels or, where
|
||||
the capture reads the screen (X11, macOS 14.4 and later), our windows over it as well, never another
|
||||
application's, with every visible 3D canvas composited in from its canvas capture, since window
|
||||
capture loses OpenGL content on several platforms.
|
||||
- `dialog`: the topmost modal, captured like a window.
|
||||
- a widget's ref or locator: its top-level window captured like a window (a window that is not
|
||||
modal, such as an object's settings, has no other target) and cropped to the widget, or the
|
||||
@@ -2118,7 +2119,7 @@ When the capture may differ from the screen, the result carries `approximate: tr
|
||||
| Platform | Window capture | Approximate when |
|
||||
|---|---|---|
|
||||
| Windows | Windows Graphics Capture of the window, cropped to its client area; `PrintWindow(PW_CLIENTONLY \| PW_RENDERFULLCONTENT)` where that is unavailable | `PrintWindow` fails and the screen is copied instead |
|
||||
| macOS | `cacheDisplayInRect:toBitmapImageRep:` on the content view | always: web views may be blank |
|
||||
| macOS | ScreenCaptureKit of our windows on the window's display, cropped to its client area (14.4 and later); `cacheDisplayInRect:toBitmapImageRep:` on the content view where that is unavailable or the window is not wholly on its display | always with `cacheDisplayInRect`: web views may be blank |
|
||||
| Linux X11, Xvfb, XWayland | `XGetImage` of the top-level X window | part of it is off-screen or under another application's window |
|
||||
| Linux Wayland | `gtk_widget_draw()` of the top-level window's child, which leaves out the client-side decoration's shadow, after `gtk_container_check_resize()` runs any relayout still pending, without which it draws nothing | always: web views may be blank |
|
||||
|
||||
@@ -2135,6 +2136,39 @@ around a captured window; Windows 10 shows the border while a recording runs. A
|
||||
corners Windows 11 rounds read black. A window Windows Graphics Capture cannot read falls back to
|
||||
`PrintWindow` for the rest of the recording.
|
||||
|
||||
On macOS 14.4 and later the capture comes from the window server through ScreenCaptureKit, which lets
|
||||
a process capture its own windows without the Screen Recording permission
|
||||
(`getCurrentProcessShareableContentWithCompletionHandler:`). A filter of the window's display with
|
||||
OrcaSlicer's windows only gives what the screen shows of them in the client area, at the window's
|
||||
backing scale, in sRGB: the window, web views and 3D views included, and over it our dialogs, wx
|
||||
popups, AppKit's menus and tooltips, but no other application's window, so a covered window captures
|
||||
whole. The filter names the application rather than its windows, so a menu or tooltip that opens later
|
||||
is in it too. It leaves out the shown windows hidden from automation (the script runner), their wx
|
||||
popups, and AppKit's windows over them: AppKit does not say which window opened a menu or tooltip, so
|
||||
each of our windows that is not wx's goes with the topmost wx window below it that it overlaps, as on
|
||||
Windows. The window behind such a window shows through. `SCScreenshotManager` takes one image per
|
||||
capture; the UI thread waits up to 2 s for its completion handler, which runs on a ScreenCaptureKit
|
||||
queue, even while a menu is tracking. The wait is the window server composing the image: about 25–35 ms
|
||||
for OrcaSlicer's main window on a Retina display (6–7 ms for a plain window), so a recording reaches
|
||||
about 12 frames a second however high its `fps`. The window server shows
|
||||
what was last committed, so the capture first runs `displayIfNeeded` on our visible windows and flushes
|
||||
Core Animation; without that, a change made earlier in the same turn of the event loop is missing.
|
||||
Listing the content takes 10–20 ms, so a recording keeps it and a filter per display in
|
||||
its sessions, and fetches them again when the left-out windows change or the window moves to a display
|
||||
they do not list. The capture records the rectangles of our windows above the target
|
||||
(`CGWindowListCopyWindowInfo`) in `Capture::covered`, where a screenshot's 3D views are not composited.
|
||||
The pixels the window's rounded corners leave uncovered read black. The window server shows only the
|
||||
part of a window on its display, and ScreenCaptureKit clamps what it captures to it, so a window not
|
||||
wholly on its display is drawn from its views (`cacheDisplayInRect`), which leaves AppKit's windows out
|
||||
and may leave web views blank, as it is before macOS 14.4 or with an SDK older than 14.4, and while the
|
||||
window or the app is hidden or the window is on another Space. A failure or a timeout ends
|
||||
ScreenCaptureKit captures for a recording, which draws views from then on rather than wait at every
|
||||
frame; the third timeout in the run ends them for the run, as a macOS whose answers needed the waiting
|
||||
UI thread would never answer. ScreenCaptureKit is weakly linked, since the deployment target (12.0)
|
||||
predates it. A stream of the whole display (`SCStream`) would take the composing off the UI thread, but
|
||||
holds several display-sized buffers for the recording's life, and each frame it hands over may predate a
|
||||
change of the left-out windows or a move of the window it is cropped to.
|
||||
|
||||
On every platform, a canvas that can't be captured keeps whatever the window capture drew, and the
|
||||
result is approximate. A canvas frame that reads back black (`is_blank()`, a stray pixel aside) has
|
||||
not been drawn yet. This happens on Wayland for a moment after the canvas is first shown, while
|
||||
@@ -2159,15 +2193,16 @@ GTK 3's `gdkwindow-wayland.c`): GDK puts a popup's origin at its offset from the
|
||||
shows over, plus that content's origin, less where the window GTK placed it relative to is in that
|
||||
window. wx's menus are placed relative to the window `popup_menu()` was given, a submenu or a drop-down
|
||||
menu relative to the widget it is attached to, a tooltip relative to the window it shows over, and wx's
|
||||
own popups, which wx places with `gtk_window_move()`, at their offset from the content directly. Windows
|
||||
and macOS draw them in too, each where its screen position puts it on the window it shows over. wx's
|
||||
popups (`popups_of()`) show over the window they opened from: Windows reads one from the screen, where
|
||||
it shows topmost, and macOS draws its view as it draws a window's (`capture_native_popup()`). Windows
|
||||
also reads the system's popups from the screen (`capture_native_popups()`): menus, tooltips and the
|
||||
own popups, which wx places with `gtk_window_move()`, at their offset from the content directly. Windows,
|
||||
and macOS where it draws views, draw them in too, each where its screen position puts it on the window it
|
||||
shows over. wx's popups (`popups_of()`) show over the window they opened from: Windows reads one from the
|
||||
screen, where it shows topmost, and macOS draws its view as it draws a window's (`capture_native_popup()`),
|
||||
while its window is on the screen: wx can still report a drop-down shown after its window has left it.
|
||||
Windows also reads the system's popups from the screen (`capture_native_popups()`): menus, tooltips and the
|
||||
lists of native drop-downs are top-level windows of the thread that showed them, and each shows over the
|
||||
topmost of our windows below it that it overlaps (`EnumWindows` lists windows topmost first). AppKit
|
||||
draws macOS's menus and tooltips itself, and only reading the screen, which needs the Screen Recording
|
||||
permission, would capture them, so they are left out. The full-size PNG goes to `save_path` or `<datadir>/mcp/out/OrcaSlicer-screenshot-<timestamp>.png`. The image
|
||||
draws macOS's menus and tooltips in windows of its own, which only the window server shows, so drawing
|
||||
views leaves them out. The full-size PNG goes to `save_path` or `<datadir>/mcp/out/OrcaSlicer-screenshot-<timestamp>.png`. The image
|
||||
block is scaled to `max_dim` on the long edge (default 1280, clamped to 256–2000).
|
||||
`include_image: false` returns only the path.
|
||||
|
||||
@@ -2185,20 +2220,30 @@ size (fit to `max_dim`, rounded down to even numbers for 4:2:0), and a failure f
|
||||
any file exists. The `window` target is the main window as `screenshot` captures it, with the modal
|
||||
stack (`ModalTracker::stack()`, outermost first, so in stacking order) composited at each dialog's
|
||||
client offset, resampled to the main window's content scale off MSW. Modeless windows and native
|
||||
dialogs are left out: `wxTopLevelWindows` is creation order, not stacking order. Off X11, popups,
|
||||
menus and tooltips (on macOS, wx's popups only) are drawn last, over the dialogs, rather than into the window
|
||||
each shows over (`CaptureOptions::popups`), so a drop-down list reaching past its dialog is not cut
|
||||
off, and the pointer follows a wx popup to its window. On X11 the
|
||||
capture reads the screen, so it already shows our windows over the main window as they are, the
|
||||
script runner included when it covers it, and nothing more is composited (a reparenting window manager's
|
||||
frame is searched for our window inside it); the capture records the
|
||||
dialogs are left out: `wxTopLevelWindows` is creation order, not stacking order. Where the capture
|
||||
does not read the screen, popups, menus and tooltips (on macOS, wx's popups only) are drawn last, over
|
||||
the dialogs, rather than into the window each shows over (`CaptureOptions::popups`), so a drop-down list
|
||||
reaching past its dialog is not cut off, and the pointer follows a wx popup to its window. A capture that
|
||||
reads the screen (`Capture::from_screen`: X11, and macOS's window-server capture) already shows our
|
||||
windows over the main window as they are, modeless ones and native pickers included (a native message box,
|
||||
an in-process panel, should show too; OrcaSlicer raises none on demand on macOS to check), and nothing more
|
||||
is composited; the frame decides, so a macOS recording that falls back to drawing views composites them
|
||||
from then on. Popups reaching past the window are cut at its edge, as everywhere. X11 shows the script
|
||||
runner when it covers the window (a reparenting window manager's frame is searched for our window inside
|
||||
it); macOS leaves it out. The capture records the
|
||||
rectangles it drew another of our windows in (`Capture::covered`) and composites the 3D views
|
||||
everywhere else, so they are not pasted over those windows (X11 screenshots get this too). Wayland
|
||||
everywhere else, so they are not pasted over those windows (screenshots get this too). A macOS
|
||||
window-server capture shows the 3D views as presented (`Capture::canvases_shown`), and a recording keeps
|
||||
them so (`CaptureOptions::keep_shown_canvases`): it draws no canvas there. Wayland
|
||||
never tells the app where its windows are, so there `top_level_offset_in()` centres each dialog on the
|
||||
window GTK made it transient for, and that one on its own, as compositors place a dialog: KWin centres
|
||||
its frame, title bar included, so the video shows the dialog half a title bar higher than the screen
|
||||
does. The pointer follows the same placement (`drawn_shift()`). The result's `note` says which
|
||||
applies. The `canvas` target is `shown_canvas()`. A recording captures with
|
||||
does. The pointer follows the same placement (`drawn_shift()`). It follows wx's mouse events, which
|
||||
AppKit's menu tracking and native dialogs do not send, so it is not drawn moving inside a menu. The
|
||||
result's `note` is the last frame's: which of these applies, then what that frame's capture
|
||||
approximated, so a macOS recording that fell back to drawing views says so. `capture_frame()` stores it
|
||||
under the recorder's mutex, since `stop_recording` reports from another thread while a tick may be
|
||||
capturing. The `canvas` target is `shown_canvas()`. A recording captures with
|
||||
`CaptureOptions::hide_covering` off, so X11 never hides and re-shows the script runner at each frame.
|
||||
|
||||
The costly part is a 3D view: `render_and_capture()` draws a frame, after any extra frames a change
|
||||
@@ -2206,8 +2251,9 @@ asked for, and reads it back. A recording
|
||||
keeps each canvas's last capture with `GLCanvas3D::presented_frames()`, which counts the frames the
|
||||
canvas presented, and its size and the UI generation; while all three are unchanged, the frame on
|
||||
screen is the kept one, so the canvas is drawn only when it changed. Each tick measures its capture
|
||||
and the next comes after `max(1000/fps, 3 x capture time)`, so recording takes at most about a third
|
||||
of the UI thread wherever window capture is slow (macOS `cacheDisplayInRect`, X11 `XGetImage`). A
|
||||
and starts the next `max(1000/fps, 3 x capture time)` after its own start, so recording takes at most
|
||||
about a third of the UI thread wherever window capture is slow (macOS's window-server capture or view
|
||||
drawing, X11 `XGetImage`). A
|
||||
tick is skipped while the main window is minimized or being rebuilt, or no canvas is shown for
|
||||
`canvas`. A frame whose pixels equal the last queued one (`memcmp`), under the same overlay, is not
|
||||
queued, unless an overlay is animating (a ripple, a caption or the pointer fading) or a second has
|
||||
|
||||
@@ -1103,6 +1103,8 @@ elseif (APPLE)
|
||||
else()
|
||||
target_link_libraries(libslic3r_gui ${DISKARBITRATION_LIBRARY} "-framework Security")
|
||||
endif()
|
||||
# MCP window captures (ScreenCapture_mac.mm); weak, since macOS before 12.3 has no ScreenCaptureKit.
|
||||
target_link_libraries(libslic3r_gui "-weak_framework ScreenCaptureKit")
|
||||
endif()
|
||||
|
||||
if (SLIC3R_STATIC)
|
||||
|
||||
@@ -168,7 +168,7 @@ struct Recording
|
||||
uint64_t files_owner = 0;
|
||||
Clock::time_point started;
|
||||
int video_w = 0, video_h = 0;
|
||||
std::string note;
|
||||
std::string note; // written on the UI thread under the recorder's mutex
|
||||
std::atomic<bool> ending{false};
|
||||
std::atomic<uint64_t> skipped{0};
|
||||
std::atomic<uint64_t> captures{0}; // ticks that captured, and their UI-thread time
|
||||
@@ -185,6 +185,7 @@ struct Recording
|
||||
Clock::time_point last_queued;
|
||||
wxPoint origin; // the captured area's top left on the screen, wx coordinates
|
||||
double scale = 1.;
|
||||
bool from_screen = false; // the last frame's capture showed our windows over it (Capture::from_screen)
|
||||
struct CanvasFrame
|
||||
{
|
||||
wxImage image;
|
||||
@@ -254,8 +255,8 @@ McpRecorder::~McpRecorder()
|
||||
namespace {
|
||||
|
||||
// The captured area: the main window with the modal dialogs on it, or the 3D view shown. Sets where it
|
||||
// is on the screen, for the pointer. UI thread.
|
||||
bool capture_area(McpService& service, Recording& rec, const CaptureOptions& options, wxImage& out, std::string& err)
|
||||
// is on the screen, for the pointer, and `note` to what the capture approximated. UI thread.
|
||||
bool capture_area(McpService& service, Recording& rec, const CaptureOptions& options, wxImage& out, std::string& note, std::string& err)
|
||||
{
|
||||
if (service.suspended()) {
|
||||
err = "OrcaSlicer is rebuilding its window";
|
||||
@@ -276,8 +277,9 @@ bool capture_area(McpService& service, Recording& rec, const CaptureOptions& opt
|
||||
std::optional<Capture> cap = capture_canvas(*canvas, err, options);
|
||||
if (!cap)
|
||||
return false;
|
||||
out = cap->image;
|
||||
area = canvas->get_wxglcanvas();
|
||||
out = cap->image;
|
||||
area = canvas->get_wxglcanvas();
|
||||
rec.from_screen = false;
|
||||
} else {
|
||||
// Popups are drawn last, over the dialogs, rather than into the window each shows over, which would
|
||||
// cut off a drop-down list reaching past its dialog.
|
||||
@@ -286,14 +288,18 @@ bool capture_area(McpService& service, Recording& rec, const CaptureOptions& opt
|
||||
std::optional<Capture> cap = capture_window(*frame, err, window_options);
|
||||
if (!cap)
|
||||
return false;
|
||||
out = cap->image;
|
||||
if (capture_reads_screen()) {
|
||||
// The capture has whatever of ours is on top, modal dialogs and popups included.
|
||||
rec.note = "X11: the windows over the main window show as they are on screen";
|
||||
} else {
|
||||
if (!window_positions_known())
|
||||
rec.note = "Wayland: dialogs are drawn centred on the window they were opened from, where the compositor usually "
|
||||
"places them, since their place on the screen is unknown";
|
||||
out = cap->image;
|
||||
rec.from_screen = cap->from_screen;
|
||||
// How its windows were drawn, then what its capture approximated, as a macOS capture that fell back to
|
||||
// drawing views says.
|
||||
if (cap->from_screen)
|
||||
note = "the windows over the main window show as they are on screen";
|
||||
else if (!window_positions_known())
|
||||
note = "Wayland: dialogs are drawn centred on the window they were opened from, where the compositor usually "
|
||||
"places them, since their place on the screen is unknown";
|
||||
if (!cap->note.empty())
|
||||
note += (note.empty() ? "" : "; ") + cap->note;
|
||||
if (!cap->from_screen) {
|
||||
const double scale = physical_scale(frame);
|
||||
auto draw_in = [&](wxImage image, double own, const wxPoint& at) {
|
||||
if (std::abs(own - scale) > 1e-3)
|
||||
@@ -446,15 +452,17 @@ json McpRecorder::start(const RecordingOptions& options, uint64_t files_owner)
|
||||
rec->started = Clock::now();
|
||||
rec->windows = open_capture_sessions();
|
||||
CaptureOptions capture_options;
|
||||
capture_options.hide_covering = false;
|
||||
capture_options.sessions = rec->windows.get();
|
||||
capture_options.canvas_frame = [this, raw = rec.get()](GLCanvas3D& canvas, wxImage& out, std::string& err) {
|
||||
capture_options.hide_covering = false;
|
||||
capture_options.keep_shown_canvases = true;
|
||||
capture_options.sessions = rec->windows.get();
|
||||
capture_options.canvas_frame = [this, raw = rec.get()](GLCanvas3D& canvas, wxImage& out, std::string& err) {
|
||||
return canvas_frame(*raw, canvas, out, err);
|
||||
};
|
||||
wxImage first;
|
||||
std::string err;
|
||||
if (!capture_area(m_service, *rec, capture_options, first, err))
|
||||
std::string note, err;
|
||||
if (!capture_area(m_service, *rec, capture_options, first, note, err))
|
||||
throw ToolFailure("Cannot record: " + err);
|
||||
rec->note = note; // no other thread has it yet
|
||||
std::tie(rec->video_w, rec->video_h) = video_size(first.GetWidth(), first.GetHeight(), options.max_dim);
|
||||
|
||||
auto output = std::make_unique<MkvOutput>();
|
||||
@@ -539,8 +547,10 @@ void McpRecorder::tick(const std::shared_ptr<Recording>& rec)
|
||||
const auto spent = std::chrono::duration_cast<std::chrono::microseconds>(Clock::now() - now);
|
||||
++rec->captures;
|
||||
rec->capture_us += uint64_t(spent.count());
|
||||
// At most about a third of the UI thread, however slow the capture is here.
|
||||
m_timer->StartOnce(std::max(1000 / rec->options.fps, int(3 * spent.count() / 1000)));
|
||||
// Frames start max(1000/fps, 3 x capture) apart: at most about a third of the UI thread, however slow the
|
||||
// capture is here.
|
||||
const int spent_ms = int(spent.count() / 1000);
|
||||
m_timer->StartOnce(std::max({1, 1000 / rec->options.fps - spent_ms, 2 * spent_ms}));
|
||||
}
|
||||
|
||||
void McpRecorder::capture_frame(Recording& rec, Clock::time_point now, const wxImage* captured)
|
||||
@@ -550,14 +560,20 @@ void McpRecorder::capture_frame(Recording& rec, Clock::time_point now, const wxI
|
||||
image = *captured;
|
||||
} else {
|
||||
CaptureOptions options;
|
||||
options.hide_covering = false;
|
||||
options.canvas_frame = [this, &rec](GLCanvas3D& canvas, wxImage& out, std::string& err) { return canvas_frame(rec, canvas, out, err); };
|
||||
options.sessions = rec.windows.get();
|
||||
std::string err;
|
||||
if (!capture_area(m_service, rec, options, image, err)) {
|
||||
options.hide_covering = false;
|
||||
options.keep_shown_canvases = true;
|
||||
options.canvas_frame = [this, &rec](GLCanvas3D& canvas, wxImage& out, std::string& err) { return canvas_frame(rec, canvas, out, err); };
|
||||
options.sessions = rec.windows.get();
|
||||
std::string note, err;
|
||||
if (!capture_area(m_service, rec, options, image, note, err)) {
|
||||
++rec.skipped;
|
||||
return;
|
||||
}
|
||||
// The last frame's, which the result reports.
|
||||
if (note != rec.note) {
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
rec.note = std::move(note);
|
||||
}
|
||||
}
|
||||
|
||||
OverlaySnapshot overlay;
|
||||
@@ -715,9 +731,12 @@ json McpRecorder::report(Recording& rec) const
|
||||
const SinkResult r = rec.sink->result();
|
||||
const double seconds = r.end_ms / 1000.;
|
||||
std::string ended = r.ended;
|
||||
if (ended.empty()) {
|
||||
std::string note;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
ended = rec.reason;
|
||||
if (ended.empty())
|
||||
ended = rec.reason;
|
||||
note = rec.note;
|
||||
}
|
||||
json out{{"path", path_to_utf8(rec.options.path)},
|
||||
{"seconds", std::round(seconds * 10.) / 10.},
|
||||
@@ -735,8 +754,8 @@ json McpRecorder::report(Recording& rec) const
|
||||
{"ended", ended}};
|
||||
if (!r.error.empty())
|
||||
out["error"] = r.error;
|
||||
if (!rec.note.empty())
|
||||
out["note"] = rec.note;
|
||||
if (!note.empty())
|
||||
out["note"] = note;
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -891,7 +910,7 @@ wxPoint drawn_shift(wxWindow& window)
|
||||
|
||||
} // namespace
|
||||
|
||||
bool McpRecorder::shows(wxWindow* window) const
|
||||
bool McpRecorder::shows(const Recording& rec, wxWindow* window) const
|
||||
{
|
||||
if (hidden_from_automation(window))
|
||||
return false;
|
||||
@@ -900,7 +919,7 @@ bool McpRecorder::shows(wxWindow* window) const
|
||||
return false;
|
||||
if (top == wxGetApp().mainframe)
|
||||
return true;
|
||||
if (capture_reads_screen())
|
||||
if (rec.from_screen)
|
||||
return top->IsShownOnScreen();
|
||||
// A popup shows where the recording draws it (capture_popups()), over the window it belongs to.
|
||||
if (dynamic_cast<wxPopupWindow*>(top) != nullptr) {
|
||||
@@ -929,7 +948,7 @@ void McpRecorder::on_event(wxEvent& event)
|
||||
if (!rec || rec->ending || !rec->options.pointer)
|
||||
return;
|
||||
auto* window = wxDynamicCast(event.GetEventObject(), wxWindow);
|
||||
if (window == nullptr || !shows(window))
|
||||
if (window == nullptr || !shows(*rec, window))
|
||||
return;
|
||||
Input& in = *m_input;
|
||||
const Clock::time_point now = Clock::now();
|
||||
|
||||
@@ -143,7 +143,7 @@ private:
|
||||
// The capture's provider of 3D canvas frames: the one kept while the canvas has presented no other.
|
||||
bool canvas_frame(Recording& rec, GLCanvas3D& canvas, wxImage& out, std::string& err);
|
||||
void on_event(wxEvent& event);
|
||||
bool shows(wxWindow* window) const;
|
||||
bool shows(const Recording& rec, wxWindow* window) const;
|
||||
// A recording runs and is not ending.
|
||||
bool running() const;
|
||||
// Shows the tab bar's REC pill while running(), and hides it otherwise; not while the main window is
|
||||
|
||||
@@ -173,15 +173,6 @@ bool canvas_frame(GLCanvas3D& canvas, wxImage& out, std::string& err, const Capt
|
||||
|
||||
} // namespace
|
||||
|
||||
bool capture_reads_screen()
|
||||
{
|
||||
#if defined(__WXGTK__)
|
||||
return get_linux_display_backend() == LinuxDisplayBackend::X11;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool window_positions_known()
|
||||
{
|
||||
#if defined(__WXGTK__)
|
||||
@@ -254,8 +245,10 @@ std::optional<Capture> capture_window(wxTopLevelWindow& window, std::string& err
|
||||
return std::nullopt;
|
||||
}
|
||||
Capture c;
|
||||
if (!capture_native_window(window, options.sessions, c.image, c.approximate, c.note, c.covered, err))
|
||||
if (!capture_native_window(window, options.sessions, c, err))
|
||||
return std::nullopt;
|
||||
if (c.canvases_shown && options.keep_shown_canvases)
|
||||
return c; // the views as presented, and our popups over them where the capture reads the screen
|
||||
|
||||
// Composite every visible 3D canvas inside this window from an exact frame capture.
|
||||
std::vector<wxWindow*> captured;
|
||||
@@ -279,7 +272,7 @@ std::optional<Capture> capture_window(wxTopLevelWindow& window, std::string& err
|
||||
}
|
||||
|
||||
// Our popups over the window, over its 3D views too, as a context menu on the 3D view shows.
|
||||
if (options.popups) {
|
||||
if (options.popups && !c.from_screen) {
|
||||
const double scale = window.GetContentScaleFactor();
|
||||
for (const PopupCapture& p : capture_popups())
|
||||
if (p.owner == &window)
|
||||
@@ -287,7 +280,9 @@ std::optional<Capture> capture_window(wxTopLevelWindow& window, std::string& err
|
||||
}
|
||||
|
||||
// An OpenGL view with no frame capture: say so rather than return its area as the window
|
||||
// capture left it.
|
||||
// capture left it, unless the capture shows OpenGL views as presented.
|
||||
if (c.canvases_shown)
|
||||
return c;
|
||||
std::function<bool(wxWindow*)> other_gl = [&](wxWindow* w) {
|
||||
if (!w->IsShownOnScreen())
|
||||
return false;
|
||||
@@ -488,9 +483,12 @@ wxTopLevelWindow* wx_window_of(GtkWidget* window)
|
||||
|
||||
std::shared_ptr<CaptureSessions> open_capture_sessions() { return nullptr; }
|
||||
|
||||
bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* /*sessions*/, wxImage& out, bool& approximate, std::string& note,
|
||||
std::vector<wxRect>& covered, std::string& err)
|
||||
bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* /*sessions*/, Capture& capture, std::string& err)
|
||||
{
|
||||
wxImage& out = capture.image;
|
||||
bool& approximate = capture.approximate;
|
||||
std::string& note = capture.note;
|
||||
std::vector<wxRect>& covered = capture.covered;
|
||||
GtkWidget* widget = static_cast<GtkWidget*>(window.GetHandle());
|
||||
GdkWindow* gdkwin = widget != nullptr ? gtk_widget_get_window(widget) : nullptr;
|
||||
if (gdkwin == nullptr) {
|
||||
@@ -628,6 +626,7 @@ bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* /*sessions
|
||||
}
|
||||
XFree(stack);
|
||||
}
|
||||
capture.from_screen = true;
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -28,9 +28,16 @@ struct Capture
|
||||
// A 3D canvas came back entirely black. The view is never drawn black, so its surface was not
|
||||
// ready yet, as on Wayland for a moment after the canvas is first shown; capture again later.
|
||||
bool blank_canvas = false;
|
||||
// Where the native capture drew one of our own windows that covers the target (X11 only, which reads
|
||||
// the screen), in image pixels; the 3D canvases are not composited there.
|
||||
// The native capture is the screen's composition of our windows (X11, and macOS's window-server capture):
|
||||
// our dialogs, popups, menus and tooltips over the target show in it as they are on screen, so none is
|
||||
// composited in.
|
||||
bool from_screen = false;
|
||||
// Where such a capture drew one of our own windows that covers the target, in image pixels; the 3D
|
||||
// canvases are not composited there.
|
||||
std::vector<wxRect> covered;
|
||||
// The native capture shows the 3D views as they were last presented (macOS's window-server capture), so
|
||||
// a caller that keeps them (CaptureOptions::keep_shown_canvases) need not draw them.
|
||||
bool canvases_shown = false;
|
||||
};
|
||||
|
||||
// How a capture gets a 3D canvas's frame: render one and read it back, unless the caller keeps frames.
|
||||
@@ -39,11 +46,12 @@ using CanvasFrameProvider = std::function<bool(GLCanvas3D& canvas, wxImage& out,
|
||||
// Window captures kept open from one capture to the next, as a recording's frames are. On Windows a window
|
||||
// is read through Windows Graphics Capture, which takes what the screen shows without making the window
|
||||
// repaint, as PrintWindow does, visibly. Opening one waits for the next composited frame, and an open one has
|
||||
// the newest at hand.
|
||||
// the newest at hand. On macOS they keep what ScreenCaptureKit lists of our windows and displays, so that a
|
||||
// recording does not fetch the list again at every frame.
|
||||
class CaptureSessions;
|
||||
|
||||
// Null where there is nothing to keep open: other platforms, and Windows without Windows Graphics Capture.
|
||||
// UI thread, which must also release it.
|
||||
// Null where there is nothing to keep open: Linux, Windows without Windows Graphics Capture, and macOS before
|
||||
// 14.4. UI thread, which must also release it.
|
||||
std::shared_ptr<CaptureSessions> open_capture_sessions();
|
||||
|
||||
struct CaptureOptions
|
||||
@@ -55,9 +63,15 @@ struct CaptureOptions
|
||||
CanvasFrameProvider canvas_frame;
|
||||
// Null: the capture opens and closes its own.
|
||||
CaptureSessions* sessions = nullptr;
|
||||
// Draw in our popups shown over the window (capture_popups()). A recording draws them itself, over the
|
||||
// dialogs it draws in, so that a popup reaching past its dialog is not cut off.
|
||||
// Draw in our popups shown over the window (capture_popups()) where the capture does not show them
|
||||
// (Capture::from_screen). A recording draws them itself, over the dialogs it draws in, so that a popup
|
||||
// reaching past its dialog is not cut off.
|
||||
bool popups = true;
|
||||
// Leave the 3D views as a capture that shows them as presented has them (Capture::canvases_shown) rather
|
||||
// than drawing each and compositing it in. A recording keeps them, since a video shows what the screen
|
||||
// showed; a screenshot draws them, so that it shows a change the view has not presented yet and can tell
|
||||
// a view that is not drawn yet.
|
||||
bool keep_shown_canvases = false;
|
||||
};
|
||||
|
||||
// One of our popups as drawn: a wx popup, a menu, a drop-down list or a tooltip, with the top-level window it
|
||||
@@ -70,9 +84,9 @@ struct PopupCapture
|
||||
wxImage image;
|
||||
};
|
||||
|
||||
// Our popups shown now, bottom to top, which window captures leave out. Empty on X11, whose captures read them
|
||||
// from the screen. macOS has wx's popups only: AppKit draws its menus and tooltips itself, and only reading the
|
||||
// screen, which needs the Screen Recording permission, would capture them.
|
||||
// Our popups shown now, bottom to top, for the captures that leave them out (not Capture::from_screen). Empty on
|
||||
// X11, whose captures read them from the screen. On macOS, where its window-server capture is unavailable, wx's
|
||||
// popups only: AppKit draws its menus and tooltips in windows of its own, which only the window server shows.
|
||||
std::vector<PopupCapture> capture_popups();
|
||||
|
||||
// The OS parts of capture_popups() on Windows and macOS. capture_native_popup() draws one of wx's popups from its
|
||||
@@ -82,8 +96,6 @@ std::vector<PopupCapture> capture_popups();
|
||||
bool capture_native_popup(wxWindow& popup, wxImage& out);
|
||||
std::vector<PopupCapture> capture_native_popups();
|
||||
|
||||
// Whether a window capture reads the screen, and so shows our own windows over the target (X11).
|
||||
bool capture_reads_screen();
|
||||
// Whether the app knows where its top-level windows are on the screen (not on Wayland).
|
||||
bool window_positions_known();
|
||||
|
||||
@@ -93,16 +105,17 @@ bool is_blank(const wxImage& image);
|
||||
// The canvas exactly as presented: scene, toolpaths, toolbars and ImGui overlays. All platforms.
|
||||
std::optional<Capture> capture_canvas(GLCanvas3D& canvas, std::string& err, const CaptureOptions& options = {});
|
||||
|
||||
// A top-level window's own pixels (never other windows on the screen), with every visible 3D
|
||||
// canvas composited in from its canvas capture, since window capture APIs miss or mangle OpenGL
|
||||
// content on several platforms. Minimized windows fail.
|
||||
// A top-level window's client area: its own pixels, or where the capture reads the screen
|
||||
// (Capture::from_screen) our windows over it too, never other applications' windows, with every visible 3D
|
||||
// canvas composited in from its canvas capture, since window capture APIs miss or mangle OpenGL content on
|
||||
// several platforms. Minimized windows fail.
|
||||
std::optional<Capture> capture_window(wxTopLevelWindow& window, std::string& err, const CaptureOptions& options = {});
|
||||
|
||||
// The OS part of capture_window(): Windows Graphics Capture (or PrintWindow without it), macOS
|
||||
// cacheDisplayInRect, Linux X11 XGetImage or (Wayland) gtk_widget_draw. Implemented per platform. `covered`
|
||||
// gets the rectangles where it drew another of our windows (X11).
|
||||
bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* sessions, wxImage& out, bool& approximate, std::string& note,
|
||||
std::vector<wxRect>& covered, std::string& err);
|
||||
// The OS part of capture_window(): Windows Graphics Capture (or PrintWindow without it), macOS ScreenCaptureKit
|
||||
// (or cacheDisplayInRect without it), Linux X11 XGetImage or (Wayland) gtk_widget_draw. Implemented per
|
||||
// platform. Fills `out`'s image, its approximate flag and note, and, where it reads the screen, from_screen,
|
||||
// covered and canvases_shown.
|
||||
bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* sessions, Capture& out, std::string& err);
|
||||
|
||||
// Physical-pixel offset of `child`'s client area inside `top`'s client area.
|
||||
wxPoint client_offset_in(wxWindow& child, wxTopLevelWindow& top);
|
||||
|
||||
@@ -1,25 +1,55 @@
|
||||
// macOS window capture for automation screenshots (see ScreenCapture.hpp).
|
||||
// macOS window capture for automation screenshots and recordings (see ScreenCapture.hpp).
|
||||
|
||||
#include "ScreenCapture.hpp"
|
||||
|
||||
#include "UiInspector.hpp"
|
||||
|
||||
#include <wx/gdicmn.h>
|
||||
#include <wx/image.h>
|
||||
#include <wx/toplevel.h>
|
||||
#include <wx/window.h>
|
||||
|
||||
#include <boost/log/trivial.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// ScreenCaptureKit lets a process capture its own windows without the Screen Recording permission from macOS
|
||||
// 14.4 on; an older SDK has no such call, and its builds draw views only.
|
||||
#if defined(MAC_OS_VERSION_14_4) && __MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_4
|
||||
#import <CoreVideo/CoreVideo.h>
|
||||
#import <ScreenCaptureKit/ScreenCaptureKit.h>
|
||||
#define ORCA_SCREEN_CAPTURE_KIT 1
|
||||
#endif
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
std::shared_ptr<CaptureSessions> open_capture_sessions() { return nullptr; }
|
||||
|
||||
namespace {
|
||||
|
||||
// The view drawn into a bitmap, which needs no screen-recording permission and works for covered windows.
|
||||
// Layer-backed OpenGL and web views don't draw this way.
|
||||
// A top-level window's NSWindow: wx's handle for one is its content view.
|
||||
NSWindow* ns_window_of(wxWindow& window)
|
||||
{
|
||||
NSView* view = (NSView*) window.GetHandle();
|
||||
return view != nil ? [view window] : nil;
|
||||
}
|
||||
|
||||
// The view drawn into a bitmap, which needs no permission and works for covered windows and windows on another
|
||||
// Space. Layer-backed OpenGL and web views don't draw this way.
|
||||
bool draw_view(NSView* view, wxImage& out, std::string& err)
|
||||
{
|
||||
if (view == nil) {
|
||||
@@ -56,25 +86,406 @@ bool draw_view(NSView* view, wxImage& out, std::string& err)
|
||||
|
||||
} // namespace
|
||||
|
||||
bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* /*sessions*/, wxImage& out, bool& approximate, std::string& note,
|
||||
std::vector<wxRect>& /*covered*/, std::string& err)
|
||||
#ifdef ORCA_SCREEN_CAPTURE_KIT
|
||||
|
||||
namespace {
|
||||
|
||||
// How long the UI thread waits for the window server; a first capture takes about 60 ms.
|
||||
constexpr std::chrono::seconds kAnswerWait{2};
|
||||
|
||||
// Why the window server does not capture for the rest of the run: it did not answer in time three times, as it
|
||||
// would not if its answers needed the UI thread, which waits for them. Waiting again at every capture would hold
|
||||
// the UI thread that long each time. UI thread.
|
||||
std::string& unanswered()
|
||||
{
|
||||
// The 3D canvases are composited from their own frames afterwards; web views may stay blank.
|
||||
if (!draw_view((NSView*) window.GetHandle(), out, err))
|
||||
static std::string reason;
|
||||
return reason;
|
||||
}
|
||||
|
||||
// What a ScreenCaptureKit call hands its completion handler, which runs on one of ScreenCaptureKit's queues.
|
||||
// The block holds it too, so an answer that comes after the UI thread stopped waiting has somewhere to go.
|
||||
struct Answer
|
||||
{
|
||||
std::mutex mutex;
|
||||
std::condition_variable arrived;
|
||||
bool done = false;
|
||||
id object = nil; // retained
|
||||
CGImageRef image = nullptr; // retained
|
||||
std::string error;
|
||||
|
||||
~Answer()
|
||||
{
|
||||
[object release];
|
||||
CGImageRelease(image);
|
||||
}
|
||||
void set(id o, CGImageRef i, NSError* e)
|
||||
{
|
||||
@autoreleasepool {
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
object = [o retain];
|
||||
image = i != nullptr ? CGImageRetain(i) : nullptr;
|
||||
if (e != nil)
|
||||
error = [[e localizedDescription] UTF8String] ?: "unknown error";
|
||||
done = true;
|
||||
}
|
||||
arrived.notify_all();
|
||||
}
|
||||
// False, with `err`, when no answer came in time; the third time turns window-server capture off for the run.
|
||||
bool wait(const char* what, std::string& err)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
if (arrived.wait_for(lock, kAnswerWait, [this] { return done; }))
|
||||
return true;
|
||||
static int timeouts = 0;
|
||||
err = std::string(what) + " did not answer in time";
|
||||
if (++timeouts >= 3)
|
||||
unanswered() = err;
|
||||
BOOST_LOG_TRIVIAL(warning) << "MCP capture: " << err << (timeouts >= 3 ? "; drawing views for the rest of the run" : "");
|
||||
return false;
|
||||
approximate = true;
|
||||
note = "drawn from the view hierarchy; web views may be blank";
|
||||
}
|
||||
};
|
||||
|
||||
// The pixels of `image` as sRGB, or false when they cannot be read. ScreenCaptureKit hands BGRA, premultiplied,
|
||||
// which is read as it is; a pixel no window covers, as at a window's rounded corners, reads black.
|
||||
bool read_image(CGImageRef image, wxImage& out)
|
||||
{
|
||||
const size_t w = CGImageGetWidth(image), h = CGImageGetHeight(image);
|
||||
const CGBitmapInfo info = CGImageGetBitmapInfo(image);
|
||||
const uint32_t alpha = info & kCGBitmapAlphaInfoMask;
|
||||
CFDataRef data = nullptr;
|
||||
size_t bpr = 0;
|
||||
if (CGImageGetBitsPerPixel(image) == 32 && (info & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Little &&
|
||||
(alpha == kCGImageAlphaPremultipliedFirst || alpha == kCGImageAlphaNoneSkipFirst)) {
|
||||
data = CGDataProviderCopyData(CGImageGetDataProvider(image));
|
||||
bpr = CGImageGetBytesPerRow(image);
|
||||
} else {
|
||||
// Another layout: drawn into one of ours.
|
||||
CFMutableDataRef pixels = CFDataCreateMutable(nullptr, CFIndex(w * h * 4));
|
||||
if (pixels == nullptr)
|
||||
return false;
|
||||
CFDataSetLength(pixels, CFIndex(w * h * 4));
|
||||
CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
|
||||
CGContextRef ctx = CGBitmapContextCreate(CFDataGetMutableBytePtr(pixels), w, h, 8, w * 4, space,
|
||||
kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
|
||||
CGColorSpaceRelease(space);
|
||||
if (ctx == nullptr) {
|
||||
CFRelease(pixels);
|
||||
return false;
|
||||
}
|
||||
CGContextDrawImage(ctx, CGRectMake(0, 0, CGFloat(w), CGFloat(h)), image);
|
||||
CGContextRelease(ctx);
|
||||
data = pixels;
|
||||
bpr = w * 4;
|
||||
}
|
||||
if (data == nullptr)
|
||||
return false;
|
||||
if (w == 0 || h == 0 || bpr < w * 4 || size_t(CFDataGetLength(data)) < bpr * (h - 1) + w * 4) {
|
||||
CFRelease(data);
|
||||
return false;
|
||||
}
|
||||
if (!out.Create(int(w), int(h), false)) {
|
||||
CFRelease(data);
|
||||
return false;
|
||||
}
|
||||
const unsigned char* base = CFDataGetBytePtr(data);
|
||||
unsigned char* rgb = out.GetData();
|
||||
for (size_t y = 0; y < h; ++y) {
|
||||
const unsigned char* bgra = base + y * bpr;
|
||||
for (size_t x = 0; x < w; ++x, bgra += 4, rgb += 3) {
|
||||
rgb[0] = bgra[2];
|
||||
rgb[1] = bgra[1];
|
||||
rgb[2] = bgra[0];
|
||||
}
|
||||
}
|
||||
CFRelease(data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// A wx popup's content view is all of it: wx makes it a borderless window.
|
||||
bool capture_native_popup(wxWindow& popup, wxImage& out)
|
||||
// The window numbers of what a capture leaves out, sorted: our shown windows that automation leaves alone (the
|
||||
// script runner), their wx popups, and the menus and tooltips AppKit shows over them. AppKit does not say which
|
||||
// window a menu or tooltip opened from; it shows over that one, so each of our windows that is not wx's goes
|
||||
// with the topmost of wx's windows below it that it overlaps, as on Windows.
|
||||
std::vector<NSInteger> excluded_windows()
|
||||
{
|
||||
std::string err;
|
||||
return draw_view((NSView*) popup.GetHandle(), out, err);
|
||||
std::map<NSInteger, bool> wx; // wx's shown windows and popups, and whether automation leaves them alone
|
||||
bool any = false;
|
||||
auto add = [&](wxWindow& w, bool hidden) {
|
||||
if (NSWindow* window = ns_window_of(w); window != nil && [window windowNumber] > 0)
|
||||
wx[[window windowNumber]] = hidden;
|
||||
};
|
||||
for (wxWindow* top : wxTopLevelWindows) {
|
||||
if (!top->IsShown())
|
||||
continue;
|
||||
const bool hidden = hidden_from_automation(top);
|
||||
any = any || hidden;
|
||||
add(*top, hidden);
|
||||
for (wxWindow* popup : popups_of(top))
|
||||
add(*popup, hidden);
|
||||
}
|
||||
std::vector<NSInteger> out;
|
||||
if (!any)
|
||||
return out;
|
||||
struct Shown
|
||||
{
|
||||
NSInteger number;
|
||||
CGRect bounds;
|
||||
};
|
||||
std::vector<Shown> ours; // topmost first
|
||||
if (CFArrayRef list = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID)) {
|
||||
const pid_t self = getpid();
|
||||
for (NSDictionary* info in (NSArray*) list) {
|
||||
CGRect r;
|
||||
if ([info[(id) kCGWindowOwnerPID] intValue] == self &&
|
||||
CGRectMakeWithDictionaryRepresentation((CFDictionaryRef) info[(id) kCGWindowBounds], &r))
|
||||
ours.push_back({NSInteger([info[(id) kCGWindowNumber] integerValue]), r});
|
||||
}
|
||||
CFRelease(list);
|
||||
}
|
||||
for (std::size_t i = 0; i < ours.size(); ++i) {
|
||||
if (const auto it = wx.find(ours[i].number); it != wx.end()) {
|
||||
if (it->second)
|
||||
out.push_back(ours[i].number);
|
||||
continue;
|
||||
}
|
||||
for (std::size_t j = i + 1; j < ours.size(); ++j)
|
||||
if (const auto below = wx.find(ours[j].number); below != wx.end() && CGRectIntersectsRect(ours[i].bounds, ours[j].bounds)) {
|
||||
if (below->second)
|
||||
out.push_back(ours[i].number);
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
// AppKit draws its menus and tooltips itself; only reading the screen would capture them.
|
||||
} // namespace
|
||||
|
||||
// What a capture through ScreenCaptureKit keeps from one frame to the next: the process's shareable content
|
||||
// and a filter per display. Both are fetched again when the excluded windows change or a window shows on a
|
||||
// display the content does not list. UI thread.
|
||||
class CaptureSessions
|
||||
{
|
||||
public:
|
||||
CaptureSessions() = default;
|
||||
CaptureSessions(const CaptureSessions&) = delete;
|
||||
CaptureSessions& operator=(const CaptureSessions&) = delete;
|
||||
~CaptureSessions() { reset(); }
|
||||
|
||||
// The window's client area as the screen shows our windows there, or false with `err`. A failure of
|
||||
// ScreenCaptureKit itself is kept, so a recording does not ask it again at every frame.
|
||||
API_AVAILABLE(macos(14.4)) bool capture(wxTopLevelWindow& window, Capture& out, std::string& err);
|
||||
|
||||
private:
|
||||
API_AVAILABLE(macos(14.4)) SCContentFilter* filter_for(CGDirectDisplayID display, std::string& err);
|
||||
void reset()
|
||||
{
|
||||
[m_content release];
|
||||
m_content = nil;
|
||||
for (auto& [display, filter] : m_filters)
|
||||
[filter release];
|
||||
m_filters.clear();
|
||||
}
|
||||
|
||||
id m_content = nil; // SCShareableContent, retained
|
||||
std::vector<NSInteger> m_excluded; // the windows the filters leave out
|
||||
std::map<CGDirectDisplayID, id> m_filters; // SCContentFilter, retained
|
||||
std::string m_failure;
|
||||
};
|
||||
|
||||
SCContentFilter* CaptureSessions::filter_for(CGDirectDisplayID display, std::string& err)
|
||||
{
|
||||
std::vector<NSInteger> excluded = excluded_windows();
|
||||
auto listed = [&] {
|
||||
for (SCDisplay* d in [(SCShareableContent*) m_content displays])
|
||||
if ([d displayID] == display)
|
||||
return d;
|
||||
return (SCDisplay*) nil;
|
||||
};
|
||||
if (m_content == nil || excluded != m_excluded || listed() == nil) {
|
||||
reset();
|
||||
auto answer = std::make_shared<Answer>();
|
||||
[SCShareableContent getCurrentProcessShareableContentWithCompletionHandler:^(SCShareableContent* content, NSError* error) {
|
||||
answer->set(content, nullptr, error);
|
||||
}];
|
||||
if (!answer->wait("ScreenCaptureKit's list of windows", err))
|
||||
return nil;
|
||||
std::lock_guard<std::mutex> lock(answer->mutex);
|
||||
if (answer->object == nil) {
|
||||
err = "ScreenCaptureKit did not list the windows: " + answer->error;
|
||||
return nil;
|
||||
}
|
||||
m_content = [answer->object retain];
|
||||
m_excluded = std::move(excluded);
|
||||
}
|
||||
if (auto it = m_filters.find(display); it != m_filters.end())
|
||||
return (SCContentFilter*) it->second;
|
||||
SCShareableContent* content = (SCShareableContent*) m_content;
|
||||
SCDisplay* shown = listed();
|
||||
SCRunningApplication* self = nil;
|
||||
for (SCRunningApplication* app in [content applications])
|
||||
if ([app processID] == getpid())
|
||||
self = app;
|
||||
if (shown == nil || self == nil) {
|
||||
err = shown == nil ? "ScreenCaptureKit does not list the window's display" : "ScreenCaptureKit does not list OrcaSlicer";
|
||||
return nil;
|
||||
}
|
||||
NSMutableArray<SCWindow*>* except = [NSMutableArray array];
|
||||
for (SCWindow* w in [content windows])
|
||||
if (std::binary_search(m_excluded.begin(), m_excluded.end(), NSInteger([w windowID])))
|
||||
[except addObject:w];
|
||||
SCContentFilter* filter = [[SCContentFilter alloc] initWithDisplay:shown includingApplications:@[self] exceptingWindows:except];
|
||||
m_filters[display] = filter; // the retain alloc gave
|
||||
return filter;
|
||||
}
|
||||
|
||||
bool CaptureSessions::capture(wxTopLevelWindow& window, Capture& out, std::string& err)
|
||||
{
|
||||
if (!unanswered().empty() || !m_failure.empty()) {
|
||||
err = !unanswered().empty() ? unanswered() : m_failure;
|
||||
return false;
|
||||
}
|
||||
// The display the window shows on is its screen, the one with most of it.
|
||||
NSWindow* ns = ns_window_of(window);
|
||||
NSScreen* screen = ns != nil ? [ns screen] : nil;
|
||||
if (screen == nil || ![ns isVisible] || [NSApp isHidden] || ![ns isOnActiveSpace]) {
|
||||
err = "the window is not on the screen";
|
||||
return false;
|
||||
}
|
||||
// wx's screen coordinates on macOS are the global display space's points, from the top left of the main
|
||||
// display, as CoreGraphics has them.
|
||||
const wxPoint origin = window.ClientToScreen(wxPoint(0, 0));
|
||||
const wxSize size = window.GetClientSize();
|
||||
if (size.x <= 0 || size.y <= 0) {
|
||||
err = "the window has no client area";
|
||||
return false;
|
||||
}
|
||||
// The window server shows only the part of a window on its display (and ScreenCaptureKit clamps the source
|
||||
// to it), where the views show all of it, so a window not wholly on its display is drawn from its views.
|
||||
const CGRect client = CGRectMake(origin.x, origin.y, size.x, size.y);
|
||||
const CGDirectDisplayID display = [[[screen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue];
|
||||
const CGRect bounds = CGDisplayBounds(display);
|
||||
if (!CGRectContainsRect(bounds, client)) {
|
||||
err = "part of the window is off its display";
|
||||
return false;
|
||||
}
|
||||
|
||||
// The window server shows what was last committed, while the views may have changed since in this turn of
|
||||
// the event loop: they are drawn and committed first.
|
||||
for (NSWindow* w in [NSApp windows])
|
||||
if ([w isVisible])
|
||||
[w displayIfNeeded];
|
||||
[CATransaction flush];
|
||||
|
||||
SCContentFilter* filter = filter_for(display, err);
|
||||
if (filter == nil) {
|
||||
m_failure = err;
|
||||
return false;
|
||||
}
|
||||
// The window's scale is its screen's, which ScreenCaptureKit captures at with the best resolution.
|
||||
const double scale = [ns backingScaleFactor];
|
||||
const size_t w = size_t(std::lround(size.x * scale)), h = size_t(std::lround(size.y * scale));
|
||||
SCStreamConfiguration* config = [[[SCStreamConfiguration alloc] init] autorelease];
|
||||
[config setSourceRect:CGRectOffset(client, -bounds.origin.x, -bounds.origin.y)];
|
||||
[config setWidth:w];
|
||||
[config setHeight:h];
|
||||
[config setCaptureResolution:SCCaptureResolutionBest];
|
||||
[config setPixelFormat:kCVPixelFormatType_32BGRA];
|
||||
[config setColorSpaceName:kCGColorSpaceSRGB];
|
||||
[config setShowsCursor:NO]; // a recording draws its own pointer
|
||||
auto answer = std::make_shared<Answer>();
|
||||
[SCScreenshotManager captureImageWithFilter:filter configuration:config completionHandler:^(CGImageRef captured, NSError* error) {
|
||||
answer->set(nil, captured, error);
|
||||
}];
|
||||
if (!answer->wait("the window server", err)) {
|
||||
m_failure = err;
|
||||
return false;
|
||||
}
|
||||
bool read = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(answer->mutex);
|
||||
if (answer->image == nullptr)
|
||||
err = "ScreenCaptureKit failed: " + answer->error;
|
||||
else if (CGImageGetWidth(answer->image) != w || CGImageGetHeight(answer->image) != h)
|
||||
err = "ScreenCaptureKit returned an image of another size";
|
||||
else if (!(read = read_image(answer->image, out.image)))
|
||||
err = "ScreenCaptureKit's image could not be read";
|
||||
}
|
||||
if (!read) {
|
||||
// A failure is kept for the session: a recording draws views from then on rather than ask at every frame.
|
||||
m_failure = err;
|
||||
BOOST_LOG_TRIVIAL(warning) << "MCP capture: " << err << "; drawing views instead";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Our windows over it, where a 3D view composited in must not go. The excluded ones are not drawn.
|
||||
if (CFArrayRef above = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenAboveWindow | kCGWindowListExcludeDesktopElements,
|
||||
CGWindowID([ns windowNumber]))) {
|
||||
const pid_t self = getpid();
|
||||
for (NSDictionary* info in (NSArray*) above) {
|
||||
CGRect r;
|
||||
if ([info[(id) kCGWindowOwnerPID] intValue] != self || [info[(id) kCGWindowAlpha] doubleValue] <= 0. ||
|
||||
std::binary_search(m_excluded.begin(), m_excluded.end(), NSInteger([info[(id) kCGWindowNumber] integerValue])) ||
|
||||
!CGRectMakeWithDictionaryRepresentation((CFDictionaryRef) info[(id) kCGWindowBounds], &r))
|
||||
continue;
|
||||
r = CGRectIntersection(r, client);
|
||||
if (CGRectIsEmpty(r))
|
||||
continue;
|
||||
const int x0 = int(std::floor((r.origin.x - client.origin.x) * scale)), y0 = int(std::floor((r.origin.y - client.origin.y) * scale));
|
||||
const int x1 = int(std::ceil((CGRectGetMaxX(r) - client.origin.x) * scale)), y1 = int(std::ceil((CGRectGetMaxY(r) - client.origin.y) * scale));
|
||||
out.covered.emplace_back(x0, y0, x1 - x0, y1 - y0);
|
||||
}
|
||||
CFRelease(above);
|
||||
}
|
||||
out.from_screen = true;
|
||||
out.canvases_shown = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif // ORCA_SCREEN_CAPTURE_KIT
|
||||
|
||||
std::shared_ptr<CaptureSessions> open_capture_sessions()
|
||||
{
|
||||
#ifdef ORCA_SCREEN_CAPTURE_KIT
|
||||
if (@available(macOS 14.4, *))
|
||||
return std::make_shared<CaptureSessions>();
|
||||
#endif
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* sessions, Capture& out, std::string& err)
|
||||
{
|
||||
std::string screen_err;
|
||||
#ifdef ORCA_SCREEN_CAPTURE_KIT
|
||||
if (@available(macOS 14.4, *)) {
|
||||
std::shared_ptr<CaptureSessions> own;
|
||||
if (sessions == nullptr) {
|
||||
own = std::make_shared<CaptureSessions>();
|
||||
sessions = own.get();
|
||||
}
|
||||
if (sessions->capture(window, out, screen_err))
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
// The 3D canvases are composited from their own frames afterwards; web views may stay blank.
|
||||
if (!draw_view((NSView*) window.GetHandle(), out.image, err))
|
||||
return false;
|
||||
out.approximate = true;
|
||||
out.note = "drawn from the view hierarchy; web views may be blank";
|
||||
if (!screen_err.empty())
|
||||
out.note += " (" + screen_err + ")";
|
||||
return true;
|
||||
}
|
||||
|
||||
// A wx popup's content view is all of it: wx makes it a borderless window. A popup wx still reports shown can
|
||||
// have its window ordered out, off the screen; only one whose window is on the screen is drawn.
|
||||
bool capture_native_popup(wxWindow& popup, wxImage& out)
|
||||
{
|
||||
NSView* view = (NSView*) popup.GetHandle();
|
||||
std::string err;
|
||||
return view != nil && [[view window] isVisible] && draw_view(view, out, err);
|
||||
}
|
||||
|
||||
// AppKit draws its menus and tooltips itself; they show only in a capture from the window server.
|
||||
std::vector<PopupCapture> capture_native_popups() { return {}; }
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -454,8 +454,7 @@ std::shared_ptr<CaptureSessions> open_capture_sessions()
|
||||
}
|
||||
}
|
||||
|
||||
bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* sessions, wxImage& out, bool& approximate, std::string& note,
|
||||
std::vector<wxRect>& /*covered*/, std::string& err)
|
||||
bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* sessions, Capture& out, std::string& err)
|
||||
{
|
||||
HWND hwnd = static_cast<HWND>(window.GetHWND());
|
||||
if (hwnd == nullptr) {
|
||||
@@ -469,12 +468,12 @@ bool capture_native_window(wxTopLevelWindow& window, CaptureSessions* sessions,
|
||||
}
|
||||
std::string wgc_err;
|
||||
if (sessions != nullptr) {
|
||||
if (sessions->capture(hwnd, out, wgc_err))
|
||||
if (sessions->capture(hwnd, out.image, wgc_err))
|
||||
return true;
|
||||
if (!wgc_err.empty())
|
||||
BOOST_LOG_TRIVIAL(warning) << "MCP capture: " << wgc_err << "; using PrintWindow";
|
||||
}
|
||||
return print_window(hwnd, out, approximate, note, err);
|
||||
return print_window(hwnd, out.image, out.approximate, out.note, err);
|
||||
}
|
||||
|
||||
bool capture_native_popup(wxWindow& popup, wxImage& out)
|
||||
|
||||
Reference in new issue
Block a user