nsWindow.cpp 283 KB
Newer Older
1
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim:set ts=2 sts=2 sw=2 et cin: */
3
4
5
/* 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/. */
kipp's avatar
kipp committed
6

7
/*
8
 * nsWindow - Native window management and event handling.
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
 * nsWindow is organized into a set of major blocks and
 * block subsections. The layout is as follows:
 *
 *  Includes
 *  Variables
 *  nsIWidget impl.
 *     nsIWidget methods and utilities
 *  nsSwitchToUIThread impl.
 *     nsSwitchToUIThread methods and utilities
 *  Moz events
 *     Event initialization
 *     Event dispatching
 *  Native events
 *     Wndproc(s)
 *     Event processing
 *     OnEvent event handlers
 *  IME management and accessibility
 *  Transparency
 *  Popup hook handling
 *  Misc. utilities
 *  Child window impl.
 *
 * Search for "BLOCK:" to find major blocks.
 * Search for "SECTION:" to find specific sections.
 *
 * Blocks should be split out into separate files if they
 * become unmanageable.
 *
 * Related source:
 *
 *  nsWindowDefs.h     - Definitions, macros, structs, enums
 *                       and general setup.
 *  nsWindowDbg.h/.cpp - Debug related code and directives.
 *  nsWindowGfx.h/.cpp - Graphics and painting.
 *
 */

/**************************************************************
 **************************************************************
 **
 ** BLOCK: Includes
 **
 ** Include headers.
 **
 **************************************************************
 **************************************************************/

57
#include "gfx2DGlue.h"
58
#include "gfxEnv.h"
59
#include "gfxPlatform.h"
60

61
#include "mozilla/AutoRestore.h"
62
#include "mozilla/Logging.h"
63
#include "mozilla/MathAlgorithms.h"
64
#include "mozilla/MiscEvents.h"
65
#include "mozilla/MouseEvents.h"
66
#include "mozilla/TouchEvents.h"
67

68
#include "mozilla/ipc/MessageChannel.h"
69
#include <algorithm>
70
#include <limits>
71

kipp's avatar
kipp committed
72
#include "nsWindow.h"
73
#include "nsAppRunner.h"
74

75
#include <shellapi.h>
76
#include <windows.h>
77
#include <wtsapi32.h>
78
79
#include <process.h>
#include <commctrl.h>
80
#include <dbt.h>
81
#include <unknwn.h>
82
#include <psapi.h>
83

84
#include "mozilla/Logging.h"
85
#include "prtime.h"
86
#include "prenv.h"
87

88
#include "mozilla/WidgetTraceEvent.h"
89
#include "nsIAppShell.h"
90
#include "nsISupportsPrimitives.h"
91
#include "nsIKeyEventInPluginCallback.h"
92
#include "nsITheme.h"
93
#include "nsIObserverService.h"
94
#include "nsIScreenManager.h"
95
#include "imgIContainer.h"
96
97
98
99
#include "nsIFile.h"
#include "nsIRollupListener.h"
#include "nsIServiceManager.h"
#include "nsIClipboard.h"
100
#include "WinMouseScrollHandler.h"
101
#include "nsFontMetrics.h"
102
103
104
105
#include "nsIFontEnumerator.h"
#include "nsFont.h"
#include "nsRect.h"
#include "nsThreadUtils.h"
106
#include "nsNativeCharsetUtils.h"
107
#include "nsGkAtoms.h"
108
109
110
#include "nsCRT.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsWidgetsCID.h"
111
112
#include "nsTHashtable.h"
#include "nsHashKeys.h"
113
#include "nsString.h"
114
#include "mozilla/Services.h"
115
#include "nsNativeThemeWin.h"
116
#include "nsWindowsDllInterceptor.h"
117
118
#include "nsLayoutUtils.h"
#include "nsView.h"
119
120
#include "nsIWindowMediator.h"
#include "nsIServiceManager.h"
121
#include "nsWindowGfx.h"
122
#include "gfxWindowsPlatform.h"
123
#include "gfxDWriteFonts.h"
124
#include "Layers.h"
125
#include "nsPrintfCString.h"
126
#include "mozilla/Preferences.h"
127
#include "nsISound.h"
128
#include "SystemTimeConverter.h"
129
#include "WinTaskbar.h"
130
#include "WidgetUtils.h"
131
#include "nsIWidgetListener.h"
132
#include "mozilla/dom/MouseEventBinding.h"
133
#include "mozilla/dom/Touch.h"
134
#include "mozilla/gfx/2D.h"
135
#include "mozilla/gfx/GPUProcessManager.h"
136
#include "nsIAppStartup.h"
137
#include "mozilla/WindowsVersion.h"
138
#include "mozilla/TextEvents.h"  // For WidgetKeyboardEvent
139
#include "mozilla/TextEventDispatcherListener.h"
140
#include "mozilla/widget/nsAutoRollup.h"
141
#include "mozilla/widget/WinNativeEventData.h"
142
#include "mozilla/widget/PlatformWidgetTypes.h"
143
#include "nsStyleConsts.h"
144
#include "nsBidiKeyboard.h"
145
#include "nsStyleConsts.h"
146
#include "gfxConfig.h"
147
#include "InProcessWinCompositorWidget.h"
148
#include "InputDeviceUtils.h"
149
#include "ScreenHelperWin.h"
150
#include "mozilla/StaticPrefs_layout.h"
151

152
#include "nsIGfxInfo.h"
153
#include "nsUXThemeConstants.h"
154
#include "KeyboardLayout.h"
155
#include "nsNativeDragTarget.h"
156
#include <mmsystem.h>  // needed for WIN32_LEAN_AND_MEAN
157
#include <zmouse.h>
158
#include <richedit.h>
159

160
#if defined(ACCESSIBILITY)
161

162
163
164
165
166
167
168
#  ifdef DEBUG
#    include "mozilla/a11y/Logging.h"
#  endif

#  include "oleidl.h"
#  include <winuser.h>
#  include "nsAccessibilityService.h"
169
#  include "mozilla/PresShell.h"
170
171
172
173
174
175
176
#  include "mozilla/a11y/DocAccessible.h"
#  include "mozilla/a11y/LazyInstantiator.h"
#  include "mozilla/a11y/Platform.h"
#  if !defined(WINABLEAPI)
#    include <winable.h>
#  endif  // !defined(WINABLEAPI)
#endif    // defined(ACCESSIBILITY)
177

178
#include "nsIWinTaskbar.h"
179
#define NS_TASKBAR_CONTRACTID "@mozilla.org/windows-taskbar;1"
180

181
182
#include "nsIWindowsUIUtils.h"

183
#include "nsWindowDefs.h"
184

185
#include "nsCrashOnException.h"
186
187
#include "nsIXULRuntime.h"

188
189
#include "nsIContent.h"

190
#include "mozilla/BackgroundHangMonitor.h"
191
#include "WinIMEHandler.h"
192

193
194
#include "npapi.h"

195
196
#include <d3d11.h>

197
198
#include "InkCollector.h"

199
200
201
202
203
// ERROR from wingdi.h (below) gets undefined by some code.
// #define ERROR               0
// #define RGN_ERROR ERROR
#define ERROR 0

204
#if !defined(SM_CONVERTIBLESLATEMODE)
205
#  define SM_CONVERTIBLESLATEMODE 0x2003
206
207
#endif

208
#if !defined(WM_DPICHANGED)
209
#  define WM_DPICHANGED 0x02E0
210
211
#endif

212
#include "mozilla/gfx/DeviceManagerDx.h"
213
#include "mozilla/layers/InputAPZContext.h"
214
#include "mozilla/layers/KnowsCompositor.h"
215
#include "InputData.h"
216

217
#include "mozilla/Telemetry.h"
218
#include "mozilla/plugins/PluginProcessParent.h"
219
#include "mozilla/webrender/WebRenderAPI.h"
220

221
using namespace mozilla;
222
using namespace mozilla::dom;
223
using namespace mozilla::gfx;
224
225
using namespace mozilla::layers;
using namespace mozilla::widget;
226
using namespace mozilla::plugins;
227

228
229
230
231
232
/**************************************************************
 **************************************************************
 **
 ** BLOCK: Variables
 **
233
 ** nsWindow Class static initializations and global variables.
234
235
236
 **
 **************************************************************
 **************************************************************/
237

238
239
240
241
242
243
/**************************************************************
 *
 * SECTION: nsWindow statics
 *
 **************************************************************/

244
245
246
247
248
249
250
251
252
253
bool nsWindow::sDropShadowEnabled = true;
uint32_t nsWindow::sInstanceCount = 0;
bool nsWindow::sSwitchKeyboardLayout = false;
BOOL nsWindow::sIsOleInitialized = FALSE;
HCURSOR nsWindow::sHCursor = nullptr;
imgIContainer* nsWindow::sCursorImgContainer = nullptr;
nsWindow* nsWindow::sCurrentWindow = nullptr;
bool nsWindow::sJustGotDeactivate = false;
bool nsWindow::sJustGotActivate = false;
bool nsWindow::sIsInMouseCapture = false;
254

255
// imported in nsWidgetFactory.cpp
256
TriStateBool nsWindow::sCanQuit = TRI_UNKNOWN;
257
258
259
260

// Hook Data Memebers for Dropdowns. sProcessHook Tells the
// hook methods whether they should be processing the hook
// messages.
261
262
263
264
265
266
267
HHOOK nsWindow::sMsgFilterHook = nullptr;
HHOOK nsWindow::sCallProcHook = nullptr;
HHOOK nsWindow::sCallMouseHook = nullptr;
bool nsWindow::sProcessHook = false;
UINT nsWindow::sRollupMsgId = 0;
HWND nsWindow::sRollupMsgWnd = nullptr;
UINT nsWindow::sHookTimerId = 0;
268
269
270

// Mouse Clicks - static variable definitions for figuring
// out 1 - 3 Clicks.
271
272
273
274
275
POINT nsWindow::sLastMousePoint = {0};
POINT nsWindow::sLastMouseMovePoint = {0};
LONG nsWindow::sLastMouseDownTime = 0L;
LONG nsWindow::sLastClickCount = 0L;
BYTE nsWindow::sLastMouseButton = 0;
276

277
bool nsWindow::sHaveInitializedPrefs = false;
278

279
280
TriStateBool nsWindow::sHasBogusPopupsDropShadowOnMultiMonitor = TRI_UNKNOWN;

281
static SystemTimeConverter<DWORD>& TimeConverter() {
282
283
284
285
  static SystemTimeConverter<DWORD> timeConverterSingleton;
  return timeConverterSingleton;
}

286
287
288
namespace mozilla {

class CurrentWindowsTimeGetter {
289
290
 public:
  explicit CurrentWindowsTimeGetter(HWND aWnd) : mWnd(aWnd) {}
291

292
  DWORD GetCurrentTime() const { return ::GetTickCount(); }
293

294
  void GetTimeAsyncForPossibleBackwardsSkew(const TimeStamp& aNow) {
295
296
297
298
299
300
301
302
    DWORD currentTime = GetCurrentTime();
    if (sBackwardsSkewStamp && currentTime == sLastPostTime) {
      // There's already one inflight with this timestamp. Don't
      // send a duplicate.
      return;
    }
    sBackwardsSkewStamp = Some(aNow);
    sLastPostTime = currentTime;
303
304
    static_assert(sizeof(WPARAM) >= sizeof(DWORD),
                  "Can't fit a DWORD in a WPARAM");
305
    ::PostMessage(mWnd, MOZ_WM_SKEWFIX, sLastPostTime, 0);
306
  }
307

308
309
  static bool GetAndClearBackwardsSkewStamp(DWORD aPostTime,
                                            TimeStamp* aOutSkewStamp) {
310
311
312
313
314
315
316
317
318
319
320
    if (aPostTime != sLastPostTime) {
      // The SKEWFIX message is stale; we've sent a new one since then.
      // Ignore this one.
      return false;
    }
    MOZ_ASSERT(sBackwardsSkewStamp);
    *aOutSkewStamp = sBackwardsSkewStamp.value();
    sBackwardsSkewStamp = Nothing();
    return true;
  }

321
 private:
322
323
324
  static Maybe<TimeStamp> sBackwardsSkewStamp;
  static DWORD sLastPostTime;
  HWND mWnd;
325
326
};

327
328
329
Maybe<TimeStamp> CurrentWindowsTimeGetter::sBackwardsSkewStamp;
DWORD CurrentWindowsTimeGetter::sLastPostTime = 0;

330
}  // namespace mozilla
331
332
333
334
335
336
337

/**************************************************************
 *
 * SECTION: globals variables
 *
 **************************************************************/

338
339
static const char* sScreenManagerContractID =
    "@mozilla.org/gfx/screenmanager;1";
340
341
342
343

extern mozilla::LazyLogModule gWindowsLog;

// Global used in Show window enumerations.
344
static bool gWindowsVisible = false;
345
346

// True if we have sent a notification that we are suspending/sleeping.
347
static bool gIsSleepMode = false;
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

static NS_DEFINE_CID(kCClipboardCID, NS_CLIPBOARD_CID);

// General purpose user32.dll hook object
static WindowsDllInterceptor sUser32Intercept;

// 2 pixel offset for eTransparencyBorderlessGlass which equals the size of
// the default window border Windows paints. Glass will be extended inward
// this distance to remove the border.
static const int32_t kGlassMarginAdjustment = 2;

// When the client area is extended out into the default window frame area,
// this is the minimum amount of space along the edge of resizable windows
// we will always display a resize cursor in, regardless of the underlying
// content.
static const int32_t kResizableBorderMinSize = 3;

// We should never really try to accelerate windows bigger than this. In some
// cases this might lead to no D3D9 acceleration where we could have had it
// but D3D9 does not reliably report when it supports bigger windows. 8192
// is as safe as we can get, we know at least D3D10 hardware always supports
// this, other hardware we expect to report correctly in D3D9.
#define MAX_ACCELERATED_DIMENSION 8192

// On window open (as well as after), Windows has an unfortunate habit of
// sending rather a lot of WM_NCHITTEST messages. Because we have to do point
// to DOM target conversions for these, we cache responses for a given
// coordinate this many milliseconds:
#define HITTEST_CACHE_LIFETIME_MS 50

378
#if defined(ACCESSIBILITY)
379
380
381

namespace mozilla {

382
383
384
385
386
387
388
389
390
391
392
393
394
/**
 * Windows touchscreen code works by setting a global WH_GETMESSAGE hook and
 * injecting tiptsf.dll. The touchscreen process then posts registered messages
 * to our main thread. The tiptsf hook picks up those registered messages and
 * uses them as commands, some of which call into UIA, which then calls into
 * MSAA, which then sends WM_GETOBJECT to us.
 *
 * We can get ahead of this by installing our own thread-local WH_GETMESSAGE
 * hook. Since thread-local hooks are called ahead of global hooks, we will
 * see these registered messages before tiptsf does. At this point we can then
 * raise a flag that blocks a11y before invoking CallNextHookEx which will then
 * invoke the global tiptsf hook. Then when we see WM_GETOBJECT, we check the
 * flag by calling TIPMessageHandler::IsA11yBlocked().
395
396
397
 *
 * For Windows 8, we also hook tiptsf!ProcessCaretEvents, which is an a11y hook
 * function that also calls into UIA.
398
 */
399
400
401
class TIPMessageHandler {
 public:
  ~TIPMessageHandler() {
402
403
404
405
406
    if (mHook) {
      ::UnhookWindowsHookEx(mHook);
    }
  }

407
  static void Initialize() {
408
409
410
411
    if (!IsWin8OrLater()) {
      return;
    }

412
413
414
415
    if (sInstance) {
      return;
    }

416
417
418
419
    sInstance = new TIPMessageHandler();
    ClearOnShutdown(&sInstance);
  }

420
  static bool IsA11yBlocked() {
421
422
423
424
425
426
427
    if (!sInstance) {
      return false;
    }

    return sInstance->mA11yBlockCount > 0;
  }

428
429
 private:
  TIPMessageHandler() : mHook(nullptr), mA11yBlockCount(0) {
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    MOZ_ASSERT(NS_IsMainThread());

    // Registered messages used by tiptsf
    mMessages[0] = ::RegisterWindowMessage(L"ImmersiveFocusNotification");
    mMessages[1] = ::RegisterWindowMessage(L"TipCloseMenus");
    mMessages[2] = ::RegisterWindowMessage(L"TabletInputPanelOpening");
    mMessages[3] = ::RegisterWindowMessage(L"IHM Pen or Touch Event noticed");
    mMessages[4] = ::RegisterWindowMessage(L"ProgrammabilityCaretVisibility");
    mMessages[5] = ::RegisterWindowMessage(L"CaretTrackingUpdateIPHidden");
    mMessages[6] = ::RegisterWindowMessage(L"CaretTrackingUpdateIPInfo");

    mHook = ::SetWindowsHookEx(WH_GETMESSAGE, &TIPHook, nullptr,
                               ::GetCurrentThreadId());
    MOZ_ASSERT(mHook);
444

445
446
447
448
    // On touchscreen devices, tiptsf.dll will have been loaded when STA COM was
    // first initialized.
    if (!IsWin10OrLater() && GetModuleHandle(L"tiptsf.dll") &&
        !sProcessCaretEventsStub) {
449
      sTipTsfInterceptor.Init("tiptsf.dll");
450
451
      DebugOnly<bool> ok = sProcessCaretEventsStub.Set(
          sTipTsfInterceptor, "ProcessCaretEvents", &ProcessCaretEventsHook);
452
453
      MOZ_ASSERT(ok);
    }
454

455
456
    if (!sSendMessageTimeoutWStub) {
      sUser32Intercept.Init("user32.dll");
457
458
      DebugOnly<bool> hooked = sSendMessageTimeoutWStub.Set(
          sUser32Intercept, "SendMessageTimeoutW", &SendMessageTimeoutWHook);
459
460
      MOZ_ASSERT(hooked);
    }
461
462
  }

463
464
465
  class MOZ_RAII A11yInstantiationBlocker {
   public:
    A11yInstantiationBlocker() {
466
467
468
      if (!TIPMessageHandler::sInstance) {
        return;
      }
469
470
471
      ++TIPMessageHandler::sInstance->mA11yBlockCount;
    }

472
    ~A11yInstantiationBlocker() {
473
474
475
476
      if (!TIPMessageHandler::sInstance) {
        return;
      }
      MOZ_ASSERT(TIPMessageHandler::sInstance->mA11yBlockCount > 0);
477
478
479
480
481
482
      --TIPMessageHandler::sInstance->mA11yBlockCount;
    }
  };

  friend class A11yInstantiationBlocker;

483
  static LRESULT CALLBACK TIPHook(int aCode, WPARAM aWParam, LPARAM aLParam) {
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
    if (aCode < 0 || !sInstance) {
      return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam);
    }

    MSG* msg = reinterpret_cast<MSG*>(aLParam);
    UINT& msgCode = msg->message;

    for (uint32_t i = 0; i < ArrayLength(sInstance->mMessages); ++i) {
      if (msgCode == sInstance->mMessages[i]) {
        A11yInstantiationBlocker block;
        return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam);
      }
    }

    return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam);
  }

501
502
503
504
  static void CALLBACK ProcessCaretEventsHook(HWINEVENTHOOK aWinEventHook,
                                              DWORD aEvent, HWND aHwnd,
                                              LONG aObjectId, LONG aChildId,
                                              DWORD aGeneratingTid,
505
                                              DWORD aEventTime) {
506
507
508
509
510
    A11yInstantiationBlocker block;
    sProcessCaretEventsStub(aWinEventHook, aEvent, aHwnd, aObjectId, aChildId,
                            aGeneratingTid, aEventTime);
  }

511
512
513
  static LRESULT WINAPI SendMessageTimeoutWHook(HWND aHwnd, UINT aMsgCode,
                                                WPARAM aWParam, LPARAM aLParam,
                                                UINT aFlags, UINT aTimeout,
514
                                                PDWORD_PTR aMsgResult) {
515
516
517
    // We don't want to handle this unless the message is a WM_GETOBJECT that we
    // want to block, and the aHwnd is a nsWindow that belongs to the current
    // thread.
518
519
    if (!aMsgResult || aMsgCode != WM_GETOBJECT ||
        static_cast<DWORD>(aLParam) != OBJID_CLIENT ||
520
521
522
        !WinUtils::GetNSWindowPtr(aHwnd) ||
        ::GetWindowThreadProcessId(aHwnd, nullptr) != ::GetCurrentThreadId() ||
        !IsA11yBlocked()) {
523
524
      return sSendMessageTimeoutWStub(aHwnd, aMsgCode, aWParam, aLParam, aFlags,
                                      aTimeout, aMsgResult);
525
526
527
528
529
    }

    // In this case we want to fake the result that would happen if we had
    // decided not to handle WM_GETOBJECT in our WndProc. We hand the message
    // off to DefWindowProc to accomplish this.
530
531
    *aMsgResult = static_cast<DWORD_PTR>(
        ::DefWindowProcW(aHwnd, aMsgCode, aWParam, aLParam));
532
533
534
535

    return static_cast<LRESULT>(TRUE);
  }

536
  static WindowsDllInterceptor sTipTsfInterceptor;
537
  static WindowsDllInterceptor::FuncHookType<WINEVENTPROC>
538
      sProcessCaretEventsStub;
539
  static WindowsDllInterceptor::FuncHookType<decltype(&SendMessageTimeoutW)>
540
      sSendMessageTimeoutWStub;
541
542
  static StaticAutoPtr<TIPMessageHandler> sInstance;

543
544
545
  HHOOK mHook;
  UINT mMessages[7];
  uint32_t mA11yBlockCount;
546
547
};

548
WindowsDllInterceptor TIPMessageHandler::sTipTsfInterceptor;
549
WindowsDllInterceptor::FuncHookType<WINEVENTPROC>
550
    TIPMessageHandler::sProcessCaretEventsStub;
551
WindowsDllInterceptor::FuncHookType<decltype(&SendMessageTimeoutW)>
552
    TIPMessageHandler::sSendMessageTimeoutWStub;
553
554
StaticAutoPtr<TIPMessageHandler> TIPMessageHandler::sInstance;

555
}  // namespace mozilla
556

557
#endif  // defined(ACCESSIBILITY)
558

559
560
561
562
563
564
565
566
567
568
/**************************************************************
 **************************************************************
 **
 ** BLOCK: nsIWidget impl.
 **
 ** nsIWidget interface implementation, broken down into
 ** sections.
 **
 **************************************************************
 **************************************************************/
569

570
571
572
573
574
/**************************************************************
 *
 * SECTION: nsWindow construction and destruction
 *
 **************************************************************/
575

576
nsWindow::nsWindow(bool aIsChildWindow)
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
    : nsWindowBase(),
      mResizeState(NOT_RESIZING),
      mIsChildWindow(aIsChildWindow) {
  mIconSmall = nullptr;
  mIconBig = nullptr;
  mWnd = nullptr;
  mTransitionWnd = nullptr;
  mPaintDC = nullptr;
  mPrevWndProc = nullptr;
  mNativeDragTarget = nullptr;
  mDeviceNotifyHandle = nullptr;
  mInDtor = false;
  mIsVisible = false;
  mIsTopWidgetWindow = false;
  mUnicodeWidget = true;
  mDisplayPanFeedback = false;
  mTouchWindow = false;
  mFutureMarginsToUse = false;
  mCustomNonClient = false;
  mHideChrome = false;
  mFullscreenMode = false;
  mMousePresent = false;
599
  mMouseInDraggableArea = false;
600
601
  mDestroyCalled = false;
  mIsEarlyBlankWindow = false;
602
  mHasTaskbarIconBeenCreated = false;
603
604
605
606
607
608
609
610
611
612
613
614
615
616
  mMouseTransparent = false;
  mPickerDisplayCount = 0;
  mWindowType = eWindowType_child;
  mBorderStyle = eBorderStyle_default;
  mOldSizeMode = nsSizeMode_Normal;
  mLastSizeMode = nsSizeMode_Normal;
  mLastSize.width = 0;
  mLastSize.height = 0;
  mOldStyle = 0;
  mOldExStyle = 0;
  mPainting = 0;
  mLastKeyboardLayout = 0;
  mBlurSuppressLevel = 0;
  mLastPaintEndTime = TimeStamp::Now();
617
618
  mCachedHitTestPoint.x = 0;
  mCachedHitTestPoint.y = 0;
619
  mCachedHitTestTime = TimeStamp::Now();
620
  mCachedHitTestResult = 0;
621
#ifdef MOZ_XUL
622
  mTransparencyMode = eTransparencyOpaque;
623
  memset(&mGlassMargins, 0, sizeof mGlassMargins);
624
#endif
625
626
627
628
  DWORD background = ::GetSysColor(COLOR_BTNFACE);
  mBrush = ::CreateSolidBrush(NSRGB_2_COLOREF(background));
  mSendingSetText = false;
  mDefaultScale = -1.0;  // not yet set, will be calculated on first use
629
  mAspectRatio = 0.0;    // not yet set, will be calculated on first use
630

631
  mTaskbarPreview = nullptr;
632

633
634
  mCompositorWidgetDelegate = nullptr;

635
636
  // Global initialization
  if (!sInstanceCount) {
637
638
639
    // Global app registration id for Win7 and up. See
    // WinTaskbar.cpp for details.
    mozilla::widget::WinTaskbar::RegisterAppUserModelID();
640
    KeyboardLayout::GetInstance()->OnLayoutChange(::GetKeyboardLayout(0));
641
#if defined(ACCESSIBILITY)
642
    mozilla::TIPMessageHandler::Initialize();
643
#endif  // defined(ACCESSIBILITY)
644
    if (SUCCEEDED(::OleInitialize(nullptr))) {
645
      sIsOleInitialized = TRUE;
646
    }
647
    NS_ASSERTION(sIsOleInitialized, "***** OLE is not initialized!\n");
648
    MouseScrollHandler::Initialize();
649
650
    // Init theme data
    nsUXThemeData::UpdateNativeThemeInfo();
651
    RedirectedKeyDownMessageManager::Forget();
652
653
654
    if (mPointerEvents.ShouldEnableInkCollector()) {
      InkCollector::sInkCollector = new InkCollector();
    }
655
  }  // !sInstanceCount
656

657
  mIdleService = nullptr;
658

659
  mSizeConstraintsScale = GetDefaultScale().scale;
660
  mMaxTextureSize = -1;  // Will be calculated when layer manager is created.
661

662
663
  mRequestFxrOutputPending = false;

664
  sInstanceCount++;
665
666
}

667
nsWindow::~nsWindow() {
668
  mInDtor = true;
669

670
671
672
673
  // If the widget was released without calling Destroy() then the native window
  // still exists, and we need to destroy it. Destroy() will early-return if it
  // was already called. In any case it is important to call it before
  // destroying mPresentLock (cf. 1156182).
674
  Destroy();
675

676
677
678
  // Free app icon resources.  This must happen after `OnDestroy` (see bug
  // 708033).
  if (mIconSmall) ::DestroyIcon(mIconSmall);
679

680
  if (mIconBig) ::DestroyIcon(mIconBig);
681

682
  sInstanceCount--;
683

684
  // Global shutdown
685
  if (sInstanceCount == 0) {
686
687
688
689
    if (InkCollector::sInkCollector) {
      InkCollector::sInkCollector->Shutdown();
      InkCollector::sInkCollector = nullptr;
    }
690
    IMEHandler::Terminate();
691
692
693
694
695
696
    NS_IF_RELEASE(sCursorImgContainer);
    if (sIsOleInitialized) {
      ::OleFlushClipboard();
      ::OleUninitialize();
      sIsOleInitialized = FALSE;
    }
697
  }
698
699

  NS_IF_RELEASE(mNativeDragTarget);
700
701
}

702
703
704
705
706
707
708
709
710
/**************************************************************
 *
 * SECTION: nsIWidget::Create, nsIWidget::Destroy
 *
 * Creating and destroying windows for this widget.
 *
 **************************************************************/

// Allow Derived classes to modify the height that is passed
711
// when the window is created or resized.
712
int32_t nsWindow::GetHeight(int32_t aProposedHeight) { return aProposedHeight; }
713

714
715
716
717
718
719
720
static bool ShouldCacheTitleBarInfo(nsWindowType aWindowType,
                                    nsBorderStyle aBorderStyle) {
  return (aWindowType == eWindowType_toplevel) &&
         (aBorderStyle == eBorderStyle_default ||
          aBorderStyle == eBorderStyle_all) &&
         (!nsUXThemeData::sTitlebarInfoPopulatedThemed ||
          !nsUXThemeData::sTitlebarInfoPopulatedAero);
721
722
}

723
// Create the proper widget
724
725
726
nsresult nsWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
                          const LayoutDeviceIntRect& aRect,
                          nsWidgetInitData* aInitData) {
727
  nsWidgetInitData defaultInitData;
728
  if (!aInitData) aInitData = &defaultInitData;
729

730
731
  mUnicodeWidget = aInitData->mUnicode;

732
733
734
735
736
737
  nsIWidget* baseParent =
      aInitData->mWindowType == eWindowType_dialog ||
              aInitData->mWindowType == eWindowType_toplevel ||
              aInitData->mWindowType == eWindowType_invisible
          ? nullptr
          : aParent;
738

739
  mIsTopWidgetWindow = (nullptr == baseParent);
740
  mBounds = aRect;
741

742
743
744
  // Ensure that the toolkit is created.
  nsToolkit::GetToolkit();

745
  BaseCreate(baseParent, aInitData);
746

747
  HWND parent;
748
  if (aParent) {  // has a nsIWidget parent
749
    parent = aParent ? (HWND)aParent->GetNativeData(NS_NATIVE_WINDOW) : nullptr;
Mats Palmgren's avatar
Mats Palmgren committed
750
    mParent = aParent;
751
  } else {  // has a nsNative parent
752
    parent = (HWND)aNativeParent;
753
754
    mParent =
        aNativeParent ? WinUtils::GetNSWindowPtr((HWND)aNativeParent) : nullptr;
755
  }
756

757
  mIsRTL = aInitData->mRTL;
758
  mOpeningAnimationSuppressed = aInitData->mIsAnimationSuppressed;
759
  mAlwaysOnTop = aInitData->mAlwaysOnTop;
760

761
762
  DWORD style = WindowStyle();
  DWORD extendedStyle = WindowExStyle();
763

764
  if (mWindowType == eWindowType_popup) {
765
    if (!aParent) {
766
      parent = nullptr;
767
768
    }

769
    if (!IsWin8OrLater() && HasBogusPopupsDropShadowOnMultiMonitor() &&
770
        ShouldUseOffMainThreadCompositing()) {
771
772
      extendedStyle |= WS_EX_COMPOSITED;
    }
773

774
    if (aInitData->mMouseTransparent) {
775
      // This flag makes the window transparent to mouse events
776
      mMouseTransparent = true;
777
778
      extendedStyle |= WS_EX_TRANSPARENT;
    }
779
780
  } else if (mWindowType == eWindowType_invisible) {
    // Make sure CreateWindowEx succeeds at creating a toplevel window
781
    style &= ~0x40000000;  // WS_CHILDWINDOW
782
  } else {
783
784
785
786
787
788
789
790
791
792
    // See if the caller wants to explictly set clip children and clip siblings
    if (aInitData->clipChildren) {
      style |= WS_CLIPCHILDREN;
    } else {
      style &= ~WS_CLIPCHILDREN;
    }
    if (aInitData->clipSiblings) {
      style |= WS_CLIPSIBLINGS;
    }
  }
793

794
  const wchar_t* className;
795
  if (aInitData->mDropShadow) {
796
    className = GetWindowPopupClass();
797
  } else {
798
    className = GetWindowClass();
799
  }
800
801
802
  // Plugins are created in the disabled state so that they can't
  // steal focus away from our main window.  This is especially
  // important if the plugin has loaded in a background tab.
803
804
805
  if (aInitData->mWindowType == eWindowType_plugin ||
      aInitData->mWindowType == eWindowType_plugin_ipc_chrome ||
      aInitData->mWindowType == eWindowType_plugin_ipc_content) {
806
807
    style |= WS_DISABLED;
  }
808
809
810
  mWnd = ::CreateWindowExW(extendedStyle, className, L"", style, aRect.X(),
                           aRect.Y(), aRect.Width(), GetHeight(aRect.Height()),
                           parent, nullptr, nsToolkit::mDllInstance, nullptr);
811

812
813
  if (!mWnd) {
    NS_WARNING("nsWindow CreateWindowEx failed.");
814
    return NS_ERROR_FAILURE;
815
  }
816
817
818

  mDeviceNotifyHandle = InputDeviceUtils::RegisterNotification(mWnd);

819
820
821
822
823
824
825
826
  // If mDefaultScale is set before mWnd has been set, it will have the scale of
  // the primary monitor, rather than the monitor that the window is actually
  // on. For non-popup windows this gets corrected by the WM_DPICHANGED message
  // which resets mDefaultScale, but for popup windows we don't reset
  // mDefaultScale on that message. In order to ensure that popup windows
  // spawned on a non-primary monitor end up with the correct scale, we reset
  // mDefaultScale here so that it gets recomputed using the correct monitor now
  // that we have a mWnd.
827
  mDefaultScale = -1.0;
828

829
  if (mIsRTL) {
830
    DWORD dwAttribute = TRUE;
831
832
    DwmSetWindowAttribute(mWnd, DWMWA_NONCLIENT_RTL_LAYOUT, &dwAttribute,
                          sizeof dwAttribute);
833
834
  }

835
  if (mOpeningAnimationSuppressed) {
836
    SuppressAnimation(true);
837
838
  }

839
840
841
842
843
  if (mAlwaysOnTop) {
    ::SetWindowPos(mWnd, HWND_TOPMOST, 0, 0, 0, 0,
                   SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
  }

844
  if (!IsPlugin() && mWindowType != eWindowType_invisible &&
845
      MouseScrollHandler::Device::IsFakeScrollableWindowNeeded()) {
846
    // Ugly Thinkpad Driver Hack (Bugs 507222 and 594977)
847
    //
848
849
    // We create two zero-sized windows as descendants of the top-level window,
    // like so:
850
851
852
853
854
    //
    //   Top-level window (MozillaWindowClass)
    //     FAKETRACKPOINTSCROLLCONTAINER (MozillaWindowClass)
    //       FAKETRACKPOINTSCROLLABLE (MozillaWindowClass)
    //
855
    // We need to have the middle window, otherwise the Trackpoint driver
856
857
858
859
860
861
862
863
864
865
    // will fail to deliver scroll messages.  WM_MOUSEWHEEL messages are
    // sent to the FAKETRACKPOINTSCROLLABLE, which then propagate up the
    // window hierarchy until they are handled by nsWindow::WindowProc.
    // WM_HSCROLL messages are also sent to the FAKETRACKPOINTSCROLLABLE,
    // but these do not propagate automatically, so we have the window
    // procedure pretend that they were dispatched to the top-level window
    // instead.
    //
    // The FAKETRACKPOINTSCROLLABLE needs to have the specific window styles it
    // is given below so that it catches the Trackpoint driver's heuristics.
866
867
868
869
870
871
872
    HWND scrollContainerWnd = ::CreateWindowW(
        className, L"FAKETRACKPOINTSCROLLCONTAINER", WS_CHILD | WS_VISIBLE, 0,
        0, 0, 0, mWnd, nullptr, nsToolkit::mDllInstance, nullptr);
    HWND scrollableWnd = ::CreateWindowW(
        className, L"FAKETRACKPOINTSCROLLABLE",
        WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_TABSTOP | 0x30, 0, 0, 0, 0,
        scrollContainerWnd, nullptr, nsToolkit::mDllInstance, nullptr);
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888

    // Give the FAKETRACKPOINTSCROLLABLE window a specific ID so that
    // WindowProcInternal can distinguish it from the top-level window
    // easily.
    ::SetWindowLongPtrW(scrollableWnd, GWLP_ID, eFakeTrackPointScrollableID);

    // Make FAKETRACKPOINTSCROLLABLE use nsWindow::WindowProc, and store the
    // old window procedure in its "user data".
    WNDPROC oldWndProc;
    if (mUnicodeWidget)
      oldWndProc = (WNDPROC)::SetWindowLongPtrW(scrollableWnd, GWLP_WNDPROC,
                                                (LONG_PTR)nsWindow::WindowProc);
    else
      oldWndProc = (WNDPROC)::SetWindowLongPtrA(scrollableWnd, GWLP_WNDPROC,
                                                (LONG_PTR)nsWindow::WindowProc);
    ::SetWindowLongPtrW(scrollableWnd, GWLP_USERDATA, (LONG_PTR)oldWndProc);
889
  }
890

891
  SubclassWindow(TRUE);
892

893
894
895
896
  // Starting with Windows XP, a process always runs within a terminal services
  // session. In order to play nicely with RDP, fast user switching, and the
  // lock screen, we should be handling WM_WTSSESSION_CHANGE. We must register
  // our HWND in order to receive this message.
897
898
  DebugOnly<BOOL> wtsRegistered =
      ::WTSRegisterSessionNotification(mWnd, NOTIFY_FOR_THIS_SESSION);
899
900
  NS_ASSERTION(wtsRegistered, "WTSRegisterSessionNotification failed!\n");

901
  mDefaultIMC.Init(this);
902
  IMEHandler::InitInputContext(this, mInputContext);
903

904
905
906
907
  // Do some initialization work, but only if (a) it hasn't already been done,
  // and (b) this is the hidden window (which is conveniently created before
  // any visible windows but after the profile has been initialized).
  if (!sHaveInitializedPrefs && mWindowType == eWindowType_invisible) {
908
    sSwitchKeyboardLayout =
909
        Preferences::GetBool("intl.keyboard.per_window_layout", false);
910
    sHaveInitializedPrefs = true;
911
  }
912

Jim Mathies's avatar
Jim Mathies committed
913
  // Query for command button metric data for rendering the titlebar. We
914
915
  // only do this once on the first window that has an actual titlebar
  if (ShouldCacheTitleBarInfo(mWindowType, mBorderStyle)) {
Jim Mathies's avatar
Jim Mathies committed
916
917
    nsUXThemeData::UpdateTitlebarInfo(mWnd);
  }
918

919
  static bool a11yPrimed = false;
920
  if (!a11yPrimed && mWindowType == eWindowType_toplevel) {
921
922
923
924
925
    a11yPrimed = true;
    if (Preferences::GetInt("accessibility.force_disabled", 0) == -1) {
      ::PostMessage(mWnd, MOZ_WM_STARTA11Y, 0, 0);
    }
  }
926
927
  return NS_OK;
}
928

929
// Close this nsWindow
930
void nsWindow::Destroy() {