• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Return-To-The-Roots / s25client / 12502045112

26 Dec 2024 09:10AM UTC coverage: 50.228% (+0.003%) from 50.225%
12502045112

Pull #1724

github

web-flow
Merge 1e31f6ef0 into 17844c810
Pull Request #1724: Workaround GUI scaling issues with HighDPI enabled.

22312 of 44421 relevant lines covered (50.23%)

35967.28 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

10.53
/extras/videoDrivers/SDL2/VideoSDL2.cpp
1
// Copyright (C) 2005 - 2021 Settlers Freaks (sf-team at siedler25.org)
2
//
3
// SPDX-License-Identifier: GPL-2.0-or-later
4

5
#include "VideoSDL2.h"
6
#include "driver/Interface.h"
7
#include "driver/VideoDriverLoaderInterface.h"
8
#include "driver/VideoInterface.h"
9
#include "enum_cast.hpp"
10
#include "helpers/LSANUtils.h"
11
#include "helpers/containerUtils.h"
12
#include "icon.h"
13
#include "openglCfg.hpp"
14
#include <s25util/utf8.h>
15
#include <boost/nowide/iostream.hpp>
16
#include <SDL.h>
17
#include <algorithm>
18
#include <memory>
19

20
#ifdef _WIN32
21
#    include <boost/nowide/convert.hpp>
22
#    ifndef WIN32_LEAN_AND_MEAN
23
#        define WIN32_LEAN_AND_MEAN
24
#    endif
25
#    include <windows.h> // Avoid "Windows headers require the default packing option" due to SDL2
26
#    include <SDL_syswm.h>
27
#endif // _WIN32
28

29
#define CHECK_SDL(call)                 \
30
    do                                  \
31
    {                                   \
32
        if((call) == -1)                \
33
            PrintError(SDL_GetError()); \
34
    } while(false)
35

36
namespace {
37
template<typename T>
38
struct SDLMemoryDeleter
39
{
40
    void operator()(T* p) const { SDL_free(p); }
×
41
};
42

43
template<typename T>
44
using SDL_memory = std::unique_ptr<T, SDLMemoryDeleter<T>>;
45
} // namespace
46

47
IVideoDriver* CreateVideoInstance(VideoDriverLoaderInterface* CallBack)
1✔
48
{
49
    return new VideoSDL2(CallBack);
1✔
50
}
51

52
void FreeVideoInstance(IVideoDriver* driver)
1✔
53
{
54
    delete driver;
1✔
55
}
1✔
56

57
const char* GetDriverName()
5✔
58
{
59
    return "(SDL2) OpenGL via SDL2-Library";
5✔
60
}
61

62
VideoSDL2::VideoSDL2(VideoDriverLoaderInterface* CallBack) : VideoDriver(CallBack), window(nullptr), context(nullptr) {}
1✔
63

64
VideoSDL2::~VideoSDL2()
2✔
65
{
66
    CleanUp();
1✔
67
}
2✔
68

69
const char* VideoSDL2::GetName() const
2✔
70
{
71
    return GetDriverName();
2✔
72
}
73

74
bool VideoSDL2::Initialize()
1✔
75
{
76
    initialized = false;
1✔
77
    rttr::ScopedLeakDisabler _;
1✔
78
    if(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
1✔
79
    {
80
        PrintError(SDL_GetError());
×
81
        return false;
×
82
    }
83

84
    initialized = true;
1✔
85
    return initialized;
1✔
86
}
87

88
void VideoSDL2::CleanUp()
1✔
89
{
90
    if(!initialized)
1✔
91
        return;
×
92

93
    if(context)
1✔
94
        SDL_GL_DeleteContext(context);
×
95
    if(window)
1✔
96
        SDL_DestroyWindow(window);
×
97
    SDL_QuitSubSystem(SDL_INIT_VIDEO);
1✔
98
    SDL_Quit();
1✔
99
    initialized = false;
1✔
100
}
101

102
void VideoSDL2::UpdateCurrentSizes()
×
103
{
104
    int w, h, w2, h2;
105
    SDL_GetWindowSize(window, &w, &h);
×
106
    SDL_GL_GetDrawableSize(window, &w2, &h2);
×
107
    SetNewSize(VideoMode(w, h), Extent(w2, h2));
×
108
}
×
109

110
bool VideoSDL2::CreateScreen(const std::string& title, const VideoMode& size, bool fullscreen)
×
111
{
112
    if(!initialized)
×
113
        return false;
×
114

115
    // GL-Attributes
116
    CHECK_SDL(SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, RTTR_OGL_MAJOR));
×
117
    CHECK_SDL(SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, RTTR_OGL_MINOR));
×
118
    SDL_GLprofile profile;
119
    if((RTTR_OGL_ES))
120
        profile = SDL_GL_CONTEXT_PROFILE_ES;
121
    else if((RTTR_OGL_COMPAT))
122
        profile = SDL_GL_CONTEXT_PROFILE_COMPATIBILITY;
×
123
    else
124
        profile = SDL_GL_CONTEXT_PROFILE_CORE;
125
    CHECK_SDL(SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profile));
×
126

127
    CHECK_SDL(SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8));
×
128
    CHECK_SDL(SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8));
×
129
    CHECK_SDL(SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8));
×
130
    CHECK_SDL(SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1));
×
131

132
    int wndPos = SDL_WINDOWPOS_CENTERED;
×
133

134
    const auto requestedSize = fullscreen ? FindClosestVideoMode(size) : size;
×
135
    unsigned commonFlags = SDL_WINDOW_OPENGL;
×
136
    // TODO: Fix GUI scaling with High DPI support enabled.
137
    // See https://github.com/Return-To-The-Roots/s25client/issues/1621
138
    // commonFlags |= SDL_WINDOW_ALLOW_HIGHDPI;
139

140
    window = SDL_CreateWindow(title.c_str(), wndPos, wndPos, requestedSize.width, requestedSize.height,
×
141
                              commonFlags | (fullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_RESIZABLE));
×
142

143
    // Fallback to non-fullscreen
144
    if(!window && fullscreen)
×
145
    {
146
        window = SDL_CreateWindow(title.c_str(), wndPos, wndPos, requestedSize.width, requestedSize.height,
×
147
                                  commonFlags | SDL_WINDOW_RESIZABLE);
148
    }
149

150
    if(!window)
×
151
    {
152
        PrintError(SDL_GetError());
×
153
        return false;
×
154
    }
155

156
    isFullscreen_ = (SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN) != 0;
×
157
    UpdateCurrentSizes();
×
158

159
    if(!isFullscreen_)
×
160
        MoveWindowToCenter();
×
161

162
    SDL_Surface* iconSurf =
163
      SDL_CreateRGBSurfaceFrom(image.data(), 48, 48, 32, 48 * 4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
×
164
    if(iconSurf)
×
165
    {
166
        SDL_SetWindowIcon(window, iconSurf);
×
167
        SDL_FreeSurface(iconSurf);
×
168
    } else
169
        PrintError(SDL_GetError());
×
170

171
    context = SDL_GL_CreateContext(window);
×
172

173
#ifdef _WIN32
174
    SetWindowTextW(GetConsoleWindow(), boost::nowide::widen(title).c_str());
175
#endif
176

177
    std::fill(keyboard.begin(), keyboard.end(), false);
×
178

179
    SDL_ShowCursor(0);
×
180

181
    return true;
×
182
}
183

184
bool VideoSDL2::ResizeScreen(const VideoMode& newSize, bool fullscreen)
×
185
{
186
    if(!initialized)
×
187
        return false;
×
188

189
    if(isFullscreen_ != fullscreen)
×
190
    {
191
        SDL_SetWindowFullscreen(window, fullscreen ? SDL_WINDOW_FULLSCREEN : 0);
×
192
        isFullscreen_ = (SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN) != 0;
×
193
        if(!isFullscreen_)
×
194
        {
195
            SDL_SetWindowResizable(window, SDL_TRUE);
×
196
            MoveWindowToCenter();
×
197
        }
198
    }
199

200
    if(newSize != GetWindowSize())
×
201
    {
202
        if(isFullscreen_)
×
203
        {
204
            auto const targetMode = FindClosestVideoMode(newSize);
×
205
            SDL_DisplayMode target;
206
            target.w = targetMode.width;
×
207
            target.h = targetMode.height;
×
208
            target.format = 0;           // don't care
×
209
            target.refresh_rate = 0;     // don't care
×
210
            target.driverdata = nullptr; // initialize to 0
×
211
            // Explicitly change the window size to avoid a bug with SDL reporting the wrong size until alt+tab
212
            SDL_SetWindowSize(window, target.w, target.h);
×
213
            if(SDL_SetWindowDisplayMode(window, &target) < 0)
×
214
            {
215
                PrintError(SDL_GetError());
×
216
                return false;
×
217
            }
218
        } else
219
        {
220
            SDL_SetWindowSize(window, newSize.width, newSize.height);
×
221
        }
222
        UpdateCurrentSizes();
×
223
    }
224
    return true;
×
225
}
226

227
void VideoSDL2::PrintError(const std::string& msg) const
×
228
{
229
    boost::nowide::cerr << msg << std::endl;
×
230
}
×
231

232
void VideoSDL2::ShowErrorMessage(const std::string& title, const std::string& message)
×
233
{
234
    // window==nullptr is okay too ("no parent")
235
    SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.c_str(), message.c_str(), window);
×
236
}
×
237

238
void VideoSDL2::HandlePaste()
×
239
{
240
    if(!SDL_HasClipboardText())
×
241
        return;
×
242

243
    SDL_memory<char> text(SDL_GetClipboardText());
×
244
    if(!text || *text == '\0') // empty string indicates error
×
245
        PrintError(text ? SDL_GetError() : "Paste failed.");
×
246

247
    KeyEvent ke = {KeyType::Char, 0, false, false, false};
×
248
    for(const char32_t c : s25util::utf8to32(text.get()))
×
249
    {
250
        ke.c = static_cast<unsigned>(c);
×
251
        CallBack->Msg_KeyDown(ke);
×
252
    }
253
}
254

255
void VideoSDL2::DestroyScreen()
×
256
{
257
    CleanUp();
×
258
}
×
259

260
bool VideoSDL2::SwapBuffers()
×
261
{
262
    SDL_GL_SwapWindow(window);
×
263
    return true;
×
264
}
265

266
bool VideoSDL2::MessageLoop()
×
267
{
268
    SDL_Event ev;
269
    while(SDL_PollEvent(&ev))
×
270
    {
271
        switch(ev.type)
×
272
        {
273
            default: break;
×
274

275
            case SDL_QUIT: return false;
×
276
            case SDL_WINDOWEVENT:
×
277
            {
278
                switch(ev.window.event)
×
279
                {
280
                    case SDL_WINDOWEVENT_RESIZED:
×
281
                    {
282
                        isFullscreen_ = (SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN) != 0;
×
283
                        VideoMode newSize(ev.window.data1, ev.window.data2);
×
284
                        if(newSize != GetWindowSize())
×
285
                        {
286
                            UpdateCurrentSizes();
×
287
                            CallBack->WindowResized();
×
288
                        }
289
                    }
290
                    break;
×
291
                }
292
            }
293
            break;
×
294

295
            case SDL_KEYDOWN:
×
296
            {
297
                KeyEvent ke = {KeyType::Invalid, 0, false, false, false};
×
298

299
                switch(ev.key.keysym.sym)
×
300
                {
301
                    default:
×
302
                    {
303
                        // Die 12 F-Tasten
304
                        if(ev.key.keysym.sym >= SDLK_F1 && ev.key.keysym.sym <= SDLK_F12)
×
305
                            ke.kt = static_cast<KeyType>(rttr::enum_cast(KeyType::F1) + ev.key.keysym.sym - SDLK_F1);
×
306
                    }
307
                    break;
×
308
                    case SDLK_RETURN: ke.kt = KeyType::Return; break;
×
309
                    case SDLK_SPACE: ke.kt = KeyType::Space; break;
×
310
                    case SDLK_LEFT: ke.kt = KeyType::Left; break;
×
311
                    case SDLK_RIGHT: ke.kt = KeyType::Right; break;
×
312
                    case SDLK_UP: ke.kt = KeyType::Up; break;
×
313
                    case SDLK_DOWN: ke.kt = KeyType::Down; break;
×
314
                    case SDLK_BACKSPACE: ke.kt = KeyType::Backspace; break;
×
315
                    case SDLK_DELETE: ke.kt = KeyType::Delete; break;
×
316
                    case SDLK_LSHIFT:
×
317
                    case SDLK_RSHIFT: ke.kt = KeyType::Shift; break;
×
318
                    case SDLK_TAB: ke.kt = KeyType::Tab; break;
×
319
                    case SDLK_HOME: ke.kt = KeyType::Home; break;
×
320
                    case SDLK_END: ke.kt = KeyType::End; break;
×
321
                    case SDLK_ESCAPE: ke.kt = KeyType::Escape; break;
×
322
                    case SDLK_PRINTSCREEN: ke.kt = KeyType::Print; break;
×
323
                    // case SDLK_BACKQUOTE: ev.key.keysym.scancode = '^'; break;
324
                    case SDLK_v:
×
325
                        if(SDL_GetModState() & KMOD_CTRL)
×
326
                        {
327
                            HandlePaste();
×
328
                            continue;
×
329
                        }
330
                        break;
×
331
                }
332

333
                if(ke.kt == KeyType::Invalid)
×
334
                    break;
×
335

336
                /// Strg, Alt, usw gedrückt?
337
                if(ev.key.keysym.mod & KMOD_CTRL)
×
338
                    ke.ctrl = true;
×
339
                if(ev.key.keysym.mod & KMOD_SHIFT)
×
340
                    ke.shift = true;
×
341
                if(ev.key.keysym.mod & KMOD_ALT)
×
342
                    ke.alt = true;
×
343

344
                CallBack->Msg_KeyDown(ke);
×
345
            }
346
            break;
×
347
            case SDL_TEXTINPUT:
×
348
            {
349
                const std::u32string text = s25util::utf8to32(ev.text.text);
×
350
                SDL_Keymod mod = SDL_GetModState();
×
351
                KeyEvent ke = {KeyType::Char, 0, (mod & KMOD_CTRL) != 0, (mod & KMOD_SHIFT) != 0,
×
352
                               (mod & KMOD_ALT) != 0};
×
353
                for(char32_t c : text)
×
354
                {
355
                    ke.c = static_cast<unsigned>(c);
×
356
                    CallBack->Msg_KeyDown(ke);
×
357
                }
358
                break;
×
359
            }
360
            case SDL_MOUSEBUTTONDOWN:
×
361
                mouse_xy.pos = getGuiScale().screenToView(Position(ev.button.x, ev.button.y));
×
362

363
                if(/*!mouse_xy.ldown && */ ev.button.button == SDL_BUTTON_LEFT)
×
364
                {
365
                    mouse_xy.ldown = true;
×
366
                    CallBack->Msg_LeftDown(mouse_xy);
×
367
                }
368
                if(/*!mouse_xy.rdown &&*/ ev.button.button == SDL_BUTTON_RIGHT)
×
369
                {
370
                    mouse_xy.rdown = true;
×
371
                    CallBack->Msg_RightDown(mouse_xy);
×
372
                }
373
                break;
×
374
            case SDL_MOUSEBUTTONUP:
×
375
                mouse_xy.pos = getGuiScale().screenToView(Position(ev.button.x, ev.button.y));
×
376

377
                if(/*mouse_xy.ldown &&*/ ev.button.button == SDL_BUTTON_LEFT)
×
378
                {
379
                    mouse_xy.ldown = false;
×
380
                    CallBack->Msg_LeftUp(mouse_xy);
×
381
                }
382
                if(/*mouse_xy.rdown &&*/ ev.button.button == SDL_BUTTON_RIGHT)
×
383
                {
384
                    mouse_xy.rdown = false;
×
385
                    CallBack->Msg_RightUp(mouse_xy);
×
386
                }
387
                break;
×
388
            case SDL_MOUSEWHEEL:
×
389
            {
390
                int y = ev.wheel.y;
×
391
                if(ev.wheel.direction == SDL_MOUSEWHEEL_FLIPPED)
×
392
                    y = -y;
×
393
                if(y > 0)
×
394
                    CallBack->Msg_WheelUp(mouse_xy);
×
395
                else if(y < 0)
×
396
                    CallBack->Msg_WheelDown(mouse_xy);
×
397
            }
398
            break;
×
399
            case SDL_MOUSEMOTION:
×
400
                mouse_xy.pos = getGuiScale().screenToView(Position(ev.motion.x, ev.motion.y));
×
401
                CallBack->Msg_MouseMove(mouse_xy);
×
402
                break;
×
403
        }
404
    }
405

406
    return true;
×
407
}
408

409
unsigned long VideoSDL2::GetTickCount() const
×
410
{
411
    return SDL_GetTicks();
×
412
}
413

414
void VideoSDL2::ListVideoModes(std::vector<VideoMode>& video_modes) const
×
415
{
416
    int display = SDL_GetWindowDisplayIndex(window);
×
417
    if(display < 0)
×
418
        display = 0;
×
419
    for(int i = SDL_GetNumDisplayModes(display) - 1; i >= 0; --i)
×
420
    {
421
        SDL_DisplayMode mode;
422
        if(SDL_GetDisplayMode(display, i, &mode) != 0)
×
423
            PrintError(SDL_GetError());
×
424
        else
425
        {
426
            VideoMode vm(mode.w, mode.h);
×
427
            if(!helpers::contains(video_modes, vm))
×
428
                video_modes.push_back(vm);
×
429
        }
430
    }
431
}
×
432

433
OpenGL_Loader_Proc VideoSDL2::GetLoaderFunction() const
×
434
{
435
    return SDL_GL_GetProcAddress;
×
436
}
437

438
void VideoSDL2::SetMousePos(Position pos)
×
439
{
440
    const auto screenPos = getGuiScale().viewToScreen(pos);
×
441
    mouse_xy.pos = pos;
×
442
    SDL_WarpMouseInWindow(window, screenPos.x, screenPos.y);
×
443
}
×
444

445
KeyEvent VideoSDL2::GetModKeyState() const
×
446
{
447
    const SDL_Keymod modifiers = SDL_GetModState();
×
448
    const KeyEvent ke = {KeyType::Invalid, 0, ((modifiers & KMOD_CTRL) != 0), ((modifiers & KMOD_SHIFT) != 0),
×
449
                         ((modifiers & KMOD_ALT) != 0)};
×
450
    return ke;
×
451
}
452

453
void* VideoSDL2::GetMapPointer() const
×
454
{
455
#ifdef WIN32
456
    SDL_SysWMinfo wmInfo;
457
    SDL_VERSION(&wmInfo.version);
458
    SDL_GetWindowWMInfo(window, &wmInfo);
459
    // return (void*)wmInfo.info.win.window;
460
    return (void*)wmInfo.info.win.window;
461
#else
462
    return nullptr;
×
463
#endif
464
}
465

466
void VideoSDL2::MoveWindowToCenter()
×
467
{
468
    SDL_Rect usableBounds;
469
    CHECK_SDL(SDL_GetDisplayUsableBounds(SDL_GetWindowDisplayIndex(window), &usableBounds));
×
470
    int top, left, bottom, right;
471
    CHECK_SDL(SDL_GetWindowBordersSize(window, &top, &left, &bottom, &right));
×
472
    usableBounds.w -= left + right;
×
473
    usableBounds.h -= top + bottom;
×
474
    if(usableBounds.w < GetWindowSize().width || usableBounds.h < GetWindowSize().height)
×
475
    {
476
        SDL_SetWindowSize(window, usableBounds.w, usableBounds.h);
×
477
        UpdateCurrentSizes();
×
478
    }
479
    SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
×
480
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc