-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.cc
2770 lines (2680 loc) · 105 KB
/
MainWindow.cc
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
/*
Copyright (c) 2015-2021 hkrn All rights reserved
This file is part of emapp component and it's licensed under Mozilla Public License. see LICENSE.md for more details.
*/
#include "MainWindow.h"
#include <Pdh.h>
#include <Psapi.h>
#include <ShlObj.h>
#include <VersionHelpers.h>
#include <windowsx.h>
/* IDXGIFactory6 */
#include <dxgi1_6.h>
#if defined(SOKOL_DEBUG) && SOKOL_DEBUG
#include <dxgidebug.h>
#endif /* SOKOL_DEBUG */
#include <d3d11.h>
#if defined(NANOEM_ENABLE_D3D11ON12)
#include <d3d11on12.h>
#endif /* NANOEM_ENABLE_D3D11ON12 */
#include "COMInline.h"
#include "Dialog.h"
#include "Preference.h"
#include "Win32ThreadedApplicationService.h"
#include "bx/commandline.h"
#include "bx/handlealloc.h"
#include "emapp/emapp.h"
#include "emapp/private/CommonInclude.h"
#include "imgui/imgui.h"
#include "sokol/sokol_time.h"
namespace nanoem {
namespace win32 {
namespace {
static char s_escapeTable[256];
static String
escapeString(const char *s)
{
String r;
r.reserve(strlen(s));
for (; *s; s++) {
if (s_escapeTable[*s]) {
bx::stringPrintf(r, "%c", s_escapeTable[*s]);
}
else {
bx::stringPrintf(r, "%%%02X", *s);
}
}
return r;
}
static void
createLastError(Error &error)
{
wchar_t buffer[1024];
MutableString msg;
const DWORD err = GetLastError();
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, LANG_USER_DEFAULT, buffer, ARRAYSIZE(buffer), 0);
StringUtils::getMultiBytesString(buffer, msg);
error = Error(msg.data(), err, Error::kDomainTypeOS);
}
} /* namespace anonymous */
MainWindow::MainWindow(const bx::CommandLine *cmd, const Preference *preference,
win32::Win32ThreadedApplicationService *service, ThreadedApplicationClient *client, HINSTANCE hInstance,
const Vector4UI32 &rect, nanoem_f32_t devicePixelRatio)
: m_preference(preference)
, m_commandLine(cmd)
, m_service(service)
, m_client(client)
, m_playingThresholder(60, false)
, m_editingThresholder(0, true)
{
ZeroMemory(&m_swapChainDesc, sizeof(m_swapChainDesc));
WNDCLASSEXW windowClass = {};
windowClass.cbSize = sizeof(windowClass);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = &handleWindowProc;
windowClass.hInstance = hInstance;
windowClass.hIcon = LoadIconW(nullptr, IDI_APPLICATION);
windowClass.hCursor = LoadCursorW(nullptr, IDC_ARROW);
windowClass.lpszClassName = Win32ThreadedApplicationService::kRegisterClassName;
windowClass.hIconSm = LoadIconW(nullptr, IDI_APPLICATION);
if (RegisterClassExW(&windowClass) != 0) {
static ACCEL accelerators[] = { { FVIRTKEY | FCONTROL, 'N',
ApplicationMenuBuilder::kMenuItemTypeFileNewProject },
{ FVIRTKEY | FCONTROL, 'O', ApplicationMenuBuilder::kMenuItemTypeFileOpenProject },
{ FVIRTKEY | FCONTROL, 'S', ApplicationMenuBuilder::kMenuItemTypeFileSaveProject },
{ FVIRTKEY | FCONTROL | FSHIFT, 'S', ApplicationMenuBuilder::kMenuItemTypeFileSaveAsProject },
{ FVIRTKEY | FCONTROL, 'P', ApplicationMenuBuilder::kMenuItemTypeFileExportImage },
{ FVIRTKEY | FCONTROL | FSHIFT, 'P', ApplicationMenuBuilder::kMenuItemTypeFileExportVideo },
{ FVIRTKEY | FALT, VK_F4, ApplicationMenuBuilder::kMenuItemTypeFileExit },
{ FVIRTKEY | FCONTROL, 'Z', ApplicationMenuBuilder::kMenuItemTypeEditUndo },
{ FVIRTKEY | FCONTROL, 'Y', ApplicationMenuBuilder::kMenuItemTypeEditRedo },
{ FVIRTKEY | FCONTROL, 'C', ApplicationMenuBuilder::kMenuItemTypeEditCopy },
{ FVIRTKEY | FCONTROL, 'X', ApplicationMenuBuilder::kMenuItemTypeEditCut },
{ FVIRTKEY | FCONTROL, 'V', ApplicationMenuBuilder::kMenuItemTypeEditPaste },
{ FVIRTKEY | FCONTROL, 'A', ApplicationMenuBuilder::kMenuItemTypeEditSelectAll },
{ FVIRTKEY | FCONTROL, '1', ApplicationMenuBuilder::kMenuItemTypeCameraPresetBottom },
{ FVIRTKEY | FCONTROL, '2', ApplicationMenuBuilder::kMenuItemTypeCameraPresetFront },
{ FVIRTKEY | FCONTROL, '4', ApplicationMenuBuilder::kMenuItemTypeCameraPresetLeft },
{ FVIRTKEY | FCONTROL, '5', ApplicationMenuBuilder::kMenuItemTypeCameraPresetTop },
{ FVIRTKEY | FCONTROL, '6', ApplicationMenuBuilder::kMenuItemTypeCameraPresetRight },
{ FVIRTKEY | FCONTROL, '8', ApplicationMenuBuilder::kMenuItemTypeCameraPresetBack },
{ FVIRTKEY | FCONTROL, ' ', ApplicationMenuBuilder::kMenuItemTypeProjectPlay },
{ FVIRTKEY | FCONTROL, '.', ApplicationMenuBuilder::kMenuItemTypeProjectStop } };
m_accelerators = CreateAcceleratorTableW(accelerators, BX_COUNTOF(accelerators));
m_devicePixelRatio = devicePixelRatio;
RECT windowRect = { 0, 0, LONG(rect.z * devicePixelRatio), LONG(rect.w * devicePixelRatio) };
AdjustWindowRectEx(&windowRect, WS_OVERLAPPEDWINDOW, TRUE, 0);
m_menuHandle = CreateMenu();
const ApplicationPreference preference(m_service);
m_menuBuilder =
new Win32ApplicationMenuBuilder(this, client, m_service->translator(), preference.isModelEditingEnabled());
m_menuBuilder->build();
m_windowHandle = CreateWindowExW(WS_EX_ACCEPTFILES | WS_EX_APPWINDOW, windowClass.lpszClassName,
windowClass.lpszClassName, WS_OVERLAPPEDWINDOW, Inline::saturateInt32(rect.x),
Inline::saturateInt32(rect.y), windowRect.right - windowRect.left, windowRect.bottom - windowRect.top,
nullptr, m_menuHandle, hInstance, this);
if (m_windowHandle) {
RegisterPowerSettingNotification(m_windowHandle, &GUID_ACDC_POWER_SOURCE, 0);
RegisterPowerSettingNotification(m_windowHandle, &GUID_POWER_SAVING_STATUS, 0);
RegisterPowerSettingNotification(m_windowHandle, &GUID_POWERSCHEME_PERSONALITY, 0);
}
}
}
MainWindow::~MainWindow()
{
destroyAllWatchEffectSources();
delete m_menuBuilder;
m_menuBuilder = nullptr;
}
bool
MainWindow::initialize(HWND windowHandle, Error &error)
{
for (size_t i = 0; i < BX_COUNTOF(s_escapeTable); i++) {
uint8_t c = uint8_t(i);
bool unescape = isalnum(c) || c == '~' || c == '-' || c == '.' || c == '_';
s_escapeTable[i] = unescape ? c : 0;
}
updateDisplayFrequency();
const Vector2UI16 windowSize(
Vector2(BaseApplicationService::minimumRequiredWindowSize()) * Vector2(m_devicePixelRatio));
String sokolPath(
json_object_dotget_string(json_object(m_service->applicationConfiguration()), "win32.plugin.path"));
const ApplicationPreference preference(m_service);
sg_pixel_format pixelFormat;
bool isLowPower, result;
#if defined(NANOEM_WIN32_HAS_OPENGL)
if (StringUtils::equalsIgnoreCase(preference.rendererBackend(), BaseApplicationService::kRendererOpenGL)) {
result = setupOpenGLRenderer(windowHandle, error);
sokolPath.append("sokol_glcore33.dll");
pixelFormat = SG_PIXELFORMAT_RGBA8;
isLowPower = result = true;
}
else
#endif /* NANOEM_WIN32_HAS_OPENGL */
{
result = setupDirectXRenderer(windowHandle, windowSize.x, windowSize.y, isLowPower, error);
sokolPath.append("sokol_d3d11.dll");
pixelFormat = SG_PIXELFORMAT_BGRA8;
}
if (result) {
m_logicalWindowSize = Vector2(windowSize) * invertedDevicePixelRatio();
const ApplicationPreference preference(m_service);
const ApplicationPreference::HighDPIViewportModeType mode = preference.highDPIViewportMode();
ThreadedApplicationClient::InitializeMessageDescription desc(
m_logicalWindowSize, pixelFormat, m_devicePixelRatio, sokolPath.c_str());
desc.m_bufferPoolSize = preference.gfxBufferPoolSize();
desc.m_imagePoolSize = preference.gfxImagePoolSize();
desc.m_shaderPoolSize = preference.gfxShaderPoolSize();
desc.m_passPoolSize = preference.gfxPassPoolSize();
desc.m_pipelinePoolSize = preference.gfxPipelinePoolSize();
desc.m_metalGlobalUniformBufferSize = preference.gfxUniformBufferSize();
if (mode == ApplicationPreference::kHighDPIViewportModeDisabled ||
(mode == ApplicationPreference::kHighDPIViewportModeAuto && isLowPower)) {
desc.m_viewportDevicePixelRatio = 1.0f;
}
m_client->sendInitializeMessage(desc);
}
return result;
}
bool
MainWindow::isRunning() const noexcept
{
return m_running;
}
void
MainWindow::processMessage(MSG *msg)
{
recenterCursor();
m_client->receiveAllEventMessages();
for (const auto &item : m_watchEffectSourceHandles) {
HANDLE ch = item.second.first;
if (WaitForSingleObject(ch, 0) == WAIT_OBJECT_0) {
const auto &handles = item.second.second;
for (const auto handle : handles) {
m_client->sendReloadAccessoryEffectMessage(handle);
m_client->sendReloadModelEffectMessage(handle);
}
FindNextChangeNotification(ch);
}
}
while (PeekMessageW(msg, nullptr, 0, 0, PM_REMOVE) != 0) {
if (!TranslateAcceleratorW(m_windowHandle, m_accelerators, msg)) {
TranslateMessage(msg);
DispatchMessageW(msg);
}
}
if (m_running) {
WaitMessage();
}
}
HWND
MainWindow::windowHandle() noexcept
{
return m_windowHandle;
}
HMENU
MainWindow::menuHandle() noexcept
{
return m_menuHandle;
}
void
MainWindow::clearTitle()
{
SetWindowTextW(m_windowHandle, L"nanoem");
}
void
MainWindow::setTitle(const URI &fileURI)
{
wchar_t title[256];
MutableWideString ws;
StringUtils::getWideCharString(fileURI.lastPathComponentConstString(), ws);
swprintf_s(title, L"%s - nanoem", ws.data());
SetWindowTextW(m_windowHandle, title);
}
nanoem_f32_t
MainWindow::invertedDevicePixelRatio() const noexcept
{
return 1.0f / m_devicePixelRatio;
}
void
MainWindow::newProject()
{
clearTitle();
m_client->sendNewProjectMessage();
}
void
MainWindow::openProject()
{
Dialog dialog(m_windowHandle);
Dialog::FilterList filters;
filters.push_back(COMDLG_FILTERSPEC { L"All Avaiable Project Format (*.nmm, *.nma, *.pmm)", L"*.nmm;*.nma;*.pmm" });
filters.push_back(COMDLG_FILTERSPEC { L"nanoem Project File (*.nmm)", L"*.nmm" });
filters.push_back(COMDLG_FILTERSPEC { L"nanoem Project Archive (*.nma)", L"*.nma" });
filters.push_back(COMDLG_FILTERSPEC { L"MikuMikuDance Project File (*.pmm)", L"*.pmm" });
if (dialog.open(filters)) {
loadProjectFromFile(dialog.filename());
}
}
void
MainWindow::saveProject()
{
m_client->sendGetProjectFileURIRequestMessage(
[](void *userData, const URI &fileURI) {
auto self = static_cast<MainWindow *>(userData);
const String &pathExtension = fileURI.pathExtension();
if (!fileURI.isEmpty() &&
(pathExtension == String("nma") || pathExtension == String("nmm") || pathExtension == String("pmm"))) {
self->saveFile(fileURI, IFileManager::kDialogTypeSaveProjectFile);
}
else {
self->saveProjectAs();
}
},
this);
}
void
MainWindow::saveProjectAs()
{
Dialog dialog(m_windowHandle);
Dialog::FilterList filters;
filters.push_back(COMDLG_FILTERSPEC { L"nanoem Project File (*.nmm)", L"*.nmm" });
filters.push_back(COMDLG_FILTERSPEC { L"nanoem Project Archive (*.nma)", L"*.nma" });
filters.push_back(COMDLG_FILTERSPEC { L"MikuMikuDance Project File (*.pmm)", L"*.pmm" });
if (dialog.save(filters, localizedString("nanoem.dialog.filename.untitled"))) {
setTitle(dialog.fileURI());
saveFile(dialog, IFileManager::kDialogTypeSaveProjectFile);
}
else {
m_client->clearAllCompleteSavingFileOnceEventListeners();
}
}
void
MainWindow::loadFile(const Dialog &dialog, IFileManager::DialogType type)
{
loadFile(dialog.fileURI(), type);
}
void
MainWindow::loadFile(const URI &fileURI, IFileManager::DialogType type)
{
IProgressDialog *dialog;
if (openProgressDialog(dialog)) {
dialog->SetTitle(localizedWideString("nanoem.dialog.progress.load.title"));
dialog->SetLine(1, localizedWideString("nanoem.dialog.progress.load.message"), FALSE, nullptr);
MutableWideString filePath;
StringUtils::getWideCharString(fileURI.absolutePathConstString(), filePath);
dialog->SetLine(2, filePath.data(), TRUE, nullptr);
m_client->addCompleteLoadingFileEventListener(
[](void *userData, const URI & /* fileURI */, uint32_t /* type */, uint64_t /* ticks */) {
auto self = static_cast<MainWindow *>(userData);
self->closeProgressDialog();
},
this, true);
}
m_client->sendLoadFileMessage(fileURI, type);
}
void
MainWindow::saveFile(const Dialog &dialog, IFileManager::DialogType type)
{
saveFile(dialog.fileURI(), type);
}
void
MainWindow::saveFile(const URI &fileURI, IFileManager::DialogType type)
{
IProgressDialog *dialog;
if (openProgressDialog(dialog)) {
dialog->SetTitle(localizedWideString("nanoem.dialog.progress.save.title"));
dialog->SetLine(1, localizedWideString("nanoem.dialog.progress.save.message"), FALSE, nullptr);
MutableWideString filePath;
StringUtils::getWideCharString(fileURI.absolutePathConstString(), filePath);
dialog->SetLine(2, filePath.data(), TRUE, nullptr);
m_client->addCompleteSavingFileEventListener(
[](void *userData, const URI & /* fileURI */, uint32_t /* type */, uint64_t /* ticks */) {
auto self = static_cast<MainWindow *>(userData);
self->closeProgressDialog();
},
this, true);
}
m_client->sendSaveFileMessage(fileURI, type);
}
void
MainWindow::exportImage()
{
m_client->addCompleteExportImageConfigurationEventListener(
[](void *userData, const StringList &availableExtensions) {
if (!availableExtensions.empty()) {
auto self = static_cast<MainWindow *>(userData);
Dialog dialog(self->m_windowHandle);
Dialog::FilterList filters;
if (dialog.save("Exportable Image Format (*.%s)", availableExtensions,
self->localizedString("nanoem.dialog.filename.untitled"))) {
self->m_client->sendExecuteExportingImageMessage(dialog.fileURI());
}
}
},
this, true);
m_client->sendRequestExportImageConfigurationMessage();
}
void
MainWindow::exportVideo()
{
m_client->addAvailableAllExportingVideoExtensionsEvent(
[](void *userData, const StringList & /* extensions */) {
auto self = static_cast<MainWindow *>(userData);
self->m_client->addCompleteExportVideoConfigurationEventListener(
[](void *userData, const StringList &availableExtensions) {
if (!availableExtensions.empty()) {
auto self = static_cast<MainWindow *>(userData);
Dialog dialog(self->m_windowHandle);
if (dialog.save("Exportable Video Format (*.%s)", availableExtensions,
self->localizedString("nanoem.dialog.filename.untitled"))) {
self->m_client->sendExecuteExportingVideoMessage(dialog.fileURI());
}
}
},
self, true);
self->m_client->sendRequestExportVideoConfigurationMessage();
},
this, true);
m_client->sendLoadAllEncoderPluginsMessage(cachedAggregateAllPlugins());
}
LRESULT CALLBACK
MainWindow::handleWindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
LRESULT result = S_OK;
switch (msg) {
case WM_CREATE: {
LPCREATESTRUCTW lpcs = reinterpret_cast<LPCREATESTRUCTW>(lparam);
if (auto self = static_cast<MainWindow *>(lpcs->lpCreateParams)) {
Error error;
if (!self->handleWindowCreate(hwnd, error)) {
self->m_running = false;
self->m_client->sendTerminateMessage();
result = -1;
wchar_t buffer[256];
MutableWideString ws;
StringUtils::getWideCharString(error.reasonConstString(), ws);
_snwprintf_s(buffer, BX_COUNTOF(buffer),
L"Failed to initialize nanoem due to failure of setup DirectX/OpenGL: %s", ws.data());
MessageBoxW(hwnd, buffer, L"nanoem", MB_ICONERROR);
DestroyAcceleratorTable(self->m_accelerators);
DestroyMenu(self->m_menuHandle);
}
}
break;
}
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_XBUTTONDOWN: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
const Vector2 coord(GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam));
self->handleMouseDown(hwnd, coord, convertCursorType(msg, wparam));
}
break;
}
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
case WM_XBUTTONUP: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
const Vector2 coord(GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam));
self->handleMouseUp(hwnd, coord, convertCursorType(msg, wparam));
}
break;
}
case WM_MOUSEMOVE: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
const Vector2SI32 coord(GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam));
self->handleMouseMove(hwnd, coord, convertCursorType(msg, wparam));
}
break;
}
case WM_MOUSEWHEEL: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
const Vector2SI32 delta(0, int16_t(HIWORD(wparam)) / WHEEL_DELTA);
self->handleMouseWheel(hwnd, delta);
}
break;
}
case WM_KEYDOWN: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
self->m_client->sendKeyPressMessage(static_cast<nanoem_u32_t>(translateKey(lparam)));
}
break;
}
case WM_KEYUP: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
self->m_client->sendKeyReleaseMessage(static_cast<nanoem_u32_t>(translateKey(lparam)));
}
break;
}
case WM_CHAR:
case WM_UNICHAR: {
auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
if (self && wparam >= 32) {
self->m_client->sendUnicodeInputMessage(static_cast<nanoem_u32_t>(wparam));
}
break;
}
case WM_ACTIVATE: {
auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
if (self) {
}
break;
}
case WM_SIZE: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
self->handleWindowResize(hwnd, wparam);
}
break;
}
case WM_MOVE: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
self->m_service->requestViewportWindowMove(hwnd);
}
break;
}
case WM_SIZING: {
auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
if (self && self->m_initialized && self->m_renderable) {
self->resizeWindow();
}
break;
}
case WM_WINDOWPOSCHANGED: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
self->handleWindowPositionChange(hwnd);
}
break;
}
case WM_GETMINMAXINFO: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
LPMINMAXINFO info = reinterpret_cast<LPMINMAXINFO>(lparam);
self->handleWindowConstraint(hwnd, info);
}
break;
}
case WM_DROPFILES: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
HDROP drop = reinterpret_cast<HDROP>(wparam);
self->handleWindowDropFile(hwnd, drop);
}
break;
}
case WM_DPICHANGED: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
auto rect = reinterpret_cast<const RECT *>(lparam);
const LONG width = rect->right - rect->left, height = rect->bottom - rect->top;
const nanoem_f32_t devicePixelRatio = LOWORD(wparam) / Win32ThreadedApplicationService::kStandardDPIValue,
invertDevicePixelRatio = 1.0f / devicePixelRatio;
const Vector2UI32 newSize(width * invertDevicePixelRatio, height * invertDevicePixelRatio);
self->m_devicePixelRatio = devicePixelRatio;
self->m_client->sendChangeDevicePixelRatioMessage(devicePixelRatio);
self->m_client->sendResizeWindowMessage(newSize);
self->m_logicalWindowSize = newSize;
SetWindowPos(hwnd, NULL, rect->left, rect->top, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
}
break;
}
case WM_DISPLAYCHANGE: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
self->updateDisplayFrequency();
self->m_service->requestUpdatingAllMonitors();
}
break;
}
case WM_SETFOCUS: {
auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
if (self && self->m_initialized && !self->m_renderable) {
self->setFocus();
self->m_renderable = true;
}
break;
}
case WM_KILLFOCUS: {
auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
if (self && self->m_initialized && self->m_renderable) {
self->killFocus();
self->m_renderable = false;
}
break;
}
case WM_POWERBROADCAST: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
if (const POWERBROADCAST_SETTING *settings = reinterpret_cast<POWERBROADCAST_SETTING *>(lparam)) {
self->updatePreferredFPS(settings);
}
}
break;
}
case WM_COMMAND: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
const uint32_t menuID = LOWORD(wparam);
ApplicationMenuBuilder::MenuItemType menuType = static_cast<ApplicationMenuBuilder::MenuItemType>(menuID);
self->handleMenuItem(hwnd, menuType);
}
return DefWindowProcW(hwnd, msg, wparam, lparam);
}
#if defined(IMGUI_HAS_VIEWPORT)
case Win32ThreadedApplicationService::ViewportData::kMessageTypeCreateWindow: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
HWND parentWindow = nullptr;
if (viewport->ParentViewportId != 0) {
if (ImGuiViewport *parent = ImGui::FindViewportByID(viewport->ParentViewportId)) {
parentWindow = static_cast<HWND>(parent->PlatformHandle);
}
}
RECT rect(Win32ThreadedApplicationService::ViewportData::rect(viewport));
userData->takeWindowStyle(viewport->Flags);
AdjustWindowRectEx(&rect, userData->m_style, FALSE, userData->m_styleEx);
UINT width = Win32ThreadedApplicationService::ViewportData::width(rect),
height = Win32ThreadedApplicationService::ViewportData::height(rect);
if (HWND windowHandle = CreateWindowExW(userData->m_styleEx,
Win32ThreadedApplicationService::kRegisterClassName, L"Untitled", userData->m_style, rect.left,
rect.top, width, height, parentWindow, nullptr, GetModuleHandleW(nullptr), nullptr)) {
auto self = static_cast<MainWindow *>(ImGui::GetIO().UserData);
SetWindowLongPtrW(windowHandle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(self));
userData->m_windowHandle = windowHandle;
userData->m_windowHandleOwned = true;
}
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeDestroyWindow: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
userData->destroyWindow();
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeShowWindow: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
DWORD flags =
EnumUtils::isEnabledT<ImGuiViewportFlags>(viewport->Flags, ImGuiViewportFlags_NoFocusOnAppearing)
? SW_SHOWNA
: SW_SHOW;
ShowWindow(userData->m_windowHandle, flags);
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeSetWindowPos: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto pos = reinterpret_cast<const ImVec2 *>(lparam);
RECT rect = { pos->x, pos->y, pos->x, pos->y };
AdjustWindowRectEx(&rect, userData->m_style, FALSE, userData->m_styleEx);
SetWindowPos(userData->m_windowHandle, nullptr, rect.left, rect.top, 0, 0,
SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeGetWindowPos: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto pos = reinterpret_cast<ImVec2 *>(lparam);
POINT point = {};
ClientToScreen(userData->m_windowHandle, &point);
*pos = ImVec2(point.x, point.y);
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeSetWindowSize: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto size = reinterpret_cast<const ImVec2 *>(lparam);
POINT point = {};
RECT rect = { 0, 0, size->x, size->y };
AdjustWindowRectEx(&rect, userData->m_style, FALSE, userData->m_styleEx);
SetWindowPos(userData->m_windowHandle, nullptr, 0, 0,
Win32ThreadedApplicationService::ViewportData::width(rect),
Win32ThreadedApplicationService::ViewportData::height(rect),
SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeGetWindowSize: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto size = reinterpret_cast<ImVec2 *>(lparam);
RECT rect;
GetClientRect(userData->m_windowHandle, &rect);
*size = Win32ThreadedApplicationService::ViewportData::size(rect);
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeSetWindowFocus: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
BringWindowToTop(userData->m_windowHandle);
SetForegroundWindow(userData->m_windowHandle);
SetFocus(userData->m_windowHandle);
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeGetWindowFocus: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto focused = reinterpret_cast<bool *>(lparam);
*focused = GetForegroundWindow() == userData->m_windowHandle;
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeGetWindowMinimized: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto minimized = reinterpret_cast<bool *>(lparam);
*minimized = IsIconic(userData->m_windowHandle) != 0;
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeSetWindowTitle: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto title = reinterpret_cast<const char *>(lparam);
MutableWideString ws;
StringUtils::getWideCharString(title, ws);
SetWindowTextW(userData->m_windowHandle, ws.data());
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeSetWindowAlpha: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto alpha = *reinterpret_cast<const float *>(lparam);
HWND windowHandle = userData->m_windowHandle;
DWORD style = GetWindowLongW(windowHandle, GWL_EXSTYLE);
if (alpha < 1.0f) {
style |= WS_EX_LAYERED;
SetWindowLongW(windowHandle, GWL_EXSTYLE, style);
SetLayeredWindowAttributes(windowHandle, 0, alpha * 0xff, LWA_ALPHA);
}
else {
style &= ~WS_EX_LAYERED;
SetWindowLongW(windowHandle, GWL_EXSTYLE, style);
}
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeUpdateWindow: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto updated = reinterpret_cast<bool *>(lparam);
DWORD style, styleEx;
Win32ThreadedApplicationService::ViewportData::getWindowStyle(viewport->Flags, style, styleEx);
if (userData->m_style != style || userData->m_styleEx != styleEx) {
userData->m_style = style;
userData->m_styleEx = style;
HWND windowHandle = userData->m_windowHandle;
SetWindowLongW(windowHandle, GWL_STYLE, style);
SetWindowLongW(windowHandle, GWL_EXSTYLE, styleEx);
RECT rect(Win32ThreadedApplicationService::ViewportData::rect(viewport));
AdjustWindowRectEx(&rect, style, FALSE, styleEx);
SetWindowPos(windowHandle, nullptr, rect.left, rect.top,
Win32ThreadedApplicationService::ViewportData::width(rect),
Win32ThreadedApplicationService::ViewportData::height(rect),
SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
ShowWindow(windowHandle, SW_SHOWNA);
*updated = true;
}
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeGetDpiScale: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto dpiScale = reinterpret_cast<float *>(lparam);
HMONITOR monitor = MonitorFromWindow(userData->m_windowHandle, MONITOR_DEFAULTTONEAREST);
*dpiScale = Win32ThreadedApplicationService::calculateDevicePixelRatio(monitor);
userData->signal();
}
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeOnChangedViewport: {
break;
}
case Win32ThreadedApplicationService::ViewportData::kMessageTypeSetIMEInputPos: {
auto viewport = reinterpret_cast<const ImGuiViewport *>(wparam);
if (auto userData = static_cast<Win32ThreadedApplicationService::ViewportData *>(viewport->PlatformUserData)) {
auto pos = reinterpret_cast<const ImVec2 *>(lparam);
COMPOSITIONFORM cf = { CFS_FORCE_POSITION,
{ static_cast<LONG>(pos->x - viewport->Pos.x), static_cast<LONG>(pos->y - viewport->Pos.y) },
{ 0, 0, 0, 0 } };
if (HWND windowHandle = static_cast<HWND>(viewport->PlatformHandle)) {
if (HIMC himc = ImmGetContext(windowHandle)) {
ImmSetCompositionWindow(himc, &cf);
ImmReleaseContext(windowHandle, himc);
}
}
userData->signal();
}
break;
}
#endif /* IMGUI_HAS_VIEWPORT */
case WM_CLOSE: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
self->handleWindowClose(hwnd);
}
break;
}
case WM_DESTROY: {
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
self->handleWindowDestroy(hwnd);
}
break;
}
default:
result = DefWindowProcW(hwnd, msg, wparam, lparam);
break;
}
if (auto self = reinterpret_cast<MainWindow *>(GetWindowLongPtrW(hwnd, GWLP_USERDATA))) {
if (IProgressDialog *dialog = self->m_progressDialog.first) {
if (dialog->HasUserCancelled()) {
Progress::requestCancel();
self->closeProgressDialog();
}
}
}
return result;
}
DWORD CALLBACK
MainWindow::collectPerformanceMetricsPeriodically(void *userData)
{
auto self = static_cast<MainWindow *>(userData);
PROCESS_MEMORY_COUNTERS counters = {};
PDH_HQUERY query = nullptr;
PDH_HCOUNTER counter = nullptr;
PDH_FMT_COUNTERVALUE value = {};
GetProcessMemoryInfo(self->m_processHandle, &counters, sizeof(counters));
self->m_client->sendUpdatePerformanceMonitorMessage(nanoem_f32_t(value.doubleValue), counters.WorkingSetSize, 0);
PdhOpenQueryW(nullptr, 0, &query);
PdhAddCounterW(query, L"\\Process(nanoem)\\% User Time", 0, &counter);
PdhCollectQueryData(query);
while (self->m_running) {
Sleep(1000);
PdhCollectQueryData(query);
PdhGetFormattedCounterValue(counter, PDH_FMT_DOUBLE, nullptr, &value);
GetProcessMemoryInfo(self->m_processHandle, &counters, sizeof(counters));
self->m_client->sendUpdatePerformanceMonitorMessage(
nanoem_f32_t(value.doubleValue), counters.WorkingSetSize, 0);
}
PdhCloseQuery(query);
return 0;
}
BaseApplicationService::KeyType
MainWindow::translateKey(LPARAM lparam) noexcept
{
BaseApplicationService::KeyType key;
switch (HIWORD(lparam) & 0x1ff) {
case 0x00B:
key = BaseApplicationService::kKeyType_0;
break;
case 0x002:
key = BaseApplicationService::kKeyType_1;
break;
case 0x003:
key = BaseApplicationService::kKeyType_2;
break;
case 0x004:
key = BaseApplicationService::kKeyType_3;
break;
case 0x005:
key = BaseApplicationService::kKeyType_4;
break;
case 0x006:
key = BaseApplicationService::kKeyType_5;
break;
case 0x007:
key = BaseApplicationService::kKeyType_6;
break;
case 0x008:
key = BaseApplicationService::kKeyType_7;
break;
case 0x009:
key = BaseApplicationService::kKeyType_8;
break;
case 0x00A:
key = BaseApplicationService::kKeyType_9;
break;
case 0x01E:
key = BaseApplicationService::kKeyType_A;
break;
case 0x030:
key = BaseApplicationService::kKeyType_B;
break;
case 0x02E:
key = BaseApplicationService::kKeyType_C;
break;
case 0x020:
key = BaseApplicationService::kKeyType_D;
break;
case 0x012:
key = BaseApplicationService::kKeyType_E;
break;
case 0x021:
key = BaseApplicationService::kKeyType_F;
break;
case 0x022:
key = BaseApplicationService::kKeyType_G;
break;
case 0x023:
key = BaseApplicationService::kKeyType_H;
break;
case 0x017:
key = BaseApplicationService::kKeyType_I;
break;
case 0x024:
key = BaseApplicationService::kKeyType_J;
break;
case 0x025:
key = BaseApplicationService::kKeyType_K;
break;
case 0x026:
key = BaseApplicationService::kKeyType_L;
break;
case 0x032:
key = BaseApplicationService::kKeyType_M;
break;
case 0x031:
key = BaseApplicationService::kKeyType_N;
break;
case 0x018:
key = BaseApplicationService::kKeyType_O;
break;
case 0x019:
key = BaseApplicationService::kKeyType_P;
break;
case 0x010:
key = BaseApplicationService::kKeyType_Q;
break;
case 0x013:
key = BaseApplicationService::kKeyType_R;
break;
case 0x01F:
key = BaseApplicationService::kKeyType_S;
break;
case 0x014:
key = BaseApplicationService::kKeyType_T;
break;
case 0x016:
key = BaseApplicationService::kKeyType_U;
break;
case 0x02F:
key = BaseApplicationService::kKeyType_V;
break;
case 0x011:
key = BaseApplicationService::kKeyType_W;
break;
case 0x02D:
key = BaseApplicationService::kKeyType_X;
break;
case 0x015:
key = BaseApplicationService::kKeyType_Y;
break;
case 0x02C:
key = BaseApplicationService::kKeyType_Z;
break;
case 0x028:
key = BaseApplicationService::kKeyType_APOSTROPHE;
break;
case 0x02B:
key = BaseApplicationService::kKeyType_BACKSLASH;
break;
case 0x033:
key = BaseApplicationService::kKeyType_COMMA;
break;
case 0x00D:
key = BaseApplicationService::kKeyType_EQUAL;
break;
case 0x029:
key = BaseApplicationService::kKeyType_GRAVE_ACCENT;
break;
case 0x01A:
key = BaseApplicationService::kKeyType_LEFT_BRACKET;
break;
case 0x00C:
key = BaseApplicationService::kKeyType_MINUS;
break;
case 0x034:
key = BaseApplicationService::kKeyType_PERIOD;
break;
case 0x01B:
key = BaseApplicationService::kKeyType_RIGHT_BRACKET;
break;
case 0x027:
key = BaseApplicationService::kKeyType_SEMICOLON;
break;
case 0x035:
key = BaseApplicationService::kKeyType_SLASH;
break;
case 0x056:
key = BaseApplicationService::kKeyType_WORLD_2;