FreeRDP
Loading...
Searching...
No Matches
SDL3/sdl_freerdp.cpp
1
20#include <iostream>
21#include <memory>
22#include <mutex>
23
24#include <freerdp/config.h>
25
26#include <cerrno>
27#include <cstdio>
28#include <cstring>
29
30#include <freerdp/constants.h>
31#include <freerdp/freerdp.h>
32#include <freerdp/gdi/gdi.h>
33#include <freerdp/streamdump.h>
34#include <freerdp/utils/signal.h>
35
36#include <freerdp/channels/channels.h>
37#include <freerdp/client/channels.h>
38#include <freerdp/client/cliprdr.h>
39#include <freerdp/client/cmdline.h>
40#include <freerdp/client/file.h>
41
42#include <freerdp/log.h>
43#include <winpr/assert.h>
44#include <winpr/config.h>
45#include <winpr/crt.h>
46#include <winpr/synch.h>
47
48#include <SDL3/SDL.h>
49#if !defined(__MINGW32__)
50#include <SDL3/SDL_main.h>
51#endif
52#include <SDL3/SDL_hints.h>
53#include <SDL3/SDL_oldnames.h>
54#include <SDL3/SDL_video.h>
55
56#include <sdl_config.hpp>
57
58#include "dialogs/sdl_connection_dialog_hider.hpp"
59#include "dialogs/sdl_dialogs.hpp"
60#include "scoped_guard.hpp"
61#include "sdl_channels.hpp"
62#include "sdl_freerdp.hpp"
63#include "sdl_context.hpp"
64#include "sdl_monitor.hpp"
65#include "sdl_pointer.hpp"
66#include "sdl_prefs.hpp"
67#include "sdl_utils.hpp"
68
69#if defined(_WIN32)
70#define SDL_TAG CLIENT_TAG("SDL")
71#endif
72
73class ErrorMsg : public std::exception
74{
75 public:
76 ErrorMsg(int rc, Uint32 type, const std::string& msg,
77 const std::string& sdlError = SDL_GetError());
78
79 [[nodiscard]] int rc() const;
80 [[nodiscard]] const char* what() const noexcept override;
81
82 private:
83 int _rc;
84 Uint32 _type;
85 std::string _msg;
86 std::string _sdlError;
87 std::string _buffer;
88};
89const char* ErrorMsg::what() const noexcept
90{
91 return _buffer.c_str();
92}
93
94int ErrorMsg::rc() const
95{
96 return _rc;
97}
98
99ErrorMsg::ErrorMsg(int rc, Uint32 type, const std::string& msg, const std::string& sdlError)
100 : _rc(rc), _type(type), _msg(msg), _sdlError(sdlError)
101{
102 std::stringstream ss;
103 ss << _msg << " {" << sdl::utils::toString(_type) << "}{SDL:" << sdlError << "}";
104 _buffer = ss.str();
105}
106
107static void sdl_term_handler([[maybe_unused]] int signum, [[maybe_unused]] const char* signame,
108 [[maybe_unused]] void* context)
109{
110 std::ignore = sdl_push_quit();
111}
112
113[[nodiscard]] static int sdl_run(SdlContext* sdl)
114{
115 int rc = -1;
116 WINPR_ASSERT(sdl);
117
118 try
119 {
120 while (!sdl->shallAbort())
121 {
122 SDL_Event windowEvent = {};
123 while (!sdl->shallAbort() && SDL_WaitEventTimeout(nullptr, 1000))
124 {
125 /* Only poll standard SDL events and SDL_EVENT_USERS meant to create
126 * dialogs. do not process the dialog return value events here.
127 */
128 const int prc = SDL_PeepEvents(&windowEvent, 1, SDL_GETEVENT, SDL_EVENT_FIRST,
129 SDL_EVENT_USER_RETRY_DIALOG);
130 if (prc < 0)
131 {
132 if (sdl_log_error(prc, sdl->getWLog(), "SDL_PeepEvents"))
133 continue;
134 }
135
136#if defined(WITH_DEBUG_SDL_EVENTS)
137 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "got event %s [0x%08" PRIx32 "]",
138 sdl::utils::toString(windowEvent.type).c_str(), windowEvent.type);
139#endif
140 if (sdl->shallAbort(true))
141 continue;
142
143 if (sdl->getDialog().handleEvent(windowEvent))
144 continue;
145
146 if (!sdl->handleEvent(windowEvent))
147 throw ErrorMsg{ -1, windowEvent.type, "sdl->handleEvent" };
148
149 switch (windowEvent.type)
150 {
151 case SDL_EVENT_QUIT:
152 std::ignore = freerdp_abort_connect_context(sdl->context());
153 break;
154 case SDL_EVENT_USER_CERT_DIALOG:
155 {
156 SDLConnectionDialogHider hider(sdl);
157 auto title = static_cast<const char*>(windowEvent.user.data1);
158 auto msg = static_cast<const char*>(windowEvent.user.data2);
159 if (!sdl_cert_dialog_show(title, msg))
160 throw ErrorMsg{ -1, windowEvent.type, "sdl_cert_dialog_show" };
161 }
162 break;
163 case SDL_EVENT_USER_SHOW_DIALOG:
164 {
165 SDLConnectionDialogHider hider(sdl);
166 auto title = static_cast<const char*>(windowEvent.user.data1);
167 auto msg = static_cast<const char*>(windowEvent.user.data2);
168 if (!sdl_message_dialog_show(title, msg, windowEvent.user.code))
169 throw ErrorMsg{ -1, windowEvent.type, "sdl_message_dialog_show" };
170 }
171 break;
172 case SDL_EVENT_USER_SCARD_DIALOG:
173 {
174 SDLConnectionDialogHider hider(sdl);
175 auto title = static_cast<const char*>(windowEvent.user.data1);
176 auto msg = static_cast<const char**>(windowEvent.user.data2);
177 if (!sdl_scard_dialog_show(title, windowEvent.user.code, msg))
178 throw ErrorMsg{ -1, windowEvent.type, "sdl_scard_dialog_show" };
179 }
180 break;
181 case SDL_EVENT_USER_AUTH_DIALOG:
182 {
183 SDLConnectionDialogHider hider(sdl);
184 if (!sdl_auth_dialog_show(
185 reinterpret_cast<const SDL_UserAuthArg*>(windowEvent.padding)))
186 throw ErrorMsg{ -1, windowEvent.type, "sdl_auth_dialog_show" };
187 }
188 break;
189 case SDL_EVENT_USER_UPDATE:
190 {
191 std::vector<SDL_Rect> rectangles;
192 do
193 {
194 rectangles = sdl->pop();
195 if (!sdl->drawToWindows(rectangles))
196 throw ErrorMsg{ -1, windowEvent.type, "sdl->drawToWindows" };
197 } while (!rectangles.empty());
198 }
199 break;
200 case SDL_EVENT_USER_CREATE_WINDOWS:
201 {
202 auto ctx = static_cast<SdlContext*>(windowEvent.user.data1);
203 if (!ctx->createWindows())
204 throw ErrorMsg{ -1, windowEvent.type, "sdl->createWindows" };
205 }
206 break;
207 case SDL_EVENT_USER_WINDOW_RESIZEABLE:
208 {
209 auto window = static_cast<SdlWindow*>(windowEvent.user.data1);
210 const bool use = windowEvent.user.code != 0;
211 if (window)
212 window->resizeable(use);
213 }
214 break;
215 case SDL_EVENT_USER_WINDOW_FULLSCREEN:
216 {
217 auto window = static_cast<SdlWindow*>(windowEvent.user.data1);
218 const bool enter = windowEvent.user.code != 0;
219 if (window)
220 window->fullscreen(enter);
221 }
222 break;
223 case SDL_EVENT_USER_WINDOW_MINIMIZE:
224 if (!sdl->minimizeAllWindows())
225 throw ErrorMsg{ -1, windowEvent.type, "sdl->minimizeAllWindows" };
226 break;
227 case SDL_EVENT_USER_POINTER_NULL:
228 if (!sdl->setCursor(SdlContext::CURSOR_NULL))
229 throw ErrorMsg{ -1, windowEvent.type, "sdl->setCursor" };
230 break;
231 case SDL_EVENT_USER_POINTER_DEFAULT:
232 if (!sdl->setCursor(SdlContext::CURSOR_DEFAULT))
233 throw ErrorMsg{ -1, windowEvent.type, "sdl->setCursor" };
234 break;
235 case SDL_EVENT_USER_POINTER_POSITION:
236 {
237 const auto x =
238 static_cast<INT32>(reinterpret_cast<uintptr_t>(windowEvent.user.data1));
239 const auto y =
240 static_cast<INT32>(reinterpret_cast<uintptr_t>(windowEvent.user.data2));
241 if (!sdl->moveMouseTo(
242 { static_cast<float>(x) * 1.0f, static_cast<float>(y) * 1.0f }))
243 throw ErrorMsg{ -1, windowEvent.type, "sdl->moveMouseTo" };
244 }
245 break;
246 case SDL_EVENT_USER_POINTER_SET:
247 if (!sdl->setCursor(static_cast<rdpPointer*>(windowEvent.user.data1)))
248 throw ErrorMsg{ -1, windowEvent.type, "sdl->setCursor" };
249 break;
250 case SDL_EVENT_USER_QUIT:
251 default:
252 break;
253 }
254 }
255 }
256 rc = 1;
257 }
258 catch (ErrorMsg& msg)
259 {
260 WLog_Print(sdl->getWLog(), WLOG_ERROR, "[exception] %s", msg.what());
261 rc = msg.rc();
262 }
263
264 return rc;
265}
266
267/* Optional global initializer.
268 * Here we just register a signal handler to print out stack traces
269 * if available. */
270[[nodiscard]] static BOOL sdl_client_global_init()
271{
272#if defined(_WIN32)
273 WSADATA wsaData = {};
274 const DWORD wVersionRequested = MAKEWORD(1, 1);
275 const int rc = WSAStartup(wVersionRequested, &wsaData);
276 if (rc != 0)
277 {
278 WLog_ERR(SDL_TAG, "WSAStartup failed with %s [%d]", gai_strerrorA(rc), rc);
279 return FALSE;
280 }
281#endif
282
283 return (freerdp_handle_signals() == 0);
284}
285
286/* Optional global tear down */
287static void sdl_client_global_uninit()
288{
289#if defined(_WIN32)
290 WSACleanup();
291#endif
292}
293
294[[nodiscard]] static BOOL sdl_client_new(freerdp* instance, rdpContext* context)
295{
296 auto sdl = reinterpret_cast<sdl_rdp_context*>(context);
297
298 if (!instance || !context)
299 return FALSE;
300
301 sdl->sdl = new SdlContext(context);
302 return sdl->sdl != nullptr;
303}
304
305static void sdl_client_free([[maybe_unused]] freerdp* instance, rdpContext* context)
306{
307 auto sdl = reinterpret_cast<sdl_rdp_context*>(context);
308
309 if (!context)
310 return;
311
312 delete sdl->sdl;
313}
314
315[[nodiscard]] static int sdl_client_start(rdpContext* context)
316{
317 auto sdl = get_context(context);
318 WINPR_ASSERT(sdl);
319 return sdl->start();
320}
321
322[[nodiscard]] static int sdl_client_stop(rdpContext* context)
323{
324 auto sdl = get_context(context);
325 WINPR_ASSERT(sdl);
326 return sdl->join();
327}
328
329static void RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints)
330{
331 WINPR_ASSERT(pEntryPoints);
332
333 ZeroMemory(pEntryPoints, sizeof(RDP_CLIENT_ENTRY_POINTS));
334 pEntryPoints->Version = RDP_CLIENT_INTERFACE_VERSION;
335 pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1);
336 pEntryPoints->GlobalInit = sdl_client_global_init;
337 pEntryPoints->GlobalUninit = sdl_client_global_uninit;
338 pEntryPoints->ContextSize = sizeof(sdl_rdp_context);
339 pEntryPoints->ClientNew = sdl_client_new;
340 pEntryPoints->ClientFree = sdl_client_free;
341 pEntryPoints->ClientStart = sdl_client_start;
342 pEntryPoints->ClientStop = sdl_client_stop;
343}
344
345static void context_free(sdl_rdp_context* sdl)
346{
347 if (sdl)
348 freerdp_client_context_free(&sdl->common.context);
349}
350
351[[nodiscard]] static const char* category2str(int category)
352{
353 switch (category)
354 {
355 case SDL_LOG_CATEGORY_APPLICATION:
356 return "SDL_LOG_CATEGORY_APPLICATION";
357 case SDL_LOG_CATEGORY_ERROR:
358 return "SDL_LOG_CATEGORY_ERROR";
359 case SDL_LOG_CATEGORY_ASSERT:
360 return "SDL_LOG_CATEGORY_ASSERT";
361 case SDL_LOG_CATEGORY_SYSTEM:
362 return "SDL_LOG_CATEGORY_SYSTEM";
363 case SDL_LOG_CATEGORY_AUDIO:
364 return "SDL_LOG_CATEGORY_AUDIO";
365 case SDL_LOG_CATEGORY_VIDEO:
366 return "SDL_LOG_CATEGORY_VIDEO";
367 case SDL_LOG_CATEGORY_RENDER:
368 return "SDL_LOG_CATEGORY_RENDER";
369 case SDL_LOG_CATEGORY_INPUT:
370 return "SDL_LOG_CATEGORY_INPUT";
371 case SDL_LOG_CATEGORY_TEST:
372 return "SDL_LOG_CATEGORY_TEST";
373 case SDL_LOG_CATEGORY_GPU:
374 return "SDL_LOG_CATEGORY_GPU";
375 case SDL_LOG_CATEGORY_RESERVED2:
376 return "SDL_LOG_CATEGORY_RESERVED2";
377 case SDL_LOG_CATEGORY_RESERVED3:
378 return "SDL_LOG_CATEGORY_RESERVED3";
379 case SDL_LOG_CATEGORY_RESERVED4:
380 return "SDL_LOG_CATEGORY_RESERVED4";
381 case SDL_LOG_CATEGORY_RESERVED5:
382 return "SDL_LOG_CATEGORY_RESERVED5";
383 case SDL_LOG_CATEGORY_RESERVED6:
384 return "SDL_LOG_CATEGORY_RESERVED6";
385 case SDL_LOG_CATEGORY_RESERVED7:
386 return "SDL_LOG_CATEGORY_RESERVED7";
387 case SDL_LOG_CATEGORY_RESERVED8:
388 return "SDL_LOG_CATEGORY_RESERVED8";
389 case SDL_LOG_CATEGORY_RESERVED9:
390 return "SDL_LOG_CATEGORY_RESERVED9";
391 case SDL_LOG_CATEGORY_RESERVED10:
392 return "SDL_LOG_CATEGORY_RESERVED10";
393 case SDL_LOG_CATEGORY_CUSTOM:
394 default:
395 return "SDL_LOG_CATEGORY_CUSTOM";
396 }
397}
398
399[[nodiscard]] static SDL_LogPriority wloglevel2dl(DWORD level)
400{
401 switch (level)
402 {
403 case WLOG_TRACE:
404 return SDL_LOG_PRIORITY_VERBOSE;
405 case WLOG_DEBUG:
406 return SDL_LOG_PRIORITY_DEBUG;
407 case WLOG_INFO:
408 return SDL_LOG_PRIORITY_INFO;
409 case WLOG_WARN:
410 return SDL_LOG_PRIORITY_WARN;
411 case WLOG_ERROR:
412 return SDL_LOG_PRIORITY_ERROR;
413 case WLOG_FATAL:
414 return SDL_LOG_PRIORITY_CRITICAL;
415 case WLOG_OFF:
416 default:
417 return SDL_LOG_PRIORITY_VERBOSE;
418 }
419}
420
421[[nodiscard]] static DWORD sdlpriority2wlog(SDL_LogPriority priority)
422{
423 DWORD level = WLOG_OFF;
424 switch (priority)
425 {
426 case SDL_LOG_PRIORITY_VERBOSE:
427 level = WLOG_TRACE;
428 break;
429 case SDL_LOG_PRIORITY_DEBUG:
430 level = WLOG_DEBUG;
431 break;
432 case SDL_LOG_PRIORITY_INFO:
433 level = WLOG_INFO;
434 break;
435 case SDL_LOG_PRIORITY_WARN:
436 level = WLOG_WARN;
437 break;
438 case SDL_LOG_PRIORITY_ERROR:
439 level = WLOG_ERROR;
440 break;
441 case SDL_LOG_PRIORITY_CRITICAL:
442 level = WLOG_FATAL;
443 break;
444 default:
445 break;
446 }
447
448 return level;
449}
450
451static void SDLCALL winpr_LogOutputFunction(void* userdata, int category, SDL_LogPriority priority,
452 const char* message)
453{
454 auto sdl = static_cast<SdlContext*>(userdata);
455 WINPR_ASSERT(sdl);
456
457 const DWORD level = sdlpriority2wlog(priority);
458 auto log = sdl->getWLog();
459 if (!WLog_IsLevelActive(log, level))
460 return;
461
462 WLog_PrintTextMessage(log, level, __LINE__, __FILE__, __func__, "[%s] %s",
463 category2str(category), message);
464}
465
466static void sdl_quit()
467{
468 SDL_Event ev = {};
469 ev.type = SDL_EVENT_QUIT;
470 if (!SDL_PushEvent(&ev))
471 {
472 SDL_Log("An error occurred: %s", SDL_GetError());
473 }
474}
475
476static void SDLCALL rdp_file_cb(void* userdata, const char* const* filelist,
477 WINPR_ATTR_UNUSED int filter)
478{
479 auto rdp = static_cast<std::string*>(userdata);
480
481 if (!filelist)
482 {
483 SDL_Log("An error occurred: %s", SDL_GetError());
484 sdl_quit();
485 return;
486 }
487 else if (!*filelist)
488 {
489 SDL_Log("The user did not select any file.");
490 SDL_Log("Most likely, the dialog was canceled.");
491 sdl_quit();
492 return;
493 }
494
495 while (*filelist)
496 {
497 SDL_Log("Full path to selected file: '%s'", *filelist);
498 *rdp = *filelist;
499 filelist++;
500 }
501
502 sdl_quit();
503}
504
505[[nodiscard]] static std::string getRdpFile()
506{
507 const auto flags = SDL_INIT_VIDEO | SDL_INIT_EVENTS;
508 SDL_DialogFileFilter filters[] = { { "RDP files", "rdp;rdpw" } };
509 std::string rdp;
510
511 bool running = true;
512 if (!SDL_Init(flags))
513 return {};
514
515 auto props = SDL_CreateProperties();
516 SDL_SetStringProperty(props, SDL_PROP_FILE_DIALOG_TITLE_STRING,
517 "SDL Freerdp - Open a RDP file");
518 SDL_SetBooleanProperty(props, SDL_PROP_FILE_DIALOG_MANY_BOOLEAN, false);
519 SDL_SetPointerProperty(props, SDL_PROP_FILE_DIALOG_FILTERS_POINTER, filters);
520 SDL_SetNumberProperty(props, SDL_PROP_FILE_DIALOG_NFILTERS_NUMBER, ARRAYSIZE(filters));
521 SDL_ShowFileDialogWithProperties(SDL_FILEDIALOG_OPENFILE, rdp_file_cb, &rdp, props);
522 SDL_DestroyProperties(props);
523
524 do
525 {
526 SDL_Event event = {};
527 std::ignore = SDL_PollEvent(&event);
528
529 switch (event.type)
530 {
531 case SDL_EVENT_QUIT:
532 running = false;
533 break;
534 default:
535 break;
536 }
537 } while (running);
538 SDL_Quit();
539 return rdp;
540}
541
542int main(int argc, char* argv[])
543{
544 int rc = -1;
545 RDP_CLIENT_ENTRY_POINTS clientEntryPoints = {};
546
547 /* Allocate the RDP context first, we need to pass it to SDL */
548 RdpClientEntry(&clientEntryPoints);
549 std::unique_ptr<sdl_rdp_context, void (*)(sdl_rdp_context*)> sdl_rdp(
550 reinterpret_cast<sdl_rdp_context*>(freerdp_client_context_new(&clientEntryPoints)),
551 context_free);
552
553 if (!sdl_rdp)
554 return -1;
555 auto sdl = sdl_rdp->sdl;
556
557 auto settings = sdl->context()->settings;
558 WINPR_ASSERT(settings);
559
560 std::string rdp_file;
561 std::vector<char*> args;
562 args.reserve(WINPR_ASSERTING_INT_CAST(size_t, argc));
563 for (auto x = 0; x < argc; x++)
564 args.push_back(argv[x]);
565
566 if (argc == 1)
567 {
568 rdp_file = getRdpFile();
569 if (!rdp_file.empty())
570 {
571 args.push_back(rdp_file.data());
572 }
573 }
574
575 auto status = freerdp_client_settings_parse_command_line(
576 settings, WINPR_ASSERTING_INT_CAST(int, args.size()), args.data(), FALSE);
577 sdl_rdp->sdl->setMetadata();
578 if (status)
579 {
580 rc = freerdp_client_settings_command_line_status_print(settings, status, argc, argv);
581 if (freerdp_settings_get_bool(settings, FreeRDP_ListMonitors))
582 {
583 if (!sdl_list_monitors(sdl))
584 return -1;
585 }
586 else
587 {
588 switch (status)
589 {
590 case COMMAND_LINE_STATUS_PRINT:
591 case COMMAND_LINE_STATUS_PRINT_VERSION:
592 case COMMAND_LINE_STATUS_PRINT_BUILDCONFIG:
593 break;
594 case COMMAND_LINE_STATUS_PRINT_HELP:
595 default:
596 SdlPref::print_config_file_help(3);
597 break;
598 }
599 }
600 return rc;
601 }
602
603 /* Basic SDL initialization */
604 if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS))
605 return -1;
606
607 /* Redirect SDL log messages to wLog */
608 SDL_SetLogOutputFunction(winpr_LogOutputFunction, sdl);
609 auto level = WLog_GetLogLevel(sdl->getWLog());
610 SDL_SetLogPriorities(wloglevel2dl(level));
611
612 auto backend = SDL_GetCurrentVideoDriver();
613 WLog_Print(sdl->getWLog(), WLOG_DEBUG, "client is using backend '%s'", backend);
614 sdl_dialogs_init();
615
616 SDL_SetHint(SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED, "0");
617 SDL_SetHint(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, "0");
618 SDL_SetHint(SDL_HINT_PEN_MOUSE_EVENTS, "0");
619 SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
620 SDL_SetHint(SDL_HINT_PEN_TOUCH_EVENTS, "1");
621 SDL_SetHint(SDL_HINT_TRACKPAD_IS_TOUCH_ONLY, "1");
622
623 /* SDL cleanup code if the client exits */
624 ScopeGuard guard(
625 [&]()
626 {
627 sdl->cleanup();
628 freerdp_del_signal_cleanup_handler(sdl->context(), sdl_term_handler);
629 sdl_dialogs_uninit();
630 SDL_Quit();
631 });
632
633 /* Initialize RDP */
634 auto context = sdl->context();
635 WINPR_ASSERT(context);
636
637 if (!stream_dump_register_handlers(context, CONNECTION_STATE_MCS_CREATE_REQUEST, FALSE))
638 return -1;
639
640 if (freerdp_client_start(context) != 0)
641 return -1;
642
643 rc = sdl_run(sdl);
644
645 if (freerdp_client_stop(context) != 0)
646 return -1;
647
648 if (sdl->exitCode() != 0)
649 rc = sdl->exitCode();
650
651 return rc;
652}
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_get_bool(const rdpSettings *settings, FreeRDP_Settings_Keys_Bool id)
Returns a boolean settings value.