-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmultiwindow_unity.cpp
More file actions
1728 lines (1489 loc) · 54.7 KB
/
multiwindow_unity.cpp
File metadata and controls
1728 lines (1489 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef WITH_WINE
#include <windef.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <d3d11.h>
#include <d3d11_4.h>
#include "unity/IUnityGraphics.h"
#include "unity/IUnityGraphicsD3D11.h"
#undef _WIN32
#undef WIN32
#undef __WIN32__
#undef WIN64
#undef _WIN64
#undef __WIN64__
#undef WINAPI_FAMILY
#undef __NT__
#undef interface
#include <QtWidgets>
#else
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
typedef void* HANDLE;
typedef void* HWND;
typedef bool BOOL;
typedef char* LPSTR;
#define WINAPI
#include "unity/IUnityGraphics.h"
#include <GL/glew.h>
#include <QtCore/QtCore>
#include <QtGui/QPainter>
#include <QtGui/QImage>
#include <QtGui/QScreen>
#include <QtGui/QCloseEvent>
#include <QtGui/QIcon>
#include <QtWidgets/QApplication>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QWidget>
#include <sys/socket.h>
#include <sys/un.h>
#endif
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusConnection>
#include <bitset>
#include <unistd.h>
#include <thread>
#include <xcb/xcb.h>
#include "multiwindow_unity.hpp"
#define SAFE_RELEASE(a) \
if (a) { \
a->Release(); \
a = NULL; \
}
#define SAFE_FREE(a) \
if (a) { \
free(a); \
a = NULL; \
}
#define SAFE_DELETE(a) \
if (a) { \
delete a; \
a = NULL; \
}
enum WaylandType { None, KDE, Hyprland };
QString kwinFile = "/tmp/multiwindow_unity_kwin.js";
void* MAIN_WINDOW = (void*)0x12345;
#ifdef WITH_WINE
HWND main_window_handle = NULL;
#else
xcb_window_t main_window_handle = 0;
#endif
int main_window_x = 0;
int main_window_y = 0;
int main_window_width = 800;
int main_window_height = 600;
bool createdApplication = false;
bool appReady = false;
WaylandType waylandType = WaylandType::None;
bool needsX11Cutoff = true;
#ifdef WITH_WINE
bool usingWine = true;
#else
bool usingWine = false;
#endif
bool unsupportedDE = false;
bool forceDisabledWayland = false;
bool hyprlandError = false;
// Need to use this hack instead of using actual "availableGeometry".
// Maximizing invisible windows (ScreenSizeWindow) is a more reliable
// method of getting the actual screen size without the taskbar.
QMap<QScreen*, QRect> screenGeometries;
int framesSinceReorder = 0;
std::vector<CustomWindow*> allCustomWindows;
QMutex customWindowMutex;
std::vector<WId> storedWindowOrder;
xcb_connection_t* globalXcbConnection;
Hyprctl* hyprctl = nullptr;
std::string boolToStr(bool value) { return value ? "true" : "false"; }
char* createString(const char* string) {
#ifdef WITH_WINE
return (char*)string;
#else
char* address = (char*)malloc(strlen(string) + 1);
strcpy(address, string);
return address;
#endif
}
class CustomApplication : public QApplication {
public:
#ifdef WITH_WINE
ID3D11Device* device = nullptr;
ID3D11DeviceContext* context = nullptr;
#endif
CustomApplication(int& argc, char** argv) : QApplication(argc, argv) { this->setQuitOnLastWindowClosed(false); }
bool createKWinFile() {
QFile file(kwinFile);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
return false;
}
QTextStream textStream(&file);
textStream << "const appPid = " << this->applicationPid();
textStream << R"""(
// puts your hands up in the sky. puts your hands up in the sky. puts your puts your. PUT YOUR HANDS UP HIGH
// https://youtu.be/eBC9r5WMNng
print("KWin Multiwindow Plugin")
const mainWindow = workspace.stackingOrder.find((win) => win.pid == appPid);
let lastOrder = "";
const lastConstraints = [];
const supportsConstraints = Object.getOwnPropertyNames(workspace).includes("constrain");
if (!supportsConstraints) {
print("[WARNING] Constraints/window ordering not supported. Update KDE Plasma.")
}
function decode(caption) {
if (!caption.endsWith("\u200B") && !caption.endsWith("\u200C")) {
return null;
}
let encoded = "";
let msg = [];
for (const letter of caption) {
if (letter != "\u200B" && letter != "\u200C") continue;
encoded += letter == "\u200B" ? "0" : 1;
if (encoded.length == 24) {
let num = parseInt(encoded.substring(1), 2);
if (encoded[0] == "1") {
num = -num;
}
msg.push(num);
encoded = "";
}
}
return msg;
}
function findWindow(id) {
for (const win of workspace.windowList()) {
if (win.destroyed) continue;
if (win.pid != appPid) continue;
const msg = decode(win.caption);
if (msg == null) continue;
if (msg[5] == id) {
return win;
}
}
return null;
}
workspace.windowAdded.connect((win) => {
if (win.pid != appPid) return;
const frameX = win.frameGeometry.x - win.clientGeometry.x;
const frameY = win.frameGeometry.y - win.clientGeometry.y;
const frameW = win.frameGeometry.width - win.clientGeometry.width;
const frameH = win.frameGeometry.height - win.clientGeometry.height;
function updateWindow() {
const msg = decode(win.caption);
if (msg == null) return;
const noBorder = msg[4] == 0;
if (!noBorder) {
msg[0] += frameX;
msg[1] += frameY;
msg[2] += frameW;
msg[3] += frameH;
}
win.frameGeometry = {
x: msg[0],
y: msg[1],
width: msg[2],
height: msg[3]
};
win.skipsCloseAnimation = true;
win.skipTaskbar = true;
win.keepAbove = true;
win.noBorder = noBorder; // "The decision whether a window has a border or not belongs to the window manager." But Rhythm Doctor says otherwise.
if (win.active) {
workspace.activeWindow = mainWindow;
}
const arrangementCount = msg[6];
if (arrangementCount > 0 && supportsConstraints) {
const orderStr = JSON.stringify(msg.slice(6, 6 + arrangementCount + 1));
if (orderStr != lastOrder) {
lastOrder = orderStr;
for (const constraint of lastConstraints) {
const bWinReal = findWindow(constraint[0]);
const aWinReal = findWindow(constraint[1]);
if (bWinReal != null && aWinReal != null) {
workspace.unconstrain(bWinReal, aWinReal);
}
}
lastConstraints.length = 0;
for (let i = 1; i < arrangementCount; i++) {
const bWin = msg[i + 6];
const aWin = msg[i + 7];
const bWinReal = findWindow(bWin);
const aWinReal = findWindow(aWin);
if (bWinReal != null && aWinReal != null) {
workspace.constrain(bWinReal, aWinReal);
lastConstraints.push([bWin, aWin]);
}
}
}
}
}
win.captionChanged.connect(() => {
updateWindow();
});
win.minimizedChanged.connect(() => {
win.minimized = false;
});
win.maximizedChanged.connect(() => {
win.setMaximize(false, false);
});
win.activeChanged.connect(() => {
if (!win.active) return;
if (win.destroyed) return;
updateWindow();
})
win.interactiveMoveResizeFinished.connect(() => {
updateWindow();
});
updateWindow();
})
)""";
return true;
}
void removeKWinFile() {
QFile file(kwinFile);
file.remove();
}
void addKWinScript() {
if (!createKWinFile()) {
return;
}
QDBusMessage message = QDBusMessage::createMethodCall(
QStringLiteral("org.kde.KWin"), QStringLiteral("/Scripting"), QString(), QStringLiteral("loadScript"));
QList<QVariant> arguments;
arguments << QVariant(kwinFile);
message.setArguments(arguments);
QDBusMessage reply = QDBusConnection::sessionBus().call(message);
if (reply.type() == QDBusMessage::ErrorMessage) {
qInfo() << "KWin load script error" << reply.errorMessage();
QMessageBox::critical(
nullptr, "RD Window Dance",
"Could not load the KWin script. Please create an issue on GitHub with the logs from the Wine output.");
removeKWinFile();
return;
}
auto id = reply.arguments().constFirst().toInt();
message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KWin"),
QString("/Scripting/Script") + QString::number(id), QString(),
QStringLiteral("run"));
reply = QDBusConnection::sessionBus().call(message);
if (reply.type() == QDBusMessage::ErrorMessage) {
qInfo() << "KWin run script error" << reply.errorMessage();
QMessageBox::critical(
nullptr, "RD Window Dance",
"Could not run the KWin script. Please create an issue on GitHub with the logs from the Wine output.");
}
removeKWinFile();
}
void startRunning() {
if (waylandType == WaylandType::KDE) {
addKWinScript();
}
appReady = true;
for (auto screen : this->screens()) {
screenGeometries[screen] = screen->availableGeometry(); // Temporary until we get actual sizes later (or use
// Wayland, there these are not used).
if (waylandType == WaylandType::None) {
ScreenSizeWindow* screenSizeWindow = new ScreenSizeWindow();
screenSizeWindow->doTheStuff(screen);
}
}
this->exec();
}
};
CustomApplication* app;
void blockWithError(QString error) {
qCritical() << "[ERROR]" << error;
QMetaObject::invokeMethod(
app, [error]() { QMessageBox::critical(nullptr, "RD Window Dance", error); }, Qt::BlockingQueuedConnection);
}
xcb_atom_t getAtom(xcb_connection_t* connection, const char* name) {
xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 0, strlen(name), name);
xcb_intern_atom_reply_t* reply = xcb_intern_atom_reply(connection, cookie, NULL);
xcb_atom_t atom = reply->atom;
free(reply);
return atom;
}
#ifdef WITH_WINE
bool WINAPI CustomGetWindowRect(HWND hWnd, LPRECT lpRect);
void writeJump(void* memory, void* function) {
DWORD oldProtect;
VirtualProtect(memory, 12, PAGE_EXECUTE_READWRITE, &oldProtect);
uint8_t* p = (uint8_t*)memory;
p[0] = 0x48;
p[1] = 0xB8;
*(uint64_t*)(p + 2) = (uint64_t)function;
p[10] = 0xFF;
p[11] = 0xE0;
VirtualProtect(memory, 12, oldProtect, &oldProtect);
}
void hookIntoDLL() {
HMODULE user32 = GetModuleHandleA("user32.dll");
void* target = (void*)GetProcAddress(user32, "GetWindowRect");
writeJump(target, (void*)CustomGetWindowRect);
FlushInstructionCache(GetCurrentProcess(), NULL, 0);
RECT rect;
bool testReturn = GetWindowRect((HWND)0x987, &rect);
if (!testReturn || rect.left != 123 || rect.top != 456 || rect.right != 789 || rect.bottom != 987) {
std::cerr << "Error hooking GetWindowRect! Incorrect return values." << std::endl;
}
}
#endif
void checkForWayland() {
auto sessionDesktop = qgetenv("XDG_SESSION_DESKTOP").toLower();
bool useX11 = false;
if (qgetenv("XDG_SESSION_TYPE").toLower() != "wayland") {
useX11 = true;
} else if (qgetenv("RD_DANCE_NO_WAYLAND").toLower() == "1") {
useX11 = true;
qInfo() << "Wayland force disabled.";
forceDisabledWayland = true;
}
if (useX11) {
if (sessionDesktop != "kde" && sessionDesktop != "plasma") {
qWarning() << "You are using an unsupported DE/WM on X11! Bug reports may be ignored.";
unsupportedDE = true;
}
return;
}
if (sessionDesktop == "kde" || sessionDesktop == "plasma") {
waylandType = WaylandType::KDE;
#ifndef WITH_WINE
} else if (sessionDesktop == "hyprland") {
waylandType = WaylandType::Hyprland;
#endif
} else {
qWarning() << "You are using an unsupported DE/WM on Wayland! Bug reports may be ignored.";
unsupportedDE = true;
}
}
bool doesDesktopNeedCutoff() {
QString sessionDesktop = qgetenv("XDG_SESSION_DESKTOP").toLower();
if (sessionDesktop == "i3" || sessionDesktop == "hyprland") {
return false;
}
return true;
}
void createApplication() {
if (createdApplication) {
return;
}
createdApplication = true;
needsX11Cutoff = doesDesktopNeedCutoff();
checkForWayland();
#ifdef WITH_WINE
hookIntoDLL();
#endif
qInfo() << "Wayland type:" << waylandType;
if (waylandType == WaylandType::None) {
qputenv("QT_QPA_PLATFORM", "xcb");
} else if (waylandType == WaylandType::Hyprland) {
hyprctl = new Hyprctl();
}
std::thread([] {
int argc = 0;
app = new CustomApplication(argc, {});
app->startRunning();
}).detach();
}
void connectX11Display() { globalXcbConnection = xcb_connect(NULL, NULL); }
#ifdef WITH_WINE
BOOL CALLBACK findMainWindowHandleCallback(HWND hwnd, LPARAM lParam) {
RECT rect;
GetWindowRect(hwnd, &rect);
if (rect.bottom > 100) {
main_window_handle = hwnd;
return FALSE;
}
return TRUE;
}
bool findMainWindowHandle() {
EnumThreadWindows(GetCurrentThreadId(), findMainWindowHandleCallback, 0);
return main_window_handle != NULL;
}
extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD reason, LPVOID reserved) {
if (reason == DLL_PROCESS_ATTACH) {
// fprintf(stderr, "[multiwindow_unity] DllMain();\n");
}
return TRUE;
}
#else
bool findMainWindowHandle() {
if (main_window_handle != 0) {
return true;
}
int currentPid = getpid();
xcb_screen_iterator_t screens = xcb_setup_roots_iterator(xcb_get_setup(globalXcbConnection));
xcb_screen_t* screen = screens.data;
xcb_window_t root = screen->root;
xcb_atom_t clientListAtom = getAtom(globalXcbConnection, "_NET_CLIENT_LIST");
xcb_atom_t pidAtom = getAtom(globalXcbConnection, "_NET_WM_PID");
xcb_get_property_cookie_t cookie =
xcb_get_property(globalXcbConnection, 0, root, clientListAtom, XCB_ATOM_WINDOW, 0, 1024);
xcb_get_property_reply_t* reply = xcb_get_property_reply(globalXcbConnection, cookie, NULL);
int length = xcb_get_property_value_length(reply) / sizeof(xcb_window_t);
xcb_window_t* windows = (xcb_window_t*)xcb_get_property_value(reply);
for (int i = 0; i < length; i++) {
xcb_window_t window = windows[i];
xcb_get_property_cookie_t pidCookie =
xcb_get_property(globalXcbConnection, 0, window, pidAtom, XCB_ATOM_CARDINAL, 0, 1);
xcb_get_property_reply_t* pidReply = xcb_get_property_reply(globalXcbConnection, pidCookie, NULL);
if (pidReply == nullptr) {
continue;
}
if (xcb_get_property_value_length(pidReply) != 4) {
continue;
}
int pid = *(int*)xcb_get_property_value(pidReply);
free(pidReply);
if (pid == currentPid) {
main_window_handle = window;
break;
}
}
free(reply);
return main_window_handle != 0;
}
#endif
struct MotifWmHints {
uint32_t flags;
uint32_t functions;
uint32_t decorations;
int32_t input_mode;
uint32_t status;
};
// ---- Start of CustomWindow ----
CustomWindow::CustomWindow() {
setAttribute(Qt::WA_TranslucentBackground);
setWindowFlag(Qt::WindowStaysOnTopHint); // Does not work on Wayland, have to use JS hack above.
setWindowFlag(Qt::WindowDoesNotAcceptFocus);
setWindowFlag(Qt::WindowTransparentForInput);
this->customId = rand() % 100000;
this->targetX = 0;
this->targetY = 0;
this->targetWidth = 1;
this->targetHeight = 1;
this->targetOpacity = 0;
if (waylandType != WaylandType::Hyprland) {
this->setFixedSize(10, 10);
}
QPixmap* cursor = new QPixmap(1, 1);
cursor->fill(QColor(0, 0, 0, 0));
this->setCursor(QCursor(*cursor));
// testLabel = new QLabel("Example Text", this);
// testLabel->setStyleSheet("QLabel { color: white; font-size: 24px; }");
// testLabel->show();
}
#ifdef WITH_WINE
void CustomWindow::setTexture(ID3D11Resource* resource) {
if (this->qtImage != nullptr) {
delete this->qtImage;
}
this->qtImage = nullptr;
this->stagingTexture = nullptr;
this->resource = resource;
this->texture = nullptr;
resource->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&texture);
texture->GetDesc(&desc);
this->qtImage = new QImage(desc.Width, desc.Height, QImage::Format_ARGB32_Premultiplied);
stagingDesc = desc;
stagingDesc.Usage = D3D11_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stagingDesc.MiscFlags = 0;
HRESULT returnCode;
returnCode = app->device->CreateTexture2D(&stagingDesc, nullptr, &stagingTexture);
if (returnCode != 0) {
std::cerr << "CreateTexture2D ERROR: " << std::hex << returnCode << std::dec << std::endl;
}
this->copyTexture();
}
bool CustomWindow::copyTexture() {
if (!isVisible) {
return false;
}
if (isClosing) {
qWarning() << "WARNING: Tried to copyTexture() when window is closing.";
return false;
}
if (this->qtImage == nullptr) {
qWarning() << "WARNING: Tried to copyTexture() when texture is deleted.";
return false;
}
ID3D11DeviceContext* ctx = NULL;
app->device->GetImmediateContext(&ctx);
ctx->CopyResource(stagingTexture, texture);
HRESULT returnCode = ctx->Map(stagingTexture, 0, D3D11_MAP_READ, 0, &mapped);
if (returnCode != 0) {
std::cerr << "Map ERROR: " << std::hex << returnCode << std::dec << std::endl;
}
int bytesPerLine = qtImage->bytesPerLine();
int height = desc.Height;
uchar* startingBits = qtImage->bits();
uchar* source = (uchar*)mapped.pData;
for (int i = 0; i < height; i++) {
int invertedY = (height - i - 1);
memcpy(startingBits + i * bytesPerLine, source + invertedY * bytesPerLine, bytesPerLine);
}
ctx->Unmap(stagingTexture, 0);
ctx->Release();
return true;
}
#else
void CustomWindow::setTexture(GLuint textureId) { this->glTextureId = textureId; }
void CustomWindow::setTextureSize(int w, int h) {
this->qtImage = new QImage(w, h, QImage::Format_RGBA8888_Premultiplied);
SAFE_FREE(this->tempTexture);
tempTexture = malloc(w * h * 4);
}
bool CustomWindow::copyTexture() {
if (!isVisible) {
return false;
}
if (isClosing) {
qWarning() << "WARNING: Tried to copyTexture() when window is closing.";
return false;
}
if (this->tempTexture == nullptr || this->qtImage == nullptr) {
qWarning() << "WARNING: Tried to copyTexture() when texture is deleted.";
return false;
}
glBindTexture(GL_TEXTURE_2D, this->glTextureId);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, tempTexture);
int bytesPerLine = qtImage->bytesPerLine();
int height = qtImage->height();
uchar* startingBits = qtImage->bits();
uchar* source = (uchar*)tempTexture;
for (int i = 0; i < height; i++) {
int invertedY = (height - i - 1);
memcpy(startingBits + i * bytesPerLine, source + invertedY * bytesPerLine, bytesPerLine);
}
return true;
}
#endif
void CustomWindow::_setX11Decorations(bool hasDecorations) {
MotifWmHints hints = {.flags = 2, .decorations = hasDecorations};
xcb_atom_t atom = getAtom(globalXcbConnection, "_MOTIF_WM_HINTS");
xcb_change_property(globalXcbConnection, XCB_PROP_MODE_REPLACE, window()->winId(), atom, atom, 32, 5, &hints);
xcb_flush(globalXcbConnection);
}
void CustomWindow::setTargetMove(int x, int y) {
this->targetX = x;
this->targetY = y;
}
void CustomWindow::setTargetSize(int w, int h) {
this->targetWidth = w;
this->targetHeight = h;
}
void CustomWindow::updateThings() {
auto primaryScreen = app->primaryScreen();
qreal scaling = waylandType == WaylandType::None ? this->devicePixelRatio() : 1;
auto primaryScreenGeometry = screenGeometries[primaryScreen];
auto unitedScreenGeometry = screenGeometries.first();
int smallestHeight = 999999; // KDE window constraints are buggy. Other monitors also have invisible taskbar limits.
int finalX = this->targetX / scaling;
int finalY = this->targetY / scaling;
int finalWidth = this->targetWidth / scaling;
int finalHeight = this->targetHeight / scaling;
float finalOpacity = this->targetOpacity;
bool finalDecorations = targetDecorations;
if (waylandType == WaylandType::None) {
for (auto g : screenGeometries) {
unitedScreenGeometry = unitedScreenGeometry.united(g);
int h = g.height() + primaryScreenGeometry.y();
if (h < smallestHeight) {
smallestHeight = h;
}
}
}
if (finalWidth > 5000) {
finalWidth = 5000;
}
if (finalHeight > 5000) {
finalHeight = 5000;
}
#ifdef WITH_WINE
finalX += primaryScreen->geometry().x();
#endif
if (waylandType == WaylandType::None && needsX11Cutoff) {
if (finalX < 0 - finalWidth) {
finalOpacity = 0;
}
if (finalX > unitedScreenGeometry.width()) {
finalOpacity = 0;
}
if (finalY < 0 - finalHeight) {
finalOpacity = 0;
}
if (finalY > smallestHeight) {
finalOpacity = 0;
}
cutoffX = 0;
cutoffY = 0;
int titleBarHeight = 30;
// Offscreen top/left
if (finalX < 0) {
finalWidth += finalX;
cutoffX = finalX;
finalX = 0;
}
if (finalY < primaryScreenGeometry.y() + titleBarHeight) {
finalDecorations = false;
}
if (finalY < primaryScreenGeometry.y()) {
finalHeight += finalY - primaryScreenGeometry.y();
cutoffY = finalY - primaryScreenGeometry.y();
finalY = primaryScreenGeometry.y();
}
// Offscreen bottom/right
int rightEdge = unitedScreenGeometry.width() - finalWidth;
int bottomEdge = smallestHeight - finalHeight;
if (finalX > rightEdge) {
int difference = finalX - rightEdge;
finalWidth -= difference;
}
if (finalY > bottomEdge) {
int difference = finalY - bottomEdge;
finalHeight -= difference;
}
}
if (finalWidth < 5) {
finalOpacity = 0;
finalWidth = 5;
}
if (finalHeight < 5) {
finalOpacity = 0;
finalHeight = 5;
}
isVisible = finalOpacity > 0;
if ((waylandType == WaylandType::KDE || waylandType == WaylandType::Hyprland) && !isVisible) {
finalY = -5000; // Just put the window far away in Wayland, do not bother with actual opacity.
}
// testLabel->setText(QString("Position: %1, %2\nSize: %3 x %4").arg(QString::number(targetX),
// QString::number(targetY), QString::number(targetWidth), QString::number(targetHeight)));
// testLabel->setGeometry(0, 0, finalWidth, finalHeight);
if (waylandType == WaylandType::KDE) { // Wayland doesn't support actual window movement. We have to "smuggle" data
// in the title to the JS plugin.
std::string encoded = "";
std::vector<int> smuggledInfo = {finalX,
finalY,
finalWidth,
finalHeight,
finalDecorations ? 1 : 0,
this->customId,
(int)storedWindowOrder.size()};
for (auto winId : storedWindowOrder) {
smuggledInfo.push_back(winId);
}
int i = 0;
for (auto info : smuggledInfo) {
std::string infoEncoded = std::bitset<23>(abs(info)).to_string();
encoded += info >= 0 ? "\u200B" : "\u200C";
for (auto character : infoEncoded) {
encoded += character == '0' ? "\u200B" : "\u200C";
}
i++;
}
this->setWindowTitle(targetTitle + QString::fromStdString(encoded));
} else if (waylandType == WaylandType::Hyprland) {
if (!hyprReady) {
if (!hyprctl->setProp("initialtitle:" + std::to_string(customId), "no_blur", "on")) {
return;
}
hyprReady = true;
hyprctl->setProp("initialtitle:" + std::to_string(customId), "no_focus", "on");
hyprctl->setProp("initialtitle:" + std::to_string(customId), "no_anim", "on");
hyprctl->sendMessage("dispatch setfloating initialtitle:" + std::to_string(customId));
}
hyprctl->moveWindow("initialtitle:" + std::to_string(customId), finalX, finalY);
hyprctl->sendMessage("dispatch resizewindowpixel exact " + std::to_string(finalWidth) + " " +
std::to_string(finalHeight) + ",initialtitle:" + std::to_string(customId));
if (finalDecorations != _lastDecorations) {
this->_lastDecorations = finalDecorations;
hyprctl->setProp("initialtitle:" + std::to_string(customId), "decorate", finalDecorations ? "on" : "off");
}
this->setWindowTitle(targetTitle);
} else {
this->setFixedSize(finalWidth, finalHeight);
this->setGeometry(finalX, finalY, finalWidth, finalHeight);
this->setWindowTitle(targetTitle);
this->setWindowOpacity(finalOpacity);
if (finalDecorations != _lastDecorations) {
this->_lastDecorations = finalDecorations;
this->_setX11Decorations(finalDecorations);
}
}
}
void CustomWindow::paintEvent(QPaintEvent* paintEvent) {
QPainter painter(this);
if (!isVisible) {
return;
}
if (this->qtImage == nullptr) {
return;
}
qreal scaling = waylandType == WaylandType::None ? this->devicePixelRatio() : 1;
painter.drawImage(QRect(this->cutoffX, this->cutoffY, this->targetWidth / scaling, this->targetHeight / scaling),
*this->qtImage, this->qtImage->rect());
}
void CustomWindow::setIcon(QImage* image) {
SAFE_DELETE(iconIcon);
if (image == nullptr) {
return;
}
iconPixmap = QPixmap::fromImage(*image);
iconIcon = new QIcon(iconPixmap);
this->setWindowIcon(*iconIcon);
}
void CustomWindow::closeEvent(QCloseEvent* closeEvent) {
if (!isClosing) {
closeEvent->ignore();
}
}
CustomWindow::~CustomWindow() {
SAFE_DELETE(this->qtImage);
#ifndef WITH_WINE
SAFE_FREE(this->tempTexture);
#endif
setIcon(nullptr);
// For some reason this segfaults often:
// SAFE_RELEASE(this->texture);
// SAFE_RELEASE(this->stagingTexture);
// delete this->testLabel;
}
// ---- End of CustomWindow ----
// ---- Start of ScreenSizeWindow ----
void ScreenSizeWindow::doTheStuff(QScreen* screen) {
this->actualScreen = screen;
this->setWindowTitle("IGNORE THIS WINDOW");
this->setWindowFlag(Qt::WindowStaysOnBottomHint);
this->setAttribute(Qt::WA_TranslucentBackground);
this->setWindowOpacity(0);
this->setGeometry(screen->geometry());
this->show();
QTimer::singleShot(500, [this] {
qWarning() << "Could not detect usable screen size";
delete this;
});
}
void ScreenSizeWindow::resizeEvent(QResizeEvent* event) {
resizeCount++;
if (resizeCount != 2) {
return;
}
QTimer::singleShot(10, [this] {
screenGeometries[this->actualScreen] = this->frameGeometry();
qInfo() << "Usable screen size is" << screenGeometries[this->actualScreen] << "now" << screenGeometries.size()
<< "screens";
this->close();
});
}
// ---- End of ScreenSizeWindow ----
// ---- Start of Hyprctl ----
Hyprctl::Hyprctl() {
const char* instance = getenv("HYPRLAND_INSTANCE_SIGNATURE");
if (instance == nullptr) {
instance = "";
}
socketPath = "/run/user/" + std::to_string(getuid()) + "/hypr/" + instance + "/.socket.sock";
if (access(socketPath.c_str(), 0) != 0) {
qCritical() << "Hyprland socket does not exist at" << socketPath;
qWarning() << "Falling back to X11";
waylandType = WaylandType::None;
qputenv("QT_QPA_PLATFORM", "xcb");
hyprlandError = true;
}
}
void Hyprctl::sendMessage(std::string message) {
std::thread([this, message] { this->sendMessageSync(message); }).detach();
}
bool Hyprctl::sendMessageSync(std::string message) {
#ifndef WITH_WINE // TODO: Find out a way to have unix sockets work with winelib (if there is a way)
auto sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock == -1) {
qCritical() << "sock -1";
close(sock);
return false;
}
sockaddr_un addr = {0};
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, socketPath.c_str(), sizeof(addr.sun_path) - 1);
int res = connect(sock, (sockaddr*)&addr, sizeof(addr));
if (res == -1) {
qCritical() << "connect -1";
close(sock);
return false;
}
const char* data = message.c_str();
res = write(sock, data, strlen(data));
if (res == -1) {
qCritical() << "write -1";
close(sock);
return false;
}
constexpr size_t bufferSize = 4096;
char buffer[bufferSize] = {0};
int written = read(sock, buffer, bufferSize);
if (written == -1) {
qCritical() << "read -1";
close(sock);
return false;
}
std::string reply = std::string(buffer, written);
if (reply != "ok") {
qCritical() << reply;
close(sock);
return false;
}
close(sock);
#endif
return true;
}
bool Hyprctl::setProp(std::string window, std::string effect, std::string argument) {
return sendMessageSync("dispatch setprop " + window + " " + effect + " " + argument);
}
void Hyprctl::moveWindow(std::string window, int x, int y) {
return sendMessage("dispatch movewindowpixel exact " + std::to_string(x) + " " + std::to_string(y) + "," + window);
}
// ---- End of Hyprctl ----
int MAIN_WINDOW_GEOMETRY_SKIP = 0xFEAB12;
void setMainWindowGeometry(int x, int y, int w, int h) {
if (x != MAIN_WINDOW_GEOMETRY_SKIP) {
main_window_x = x;
}
if (y != MAIN_WINDOW_GEOMETRY_SKIP) {
main_window_y = y;