BorrowedContext.h (2206B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef _MOZILLA_GFX_BORROWED_CONTEXT_H 8 #define _MOZILLA_GFX_BORROWED_CONTEXT_H 9 10 #include "2D.h" 11 12 #ifdef MOZ_X11 13 # include <X11/Xlib.h> 14 # include "X11UndefineNone.h" 15 #endif 16 17 namespace mozilla { 18 19 namespace gfx { 20 21 #ifdef XP_DARWIN 22 /* This is a helper class that let's you borrow a CGContextRef from a 23 * DrawTargetCG. This is used for drawing themed widgets. 24 * 25 * Callers should check the cg member after constructing the object 26 * to see if it succeeded. The DrawTarget should not be used while 27 * the context is borrowed. */ 28 class BorrowedCGContext { 29 public: 30 BorrowedCGContext() : cg(nullptr), mDT(nullptr) {} 31 32 explicit BorrowedCGContext(DrawTarget* aDT) : mDT(aDT) { 33 MOZ_ASSERT(aDT, "Caller should check for nullptr"); 34 cg = BorrowCGContextFromDrawTarget(aDT); 35 } 36 37 // We can optionally Init after construction in 38 // case we don't know what the DT will be at construction 39 // time. 40 CGContextRef Init(DrawTarget* aDT) { 41 MOZ_ASSERT(aDT, "Caller should check for nullptr"); 42 MOZ_ASSERT(!mDT, "Can't initialize twice!"); 43 mDT = aDT; 44 cg = BorrowCGContextFromDrawTarget(aDT); 45 return cg; 46 } 47 48 // The caller needs to call Finish if cg is non-null when 49 // they are done with the context. This is currently explicit 50 // instead of happening implicitly in the destructor to make 51 // what's happening in the caller more clear. It also 52 // let's you resume using the DrawTarget in the same scope. 53 void Finish() { 54 if (cg) { 55 ReturnCGContextToDrawTarget(mDT, cg); 56 cg = nullptr; 57 } 58 } 59 60 ~BorrowedCGContext() { MOZ_ASSERT(!cg); } 61 62 CGContextRef cg; 63 64 private: 65 static CGContextRef BorrowCGContextFromDrawTarget(DrawTarget* aDT); 66 static void ReturnCGContextToDrawTarget(DrawTarget* aDT, CGContextRef cg); 67 DrawTarget* mDT; 68 }; 69 #endif 70 71 } // namespace gfx 72 } // namespace mozilla 73 74 #endif // _MOZILLA_GFX_BORROWED_CONTEXT_H