forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWinUtils.cpp
1280 lines (1114 loc) · 37.3 KB
/
WinUtils.cpp
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sts=2 sw=2 et cin: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "WinUtils.h"
#include "gfxPlatform.h"
#include "gfxUtils.h"
#include "nsWindow.h"
#include "nsWindowDefs.h"
#include "KeyboardLayout.h"
#include "nsIDOMMouseEvent.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/DataSurfaceHelpers.h"
#include "mozilla/Preferences.h"
#include "mozilla/RefPtr.h"
#include "mozilla/WindowsVersion.h"
#ifdef MOZ_LOGGING
#define FORCE_PR_LOG /* Allow logging in the release build */
#endif // MOZ_LOGGING
#include "prlog.h"
#include "nsString.h"
#include "nsDirectoryServiceUtils.h"
#include "imgIContainer.h"
#include "imgITools.h"
#include "nsStringStream.h"
#include "nsNetUtil.h"
#ifdef MOZ_PLACES
#include "mozIAsyncFavicons.h"
#endif
#include "nsIIconURI.h"
#include "nsIDownloader.h"
#include "nsINetUtil.h"
#include "nsIChannel.h"
#include "nsIObserver.h"
#include "imgIEncoder.h"
#include "nsIThread.h"
#include "MainThreadUtils.h"
#include "gfxColor.h"
#ifdef MOZ_METRO
#include "winrt/MetroInput.h"
#include "winrt/MetroUtils.h"
#endif // MOZ_METRO
#ifdef NS_ENABLE_TSF
#include <textstor.h>
#include "nsTextStore.h"
#endif // #ifdef NS_ENABLE_TSF
#ifdef PR_LOGGING
PRLogModuleInfo* gWindowsLog = nullptr;
#endif
using namespace mozilla::gfx;
namespace mozilla {
namespace widget {
NS_IMPL_ISUPPORTS(myDownloadObserver, nsIDownloadObserver)
#ifdef MOZ_PLACES
NS_IMPL_ISUPPORTS(AsyncFaviconDataReady, nsIFaviconDataCallback)
#endif
NS_IMPL_ISUPPORTS(AsyncEncodeAndWriteIcon, nsIRunnable)
NS_IMPL_ISUPPORTS(AsyncDeleteIconFromDisk, nsIRunnable)
NS_IMPL_ISUPPORTS(AsyncDeleteAllFaviconsFromDisk, nsIRunnable)
const char FaviconHelper::kJumpListCacheDir[] = "jumpListCache";
const char FaviconHelper::kShortcutCacheDir[] = "shortcutCache";
// apis available on vista and up.
WinUtils::SHCreateItemFromParsingNamePtr WinUtils::sCreateItemFromParsingName = nullptr;
WinUtils::SHGetKnownFolderPathPtr WinUtils::sGetKnownFolderPath = nullptr;
// We just leak these DLL HMODULEs. There's no point in calling FreeLibrary
// on them during shutdown anyway.
static const wchar_t kShellLibraryName[] = L"shell32.dll";
static HMODULE sShellDll = nullptr;
static const wchar_t kDwmLibraryName[] = L"dwmapi.dll";
static HMODULE sDwmDll = nullptr;
WinUtils::DwmExtendFrameIntoClientAreaProc WinUtils::dwmExtendFrameIntoClientAreaPtr = nullptr;
WinUtils::DwmIsCompositionEnabledProc WinUtils::dwmIsCompositionEnabledPtr = nullptr;
WinUtils::DwmSetIconicThumbnailProc WinUtils::dwmSetIconicThumbnailPtr = nullptr;
WinUtils::DwmSetIconicLivePreviewBitmapProc WinUtils::dwmSetIconicLivePreviewBitmapPtr = nullptr;
WinUtils::DwmGetWindowAttributeProc WinUtils::dwmGetWindowAttributePtr = nullptr;
WinUtils::DwmSetWindowAttributeProc WinUtils::dwmSetWindowAttributePtr = nullptr;
WinUtils::DwmInvalidateIconicBitmapsProc WinUtils::dwmInvalidateIconicBitmapsPtr = nullptr;
WinUtils::DwmDefWindowProcProc WinUtils::dwmDwmDefWindowProcPtr = nullptr;
WinUtils::DwmGetCompositionTimingInfoProc WinUtils::dwmGetCompositionTimingInfoPtr = nullptr;
/* static */
void
WinUtils::Initialize()
{
#ifdef PR_LOGGING
if (!gWindowsLog) {
gWindowsLog = PR_NewLogModule("Widget");
}
#endif
if (!sDwmDll && IsVistaOrLater()) {
sDwmDll = ::LoadLibraryW(kDwmLibraryName);
if (sDwmDll) {
dwmExtendFrameIntoClientAreaPtr = (DwmExtendFrameIntoClientAreaProc)::GetProcAddress(sDwmDll, "DwmExtendFrameIntoClientArea");
dwmIsCompositionEnabledPtr = (DwmIsCompositionEnabledProc)::GetProcAddress(sDwmDll, "DwmIsCompositionEnabled");
dwmSetIconicThumbnailPtr = (DwmSetIconicThumbnailProc)::GetProcAddress(sDwmDll, "DwmSetIconicThumbnail");
dwmSetIconicLivePreviewBitmapPtr = (DwmSetIconicLivePreviewBitmapProc)::GetProcAddress(sDwmDll, "DwmSetIconicLivePreviewBitmap");
dwmGetWindowAttributePtr = (DwmGetWindowAttributeProc)::GetProcAddress(sDwmDll, "DwmGetWindowAttribute");
dwmSetWindowAttributePtr = (DwmSetWindowAttributeProc)::GetProcAddress(sDwmDll, "DwmSetWindowAttribute");
dwmInvalidateIconicBitmapsPtr = (DwmInvalidateIconicBitmapsProc)::GetProcAddress(sDwmDll, "DwmInvalidateIconicBitmaps");
dwmDwmDefWindowProcPtr = (DwmDefWindowProcProc)::GetProcAddress(sDwmDll, "DwmDefWindowProc");
dwmGetCompositionTimingInfoPtr = (DwmGetCompositionTimingInfoProc)::GetProcAddress(sDwmDll, "DwmGetCompositionTimingInfo");
}
}
}
// static
void
WinUtils::LogW(const wchar_t *fmt, ...)
{
va_list args = nullptr;
if(!lstrlenW(fmt)) {
return;
}
va_start(args, fmt);
int buflen = _vscwprintf(fmt, args);
wchar_t* buffer = new wchar_t[buflen+1];
if (!buffer) {
va_end(args);
return;
}
vswprintf(buffer, buflen, fmt, args);
va_end(args);
// MSVC, including remote debug sessions
OutputDebugStringW(buffer);
OutputDebugStringW(L"\n");
int len = wcslen(buffer);
if (len) {
char* utf8 = new char[len+1];
memset(utf8, 0, sizeof(utf8));
if (WideCharToMultiByte(CP_ACP, 0, buffer,
-1, utf8, len+1, nullptr,
nullptr) > 0) {
// desktop console
printf("%s\n", utf8);
#ifdef PR_LOGGING
NS_ASSERTION(gWindowsLog, "Called WinUtils Log() but Widget "
"log module doesn't exist!");
PR_LOG(gWindowsLog, PR_LOG_ALWAYS, (utf8));
#endif
}
delete[] utf8;
}
delete[] buffer;
}
// static
void
WinUtils::Log(const char *fmt, ...)
{
va_list args = nullptr;
if(!strlen(fmt)) {
return;
}
va_start(args, fmt);
int buflen = _vscprintf(fmt, args);
char* buffer = new char[buflen+1];
if (!buffer) {
va_end(args);
return;
}
vsprintf(buffer, fmt, args);
va_end(args);
// MSVC, including remote debug sessions
OutputDebugStringA(buffer);
OutputDebugStringW(L"\n");
// desktop console
printf("%s\n", buffer);
#ifdef PR_LOGGING
NS_ASSERTION(gWindowsLog, "Called WinUtils Log() but Widget "
"log module doesn't exist!");
PR_LOG(gWindowsLog, PR_LOG_ALWAYS, (buffer));
#endif
delete[] buffer;
}
/* static */
double
WinUtils::LogToPhysFactor()
{
// dpi / 96.0
if (XRE_GetWindowsEnvironment() == WindowsEnvironmentType_Metro) {
#ifdef MOZ_METRO
return MetroUtils::LogToPhysFactor();
#else
return 1.0;
#endif
} else {
HDC hdc = ::GetDC(nullptr);
double result = ::GetDeviceCaps(hdc, LOGPIXELSY) / 96.0;
::ReleaseDC(nullptr, hdc);
if (result == 0) {
// Bug 1012487 - This can occur when the Screen DC is used off the
// main thread on windows. For now just assume a 100% DPI for this
// drawing call.
// XXX - fixme!
result = 1.0;
}
return result;
}
}
/* static */
double
WinUtils::PhysToLogFactor()
{
// 1.0 / (dpi / 96.0)
return 1.0 / LogToPhysFactor();
}
/* static */
double
WinUtils::PhysToLog(int32_t aValue)
{
return double(aValue) * PhysToLogFactor();
}
/* static */
int32_t
WinUtils::LogToPhys(double aValue)
{
return int32_t(NS_round(aValue * LogToPhysFactor()));
}
/* static */
bool
WinUtils::PeekMessage(LPMSG aMsg, HWND aWnd, UINT aFirstMessage,
UINT aLastMessage, UINT aOption)
{
#ifdef NS_ENABLE_TSF
ITfMessagePump* msgPump = nsTextStore::GetMessagePump();
if (msgPump) {
BOOL ret = FALSE;
HRESULT hr = msgPump->PeekMessageW(aMsg, aWnd, aFirstMessage, aLastMessage,
aOption, &ret);
NS_ENSURE_TRUE(SUCCEEDED(hr), false);
return ret;
}
#endif // #ifdef NS_ENABLE_TSF
return ::PeekMessageW(aMsg, aWnd, aFirstMessage, aLastMessage, aOption);
}
/* static */
bool
WinUtils::GetMessage(LPMSG aMsg, HWND aWnd, UINT aFirstMessage,
UINT aLastMessage)
{
#ifdef NS_ENABLE_TSF
ITfMessagePump* msgPump = nsTextStore::GetMessagePump();
if (msgPump) {
BOOL ret = FALSE;
HRESULT hr = msgPump->GetMessageW(aMsg, aWnd, aFirstMessage, aLastMessage,
&ret);
NS_ENSURE_TRUE(SUCCEEDED(hr), false);
return ret;
}
#endif // #ifdef NS_ENABLE_TSF
return ::GetMessageW(aMsg, aWnd, aFirstMessage, aLastMessage);
}
/* static */
void
WinUtils::WaitForMessage()
{
DWORD result = ::MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_ALLINPUT,
MWMO_INPUTAVAILABLE);
NS_WARN_IF_FALSE(result != WAIT_FAILED, "Wait failed");
// This idiom is taken from the Chromium ipc code, see
// ipc/chromium/src/base/message+puimp_win.cpp:270.
// The intent is to avoid a busy wait when MsgWaitForMultipleObjectsEx
// returns quickly but PeekMessage would not return a message.
if (result == WAIT_OBJECT_0) {
MSG msg = {0};
DWORD queue_status = ::GetQueueStatus(QS_MOUSE);
if (HIWORD(queue_status) & QS_MOUSE &&
!PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_NOREMOVE)) {
::WaitMessage();
}
}
}
/* static */
bool
WinUtils::GetRegistryKey(HKEY aRoot,
char16ptr_t aKeyName,
char16ptr_t aValueName,
wchar_t* aBuffer,
DWORD aBufferLength)
{
NS_PRECONDITION(aKeyName, "The key name is NULL");
HKEY key;
LONG result =
::RegOpenKeyExW(aRoot, aKeyName, 0, KEY_READ | KEY_WOW64_32KEY, &key);
if (result != ERROR_SUCCESS) {
result =
::RegOpenKeyExW(aRoot, aKeyName, 0, KEY_READ | KEY_WOW64_64KEY, &key);
if (result != ERROR_SUCCESS) {
return false;
}
}
DWORD type;
result =
::RegQueryValueExW(key, aValueName, nullptr, &type, (BYTE*) aBuffer,
&aBufferLength);
::RegCloseKey(key);
if (result != ERROR_SUCCESS || type != REG_SZ) {
return false;
}
if (aBuffer) {
aBuffer[aBufferLength / sizeof(*aBuffer) - 1] = 0;
}
return true;
}
/* static */
bool
WinUtils::HasRegistryKey(HKEY aRoot, char16ptr_t aKeyName)
{
MOZ_ASSERT(aRoot, "aRoot must not be NULL");
MOZ_ASSERT(aKeyName, "aKeyName must not be NULL");
HKEY key;
LONG result =
::RegOpenKeyExW(aRoot, aKeyName, 0, KEY_READ | KEY_WOW64_32KEY, &key);
if (result != ERROR_SUCCESS) {
result =
::RegOpenKeyExW(aRoot, aKeyName, 0, KEY_READ | KEY_WOW64_64KEY, &key);
if (result != ERROR_SUCCESS) {
return false;
}
}
::RegCloseKey(key);
return true;
}
/* static */
HWND
WinUtils::GetTopLevelHWND(HWND aWnd,
bool aStopIfNotChild,
bool aStopIfNotPopup)
{
HWND curWnd = aWnd;
HWND topWnd = nullptr;
while (curWnd) {
topWnd = curWnd;
if (aStopIfNotChild) {
DWORD_PTR style = ::GetWindowLongPtrW(curWnd, GWL_STYLE);
VERIFY_WINDOW_STYLE(style);
if (!(style & WS_CHILD)) // first top-level window
break;
}
HWND upWnd = ::GetParent(curWnd); // Parent or owner (if has no parent)
// GetParent will only return the owner if the passed in window
// has the WS_POPUP style.
if (!upWnd && !aStopIfNotPopup) {
upWnd = ::GetWindow(curWnd, GW_OWNER);
}
curWnd = upWnd;
}
return topWnd;
}
static const wchar_t*
GetNSWindowPropName()
{
static wchar_t sPropName[40] = L"";
if (!*sPropName) {
_snwprintf(sPropName, 39, L"MozillansIWidgetPtr%p",
::GetCurrentProcessId());
sPropName[39] = '\0';
}
return sPropName;
}
/* static */
bool
WinUtils::SetNSWindowBasePtr(HWND aWnd, nsWindowBase* aWidget)
{
if (!aWidget) {
::RemovePropW(aWnd, GetNSWindowPropName());
return true;
}
return ::SetPropW(aWnd, GetNSWindowPropName(), (HANDLE)aWidget);
}
/* static */
nsWindowBase*
WinUtils::GetNSWindowBasePtr(HWND aWnd)
{
return static_cast<nsWindowBase*>(::GetPropW(aWnd, GetNSWindowPropName()));
}
/* static */
nsWindow*
WinUtils::GetNSWindowPtr(HWND aWnd)
{
return static_cast<nsWindow*>(::GetPropW(aWnd, GetNSWindowPropName()));
}
static BOOL CALLBACK
AddMonitor(HMONITOR, HDC, LPRECT, LPARAM aParam)
{
(*(int32_t*)aParam)++;
return TRUE;
}
/* static */
int32_t
WinUtils::GetMonitorCount()
{
int32_t monitorCount = 0;
EnumDisplayMonitors(nullptr, nullptr, AddMonitor, (LPARAM)&monitorCount);
return monitorCount;
}
/* static */
bool
WinUtils::IsOurProcessWindow(HWND aWnd)
{
if (!aWnd) {
return false;
}
DWORD processId = 0;
::GetWindowThreadProcessId(aWnd, &processId);
return (processId == ::GetCurrentProcessId());
}
/* static */
HWND
WinUtils::FindOurProcessWindow(HWND aWnd)
{
for (HWND wnd = ::GetParent(aWnd); wnd; wnd = ::GetParent(wnd)) {
if (IsOurProcessWindow(wnd)) {
return wnd;
}
}
return nullptr;
}
static bool
IsPointInWindow(HWND aWnd, const POINT& aPointInScreen)
{
RECT bounds;
if (!::GetWindowRect(aWnd, &bounds)) {
return false;
}
return (aPointInScreen.x >= bounds.left && aPointInScreen.x < bounds.right &&
aPointInScreen.y >= bounds.top && aPointInScreen.y < bounds.bottom);
}
/**
* FindTopmostWindowAtPoint() returns the topmost child window (topmost means
* forground in this context) of aWnd.
*/
static HWND
FindTopmostWindowAtPoint(HWND aWnd, const POINT& aPointInScreen)
{
if (!::IsWindowVisible(aWnd) || !IsPointInWindow(aWnd, aPointInScreen)) {
return nullptr;
}
HWND childWnd = ::GetTopWindow(aWnd);
while (childWnd) {
HWND topmostWnd = FindTopmostWindowAtPoint(childWnd, aPointInScreen);
if (topmostWnd) {
return topmostWnd;
}
childWnd = ::GetNextWindow(childWnd, GW_HWNDNEXT);
}
return aWnd;
}
struct FindOurWindowAtPointInfo
{
POINT mInPointInScreen;
HWND mOutWnd;
};
static BOOL CALLBACK
FindOurWindowAtPointCallback(HWND aWnd, LPARAM aLPARAM)
{
if (!WinUtils::IsOurProcessWindow(aWnd)) {
// This isn't one of our top-level windows; continue enumerating.
return TRUE;
}
// Get the top-most child window under the point. If there's no child
// window, and the point is within the top-level window, then the top-level
// window will be returned. (This is the usual case. A child window
// would be returned for plugins.)
FindOurWindowAtPointInfo* info =
reinterpret_cast<FindOurWindowAtPointInfo*>(aLPARAM);
HWND childWnd = FindTopmostWindowAtPoint(aWnd, info->mInPointInScreen);
if (!childWnd) {
// This window doesn't contain the point; continue enumerating.
return TRUE;
}
// Return the HWND and stop enumerating.
info->mOutWnd = childWnd;
return FALSE;
}
/* static */
HWND
WinUtils::FindOurWindowAtPoint(const POINT& aPointInScreen)
{
FindOurWindowAtPointInfo info;
info.mInPointInScreen = aPointInScreen;
info.mOutWnd = nullptr;
// This will enumerate all top-level windows in order from top to bottom.
EnumWindows(FindOurWindowAtPointCallback, reinterpret_cast<LPARAM>(&info));
return info.mOutWnd;
}
/* static */
UINT
WinUtils::GetInternalMessage(UINT aNativeMessage)
{
switch (aNativeMessage) {
case WM_MOUSEWHEEL:
return MOZ_WM_MOUSEVWHEEL;
case WM_MOUSEHWHEEL:
return MOZ_WM_MOUSEHWHEEL;
case WM_VSCROLL:
return MOZ_WM_VSCROLL;
case WM_HSCROLL:
return MOZ_WM_HSCROLL;
default:
return aNativeMessage;
}
}
/* static */
UINT
WinUtils::GetNativeMessage(UINT aInternalMessage)
{
switch (aInternalMessage) {
case MOZ_WM_MOUSEVWHEEL:
return WM_MOUSEWHEEL;
case MOZ_WM_MOUSEHWHEEL:
return WM_MOUSEHWHEEL;
case MOZ_WM_VSCROLL:
return WM_VSCROLL;
case MOZ_WM_HSCROLL:
return WM_HSCROLL;
default:
return aInternalMessage;
}
}
/* static */
uint16_t
WinUtils::GetMouseInputSource()
{
int32_t inputSource = nsIDOMMouseEvent::MOZ_SOURCE_MOUSE;
LPARAM lParamExtraInfo = ::GetMessageExtraInfo();
if ((lParamExtraInfo & TABLET_INK_SIGNATURE) == TABLET_INK_CHECK) {
inputSource = (lParamExtraInfo & TABLET_INK_TOUCH) ?
nsIDOMMouseEvent::MOZ_SOURCE_TOUCH : nsIDOMMouseEvent::MOZ_SOURCE_PEN;
}
return static_cast<uint16_t>(inputSource);
}
bool
WinUtils::GetIsMouseFromTouch(uint32_t aEventType)
{
#define MOUSEEVENTF_FROMTOUCH 0xFF515700
return (aEventType == NS_MOUSE_BUTTON_DOWN ||
aEventType == NS_MOUSE_BUTTON_UP ||
aEventType == NS_MOUSE_MOVE) &&
(GetMessageExtraInfo() & MOUSEEVENTF_FROMTOUCH);
}
/* static */
MSG
WinUtils::InitMSG(UINT aMessage, WPARAM wParam, LPARAM lParam, HWND aWnd)
{
MSG msg;
msg.message = aMessage;
msg.wParam = wParam;
msg.lParam = lParam;
msg.hwnd = aWnd;
return msg;
}
/* static */
HRESULT
WinUtils::SHCreateItemFromParsingName(PCWSTR pszPath, IBindCtx *pbc,
REFIID riid, void **ppv)
{
if (sCreateItemFromParsingName) {
return sCreateItemFromParsingName(pszPath, pbc, riid, ppv);
}
if (!sShellDll) {
sShellDll = ::LoadLibraryW(kShellLibraryName);
if (!sShellDll) {
return false;
}
}
sCreateItemFromParsingName = (SHCreateItemFromParsingNamePtr)
GetProcAddress(sShellDll, "SHCreateItemFromParsingName");
if (!sCreateItemFromParsingName)
return E_FAIL;
return sCreateItemFromParsingName(pszPath, pbc, riid, ppv);
}
/* static */
HRESULT
WinUtils::SHGetKnownFolderPath(REFKNOWNFOLDERID rfid,
DWORD dwFlags,
HANDLE hToken,
PWSTR *ppszPath)
{
if (sGetKnownFolderPath) {
return sGetKnownFolderPath(rfid, dwFlags, hToken, ppszPath);
}
if (!sShellDll) {
sShellDll = ::LoadLibraryW(kShellLibraryName);
if (!sShellDll) {
return false;
}
}
sGetKnownFolderPath = (SHGetKnownFolderPathPtr)
GetProcAddress(sShellDll, "SHGetKnownFolderPath");
if (!sGetKnownFolderPath)
return E_FAIL;
return sGetKnownFolderPath(rfid, dwFlags, hToken, ppszPath);
}
#ifdef MOZ_PLACES
/************************************************************************/
/* Constructs as AsyncFaviconDataReady Object
/* @param aIOThread : the thread which performs the action
/* @param aURLShortcut : Differentiates between (false)Jumplistcache and (true)Shortcutcache
/************************************************************************/
AsyncFaviconDataReady::AsyncFaviconDataReady(nsIURI *aNewURI,
nsCOMPtr<nsIThread> &aIOThread,
const bool aURLShortcut):
mNewURI(aNewURI),
mIOThread(aIOThread),
mURLShortcut(aURLShortcut)
{
}
NS_IMETHODIMP
myDownloadObserver::OnDownloadComplete(nsIDownloader *downloader,
nsIRequest *request,
nsISupports *ctxt,
nsresult status,
nsIFile *result)
{
return NS_OK;
}
nsresult AsyncFaviconDataReady::OnFaviconDataNotAvailable(void)
{
if (!mURLShortcut) {
return NS_OK;
}
nsCOMPtr<nsIFile> icoFile;
nsresult rv = FaviconHelper::GetOutputIconPath(mNewURI, icoFile, mURLShortcut);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIURI> mozIconURI;
rv = NS_NewURI(getter_AddRefs(mozIconURI), "moz-icon://.html?size=32");
if (NS_FAILED(rv)) {
return rv;
}
nsCOMPtr<nsIChannel> channel;
rv = NS_NewChannel(getter_AddRefs(channel), mozIconURI);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIDownloadObserver> downloadObserver = new myDownloadObserver;
nsCOMPtr<nsIStreamListener> listener;
rv = NS_NewDownloader(getter_AddRefs(listener), downloadObserver, icoFile);
NS_ENSURE_SUCCESS(rv, rv);
channel->AsyncOpen(listener, nullptr);
return NS_OK;
}
NS_IMETHODIMP
AsyncFaviconDataReady::OnComplete(nsIURI *aFaviconURI,
uint32_t aDataLen,
const uint8_t *aData,
const nsACString &aMimeType)
{
if (!aDataLen || !aData) {
if (mURLShortcut) {
OnFaviconDataNotAvailable();
}
return NS_OK;
}
nsCOMPtr<nsIFile> icoFile;
nsresult rv = FaviconHelper::GetOutputIconPath(mNewURI, icoFile, mURLShortcut);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString path;
rv = icoFile->GetPath(path);
NS_ENSURE_SUCCESS(rv, rv);
// Convert the obtained favicon data to an input stream
nsCOMPtr<nsIInputStream> stream;
rv = NS_NewByteInputStream(getter_AddRefs(stream),
reinterpret_cast<const char*>(aData),
aDataLen,
NS_ASSIGNMENT_DEPEND);
NS_ENSURE_SUCCESS(rv, rv);
// Decode the image from the format it was returned to us in (probably PNG)
nsCOMPtr<imgIContainer> container;
nsCOMPtr<imgITools> imgtool = do_CreateInstance("@mozilla.org/image/tools;1");
rv = imgtool->DecodeImageData(stream, aMimeType,
getter_AddRefs(container));
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<SourceSurface> surface =
container->GetFrame(imgIContainer::FRAME_FIRST, 0);
NS_ENSURE_TRUE(surface, NS_ERROR_FAILURE);
RefPtr<DataSourceSurface> dataSurface;
IntSize size;
if (mURLShortcut) {
// Create a 48x48 surface and paint the icon into the central 16x16 rect.
size.width = 48;
size.height = 48;
dataSurface =
Factory::CreateDataSourceSurface(size, SurfaceFormat::B8G8R8A8);
NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
DataSourceSurface::MappedSurface map;
if (!dataSurface->Map(DataSourceSurface::MapType::WRITE, &map)) {
return NS_ERROR_FAILURE;
}
RefPtr<DrawTarget> dt =
Factory::CreateDrawTargetForData(BackendType::CAIRO,
map.mData,
dataSurface->GetSize(),
map.mStride,
dataSurface->GetFormat());
dt->FillRect(Rect(0, 0, size.width, size.height),
ColorPattern(Color(1.0f, 1.0f, 1.0f, 1.0f)));
dt->DrawSurface(surface,
Rect(16, 16, 16, 16),
Rect(Point(0, 0),
Size(surface->GetSize().width, surface->GetSize().height)));
dataSurface->Unmap();
} else {
// By using the input image surface's size, we may end up encoding
// to a different size than a 16x16 (or bigger for higher DPI) ICO, but
// Windows will resize appropriately for us. If we want to encode ourselves
// one day because we like our resizing better, we'd have to manually
// resize the image here and use GetSystemMetrics w/ SM_CXSMICON and
// SM_CYSMICON. We don't support resizing images asynchronously at the
// moment anyway so getting the DPI aware icon size won't help.
size.width = surface->GetSize().width;
size.height = surface->GetSize().height;
dataSurface = surface->GetDataSurface();
NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
}
// Allocate a new buffer that we own and can use out of line in
// another thread.
uint8_t *data = SurfaceToPackedBGRA(dataSurface);
if (!data) {
return NS_ERROR_OUT_OF_MEMORY;
}
int32_t stride = 4 * size.width;
int32_t dataLength = stride * size.height;
// AsyncEncodeAndWriteIcon takes ownership of the heap allocated buffer
nsCOMPtr<nsIRunnable> event = new AsyncEncodeAndWriteIcon(path, data,
dataLength,
stride,
size.width,
size.height,
mURLShortcut);
mIOThread->Dispatch(event, NS_DISPATCH_NORMAL);
return NS_OK;
}
#endif
// Warning: AsyncEncodeAndWriteIcon assumes ownership of the aData buffer passed in
AsyncEncodeAndWriteIcon::AsyncEncodeAndWriteIcon(const nsAString &aIconPath,
uint8_t *aBuffer,
uint32_t aBufferLength,
uint32_t aStride,
uint32_t aWidth,
uint32_t aHeight,
const bool aURLShortcut) :
mURLShortcut(aURLShortcut),
mIconPath(aIconPath),
mBuffer(aBuffer),
mBufferLength(aBufferLength),
mStride(aStride),
mWidth(aWidth),
mHeight(aHeight)
{
}
NS_IMETHODIMP AsyncEncodeAndWriteIcon::Run()
{
NS_PRECONDITION(!NS_IsMainThread(), "Should not be called on the main thread.");
RefPtr<DrawTarget> dt =
gfxPlatform::GetPlatform()->ScreenReferenceDrawTarget();
RefPtr<SourceSurface> surface =
dt->CreateSourceSurfaceFromData(mBuffer, IntSize(mWidth, mHeight), mStride,
SurfaceFormat::B8G8R8A8);
FILE* file = fopen(NS_ConvertUTF16toUTF8(mIconPath).get(), "wb");
if (!file) {
// Maybe the directory doesn't exist; try creating it, then fopen again.
nsresult rv = NS_ERROR_FAILURE;
nsCOMPtr<nsIFile> comFile = do_CreateInstance("@mozilla.org/file/local;1");
if (comFile) {
//NS_ConvertUTF8toUTF16 utf16path(mIconPath);
rv = comFile->InitWithPath(mIconPath);
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIFile> dirPath;
comFile->GetParent(getter_AddRefs(dirPath));
if (dirPath) {
rv = dirPath->Create(nsIFile::DIRECTORY_TYPE, 0777);
if (NS_SUCCEEDED(rv) || rv == NS_ERROR_FILE_ALREADY_EXISTS) {
file = fopen(NS_ConvertUTF16toUTF8(mIconPath).get(), "wb");
if (!file) {
rv = NS_ERROR_FAILURE;
}
}
}
}
}
if (!file) {
return rv;
}
}
nsresult rv =
gfxUtils::EncodeSourceSurface(surface,
NS_LITERAL_CSTRING("image/vnd.microsoft.icon"),
EmptyString(),
gfxUtils::eBinaryEncode,
file);
fclose(file);
NS_ENSURE_SUCCESS(rv, rv);
// Cleanup
if (mURLShortcut) {
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, SPI_SETNONCLIENTMETRICS, 0);
}
return rv;
}
AsyncEncodeAndWriteIcon::~AsyncEncodeAndWriteIcon()
{
}
AsyncDeleteIconFromDisk::AsyncDeleteIconFromDisk(const nsAString &aIconPath)
: mIconPath(aIconPath)
{
}
NS_IMETHODIMP AsyncDeleteIconFromDisk::Run()
{
// Construct the parent path of the passed in path
nsCOMPtr<nsIFile> icoFile = do_CreateInstance("@mozilla.org/file/local;1");
NS_ENSURE_TRUE(icoFile, NS_ERROR_FAILURE);
nsresult rv = icoFile->InitWithPath(mIconPath);
NS_ENSURE_SUCCESS(rv, rv);
// Check if the cached ICO file exists
bool exists;
rv = icoFile->Exists(&exists);
NS_ENSURE_SUCCESS(rv, rv);
// Check that we aren't deleting some arbitrary file that is not an icon
if (StringTail(mIconPath, 4).LowerCaseEqualsASCII(".ico")) {
// Check if the cached ICO file exists
bool exists;
if (NS_FAILED(icoFile->Exists(&exists)) || !exists)
return NS_ERROR_FAILURE;
// We found an ICO file that exists, so we should remove it
icoFile->Remove(false);
}
return NS_OK;
}
AsyncDeleteIconFromDisk::~AsyncDeleteIconFromDisk()
{
}
AsyncDeleteAllFaviconsFromDisk::
AsyncDeleteAllFaviconsFromDisk(bool aIgnoreRecent)
: mIgnoreRecent(aIgnoreRecent)
{
// We can't call FaviconHelper::GetICOCacheSecondsTimeout() on non-main
// threads, as it reads a pref, so cache its value here.
mIcoNoDeleteSeconds = FaviconHelper::GetICOCacheSecondsTimeout() + 600;
}
NS_IMETHODIMP AsyncDeleteAllFaviconsFromDisk::Run()
{
// Construct the path of our jump list cache
nsCOMPtr<nsIFile> jumpListCacheDir;
nsresult rv = NS_GetSpecialDirectory("ProfLDS",
getter_AddRefs(jumpListCacheDir));
NS_ENSURE_SUCCESS(rv, rv);
rv = jumpListCacheDir->AppendNative(
nsDependentCString(FaviconHelper::kJumpListCacheDir));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsISimpleEnumerator> entries;
rv = jumpListCacheDir->GetDirectoryEntries(getter_AddRefs(entries));
NS_ENSURE_SUCCESS(rv, rv);
// Loop through each directory entry and remove all ICO files found
do {
bool hasMore = false;
if (NS_FAILED(entries->HasMoreElements(&hasMore)) || !hasMore)
break;
nsCOMPtr<nsISupports> supp;
if (NS_FAILED(entries->GetNext(getter_AddRefs(supp))))
break;
nsCOMPtr<nsIFile> currFile(do_QueryInterface(supp));
nsAutoString path;
if (NS_FAILED(currFile->GetPath(path)))
continue;
if (StringTail(path, 4).LowerCaseEqualsASCII(".ico")) {
// Check if the cached ICO file exists
bool exists;
if (NS_FAILED(currFile->Exists(&exists)) || !exists)
continue;
if (mIgnoreRecent) {
// Check to make sure the icon wasn't just recently created.
// If it was created recently, don't delete it yet.
int64_t fileModTime = 0;
rv = currFile->GetLastModifiedTime(&fileModTime);
fileModTime /= PR_MSEC_PER_SEC;
// If the icon is older than the regeneration time (+ 10 min to be
// safe), then it's old and we can get rid of it.
// This code is only hit directly after a regeneration.
int64_t nowTime = PR_Now() / int64_t(PR_USEC_PER_SEC);
if (NS_FAILED(rv) ||
(nowTime - fileModTime) < mIcoNoDeleteSeconds) {
continue;
}