xref: /aosp_15_r20/external/cronet/base/win/scoped_hdc.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_WIN_SCOPED_HDC_H_
6 #define BASE_WIN_SCOPED_HDC_H_
7 
8 #include <windows.h>
9 
10 #include "base/check.h"
11 #include "base/debug/gdi_debug_util_win.h"
12 #include "base/win/scoped_handle.h"
13 
14 namespace base {
15 namespace win {
16 
17 // Like ScopedHandle but for HDC.  Only use this on HDCs returned from
18 // GetDC.
19 class ScopedGetDC {
20  public:
ScopedGetDC(HWND hwnd)21   explicit ScopedGetDC(HWND hwnd) : hwnd_(hwnd), hdc_(GetDC(hwnd)) {
22     if (hwnd_) {
23       DCHECK(IsWindow(hwnd_));
24       DCHECK(hdc_);
25     } else {
26       // If GetDC(NULL) returns NULL, something really bad has happened, like
27       // GDI handle exhaustion.  In this case Chrome is going to behave badly no
28       // matter what, so we may as well just force a crash now.
29       if (!hdc_)
30         base::debug::CollectGDIUsageAndDie();
31     }
32   }
33 
34   ScopedGetDC(const ScopedGetDC&) = delete;
35   ScopedGetDC& operator=(const ScopedGetDC&) = delete;
36 
~ScopedGetDC()37   ~ScopedGetDC() {
38     if (hdc_)
39       ReleaseDC(hwnd_, hdc_);
40   }
41 
HDC()42   operator HDC() { return hdc_; }
43 
44  private:
45   HWND hwnd_;
46   HDC hdc_;
47 };
48 
49 // Like ScopedHandle but for HDC.  Only use this on HDCs returned from
50 // CreateCompatibleDC, CreateDC and CreateIC.
51 class CreateDCTraits {
52  public:
53   typedef HDC Handle;
54 
55   CreateDCTraits() = delete;
56   CreateDCTraits(const CreateDCTraits&) = delete;
57   CreateDCTraits& operator=(const CreateDCTraits&) = delete;
58 
CloseHandle(HDC handle)59   static bool CloseHandle(HDC handle) { return ::DeleteDC(handle) != FALSE; }
60 
IsHandleValid(HDC handle)61   static bool IsHandleValid(HDC handle) { return handle != NULL; }
62 
NullHandle()63   static HDC NullHandle() { return NULL; }
64 };
65 
66 typedef GenericScopedHandle<CreateDCTraits, DummyVerifierTraits> ScopedCreateDC;
67 
68 }  // namespace win
69 }  // namespace base
70 
71 #endif  // BASE_WIN_SCOPED_HDC_H_
72