Collections.toMap()

使用流(stream)操作时,很多场景会用到list.stream()…filter()…collect(Collectors.toMap())操作。
今天进入collections源码,看一下Collectors.toMap参数的含义。

Collectors.toMap()有多个重载方法。

public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper) {
        return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
    }

坑1

throwingMerger():遇到流中的重复key时,抛出异常,并打印key。(重复key抛异常)
默认new HashMap。




private static <T> BinaryOperator<T> throwingMerger() {
        return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
    }
public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper,
                                    BinaryOperator<U> mergeFunction) {
        return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
    }

自定义重复key处理策略
例:list.stream().collect(Collectors.toMap(Student::getId, Student::getName, (v1, v2) -> v1));
即遇到重复key时,value取先来的v1
默认new HashMap。




上面这两个重载方法其实调用的就是下面的这个:

public static <T, K, U, M extends Map<K, U>>
    Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
                                Function<? super T, ? extends U> valueMapper,
                                BinaryOperator<U> mergeFunction,
                                Supplier<M> mapSupplier) {
        BiConsumer<M, T> accumulator
                = (map, element) -> map.merge(keyMapper.apply(element),
                                              valueMapper.apply(element), mergeFunction);
        return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
    }

参数KeyMapper:返回key的method,ex:(Book::getId)
参数valueMapper:返回value的method,ex:(Book::getName)
参数mergeFunction:遇到重复key时,处理策略,ex((v1,v2) -> v1)
Supplier mapSupplier:返回map/list的method,(HashMap::new/ConcurrentHashMap::new)

坑2

看其他文章说的,key为null也会导致异常,可自己试试。

解决办法:增加filter,过滤null key

bookList.stream().filter(book-> StringUtils.isNotEmpty(book.getId()))
                .collect(Collectors.toMap(BookDTO::getId,book -> (book.getName()+book.getPrice())));
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
前言 ............................................................................ xi 1. 教程 ......................................................................... 1 1.1. 第一部分 - 第一个 Hibernate 应用程序 ................................. 1 1.1.1. 设置 ............................................................ 1 1.1.2. 第一个 class ................................................... 3 1.1.3. 映射文件 ........................................................ 4 1.1.4. Hibernate 配置 .................................................. 7 1.1.5. 用 Maven 构建 .................................................. 9 1.1.6. 启动和辅助类 .................................................... 9 1.1.7. 加载并存储对象 ................................................. 10 1.2. 第二部分 - 关联映射 ................................................. 13 1.2.1. 映射 Person 类 ................................................ 13 1.2.2. 单向 Set-based 的关联 ......................................... 14 1.2.3. 使关联工作 ..................................................... 15 1.2.4. 值类型的集合 ................................................... 17 1.2.5. 双向关联 ....................................................... 18 1.2.6. 使双向连起来 ................................................... 19 1.3. 第三部分 - EventManager web 应用程序 ................................. 20 1.3.1. 编写基本的 servlet ............................................. 20 1.3.2. 处理与渲染 ..................................................... 21 1.3.3. 部署与测试 ..................................................... 24 1.4. 总结 ................................................................. 25 2. 体系结构(Architecture) ..................................................... 27 2.1. 概况(Overview) ...................................................... 27 2.2. 实例状态 .............................................................. 29 2.3. JMX 整合 ............................................................. 30 2.4. 对 JCA 的支持 ........................................................ 30 2.5. 上下文相关的会话(Contextual Session) ................................ 30 3. 配置 ........................................................................ 33 3.1. 可编程的配置方式 ...................................................... 33 3.2. 获得 SessionFactory .................................................. 34 3.3. JDBC 连接 ............................................................ 34 3.4. 可选的配置属性 ........................................................ 36 3.4.1. SQL 方言 ...................................................... 42 3.4.2. 外连接抓取(Outer Join Fetching) .............................. 43 3.4.3. 二进制流(Binary Streams) ..................................... 43 3.4.4. 二级缓存与查询缓存 ............................................. 43 3.4.5. 查询语言中的替换 ............................................... 43 3.4.6. Hibernate 的统计(statistics)机制 ............................. 43 3.5. 日志 ................................................................. 44 3.6. 实现 NamingStrategy .................................................. 44 3.7. XML 配置文件 ......................................................... 45 3.8. J2EE 应用程序服务器的集成 ............................................. 46 3.8.1. 事务策略配置 ................................................... 46HIBERNATE - Relational Persis... iv 3.8.2. JNDI 绑定的 SessionFactory ..................................... 47 3.8.3. 在 JTA 环境下使用 Current Session context(当前 session 上下文) 管理 .................................................................. 48 3.8.4. JMX 部署 ...................................................... 48 4. 持久化类(Persistent Classes) .............................................. 51 4.1. 一个简单的 POJO 例子 ................................................. 51 4.1.1. 实现一个默认的(即无参数的)构造方法(constructor) ............. 52 4.1.2. 提供一个标识属性(identifier property)(可选) ................. 52 4.1.3. 使用非final的类(可选) ........................................ 53 4.1.4. 为持久化字段声明访问器(accessors)和是否可变的标志(mutators) (可选) .............................................................. 53 4.2. 实现继承(Inheritance) ............................................... 53 4.3. 实现 equals() 和 hashCode() 方法: ................................... 54 4.4. 动态模型(Dynamic models) ............................................ 55 4.5. 元组片断映射(Tuplizers) ............................................. 57 4.6. EntityNameResolvers ................................................... 58 5. 对象/关系数据库映射基础(Basic O/R Mapping) ................................. 61 5.1. 映射定义(Mapping declaration) ....................................... 61 5.1.1. Doctype ........................................................ 62 5.1.2. Hibernate-mapping .............................................. 63 5.1.3. 类 ............................................................. 64 5.1.4. id ............................................................. 67 5.1.5. 增强的标识符生成器 ............................................. 71 5.1.6. 标识符生成器的优化 ............................................. 72 5.1.7. composite-id ................................................... 72 5.1.8. 鉴别器(discriminator) ........................................ 73 5.1.9. 版本(version)(可选) ........................................ 74 5.1.10. timestamp(可选) .............................................. 75 5.1.11. Property ...................................................... 76 5.1.12. 多对一(many-to-one) ......................................... 78 5.1.13. 一对一 ........................................................ 80 5.1.14. 自然 ID(natural-id) ......................................... 82 5.1.15. 组件(component)和动态组件(dynamic-component) ............... 82 5.1.16. 属性(Properties) ............................................ 83 5.1.17. 子类(subclass) .............................................. 84 5.1.18. 连接的子类(joined-subclass) ................................. 85 5.1.19. 联合子类(union-subclass) .................................... 86 5.1.20. 连接(join) .................................................. 87 5.1.21. Key ........................................................... 88 5.1.22. 字段和规则元素(column and formula elements) ................. 89 5.1.23. 引用(import) ................................................ 90 5.1.24. Any ........................................................... 90 5.2. Hibernate 的类型 ..................................................... 91 5.2.1. 实体(Entities)和值(values) ................................. 91v 5.2.2. 基本值类型 ..................................................... 92 5.2.3. 自定义值类型 ................................................... 93 5.3. 多次映射同一个类 ...................................................... 94 5.4. SQL 中引号包围的标识符 ............................................... 95 5.5. 其他元数据(Metadata) ................................................ 95 5.5.1. 使用 XDoclet 标记 ............................................. 95 5.5.2. 使用 JDK 5.0 的注解(Annotation) .............................. 97 5.6. 数据库生成属性(Generated Properties) ................................ 98 5.7. 字段的读写表达式 ...................................................... 98 5.8. 辅助数据库对象(Auxiliary Database Objects) .......................... 99 6. 集合映射(Collection mappings) ............................................ 101 6.1. 持久化集合类(Persistent collections) ............................... 101 6.2. 集合映射( Collection mappings ) ................................... 102 6.2.1. 集合外键(Collection foreign keys) ........................... 103 6.2.2. 集合元素(Collection elements) ............................... 104 6.2.3. 索引集合类(Indexed collections) ............................. 104 6.2.4. 值集合于多对多关联(Collections of values and many-to-many associations) ....................................................... 105 6.2.5. 一对多关联(One-to-many Associations) ........................ 107 6.3. 高级集合映射(Advanced collection mappings) ......................... 108 6.3.1. 有序集合(Sorted collections) ................................ 108 6.3.2. 双向关联(Bidirectional associations) ........................ 109 6.3.3. 双向关联,涉及有序集合类 ...................................... 111 6.3.4. 三重关联(Ternary associations) .............................. 112 6.3.5. Using an <idbag> ............................................. 112 6.4. 集合例子(Collection example) ....................................... 113 7. 关联关系映射 ............................................................... 117 7.1. 介绍 ................................................................ 117 7.2. 单向关联(Unidirectional associations) .............................. 117 7.2.1. 多对一(many-to-one) ......................................... 117 7.2.2. 一对一(One-to-one) .......................................... 117 7.2.3. 一对多(one-to-many) ......................................... 118 7.3. 使用连接表的单向关联(Unidirectional associations with join tables) .. 119 7.3.1. 一对多(one-to-many) ......................................... 119 7.3.2. 多对一(many-to-one) ......................................... 120 7.3.3. 一对一(One-to-one) .......................................... 120 7.3.4. 多对多(many-to-many) ........................................ 121 7.4. 双向关联(Bidirectional associations) ............................... 122 7.4.1. 一对多(one to many)/多对一(many to one) .................... 122 7.4.2. 一对一(One-to-one) .......................................... 123 7.5. 使用连接表的双向关联(Bidirectional associations with join tables) ... 124 7.5.1. 一对多(one to many)/多对一(many to one) .................... 124 7.5.2. 一对一(one to one) ......................................... 125 7.5.3. 多对多(many-to-many) ........................................ 126HIBERNATE - Relational Persis... vi 7.6. 更复杂的关联映射 ..................................................... 126 8. 组件(Component)映射 ....................................................... 129 8.1. 依赖对象(Dependent objects) ........................................ 129 8.2. 在集合中出现的依赖对象(Collections of dependent objects) ........... 131 8.3. 组件作为 Map 的索引(Components as Map indices ) .................... 132 8.4. 组件作为联合标识符(Components as composite identifiers) ............ 132 8.5. 动态组件(Dynamic components) ....................................... 134 9. 继承映射(Inheritance Mapping) ............................................ 137 9.1. 三种策略 ............................................................. 137 9.1.1. 每个类分层结构一张表(Table per class hierarchy) ............. 137 9.1.2. 每个子类一张表(Table per subclass) .......................... 138 9.1.3. 每个子类一张表(Table per subclass),使用辨别标志 (Discriminator) .................................................... 138 9.1.4. 混合使用“每个类分层结构一张表”和“每个子类一张表” ........... 139 9.1.5. 每个具体类一张表(Table per concrete class) .................. 140 9.1.6. 每个具体类一张表,使用隐式多态 ................................ 141 9.1.7. 隐式多态和其他继承映射混合使用 ................................ 142 9.2. 限制 ................................................................ 142 10. 与对象共事 ................................................................ 145 10.1. Hibernate 对象状态(object states) ................................. 145 10.2. 使对象持久化 ........................................................ 145 10.3. 装载对象 ............................................................ 146 10.4. 查询 ............................................................... 148 10.4.1. 执行查询 ..................................................... 148 10.4.2. 过滤集合 ..................................................... 152 10.4.3. 条件查询(Criteria queries) ................................. 153 10.4.4. 使用原生 SQL 的查询 ......................................... 153 10.5. 修改持久对象 ........................................................ 153 10.6. 修改脱管(Detached)对象 ............................................ 154 10.7. 自动状态检测 ........................................................ 155 10.8. 删除持久对象 ........................................................ 156 10.9. 在两个不同数据库间复制对象 .......................................... 156 10.10. Session 刷出(flush) .............................................. 157 10.11. 传播性持久化(transitive persistence) ............................. 158 10.12. 使用元数据 ......................................................... 160 11. Read-only entities ........................................................ 161 11.1. Making persistent entities read-only ................................ 162 11.1.1. Entities of immutable classes ................................ 162 11.1.2. Loading persistent entities as read-only ..................... 162 11.1.3. Loading read-only entities from an HQL query/criteria ......... 163 11.1.4. Making a persistent entity read-only ......................... 165 11.2. Read-only affect on property type .................................. 166 11.2.1. Simple properties ............................................ 167 11.2.2. Unidirectional associations .................................. 167
stdafx.h的代码// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) 1992-1998 Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #ifndef __AFXWIN_H__ #ifndef RC_INVOKED #define __AFXWIN_H__ ///////////////////////////////////////////////////////////////////////////// // Make sure 'afx.h' is included first #ifndef __AFX_H__ #include #endif // Note: WINDOWS.H already included from AFXV_W32.H #ifndef _INC_SHELLAPI #include #endif #ifndef __AFXRES_H__ #include // standard resource IDs #endif #ifndef __AFXCOLL_H__ #include // standard collections #endif #ifdef _AFX_MINREBUILD #pragma component(minrebuild, off) #endif #ifndef _AFX_FULLTYPEINFO #pragma component(mintypeinfo, on) #endif #ifndef _AFX_NOFORCE_LIBS #pragma comment(lib, "uuid.lib") #endif #ifdef _INC_WINDOWSX // The following names from WINDOWSX.H collide with names in this header #undef SubclassWindow #undef CopyRgn #endif #ifdef _AFX_PACKING #pragma pack(push, _AFX_PACKING) #endif ///////////////////////////////////////////////////////////////////////////// // Classes declared in this file class CSize; class CPoint; class CRect; //CObject //CException //CSimpleException class CResourceException;// Win resource failure exception class CUserException; // Message Box alert and stop operation class CGdiObject; // CDC drawing tool class CPen; // a pen / HPEN wrapper class CBrush; // a brush / HBRUSH wrapper class CFont; // a font / HFONT wrapper class CBitmap; // a bitmap / HBITMAP wrapper class CPalette; // a palette / HPALLETE wrapper class CRgn; // a region / HRGN wrapper class CDC; // a Display Context / HDC wrapper class CClientDC; // CDC for client of window class CWindowDC; // CDC for entire window class CPaintDC; // embeddable BeginPaint struct helper class CMenu; // a menu / HMENU wrapper class CCmdTarget; // a target for user commands class CWnd; // a window / HWND wrapper class CDialog; // a dialog // standard windows controls class CStatic; // Static control class CButton; // Button control class CListBox; // ListBox control class CCheckListBox;// special listbox with checks class CComboBox; // ComboBox control class CEdit; // Edit control class CScrollBar; // ScrollBar control // frame windows class CFrameWnd; // standard SDI frame class CMDIFrameWnd; // standard MDI frame class CMDIChildWnd; // standard MDI child class CMiniFrameWnd;// half-height caption frame wnd // views on a document class CView; // a view on a document class CScrollView; // a scrolling view class CWinThread; // thread base class class CWinApp; // application base class class CDocTemplate; // template for document creation class CSingleDocTemplate;// SDI support class CMultiDocTemplate; // MDI support class CDocument; // main document abstraction // Helper classes class CCmdUI; // Menu/button enabling class CDataExchange; // Data exchange and validation context class CCommandLineInfo; // CommandLine parsing helper class CDocManager; // CDocTemplate manager object ///////////////////////////////////////////////////////////////////////////// // Type modifier for message handlers #ifndef afx_msg #define afx_msg // intentional placeholder #endif #undef AFX_DATA #define AFX_DATA AFX_CORE_DATA ///////////////////////////////////////////////////////////////////////////// // CSize - An extent, similar to Windows SIZE structure. class CSize : public tagSIZE { public: // Constructors // construct an uninitialized size CSize(); // create from two integers CSize(int initCX, int initCY); // create from another size CSize(SIZE initSize); // create from a point CSize(POINT initPt); // create from a DWORD: cx = LOWORD(dw) cy = HIWORD(dw) CSize(DWORD dwSize); // Operations BOOL operator==(SIZE size) const; BOOL operator!=(SIZE size) const; void operator+=(SIZE size); void operator-=(SIZE size); // Operators returning CSize values CSize operator+(SIZE size) const; CSize operator-(SIZE size) const; CSize operator-() const; // Operators returning CPoint values CPoint operator+(POINT point) const; CPoint operator-(POINT point) const; // Operators returning CRect values CRect operator+(const RECT* lpRect) const; CRect operator-(const RECT* lpRect) const; }; ///////////////////////////////////////////////////////////////////////////// // CPoint - A 2-D point, similar to Windows POINT structure. class CPoint : public tagPOINT { public: // Constructors // create an uninitialized point CPoint(); // create from two integers CPoint(int initX, int initY); // create from another point CPoint(POINT initPt); // create from a size CPoint(SIZE initSize); // create from a dword: x = LOWORD(dw) y = HIWORD(dw) CPoint(DWORD dwPoint); // Operations // translate the point void Offset(int xOffset, int yOffset); void Offset(POINT point); void Offset(SIZE size); BOOL operator==(POINT point) const; BOOL operator!=(POINT point) const; void operator+=(SIZE size); void operator-=(SIZE size); void operator+=(POINT point); void operator-=(POINT point); // Operators returning CPoint values CPoint operator+(SIZE size) const; CPoint operator-(SIZE size) const; CPoint operator-() const; CPoint operator+(POINT point) const; // Operators returning CSize values CSize operator-(POINT point) const; // Operators returning CRect values CRect operator+(const RECT* lpRect) const; CRect operator-(const RECT* lpRect) const; }; ///////////////////////////////////////////////////////////////////////////// // CRect - A 2-D rectangle, similar to Windows RECT structure. typedef const RECT* LPCRECT; // pointer to read/only RECT class CRect : public tagRECT { public: // Constructors // uninitialized rectangle CRect(); // from left, top, right, and bottom CRect(int l, int t, int r, int b); // copy constructor CRect(const RECT& srcRect); // from a pointer to another rect CRect(LPCRECT lpSrcRect); // from a point and size CRect(POINT point, SIZE size); // from two points CRect(POINT topLeft, POINT bottomRight); // Attributes (in addition to RECT members) // retrieves the width int Width() const; // returns the height int Height() const; // returns the size CSize Size() const; // reference to the top-left point CPoint& TopLeft(); // reference to the bottom-right point CPoint& BottomRight(); // const reference to the top-left point const CPoint& TopLeft() const; // const reference to the bottom-right point const CPoint& BottomRight() const; // the geometric center point of the rectangle CPoint CenterPoint() const; // swap the left and right void SwapLeftRight(); static void SwapLeftRight(LPRECT lpRect); // convert between CRect and LPRECT/LPCRECT (no need for &) operator LPRECT(); operator LPCRECT() const; // returns TRUE if rectangle has no area BOOL IsRectEmpty() const; // returns TRUE if rectangle is at (0,0) and has no area BOOL IsRectNull() const; // returns TRUE if point is within rectangle BOOL PtInRect(POINT point) const; // Operations // set rectangle from left, top, right, and bottom void SetRect(int x1, int y1, int x2, int y2); void SetRect(POINT topLeft, POINT bottomRight); // empty the rectangle void SetRectEmpty(); // copy from another rectangle void CopyRect(LPCRECT lpSrcRect); // TRUE if exactly the same as another rectangle BOOL EqualRect(LPCRECT lpRect) const; // inflate rectangle's width and height without // moving its top or left void InflateRect(int x, int y); void InflateRect(SIZE size); void InflateRect(LPCRECT lpRect); void InflateRect(int l, int t, int r, int b); // deflate the rectangle's width and height without // moving its top or left void DeflateRect(int x, int y); void DeflateRect(SIZE size); void DeflateRect(LPCRECT lpRect); void DeflateRect(int l, int t, int r, int b); // translate the rectangle by moving its top and left void OffsetRect(int x, int y); void OffsetRect(SIZE size); void OffsetRect(POINT point); void NormalizeRect(); // set this rectangle to intersection of two others BOOL IntersectRect(LPCRECT lpRect1, LPCRECT lpRect2); // set this rectangle to bounding union of two others BOOL UnionRect(LPCRECT lpRect1, LPCRECT lpRect2); // set this rectangle to minimum of two others BOOL SubtractRect(LPCRECT lpRectSrc1, LPCRECT lpRectSrc2); // Additional Operations void operator=(const RECT& srcRect); BOOL operator==(const RECT& rect) const; BOOL operator!=(const RECT& rect) const; void operator+=(POINT point); void operator+=(SIZE size); void operator+=(LPCRECT lpRect); void operator-=(POINT point); void operator-=(SIZE size); void operator-=(LPCRECT lpRect); void operator&=(const RECT& rect); void operator|=(const RECT& rect); // Operators returning CRect values CRect operator+(POINT point) const; CRect operator-(POINT point) const; CRect operator+(LPCRECT lpRect) const; CRect operator+(SIZE size) const; CRect operator-(SIZE size) const; CRect operator-(LPCRECT lpRect) const; CRect operator&(const RECT& rect2) const; CRect operator|(const RECT& rect2) const; CRect MulDiv(int nMultiplier, int nDivisor) const; }; #ifdef _DEBUG // Diagnostic Output CDumpContext& AFXAPI operator<<(CDumpContext& dc, SIZE size); CDumpContext& AFXAPI operator<<(CDumpContext& dc, POINT point); CDumpContext& AFXAPI operator<<(CDumpContext& dc, const RECT& rect); #endif //_DEBUG // Serialization CArchive& AFXAPI operator<<(CArchive& ar, SIZE size); CArchive& AFXAPI operator<<(CArchive& ar, POINT point); CArchive& AFXAPI operator<>(CArchive& ar, SIZE& size); CArchive& AFXAPI operator>>(CArchive& ar, POINT& point); CArchive& AFXAPI operator>>(CArchive& ar, RECT& rect); ///////////////////////////////////////////////////////////////////////////// // Standard exceptions class CResourceException : public CSimpleException // resource failure { DECLARE_DYNAMIC(CResourceException) public: CResourceException(); // Implementation public: CResourceException(BOOL bAutoDelete); CResourceException(BOOL bAutoDelete, UINT nResourceID); virtual ~CResourceException(); }; class CUserException : public CSimpleException // general user visible alert { DECLARE_DYNAMIC(CUserException) public: CUserException(); // Implementation public: CUserException(BOOL bAutoDelete); CUserException(BOOL bAutoDelete, UINT nResourceID); virtual ~CUserException(); }; void AFXAPI AfxThrowResourceException(); void AFXAPI AfxThrowUserException(); ///////////////////////////////////////////////////////////////////////////// // CGdiObject abstract class for CDC SelectObject class CGdiObject : public CObject { DECLARE_DYNCREATE(CGdiObject) public: // Attributes HGDIOBJ m_hObject; // must be first data member operator HGDIOBJ() const; HGDIOBJ GetSafeHandle() const; static CGdiObject* PASCAL FromHandle(HGDIOBJ hObject); static void PASCAL DeleteTempMap(); BOOL Attach(HGDIOBJ hObject); HGDIOBJ Detach(); // Constructors CGdiObject(); // must Create a derived class object BOOL DeleteObject(); // Operations int GetObject(int nCount, LPVOID lpObject) const; UINT GetObjectType() const; BOOL CreateStockObject(int nIndex); BOOL UnrealizeObject(); BOOL operator==(const CGdiObject& obj) const; BOOL operator!=(const CGdiObject& obj) const; // Implementation public: virtual ~CGdiObject(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; virtual void AssertValid() const; #endif }; ///////////////////////////////////////////////////////////////////////////// // CGdiObject subclasses (drawing tools) class CPen : public CGdiObject { DECLARE_DYNAMIC(CPen) public: static CPen* PASCAL FromHandle(HPEN hPen); // Constructors CPen(); CPen(int nPenStyle, int nWidth, COLORREF crColor); CPen(int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, int nStyleCount = 0, const DWORD* lpStyle = NULL); BOOL CreatePen(int nPenStyle, int nWidth, COLORREF crColor); BOOL CreatePen(int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, int nStyleCount = 0, const DWORD* lpStyle = NULL); BOOL CreatePenIndirect(LPLOGPEN lpLogPen); // Attributes operator HPEN() const; int GetLogPen(LOGPEN* pLogPen); int GetExtLogPen(EXTLOGPEN* pLogPen); // Implementation public: virtual ~CPen(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif }; class CBrush : public CGdiObject { DECLARE_DYNAMIC(CBrush) public: static CBrush* PASCAL FromHandle(HBRUSH hBrush); // Constructors CBrush(); CBrush(COLORREF crColor); // CreateSolidBrush CBrush(int nIndex, COLORREF crColor); // CreateHatchBrush CBrush(CBitmap* pBitmap); // CreatePatternBrush BOOL CreateSolidBrush(COLORREF crColor); BOOL CreateHatchBrush(int nIndex, COLORREF crColor); BOOL CreateBrushIndirect(const LOGBRUSH* lpLogBrush); BOOL CreatePatternBrush(CBitmap* pBitmap); BOOL CreateDIBPatternBrush(HGLOBAL hPackedDIB, UINT nUsage); BOOL CreateDIBPatternBrush(const void* lpPackedDIB, UINT nUsage); BOOL CreateSysColorBrush(int nIndex); // Attributes operator HBRUSH() const; int GetLogBrush(LOGBRUSH* pLogBrush); // Implementation public: virtual ~CBrush(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif }; class CFont : public CGdiObject { DECLARE_DYNAMIC(CFont) public: static CFont* PASCAL FromHandle(HFONT hFont); // Constructors CFont(); BOOL CreateFontIndirect(const LOGFONT* lpLogFont); BOOL CreateFont(int nHeight, int nWidth, int nEscapement, int nOrientation, int nWeight, BYTE bItalic, BYTE bUnderline, BYTE cStrikeOut, BYTE nCharSet, BYTE nOutPrecision, BYTE nClipPrecision, BYTE nQuality, BYTE nPitchAndFamily, LPCTSTR lpszFacename); BOOL CreatePointFont(int nPointSize, LPCTSTR lpszFaceName, CDC* pDC = NULL); BOOL CreatePointFontIndirect(const LOGFONT* lpLogFont, CDC* pDC = NULL); // Attributes operator HFONT() const; int GetLogFont(LOGFONT* pLogFont); // Implementation public: virtual ~CFont(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif }; class CBitmap : public CGdiObject { DECLARE_DYNAMIC(CBitmap) public: static CBitmap* PASCAL FromHandle(HBITMAP hBitmap); // Constructors CBitmap(); BOOL LoadBitmap(LPCTSTR lpszResourceName); BOOL LoadBitmap(UINT nIDResource); BOOL LoadOEMBitmap(UINT nIDBitmap); // for OBM_/OCR_/OIC_ BOOL LoadMappedBitmap(UINT nIDBitmap, UINT nFlags = 0, LPCOLORMAP lpColorMap = NULL, int nMapSize = 0); BOOL CreateBitmap(int nWidth, int nHeight, UINT nPlanes, UINT nBitcount, const void* lpBits); BOOL CreateBitmapIndirect(LPBITMAP lpBitmap); BOOL CreateCompatibleBitmap(CDC* pDC, int nWidth, int nHeight); BOOL CreateDiscardableBitmap(CDC* pDC, int nWidth, int nHeight); // Attributes operator HBITMAP() const; int GetBitmap(BITMAP* pBitMap); // Operations DWORD SetBitmapBits(DWORD dwCount, const void* lpBits); DWORD GetBitmapBits(DWORD dwCount, LPVOID lpBits) const; CSize SetBitmapDimension(int nWidth, int nHeight); CSize GetBitmapDimension() const; // Implementation public: virtual ~CBitmap(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif }; class CPalette : public CGdiObject { DECLARE_DYNAMIC(CPalette) public: static CPalette* PASCAL FromHandle(HPALETTE hPalette); // Constructors CPalette(); BOOL CreatePalette(LPLOGPALETTE lpLogPalette); BOOL CreateHalftonePalette(CDC* pDC); // Attributes operator HPALETTE() const; int GetEntryCount(); UINT GetPaletteEntries(UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors) const; UINT SetPaletteEntries(UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors); // Operations void AnimatePalette(UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors); UINT GetNearestPaletteIndex(COLORREF crColor) const; BOOL ResizePalette(UINT nNumEntries); // Implementation virtual ~CPalette(); }; class CRgn : public CGdiObject { DECLARE_DYNAMIC(CRgn) public: static CRgn* PASCAL FromHandle(HRGN hRgn); operator HRGN() const; // Constructors CRgn(); BOOL CreateRectRgn(int x1, int y1, int x2, int y2); BOOL CreateRectRgnIndirect(LPCRECT lpRect); BOOL CreateEllipticRgn(int x1, int y1, int x2, int y2); BOOL CreateEllipticRgnIndirect(LPCRECT lpRect); BOOL CreatePolygonRgn(LPPOINT lpPoints, int nCount, int nMode); BOOL CreatePolyPolygonRgn(LPPOINT lpPoints, LPINT lpPolyCounts, int nCount, int nPolyFillMode); BOOL CreateRoundRectRgn(int x1, int y1, int x2, int y2, int x3, int y3); BOOL CreateFromPath(CDC* pDC); BOOL CreateFromData(const XFORM* lpXForm, int nCount, const RGNDATA* pRgnData); // Operations void SetRectRgn(int x1, int y1, int x2, int y2); void SetRectRgn(LPCRECT lpRect); int CombineRgn(CRgn* pRgn1, CRgn* pRgn2, int nCombineMode); int CopyRgn(CRgn* pRgnSrc); BOOL EqualRgn(CRgn* pRgn) const; int OffsetRgn(int x, int y); int OffsetRgn(POINT point); int GetRgnBox(LPRECT lpRect) const; BOOL PtInRegion(int x, int y) const; BOOL PtInRegion(POINT point) const; BOOL RectInRegion(LPCRECT lpRect) const; int GetRegionData(LPRGNDATA lpRgnData, int nCount) const; // Implementation virtual ~CRgn(); }; ///////////////////////////////////////////////////////////////////////////// // The device context class CDC : public CObject { DECLARE_DYNCREATE(CDC) public: // Attributes HDC m_hDC; // The output DC (must be first data member) HDC m_hAttribDC; // The Attribute DC operator HDC() const; HDC GetSafeHdc() const; // Always returns the Output DC CWnd* GetWindow() const; static CDC* PASCAL FromHandle(HDC hDC); static void PASCAL DeleteTempMap(); BOOL Attach(HDC hDC); // Attach/Detach affects only the Output DC HDC Detach(); virtual void SetAttribDC(HDC hDC); // Set the Attribute DC virtual void SetOutputDC(HDC hDC); // Set the Output DC virtual void ReleaseAttribDC(); // Release the Attribute DC virtual void ReleaseOutputDC(); // Release the Output DC BOOL IsPrinting() const; // TRUE if being used for printing CPen* GetCurrentPen() const; CBrush* GetCurrentBrush() const; CPalette* GetCurrentPalette() const; CFont* GetCurrentFont() const; CBitmap* GetCurrentBitmap() const; // for bidi and mirrored localization DWORD GetLayout() const; DWORD SetLayout(DWORD dwLayout); // Constructors CDC(); BOOL CreateDC(LPCTSTR lpszDriverName, LPCTSTR lpszDeviceName, LPCTSTR lpszOutput, const void* lpInitData); BOOL CreateIC(LPCTSTR lpszDriverName, LPCTSTR lpszDeviceName, LPCTSTR lpszOutput, const void* lpInitData); BOOL CreateCompatibleDC(CDC* pDC); BOOL DeleteDC(); // Device-Context Functions virtual int SaveDC(); virtual BOOL RestoreDC(int nSavedDC); int GetDeviceCaps(int nIndex) const; UINT SetBoundsRect(LPCRECT lpRectBounds, UINT flags); UINT GetBoundsRect(LPRECT lpRectBounds, UINT flags); BOOL ResetDC(const DEVMODE* lpDevMode); // Drawing-Tool Functions CPoint GetBrushOrg() const; CPoint SetBrushOrg(int x, int y); CPoint SetBrushOrg(POINT point); int EnumObjects(int nObjectType, int (CALLBACK* lpfn)(LPVOID, LPARAM), LPARAM lpData); // Type-safe selection helpers public: virtual CGdiObject* SelectStockObject(int nIndex); CPen* SelectObject(CPen* pPen); CBrush* SelectObject(CBrush* pBrush); virtual CFont* SelectObject(CFont* pFont); CBitmap* SelectObject(CBitmap* pBitmap); int SelectObject(CRgn* pRgn); // special return for regions CGdiObject* SelectObject(CGdiObject* pObject); // CGdiObject* provided so compiler doesn't use SelectObject(HGDIOBJ) // Color and Color Palette Functions COLORREF GetNearestColor(COLORREF crColor) const; CPalette* SelectPalette(CPalette* pPalette, BOOL bForceBackground); UINT RealizePalette(); void UpdateColors(); // Drawing-Attribute Functions COLORREF GetBkColor() const; int GetBkMode() const; int GetPolyFillMode() const; int GetROP2() const; int GetStretchBltMode() const; COLORREF GetTextColor() const; virtual COLORREF SetBkColor(COLORREF crColor); int SetBkMode(int nBkMode); int SetPolyFillMode(int nPolyFillMode); int SetROP2(int nDrawMode); int SetStretchBltMode(int nStretchMode); virtual COLORREF SetTextColor(COLORREF crColor); BOOL GetColorAdjustment(LPCOLORADJUSTMENT lpColorAdjust) const; BOOL SetColorAdjustment(const COLORADJUSTMENT* lpColorAdjust); // Mapping Functions int GetMapMode() const; CPoint GetViewportOrg() const; virtual int SetMapMode(int nMapMode); // Viewport Origin virtual CPoint SetViewportOrg(int x, int y); CPoint SetViewportOrg(POINT point); virtual CPoint OffsetViewportOrg(int nWidth, int nHeight); // Viewport Extent CSize GetViewportExt() const; virtual CSize SetViewportExt(int cx, int cy); CSize SetViewportExt(SIZE size); virtual CSize ScaleViewportExt(int xNum, int xDenom, int yNum, int yDenom); // Window Origin CPoint GetWindowOrg() const; CPoint SetWindowOrg(int x, int y); CPoint SetWindowOrg(POINT point); CPoint OffsetWindowOrg(int nWidth, int nHeight); // Window extent CSize GetWindowExt() const; virtual CSize SetWindowExt(int cx, int cy); CSize SetWindowExt(SIZE size); virtual CSize ScaleWindowExt(int xNum, int xDenom, int yNum, int yDenom); // Coordinate Functions void DPtoLP(LPPOINT lpPoints, int nCount = 1) const; void DPtoLP(LPRECT lpRect) const; void DPtoLP(LPSIZE lpSize) const; void LPtoDP(LPPOINT lpPoints, int nCount = 1) const; void LPtoDP(LPRECT lpRect) const; void LPtoDP(LPSIZE lpSize) const; // Special Coordinate Functions (useful for dealing with metafiles and OLE) void DPtoHIMETRIC(LPSIZE lpSize) const; void LPtoHIMETRIC(LPSIZE lpSize) const; void HIMETRICtoDP(LPSIZE lpSize) const; void HIMETRICtoLP(LPSIZE lpSize) const; // Region Functions BOOL FillRgn(CRgn* pRgn, CBrush* pBrush); BOOL FrameRgn(CRgn* pRgn, CBrush* pBrush, int nWidth, int nHeight); BOOL InvertRgn(CRgn* pRgn); BOOL PaintRgn(CRgn* pRgn); // Clipping Functions virtual int GetClipBox(LPRECT lpRect) const; virtual BOOL PtVisible(int x, int y) const; BOOL PtVisible(POINT point) const; virtual BOOL RectVisible(LPCRECT lpRect) const; int SelectClipRgn(CRgn* pRgn); int ExcludeClipRect(int x1, int y1, int x2, int y2); int ExcludeClipRect(LPCRECT lpRect); int ExcludeUpdateRgn(CWnd* pWnd); int IntersectClipRect(int x1, int y1, int x2, int y2); int IntersectClipRect(LPCRECT lpRect); int OffsetClipRgn(int x, int y); int OffsetClipRgn(SIZE size); int SelectClipRgn(CRgn* pRgn, int nMode); // Line-Output Functions CPoint GetCurrentPosition() const; CPoint MoveTo(int x, int y); CPoint MoveTo(POINT point); BOOL LineTo(int x, int y); BOOL LineTo(POINT point); BOOL Arc(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); BOOL Arc(LPCRECT lpRect, POINT ptStart, POINT ptEnd); BOOL Polyline(LPPOINT lpPoints, int nCount); BOOL AngleArc(int x, int y, int nRadius, float fStartAngle, float fSweepAngle); BOOL ArcTo(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); BOOL ArcTo(LPCRECT lpRect, POINT ptStart, POINT ptEnd); int GetArcDirection() const; int SetArcDirection(int nArcDirection); BOOL PolyDraw(const POINT* lpPoints, const BYTE* lpTypes, int nCount); BOOL PolylineTo(const POINT* lpPoints, int nCount); BOOL PolyPolyline(const POINT* lpPoints, const DWORD* lpPolyPoints, int nCount); BOOL PolyBezier(const POINT* lpPoints, int nCount); BOOL PolyBezierTo(const POINT* lpPoints, int nCount); // Simple Drawing Functions void FillRect(LPCRECT lpRect, CBrush* pBrush); void FrameRect(LPCRECT lpRect, CBrush* pBrush); void InvertRect(LPCRECT lpRect); BOOL DrawIcon(int x, int y, HICON hIcon); BOOL DrawIcon(POINT point, HICON hIcon); #if (WINVER >= 0x400) BOOL DrawState(CPoint pt, CSize size, HBITMAP hBitmap, UINT nFlags, HBRUSH hBrush = NULL); BOOL DrawState(CPoint pt, CSize size, CBitmap* pBitmap, UINT nFlags, CBrush* pBrush = NULL); BOOL DrawState(CPoint pt, CSize size, HICON hIcon, UINT nFlags, HBRUSH hBrush = NULL); BOOL DrawState(CPoint pt, CSize size, HICON hIcon, UINT nFlags, CBrush* pBrush = NULL); BOOL DrawState(CPoint pt, CSize size, LPCTSTR lpszText, UINT nFlags, BOOL bPrefixText = TRUE, int nTextLen = 0, HBRUSH hBrush = NULL); BOOL DrawState(CPoint pt, CSize size, LPCTSTR lpszText, UINT nFlags, BOOL bPrefixText = TRUE, int nTextLen = 0, CBrush* pBrush = NULL); BOOL DrawState(CPoint pt, CSize size, DRAWSTATEPROC lpDrawProc, LPARAM lData, UINT nFlags, HBRUSH hBrush = NULL); BOOL DrawState(CPoint pt, CSize size, DRAWSTATEPROC lpDrawProc, LPARAM lData, UINT nFlags, CBrush* pBrush = NULL); #endif // Ellipse and Polygon Functions BOOL Chord(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); BOOL Chord(LPCRECT lpRect, POINT ptStart, POINT ptEnd); void DrawFocusRect(LPCRECT lpRect); BOOL Ellipse(int x1, int y1, int x2, int y2); BOOL Ellipse(LPCRECT lpRect); BOOL Pie(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); BOOL Pie(LPCRECT lpRect, POINT ptStart, POINT ptEnd); BOOL Polygon(LPPOINT lpPoints, int nCount); BOOL PolyPolygon(LPPOINT lpPoints, LPINT lpPolyCounts, int nCount); BOOL Rectangle(int x1, int y1, int x2, int y2); BOOL Rectangle(LPCRECT lpRect); BOOL RoundRect(int x1, int y1, int x2, int y2, int x3, int y3); BOOL RoundRect(LPCRECT lpRect, POINT point); // Bitmap Functions BOOL PatBlt(int x, int y, int nWidth, int nHeight, DWORD dwRop); BOOL BitBlt(int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, DWORD dwRop); BOOL StretchBlt(int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, DWORD dwRop); COLORREF GetPixel(int x, int y) const; COLORREF GetPixel(POINT point) const; COLORREF SetPixel(int x, int y, COLORREF crColor); COLORREF SetPixel(POINT point, COLORREF crColor); BOOL FloodFill(int x, int y, COLORREF crColor); BOOL ExtFloodFill(int x, int y, COLORREF crColor, UINT nFillType); BOOL MaskBlt(int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, CBitmap& maskBitmap, int xMask, int yMask, DWORD dwRop); BOOL PlgBlt(LPPOINT lpPoint, CDC* pSrcDC, int xSrc, int ySrc, int nWidth, int nHeight, CBitmap& maskBitmap, int xMask, int yMask); BOOL SetPixelV(int x, int y, COLORREF crColor); BOOL SetPixelV(POINT point, COLORREF crColor); // Text Functions virtual BOOL TextOut(int x, int y, LPCTSTR lpszString, int nCount); BOOL TextOut(int x, int y, const CString& str); virtual BOOL ExtTextOut(int x, int y, UINT nOptions, LPCRECT lpRect, LPCTSTR lpszString, UINT nCount, LPINT lpDxWidths); BOOL ExtTextOut(int x, int y, UINT nOptions, LPCRECT lpRect, const CString& str, LPINT lpDxWidths); virtual CSize TabbedTextOut(int x, int y, LPCTSTR lpszString, int nCount, int nTabPositions, LPINT lpnTabStopPositions, int nTabOrigin); CSize TabbedTextOut(int x, int y, const CString& str, int nTabPositions, LPINT lpnTabStopPositions, int nTabOrigin); virtual int DrawText(LPCTSTR lpszString, int nCount, LPRECT lpRect, UINT nFormat); int DrawText(const CString& str, LPRECT lpRect, UINT nFormat); CSize GetTextExtent(LPCTSTR lpszString, int nCount) const; CSize GetTextExtent(const CString& str) const; CSize GetOutputTextExtent(LPCTSTR lpszString, int nCount) const; CSize GetOutputTextExtent(const CString& str) const; CSize GetTabbedTextExtent(LPCTSTR lpszString, int nCount, int nTabPositions, LPINT lpnTabStopPositions) const; CSize GetTabbedTextExtent(const CString& str, int nTabPositions, LPINT lpnTabStopPositions) const; CSize GetOutputTabbedTextExtent(LPCTSTR lpszString, int nCount, int nTabPositions, LPINT lpnTabStopPositions) const; CSize GetOutputTabbedTextExtent(const CString& str, int nTabPositions, LPINT lpnTabStopPositions) const; virtual BOOL GrayString(CBrush* pBrush, BOOL (CALLBACK* lpfnOutput)(HDC, LPARAM, int), LPARAM lpData, int nCount, int x, int y, int nWidth, int nHeight); UINT GetTextAlign() const; UINT SetTextAlign(UINT nFlags); int GetTextFace(int nCount, LPTSTR lpszFacename) const; int GetTextFace(CString& rString) const; BOOL GetTextMetrics(LPTEXTMETRIC lpMetrics) const; BOOL GetOutputTextMetrics(LPTEXTMETRIC lpMetrics) const; int SetTextJustification(int nBreakExtra, int nBreakCount); int GetTextCharacterExtra() const; int SetTextCharacterExtra(int nCharExtra); // Advanced Drawing #if (WINVER >= 0x400) BOOL DrawEdge(LPRECT lpRect, UINT nEdge, UINT nFlags); BOOL DrawFrameControl(LPRECT lpRect, UINT nType, UINT nState); #endif // Scrolling Functions BOOL ScrollDC(int dx, int dy, LPCRECT lpRectScroll, LPCRECT lpRectClip, CRgn* pRgnUpdate, LPRECT lpRectUpdate); // Font Functions BOOL GetCharWidth(UINT nFirstChar, UINT nLastChar, LPINT lpBuffer) const; BOOL GetOutputCharWidth(UINT nFirstChar, UINT nLastChar, LPINT lpBuffer) const; DWORD SetMapperFlags(DWORD dwFlag); CSize GetAspectRatioFilter() const; BOOL GetCharABCWidths(UINT nFirstChar, UINT nLastChar, LPABC lpabc) const; DWORD GetFontData(DWORD dwTable, DWORD dwOffset, LPVOID lpData, DWORD cbData) const; int GetKerningPairs(int nPairs, LPKERNINGPAIR lpkrnpair) const; UINT GetOutlineTextMetrics(UINT cbData, LPOUTLINETEXTMETRIC lpotm) const; DWORD GetGlyphOutline(UINT nChar, UINT nFormat, LPGLYPHMETRICS lpgm, DWORD cbBuffer, LPVOID lpBuffer, const MAT2* lpmat2) const; BOOL GetCharABCWidths(UINT nFirstChar, UINT nLastChar, LPABCFLOAT lpABCF) const; BOOL GetCharWidth(UINT nFirstChar, UINT nLastChar, float* lpFloatBuffer) const; // Printer/Device Escape Functions virtual int Escape(int nEscape, int nCount, LPCSTR lpszInData, LPVOID lpOutData); int Escape(int nEscape, int nInputSize, LPCSTR lpszInputData, int nOutputSize, LPSTR lpszOutputData); int DrawEscape(int nEscape, int nInputSize, LPCSTR lpszInputData); // Escape helpers int StartDoc(LPCTSTR lpszDocName); // old Win3.0 version int StartDoc(LPDOCINFO lpDocInfo); int StartPage(); int EndPage(); int SetAbortProc(BOOL (CALLBACK* lpfn)(HDC, int)); int AbortDoc(); int EndDoc(); // MetaFile Functions BOOL PlayMetaFile(HMETAFILE hMF); BOOL PlayMetaFile(HENHMETAFILE hEnhMetaFile, LPCRECT lpBounds); BOOL AddMetaFileComment(UINT nDataSize, const BYTE* pCommentData); // can be used for enhanced metafiles only // Path Functions BOOL AbortPath(); BOOL BeginPath(); BOOL CloseFigure(); BOOL EndPath(); BOOL FillPath(); BOOL FlattenPath(); BOOL StrokeAndFillPath(); BOOL StrokePath(); BOOL WidenPath(); float GetMiterLimit() const; BOOL SetMiterLimit(float fMiterLimit); int GetPath(LPPOINT lpPoints, LPBYTE lpTypes, int nCount) const; BOOL SelectClipPath(int nMode); // Misc Helper Functions static CBrush* PASCAL GetHalftoneBrush(); void DrawDragRect(LPCRECT lpRect, SIZE size, LPCRECT lpRectLast, SIZE sizeLast, CBrush* pBrush = NULL, CBrush* pBrushLast = NULL); void FillSolidRect(LPCRECT lpRect, COLORREF clr); void FillSolidRect(int x, int y, int cx, int cy, COLORREF clr); void Draw3dRect(LPCRECT lpRect, COLORREF clrTopLeft, COLORREF clrBottomRight); void Draw3dRect(int x, int y, int cx, int cy, COLORREF clrTopLeft, COLORREF clrBottomRight); // Implementation public: virtual ~CDC(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // advanced use and implementation BOOL m_bPrinting; HGDIOBJ SelectObject(HGDIOBJ); // do not use for regions protected: // used for implementation of non-virtual SelectObject calls static CGdiObject* PASCAL SelectGdiObject(HDC hDC, HGDIOBJ h); }; ///////////////////////////////////////////////////////////////////////////// // CDC Helpers class CPaintDC : public CDC { DECLARE_DYNAMIC(CPaintDC) // Constructors public: CPaintDC(CWnd* pWnd); // BeginPaint // Attributes protected: HWND m_hWnd; public: PAINTSTRUCT m_ps; // actual paint struct! // Implementation public: virtual ~CPaintDC(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif }; class CClientDC : public CDC { DECLARE_DYNAMIC(CClientDC) // Constructors public: CClientDC(CWnd* pWnd); // Attributes protected: HWND m_hWnd; // Implementation public: virtual ~CClientDC(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif }; class CWindowDC : public CDC { DECLARE_DYNAMIC(CWindowDC) // Constructors public: CWindowDC(CWnd* pWnd); // Attributes protected: HWND m_hWnd; // Implementation public: virtual ~CWindowDC(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif }; ///////////////////////////////////////////////////////////////////////////// // CMenu class CMenu : public CObject { DECLARE_DYNCREATE(CMenu) public: // Constructors CMenu(); BOOL CreateMenu(); BOOL CreatePopupMenu(); BOOL LoadMenu(LPCTSTR lpszResourceName); BOOL LoadMenu(UINT nIDResource); BOOL LoadMenuIndirect(const void* lpMenuTemplate); BOOL DestroyMenu(); // Attributes HMENU m_hMenu; // must be first data member HMENU GetSafeHmenu() const; operator HMENU() const; static CMenu* PASCAL FromHandle(HMENU hMenu); static void PASCAL DeleteTempMap(); BOOL Attach(HMENU hMenu); HMENU Detach(); // CMenu Operations BOOL DeleteMenu(UINT nPosition, UINT nFlags); BOOL TrackPopupMenu(UINT nFlags, int x, int y, CWnd* pWnd, LPCRECT lpRect = 0); BOOL operator==(const CMenu& menu) const; BOOL operator!=(const CMenu& menu) const; // CMenuItem Operations BOOL AppendMenu(UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL); BOOL AppendMenu(UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp); UINT CheckMenuItem(UINT nIDCheckItem, UINT nCheck); UINT EnableMenuItem(UINT nIDEnableItem, UINT nEnable); UINT GetMenuItemCount() const; UINT GetMenuItemID(int nPos) const; UINT GetMenuState(UINT nID, UINT nFlags) const; int GetMenuString(UINT nIDItem, LPTSTR lpString, int nMaxCount, UINT nFlags) const; int GetMenuString(UINT nIDItem, CString& rString, UINT nFlags) const; BOOL GetMenuItemInfo(UINT nIDItem, LPMENUITEMINFO lpMenuItemInfo, BOOL fByPos = FALSE); CMenu* GetSubMenu(int nPos) const; BOOL InsertMenu(UINT nPosition, UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL); BOOL InsertMenu(UINT nPosition, UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp); BOOL ModifyMenu(UINT nPosition, UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL); BOOL ModifyMenu(UINT nPosition, UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp); BOOL RemoveMenu(UINT nPosition, UINT nFlags); BOOL SetMenuItemBitmaps(UINT nPosition, UINT nFlags, const CBitmap* pBmpUnchecked, const CBitmap* pBmpChecked); BOOL CheckMenuRadioItem(UINT nIDFirst, UINT nIDLast, UINT nIDItem, UINT nFlags); BOOL SetDefaultItem(UINT uItem, BOOL fByPos = FALSE); UINT GetDefaultItem(UINT gmdiFlags, BOOL fByPos = FALSE); // Context Help Functions BOOL SetMenuContextHelpId(DWORD dwContextHelpId); DWORD GetMenuContextHelpId() const; // Overridables (must override draw and measure for owner-draw menu items) virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct); // Implementation public: virtual ~CMenu(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif static CMenu* PASCAL CMenu::FromHandlePermanent(HMENU hMenu); }; ///////////////////////////////////////////////////////////////////////////// // Window message map handling struct AFX_MSGMAP_ENTRY; // declared below after CWnd struct AFX_MSGMAP { #ifdef _AFXDLL const AFX_MSGMAP* (PASCAL* pfnGetBaseMap)(); #else const AFX_MSGMAP* pBaseMap; #endif const AFX_MSGMAP_ENTRY* lpEntries; }; #ifdef _AFXDLL #define DECLARE_MESSAGE_MAP() \ private: \ static const AFX_MSGMAP_ENTRY _messageEntries[]; \ protected: \ static AFX_DATA const AFX_MSGMAP messageMap; \ static const AFX_MSGMAP* PASCAL _GetBaseMessageMap(); \ virtual const AFX_MSGMAP* GetMessageMap() const; \ #else #define DECLARE_MESSAGE_MAP() \ private: \ static const AFX_MSGMAP_ENTRY _messageEntries[]; \ protected: \ static AFX_DATA const AFX_MSGMAP messageMap; \ virtual const AFX_MSGMAP* GetMessageMap() const; \ #endif #ifdef _AFXDLL #define BEGIN_MESSAGE_MAP(theClass, baseClass) \ const AFX_MSGMAP* PASCAL theClass::_GetBaseMessageMap() \ { return &baseClass;::messageMap; } \ const AFX_MSGMAP* theClass::GetMessageMap() const \ { return &theClass;::messageMap; } \ AFX_COMDAT AFX_DATADEF const AFX_MSGMAP theClass::messageMap = \ { &theClass;::_GetBaseMessageMap, &theClass;::_messageEntries[0] }; \ AFX_COMDAT const AFX_MSGMAP_ENTRY theClass::_messageEntries[] = \ { \ #else #define BEGIN_MESSAGE_MAP(theClass, baseClass) \ const AFX_MSGMAP* theClass::GetMessageMap() const \ { return &theClass;::messageMap; } \ AFX_COMDAT AFX_DATADEF const AFX_MSGMAP theClass::messageMap = \ { &baseClass;::messageMap, &theClass;::_messageEntries[0] }; \ AFX_COMDAT const AFX_MSGMAP_ENTRY theClass::_messageEntries[] = \ { \ #endif #define END_MESSAGE_MAP() \ {0, 0, 0, 0, AfxSig_end, (AFX_PMSG)0 } \ }; \ // Message map signature values and macros in separate header #include ///////////////////////////////////////////////////////////////////////////// // Dialog data exchange (DDX_) and validation (DDV_) // CDataExchange - for data exchange and validation class CDataExchange { // Attributes public: BOOL m_bSaveAndValidate; // TRUE => save and validate data CWnd* m_pDlgWnd; // container usually a dialog // Operations (for implementors of DDX and DDV procs) HWND PrepareCtrl(int nIDC); // return HWND of control HWND PrepareEditCtrl(int nIDC); // return HWND of control void Fail(); // will throw exception #ifndef _AFX_NO_OCC_SUPPORT CWnd* PrepareOleCtrl(int nIDC); // for OLE controls in dialog #endif // Implementation CDataExchange(CWnd* pDlgWnd, BOOL bSaveAndValidate); HWND m_hWndLastControl; // last control used (for validation) BOOL m_bEditLastControl; // last control was an edit item }; #include // standard DDX_ and DDV_ routines ///////////////////////////////////////////////////////////////////////////// // OLE types typedef LONG HRESULT; struct IUnknown; typedef IUnknown* LPUNKNOWN; struct IDispatch; typedef IDispatch* LPDISPATCH; struct IConnectionPoint; typedef IConnectionPoint* LPCONNECTIONPOINT; struct IEnumOLEVERB; typedef IEnumOLEVERB* LPENUMOLEVERB; typedef struct _GUID GUID; typedef GUID IID; typedef GUID CLSID; #ifndef _REFCLSID_DEFINED #define REFCLSID const CLSID & #endif typedef long DISPID; typedef unsigned short VARTYPE; typedef long SCODE; #if defined(WIN32) && !defined(OLE2ANSI) typedef WCHAR OLECHAR; #else typedef char OLECHAR; #endif typedef OLECHAR* BSTR; struct tagDISPPARAMS; typedef tagDISPPARAMS DISPPARAMS; struct tagVARIANT; typedef tagVARIANT VARIANT; struct ITypeInfo; typedef ITypeInfo* LPTYPEINFO; struct ITypeLib; typedef ITypeLib* LPTYPELIB; ///////////////////////////////////////////////////////////////////////////// // CCmdTarget // private structures struct AFX_CMDHANDLERINFO; // info about where the command is handled struct AFX_EVENT; // info about an event class CTypeLibCache; // cache for OLE type libraries ///////////////////////////////////////////////////////////////////////////// // OLE interface map handling (more in AFXDISP.H) #ifndef _AFX_NO_OLE_SUPPORT struct AFX_INTERFACEMAP_ENTRY { const void* piid; // the interface id (IID) (NULL for aggregate) size_t nOffset; // offset of the interface vtable from m_unknown }; struct AFX_INTERFACEMAP { #ifdef _AFXDLL const AFX_INTERFACEMAP* (PASCAL* pfnGetBaseMap)(); // NULL is root class #else const AFX_INTERFACEMAP* pBaseMap; #endif const AFX_INTERFACEMAP_ENTRY* pEntry; // map for this class }; #ifdef _AFXDLL #define DECLARE_INTERFACE_MAP() \ private: \ static const AFX_INTERFACEMAP_ENTRY _interfaceEntries[]; \ protected: \ static AFX_DATA const AFX_INTERFACEMAP interfaceMap; \ static const AFX_INTERFACEMAP* PASCAL _GetBaseInterfaceMap(); \ virtual const AFX_INTERFACEMAP* GetInterfaceMap() const; \ #else #define DECLARE_INTERFACE_MAP() \ private: \ static const AFX_INTERFACEMAP_ENTRY _interfaceEntries[]; \ protected: \ static AFX_DATA const AFX_INTERFACEMAP interfaceMap; \ virtual const AFX_INTERFACEMAP* GetInterfaceMap() const; \ #endif #endif //!_AFX_NO_OLE_SUPPORT ///////////////////////////////////////////////////////////////////////////// // OLE dispatch map handling (more in AFXDISP.H) #ifndef _AFX_NO_OLE_SUPPORT struct AFX_DISPMAP_ENTRY; struct AFX_DISPMAP { #ifdef _AFXDLL const AFX_DISPMAP* (PASCAL* pfnGetBaseMap)(); #else const AFX_DISPMAP* pBaseMap; #endif const AFX_DISPMAP_ENTRY* lpEntries; UINT* lpEntryCount; DWORD* lpStockPropMask; }; #ifdef _AFXDLL #define DECLARE_DISPATCH_MAP() \ private: \ static const AFX_DISPMAP_ENTRY _dispatchEntries[]; \ static UINT _dispatchEntryCount; \ static DWORD _dwStockPropMask; \ protected: \ static AFX_DATA const AFX_DISPMAP dispatchMap; \ static const AFX_DISPMAP* PASCAL _GetBaseDispatchMap(); \ virtual const AFX_DISPMAP* GetDispatchMap() const; \ #else #define DECLARE_DISPATCH_MAP() \ private: \ static const AFX_DISPMAP_ENTRY _dispatchEntries[]; \ static UINT _dispatchEntryCount; \ static DWORD _dwStockPropMask; \ protected: \ static AFX_DATA const AFX_DISPMAP dispatchMap; \ virtual const AFX_DISPMAP* GetDispatchMap() const; \ #endif #endif //!_AFX_NO_OLE_SUPPORT ///////////////////////////////////////////////////////////////////////////// // OLE Document Object command target handling #ifndef _AFX_NO_DOCOBJECT_SUPPORT struct AFX_OLECMDMAP_ENTRY { const GUID* pguid; // id of the command group ULONG cmdID; // OLECMD ID UINT nID; // corresponding WM_COMMAND message ID }; struct AFX_OLECMDMAP { #ifdef _AFXDLL const AFX_OLECMDMAP* (PASCAL* pfnGetBaseMap)(); #else const AFX_OLECMDMAP* pBaseMap; #endif const AFX_OLECMDMAP_ENTRY* lpEntries; }; #ifdef _AFXDLL #define DECLARE_OLECMD_MAP() \ private: \ static const AFX_OLECMDMAP_ENTRY _commandEntries[]; \ protected: \ static AFX_DATA const AFX_OLECMDMAP commandMap; \ static const AFX_OLECMDMAP* PASCAL _GetBaseCommandMap(); \ virtual const AFX_OLECMDMAP* GetCommandMap() const; \ #else #define DECLARE_OLECMD_MAP() \ private: \ static const AFX_OLECMDMAP_ENTRY _commandEntries[]; \ protected: \ static AFX_DATA const AFX_OLECMDMAP commandMap; \ virtual const AFX_OLECMDMAP* GetCommandMap() const; \ #endif #ifdef _AFXDLL #define BEGIN_OLECMD_MAP(theClass, baseClass) \ const AFX_OLECMDMAP* PASCAL theClass::_GetBaseCommandMap() \ { return &baseClass;::commandMap; } \ const AFX_OLECMDMAP* theClass::GetCommandMap() const \ { return &theClass;::commandMap; } \ AFX_COMDAT AFX_DATADEF const AFX_OLECMDMAP theClass::commandMap = \ { &theClass;::_GetBaseCommandMap, &theClass;::_commandEntries[0] }; \ AFX_COMDAT const AFX_OLECMDMAP_ENTRY theClass::_commandEntries[] = \ { \ #else #define BEGIN_OLECMD_MAP(theClass, baseClass) \ const AFX_OLECMDMAP* theClass::GetCommandMap() const \ { return &theClass;::commandMap; } \ AFX_COMDAT AFX_DATADEF const AFX_OLECMDMAP theClass::commandMap = \ { &baseClass;::commandMap, &theClass;::_commandEntries[0] }; \ AFX_COMDAT const AFX_OLECMDMAP_ENTRY theClass::_commandEntries[] = \ { \ #endif #define END_OLECMD_MAP() \ {NULL, 0, 0} \ }; \ class COleCmdUI; #endif //!_AFX_NO_DOCOBJECT_SUPPORT ///////////////////////////////////////////////////////////////////////////// // OLE event sink map handling (more in AFXDISP.H) #ifndef _AFX_NO_OCC_SUPPORT struct AFX_EVENTSINKMAP_ENTRY; struct AFX_EVENTSINKMAP { #ifdef _AFXDLL const AFX_EVENTSINKMAP* (PASCAL* pfnGetBaseMap)(); #else const AFX_EVENTSINKMAP* pBaseMap; #endif const AFX_EVENTSINKMAP_ENTRY* lpEntries; UINT* lpEntryCount; }; #ifdef _AFXDLL #define DECLARE_EVENTSINK_MAP() \ private: \ static const AFX_EVENTSINKMAP_ENTRY _eventsinkEntries[]; \ static UINT _eventsinkEntryCount; \ protected: \ static AFX_DATA const AFX_EVENTSINKMAP eventsinkMap; \ static const AFX_EVENTSINKMAP* PASCAL _GetBaseEventSinkMap(); \ virtual const AFX_EVENTSINKMAP* GetEventSinkMap() const; \ #else #define DECLARE_EVENTSINK_MAP() \ private: \ static const AFX_EVENTSINKMAP_ENTRY _eventsinkEntries[]; \ static UINT _eventsinkEntryCount; \ protected: \ static AFX_DATA const AFX_EVENTSINKMAP eventsinkMap; \ virtual const AFX_EVENTSINKMAP* GetEventSinkMap() const; \ #endif #endif //!_AFX_NO_OCC_SUPPORT ///////////////////////////////////////////////////////////////////////////// // OLE connection map handling (more in AFXDISP.H) #ifndef _AFX_NO_OLE_SUPPORT struct AFX_CONNECTIONMAP_ENTRY { const void* piid; // the interface id (IID) size_t nOffset; // offset of the interface vtable from m_unknown }; struct AFX_CONNECTIONMAP { #ifdef _AFXDLL const AFX_CONNECTIONMAP* (PASCAL* pfnGetBaseMap)(); // NULL is root class #else const AFX_CONNECTIONMAP* pBaseMap; #endif const AFX_CONNECTIONMAP_ENTRY* pEntry; // map for this class }; #ifdef _AFXDLL #define DECLARE_CONNECTION_MAP() \ private: \ static const AFX_CONNECTIONMAP_ENTRY _connectionEntries[]; \ protected: \ static AFX_DATA const AFX_CONNECTIONMAP connectionMap; \ static const AFX_CONNECTIONMAP* PASCAL _GetBaseConnectionMap(); \ virtual const AFX_CONNECTIONMAP* GetConnectionMap() const; \ #else #define DECLARE_CONNECTION_MAP() \ private: \ static const AFX_CONNECTIONMAP_ENTRY _connectionEntries[]; \ protected: \ static AFX_DATA const AFX_CONNECTIONMAP connectionMap; \ virtual const AFX_CONNECTIONMAP* GetConnectionMap() const; \ #endif #endif //!_AFX_NO_OLE_SUPPORT ///////////////////////////////////////////////////////////////////////////// // CCmdTarget proper #ifndef _AFX_NO_OCC_SUPPORT class COccManager; // forward reference (see ..\src\occimpl.h) #endif #ifdef _AFXDLL class CCmdTarget : public CObject #else class AFX_NOVTABLE CCmdTarget : public CObject #endif { DECLARE_DYNAMIC(CCmdTarget) protected: public: // Constructors CCmdTarget(); // Attributes LPDISPATCH GetIDispatch(BOOL bAddRef); // retrieve IDispatch part of CCmdTarget static CCmdTarget* PASCAL FromIDispatch(LPDISPATCH lpDispatch); // map LPDISPATCH back to CCmdTarget* (inverse of GetIDispatch) BOOL IsResultExpected(); // returns TRUE if automation function should return a value // Operations void EnableAutomation(); // call in constructor to wire up IDispatch void EnableConnections(); // call in constructor to wire up IConnectionPointContainer void BeginWaitCursor(); void EndWaitCursor(); void RestoreWaitCursor(); // call after messagebox #ifndef _AFX_NO_OLE_SUPPORT // dispatch OLE verbs through the message map BOOL EnumOleVerbs(LPENUMOLEVERB* ppenumOleVerb); BOOL DoOleVerb(LONG iVerb, LPMSG lpMsg, HWND hWndParent, LPCRECT lpRect); #endif // Overridables // route and dispatch standard command message types // (more sophisticated than OnCommand) virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); #ifndef _AFX_NO_OLE_SUPPORT // called when last OLE reference is released virtual void OnFinalRelease(); #endif #ifndef _AFX_NO_OLE_SUPPORT // called before dispatching to an automation handler function virtual BOOL IsInvokeAllowed(DISPID dispid); #endif #ifndef _AFX_NO_OLE_SUPPORT // support for OLE type libraries void EnableTypeLib(); HRESULT GetTypeInfoOfGuid(LCID lcid, const GUID& guid, LPTYPEINFO* ppTypeInfo); virtual BOOL GetDispatchIID(IID* pIID); virtual UINT GetTypeInfoCount(); virtual CTypeLibCache* GetTypeLibCache(); virtual HRESULT GetTypeLib(LCID lcid, LPTYPELIB* ppTypeLib); #endif // Implementation public: virtual ~CCmdTarget(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; virtual void AssertValid() const; #endif #ifndef _AFX_NO_OLE_SUPPORT void GetNotSupported(); void SetNotSupported(); #endif protected: friend class CView; CView* GetRoutingView(); CFrameWnd* GetRoutingFrame(); static CView* PASCAL GetRoutingView_(); static CFrameWnd* PASCAL GetRoutingFrame_(); DECLARE_MESSAGE_MAP() // base class - no {{ }} macros #ifndef _AFX_NO_DOCOBJECT_SUPPORT DECLARE_OLECMD_MAP() friend class COleCmdUI; #endif #ifndef _AFX_NO_OLE_SUPPORT DECLARE_DISPATCH_MAP() DECLARE_CONNECTION_MAP() DECLARE_INTERFACE_MAP() #ifndef _AFX_NO_OCC_SUPPORT DECLARE_EVENTSINK_MAP() #endif // !_AFX_NO_OCC_SUPPORT // OLE interface map implementation public: // data used when CCmdTarget is made OLE aware long m_dwRef; LPUNKNOWN m_pOuterUnknown; // external controlling unknown if != NULL DWORD m_xInnerUnknown; // place-holder for inner controlling unknown public: // advanced operations void EnableAggregation(); // call to enable aggregation void ExternalDisconnect(); // forcibly disconnect LPUNKNOWN GetControllingUnknown(); // get controlling IUnknown for aggregate creation // these versions do not delegate to m_pOuterUnknown DWORD InternalQueryInterface(const void*, LPVOID* ppvObj); DWORD InternalAddRef(); DWORD InternalRelease(); // these versions delegate to m_pOuterUnknown DWORD ExternalQueryInterface(const void*, LPVOID* ppvObj); DWORD ExternalAddRef(); DWORD ExternalRelease(); // implementation helpers LPUNKNOWN GetInterface(const void*); LPUNKNOWN QueryAggregates(const void*); // advanced overrideables for implementation virtual BOOL OnCreateAggregates(); virtual LPUNKNOWN GetInterfaceHook(const void*); // OLE automation implementation protected: struct XDispatch { DWORD m_vtbl; // place-holder for IDispatch vtable #ifndef _AFX_NO_NESTED_DERIVATION size_t m_nOffset; #endif } m_xDispatch; BOOL m_bResultExpected; // member variable-based properties void GetStandardProp(const AFX_DISPMAP_ENTRY* pEntry, VARIANT* pvarResult, UINT* puArgErr); SCODE SetStandardProp(const AFX_DISPMAP_ENTRY* pEntry, DISPPARAMS* pDispParams, UINT* puArgErr); // DISPID to dispatch map lookup static UINT PASCAL GetEntryCount(const AFX_DISPMAP* pDispMap); const AFX_DISPMAP_ENTRY* PASCAL GetDispEntry(LONG memid); static LONG PASCAL MemberIDFromName(const AFX_DISPMAP* pDispMap, LPCTSTR lpszName); // helpers for member function calling implementation static UINT PASCAL GetStackSize(const BYTE* pbParams, VARTYPE vtResult); #ifdef _PPC_ SCODE PushStackArgs(BYTE* pStack, const BYTE* pbParams, void* pResult, VARTYPE vtResult, DISPPARAMS* pDispParams, UINT* puArgErr, VARIANT* rgTempVars, UINT nSizeArgs); #else SCODE PushStackArgs(BYTE* pStack, const BYTE* pbParams, void* pResult, VARTYPE vtResult, DISPPARAMS* pDispParams, UINT* puArgErr, VARIANT* rgTempVars); #endif SCODE CallMemberFunc(const AFX_DISPMAP_ENTRY* pEntry, WORD wFlags, VARIANT* pvarResult, DISPPARAMS* pDispParams, UINT* puArgErr); friend class COleDispatchImpl; #ifndef _AFX_NO_OCC_SUPPORT public: // OLE event sink implementation BOOL OnEvent(UINT idCtrl, AFX_EVENT* pEvent, AFX_CMDHANDLERINFO* pHandlerInfo); protected: const AFX_EVENTSINKMAP_ENTRY* PASCAL GetEventSinkEntry(UINT idCtrl, AFX_EVENT* pEvent); #endif // !_AFX_NO_OCC_SUPPORT // OLE connection implementation struct XConnPtContainer { DWORD m_vtbl; // place-holder for IConnectionPointContainer vtable #ifndef _AFX_NO_NESTED_DERIVATION size_t m_nOffset; #endif } m_xConnPtContainer; #ifdef _AFXDLL AFX_MODULE_STATE* m_pModuleState; friend class CInnerUnknown; friend UINT APIENTRY _AfxThreadEntry(void* pParam); #endif virtual BOOL GetExtraConnectionPoints(CPtrArray* pConnPoints); virtual LPCONNECTIONPOINT GetConnectionHook(const IID& iid); friend class COleConnPtContainer; #endif //!_AFX_NO_OLE_SUPPORT }; class CCmdUI // simple helper class { public: // Attributes UINT m_nID; UINT m_nIndex; // menu item or other index // if a menu item CMenu* m_pMenu; // NULL if not a menu CMenu* m_pSubMenu; // sub containing menu item // if a popup sub menu - ID is for first in popup // if from some other window CWnd* m_pOther; // NULL if a menu or not a CWnd // Operations to do in ON_UPDATE_COMMAND_UI virtual void Enable(BOOL bOn = TRUE); virtual void SetCheck(int nCheck = 1); // 0, 1 or 2 (indeterminate) virtual void SetRadio(BOOL bOn = TRUE); virtual void SetText(LPCTSTR lpszText); // Advanced operation void ContinueRouting(); // Implementation CCmdUI(); BOOL m_bEnableChanged; BOOL m_bContinueRouting; UINT m_nIndexMax; // last + 1 for iterating m_nIndex CMenu* m_pParentMenu; // NULL if parent menu not easily determined // (probably a secondary popup menu) BOOL DoUpdate(CCmdTarget* pTarget, BOOL bDisableIfNoHndler); }; // special CCmdUI derived classes are used for other UI paradigms // like toolbar buttons and status indicators // pointer to afx_msg member function #ifndef AFX_MSG_CALL #define AFX_MSG_CALL #endif typedef void (AFX_MSG_CALL CCmdTarget::*AFX_PMSG)(void); enum AFX_DISPMAP_FLAGS { afxDispCustom = 0, afxDispStock = 1 }; struct AFX_DISPMAP_ENTRY { LPCTSTR lpszName; // member/property name long lDispID; // DISPID (may be DISPID_UNKNOWN) LPCSTR lpszParams; // member parameter description WORD vt; // return value type / or type of property AFX_PMSG pfn; // normal member On or, OnGet AFX_PMSG pfnSet; // special member for OnSet size_t nPropOffset; // property offset AFX_DISPMAP_FLAGS flags;// flags (e.g. stock/custom) }; struct AFX_EVENTSINKMAP_ENTRY { AFX_DISPMAP_ENTRY dispEntry; UINT nCtrlIDFirst; UINT nCtrlIDLast; }; // DSC Sink state/reason codes passed to MFC user event handlers enum DSCSTATE { dscNoState = 0, dscOKToDo, dscCancelled, dscSyncBefore, dscAboutToDo, dscFailedToDo, dscSyncAfter, dscDidEvent }; enum DSCREASON { dscNoReason = 0, dscClose, dscCommit, dscDelete, dscEdit, dscInsert, dscModify, dscMove }; ///////////////////////////////////////////////////////////////////////////// // CWnd implementation // structures (see afxext.h) struct CCreateContext; // context for creating things struct CPrintInfo; // print preview customization info struct AFX_MSGMAP_ENTRY { UINT nMessage; // windows message UINT nCode; // control code or WM_NOTIFY code UINT nID; // control ID (or 0 for windows messages) UINT nLastID; // used for entries specifying a range of control id's UINT nSig; // signature type (action) or pointer to message # AFX_PMSG pfn; // routine to call (or special value) }; ///////////////////////////////////////////////////////////////////////////// // CWnd - a Microsoft Windows application window class COleDropTarget; // for more information see AFXOLE.H class COleControlContainer; class COleControlSite; // CWnd::m_nFlags (generic to CWnd) #define WF_TOOLTIPS 0x0001 // window is enabled for tooltips #define WF_TEMPHIDE 0x0002 // window is temporarily hidden #define WF_STAYDISABLED 0x0004 // window should stay disabled #define WF_MODALLOOP 0x0008 // currently in modal loop #define WF_CONTINUEMODAL 0x0010 // modal loop should continue running #define WF_OLECTLCONTAINER 0x0100 // some descendant is an OLE control #define WF_TRACKINGTOOLTIPS 0x0400 // window is enabled for tracking tooltips // CWnd::m_nFlags (specific to CFrameWnd) #define WF_STAYACTIVE 0x0020 // look active even though not active #define WF_NOPOPMSG 0x0040 // ignore WM_POPMESSAGESTRING calls #define WF_MODALDISABLE 0x0080 // window is disabled #define WF_KEEPMINIACTIVE 0x0200 // stay activate even though you are deactivated // flags for CWnd::RunModalLoop #define ML
go程序设计语言 Contents Preface................................................................................................................................. xix PART 1—WHY LEARN GO—GETTING STARTED Chapter 1—Origins, Context and Popularity of Go...............................................................1 1.1 Origins and evolution................................................................................................1 1.2 Main characteristics, context and reasons for developing a new language....................4 1.2.1 Languages that influenced Go.........................................................................4 1.2.2 Why a new language?......................................................................................5 1.2.3 Targets of the language....................................................................................5 1.2.4 Guiding design principles...............................................................................7 1.2.5 Characteristics of the language........................................................................7 1.2.6 Uses of the language........................................................................................8 1.2.7 Missing features?.............................................................................................9 1.2.8 Programming in Go......................................................................................10 1.2.9 Summary......................................................................................................10 Chapter 2—Installation and Runtime Environment............................................................11 2.1 Platforms and architectures.....................................................................................11 (1) The gc Go-compilers:..................................................................................11 (2) The gccgo-compiler:....................................................................................13 (3) File extensions and packages:.......................................................................14 2.2 Go Environment variables........................................................................................14 2.3 Installing Go on a Linux system...............................................................................16 2.4 Installing Go on an OS X system.............................................................................21 2.5 Installing Go on a Windows system.........................................................................21 2.6 What is installed on your machine? .........................................................................26 2.7 The Go runtime.......................................................................................................27 2.8 A Go interpreter ......................................................................................................27 Chapter 3—Editors, IDE’s and Other tools.........................................................................28 3.1 Basic requirements for a decent Go development environment.................................28 3.2 Editors and Integrated Development Environments.................................................29 3.2.1. Golang LiteIDE ..........................................................................................32 3.2.2. GoClipse......................................................................................................33 3.3 Debuggers................................................................................................................34 3.4 Building and running go-programs with command- and Makefiles..........................35 3.5 Formatting code: go fmt or gofmt............................................................................39 3.6 Documenting code: go doc or godoc........................................................................40 3.7 Other tools...............................................................................................................41 3.8 Go’s performance.....................................................................................................41 3.9 Interaction with other languages...............................................................................43 3.9.1. Interacting with C .......................................................................................43 3.9.2. Interacting with C++....................................................................................45 PART 2—CORE CONSTRUCTS AND TECHNIQUES OF THE LANGUAGE Chapter 4—Basic constructs and elementary data types.......................................................49 4.1. Filenames—Keywords—Identifiers..........................................................................49 4.2. Basic structure and components of a Go-program...................................................50 4.2.1 Packages, import and visibility......................................................................51 4.2.3 Comments....................................................................................................56 4.2.4 Types............................................................................................................57 4.2.5 General structure of a Go-program...............................................................58 4.2.6 Conversions..................................................................................................60 4.2.7 About naming things in Go..........................................................................60 4.3. Constants................................................................................................................60 4.4. Variables..................................................................................................................63 4.4.1 Introduction.................................................................................................63 4.4.2 Value types and reference types.....................................................................66 4.4.3 Printing........................................................................................................68 4.4.4 Short form with the := assignment operator..................................................69 4.4.5 Init-functions................................................................................................70 4.5. Elementary types and operators...............................................................................73 4.5.1. Boolean type bool........................................................................................73 4.5.2. Numerical types...........................................................................................75 4.5.2.1 ints and floats.............................................................................................75 4.5.2.2 Complex numbers.....................................................................................79 4.5.2.3 Bit operators..............................................................................................79 4.5.2.4 Logical operators........................................................................................81 4.5.2.5 Arithmetic operators.................................................................................82 4.5.2.6 Random numbers......................................................................................82 4.5.3. Operators and precedence............................................................................84 4.5.4. Aliasing types...............................................................................................84 4.5.5. Character type.............................................................................................85 4.6. Strings.....................................................................................................................86 4.7. The strings and strconv package..............................................................................88 4.7.1—Prefixes and suffixes:...................................................................................88 4.7.2—Testing whether a string contains a substring:.............................................89 4.7.3—Indicating at which position (index) a substring or character occurs in a string:...................................................................................................89 4.7.4—Replacing a substring:................................................................................90 4.7.5—Counting occurrences of a substring:..........................................................90 4.7.6—Repeating a string:.....................................................................................90 4.7.7—Changing the case of a string:....................................................................91 4.7.8—Trimming a string:.....................................................................................92 4.7.9—Splitting a string:........................................................................................92 4.7.10—Joining over a slice:..................................................................................92 4.7.11—Reading from a string:..............................................................................93 4.8. Times and dates.......................................................................................................95 4.9. Pointers...................................................................................................................96 Chapter 5—Control structures...........................................................................................101 5.1—The if else construct............................................................................................101 5.2—Testing for errors on functions with multiple return values..................................106 5.3—The switch keyword............................................................................................110 5.4—The for construct................................................................................................114 5.4.1 Counter-controlled iteration.......................................................................114 Character on position 2 is:...........................................................................................116 5.4.2 Condition-controlled iteration ...................................................................117 5.4.3 Infinite loops .............................................................................................118 5.4.4 The for range construct...............................................................................119 5.5—Break / continue..................................................................................................121 5.6—Use of labels with break and continue—goto.......................................................123 Chapter 6—Functions.......................................................................................................126 6.1 Introduction...........................................................................................................126 6.2 Parameters and return values..................................................................................129 6.2.1 Call by value / Call by reference..................................................................129 6.2.2 Named return variables...............................................................................131 6.2.3 Blank identifier...........................................................................................133 6.2.4 Changing an outside variable......................................................................134 6.3 Passing a variable number of parameters.................................................................135 6.4 Defer and tracing...................................................................................................137 6.5 Built-in functions...................................................................................................142 6.6 Recursive functions................................................................................................143 6.8 Closures (function literals).....................................................................................147 6.9 Applying closures: a function returning another function ......................................150 6.10 Debugging with closures......................................................................................153 6.11 Timing a function ...............................................................................................154 6.12 Using memoization for performance....................................................................154 Chapter 7—Arrays and Slices.............................................................................................157 7.1 Declaration and initialization.................................................................................157 7.1.1 Concept......................................................................................................157 7.1.2 Array literals................................................................................................161 7.1.3 Multidimensional arrays..............................................................................162 7.1.4 Passing an array to a function......................................................................163 7.2 Slices......................................................................................................................164 7.2.1 Concept......................................................................................................164 7.2.2 Passing a slice to a function.........................................................................168 7.2.3 Creating a slice with make()........................................................................168 7.2.4 Difference between new() and make().........................................................170 7.2.5 Multidimensional slices...............................................................................171 7.2.6 The bytes package.......................................................................................171 7.3 For range construct................................................................................................172 7.4 Reslicing.................................................................................................................175 7.5 Copying and appending slices................................................................................176 7.6 Applying strings, arrays and slices...........................................................................178 7.6.1 Making a slice of bytes from a string...........................................................178 7.6.2 Making a substring of a string.....................................................................179 7.6.3 Memory representation of a string and a slice..............................................179 7.6.4 Changing a character in a string..................................................................180 7.6.5 Comparison function for byte arrays...........................................................180 7.6.6 Searching and sorting slices and arrays.......................................................181 7.6.7 Simulating operations with append.............................................................182 7.6.8 Slices and garbage collection.......................................................................182 Chapter 8—Maps..............................................................................................................185 8.1 Declaration, initialization and make.......................................................................185 8.1.1 Concept......................................................................................................185 8.1.2 Map capacity..............................................................................................188 8.1.3 Slices as map values.....................................................................................188 8.2 Testing if a key-value item exists in a map—Deleting an element...........................188 8.3 The for range construct..........................................................................................190 8.4 A slice of maps......................................................................................................191 8.5 Sorting a map.........................................................................................................192 8.6 Inverting a map......................................................................................................194 Chapter 9—Packages.........................................................................................................196 A The standard library..................................................................................................196 9.1 Overview of the standard library.............................................................................196 9.2 The regexp package................................................................................................199 9.3 Locking and the sync package................................................................................200 9.4 Accurate computations and the big package...........................................................202 B Custom and external packages: use, build, test, document, install.............................203 9.5 Custom packages and visibility...............................................................................203 9.6 Using godoc for your custom packages...................................................................208 9.7 Using go install for installing custom packages.......................................................210 9.8 Custom packages: map structure, go install and go test..........................................212 9.8.1 Map-structure for custom packages.............................................................212 9.8.2 Locally installing the package......................................................................215 9.8.3 OS dependent code.....................................................................................216 9.9 Using git for distribution and installation...............................................................216 9.9.1 Installing to github.....................................................................................216 9.9.2 Installing from github.................................................................................217 9.10 Go external packages and projects. ......................................................................218 9.11 Using an external library in a Go program............................................................219 Chapter 10—Structs and Methods.....................................................................................224 10.1 Definition of a struct............................................................................................224 10.2 Creating a struct variable with a Factory method..................................................232 10.2.1 A factory for structs..................................................................................232 10.2.2 new() and make() revisited for maps and structs:.......................................234 10.3 Custom package using structs...............................................................................235 10.4 Structs with tags...................................................................................................236 10.5 Anonymous fields and embedded structs..............................................................237 10.5.1 Definition.................................................................................................237 10.5.2 Embedded structs.....................................................................................238 10.5.3 Conflicting names.....................................................................................239 10.6 Methods...............................................................................................................240 10.6.1 What is a method?....................................................................................240 10.6.2 Difference between a function and a method............................................244 10.6.3 Pointer or value as receiver........................................................................245 10.6.4 Methods and not-exported fields..............................................................247 10.6.5 Methods on embedded types and inheritance............................................248 10.6.6 How to embed functionality in a type.......................................................251 10.6.7 Multiple inheritance..................................................................................253 10.6.8 Universal methods and method naming....................................................256 10.6.9 Comparison between Go types and methods and other object-oriented languages...........................................................................256 10.7 The String()-method and format specifiers for a type...........................................258 10.8 Garbage collection and SetFinalizer......................................................................261 Chapter 11—Interfaces and reflection................................................................................263 11.1 What is an interface?............................................................................................263 11.2 Interface embedding interface(s)...........................................................................270 11.3 How to detect and convert the type of an interface variable: type assertions.........270 11.4 The type switch....................................................................................................273 11.5 Testing if a value implements an interface.............................................................274 11.6 Using method sets with interfaces.........................................................................275 11.7 1st example: sorting with the Sorter interface........................................................277 11.8 2nd example: Reading and Writing......................................................................282 11.9 Empty Interface...................................................................................................284 11.9.1 Concept....................................................................................................284 11.9.2 Constructing an array of a general type or with variables of different types............................................................................................286 11.9.3 Copying a data-slice in a slice of interface{}...............................................287 11.9.4 Node structures of general or different types.............................................288 11.9.5 Interface to interface.................................................................................289 11.10 The reflect package.............................................................................................290 11.10.1 Methods and types in reflect...................................................................290 11.10.2 Modifying (setting) a value through reflection........................................293 11.10.3 Reflection on structs...............................................................................294 11.11 Printf and reflection...........................................................................................296 11.12 Interfaces and dynamic typing............................................................................298 11.12.1 Dynamic typing in Go............................................................................298 11.12.2 Dynamic method invocation...................................................................300 11.12.3 Extraction of an interface........................................................................301 11.12.4 Explicitly indicating that a type implements an interface........................303 11.12.5 Empty interface and function overloading..............................................304 11.12.6 Inheritance of interfaces..........................................................................304 11.13 Summary: the object-orientedness of Go............................................................306 11.14 Structs, collections and higher order functions...................................................306 PART 3—ADVANCED GO Chapter 12—Reading and writing.....................................................................................313 12.1 Reading input from the user.................................................................................313 12.2 Reading from and writing to a file........................................................................317 12.2.1 Reading from a file....................................................................................317 12.2.2 The package compress: reading from a zipped file.....................................321 12.2.3 Writing to a file.........................................................................................322 12.3 Copying files........................................................................................................324 12.4 Reading arguments from the command-line.........................................................325 12.4.1 With the os-package..................................................................................325 12.4.2 With the flag-package...............................................................................326 12.5 Reading files with a buffer....................................................................................328 12.6 Reading and writing files with slices.....................................................................330 12.7 Using defer to close a file.....................................................................................332 12.8 A practical example of the use of interfaces: fmt.Fprintf......................................332 12.9 The json dataformat.............................................................................................334 12.10 The xml dataformat............................................................................................340 12.11 Datatransport through gob.................................................................................342 12.12 Cryptography with go........................................................................................345 Chapter 13—Error-handling and Testing...........................................................................348 13.1 Error-handling.....................................................................................................349 13.1.1 Defining errors..........................................................................................349 13.1.2 Making an error-object with fmt..............................................................353 13.2 Run-time exceptions and panic............................................................................353 13.4 Error-handling and panicking in a custom package..............................................357 13.5 An error-handling scheme with closures...............................................................360 13.6 Starting an external command or program...........................................................363 13.7 Testing and benchmarking in Go.........................................................................364 13.8 Testing: a concrete example..................................................................................367 13.9 Using table-driven tests........................................................................................369 13.10 Investigating performance: tuning and profiling Go programs............................371 13.10.1 Time and memory consumption.............................................................371 13.10.2 Tuning with go test.................................................................................371 13.10.3 Tuning with pprof...................................................................................371 Chapter 14—Goroutines and Channels.............................................................................375 14.1 Concurrency, parallelism and goroutines..............................................................375 14.1.1 What are goroutines?................................................................................375 14.1.2 The difference between concurrency and parallelism.................................377 14.1.3 Using GOMAXPROCS............................................................................378 14.1.4 How to specify the number of cores to be used on the command-line?.....379 14.1.5 Goroutines and coroutines........................................................................381 14.2 Channels for communication between goroutines................................................381 14.2.1 Concept....................................................................................................381 14.2.2 Communication operator <-.....................................................................383 14.2.3 Blocking of channels.................................................................................385 14.2.4 Goroutines synchronize through the exchange of data on one (or more) channel(s)........................................................................................387 14.2.5 Asynchronous channels—making a channel with a buffer.........................387 14.2.6 Goroutine using a channel for outputting result(s)....................................388 14.2.7 Semaphore pattern....................................................................................389 14.2.8 Implementing a parallel for-loop...............................................................391 14.2.9 Implementing a semaphore using a buffered channel................................391 14.2.10 For—range applied to channels...............................................................394 14.2.11 Channel directionality............................................................................396 14.3 Synchronization of goroutines: closing a channel—testing for blocked channels..400 14.4 Switching between goroutines with select.............................................................403 14.5 Channels, Timeouts and Tickers...........................................................................408 14.6 Using recover with goroutines..............................................................................412 14.7 Comparing the old and the new model: Tasks and Worker processes....................413 14.8 Implementing a lazy generator..............................................................................416 14.9 Implementing Futures..........................................................................................420 14.10 Multiplexing......................................................................................................421 14.10.1 A typical client-server pattern..................................................................421 14.10.2 Teardown: shutdown the server by signaling a channel............................424 14.11 Limiting the number of requests processed concurrently....................................427 14.12 Chaining goroutines...........................................................................................428 14.13 Parallelizing a computation over a number of cores............................................429 14.14 Parallelizing a computation over a large amount of data.....................................430 14.15 The leaky bucket algorithm................................................................................431 14.16 Benchmarking goroutines...................................................................................433 14.17 Concurrent acces to objects by using a channel..................................................434 Chapter 15—Networking, templating and web-applications..............................................436 15.1 A tcp-server .........................................................................................................436 15.2 A simple webserver...............................................................................................445 15.3 Polling websites and reading in a web page...........................................................448 15.4 Writing a simple web application.........................................................................452 15.5 Making a web application robust..........................................................................454 15.6 Writing a web application with templates.............................................................456 15.7 Exploring the template package............................................................................461 15.7.1. Field substitution: {{.FieldName}}............................................................462 15.7.2. Validation of the templates.......................................................................463 15.7.3 If-else........................................................................................................464 15.7.4 Dot and with-end.....................................................................................465 15.7.5 Template variables $..................................................................................466 15.7.6 Range-end.................................................................................................467 15.7.7 Predefined template functions...................................................................467 15.8 An elaborated webserver with different functions.................................................468 (works only on Unix because calls /bin/date)........................................................474 15.9 Remote procedure calls with rpc...........................................................................474 15.10 Channels over a network with netchan...............................................................477 15.11 Communication with websocket........................................................................478 15.12 Sending mails with smtp....................................................................................480 PART 4—APPLYING GO Chapter 16—Common Go Pitfalls or Mistakes..................................................................485 16.1 Hiding (shadowing) a variable by misusing short declaration...............................486 16.2 Misusing strings...................................................................................................486 16.3 Using defer for closing a file in the wrong scope...................................................487 16.4 Confusing new() and make()................................................................................488 16.5 No need to pass a pointer to a slice to a function..................................................488 16.6 Using pointers to interface types...........................................................................488 16.7 Misusing pointers with value types.......................................................................489 16.8 Misusing goroutines and channels........................................................................489 16.9 Using closures with goroutines.............................................................................490 16.10 Bad error handling.............................................................................................491 16.10.1 Don’t use booleans:.................................................................................491 16.10.2 Don’t clutter your code with error-checking:...........................................492 Chapter 17—Go Language Patterns...................................................................................494 17.1 The comma, ok pattern........................................................................................494 17.2 The defer pattern..................................................................................................495 17.3 The visibility pattern............................................................................................497 17.4 The operator pattern and interface.......................................................................497 17.4.1 Implement the operators as functions.......................................................497 17.4.2 Implement the operators as methods.........................................................498 17.4.3 Using an interface.....................................................................................499 Chapter 18—Useful Code Snippets—Performance Advice.................................................500 18.1 Strings..................................................................................................................500 18.2 Arrays and slices...................................................................................................501 18.3 Maps....................................................................................................................502 18.4 Structs..................................................................................................................502 18.5 Interfaces..............................................................................................................503 18.6 Functions.............................................................................................................503 18.7 Files......................................................................................................................504 18.8 Goroutines and channels......................................................................................505 18.9 Networking and web applications.........................................................................507 18.9.1. Templating:......................................................................................................507 18.10 General..............................................................................................................508 18.11 Performance best practices and advice................................................................508 Chapter 19—Building a complete application....................................................................509 19.1 Introduction.........................................................................................................509 19.2 Introducing Project UrlShortener.........................................................................509 19.3 Data structure......................................................................................................510 19.4 Our user interface: a web server frontend.............................................................515 19.5 Persistent storage: gob..........................................................................................519 19.6 Using goroutines for performance........................................................................524 19.7 Using json for storage...........................................................................................527 19.8 Multiprocessing on many machines......................................................................528 19.9 Using a ProxyStore...............................................................................................532 19.10 Summary and enhancements..............................................................................536 Chapter 20—Go in Google App Engine............................................................................538 20.1 What is Google App Engine ?...............................................................................538 20.2 Go in the cloud ...................................................................................................540 20.3 Installation of the Go App Engine SDK: the development environment for Go...540 20.3.1. Installation...............................................................................................540 20.3.2. Checking and testing...............................................................................542 20.4 Building your own Hello world app ....................................................................543 20.4.1 Map structure—Creating a simple http-handler........................................543 20.4.2 Creating the configuration file app.yaml...................................................544 20.4.3 Iterative development................................................................................548 20.4.4. Integrating with the GoClipse IDE..........................................................548 20.5 Using the Users service and exploring its API.......................................................549 20.6 Handling forms....................................................................................................551 20.7 Using the datastore...............................................................................................552 20.8 Uploading to the cloud.......................................................................................556 Chapter 21—Real World Uses of Go.................................................................................559 21.1 Heroku—a highly available consistent data store in Go. ......................................559 21.2 MROffice—a VOIP system for call centers in Go................................................561 21.3 Atlassian—a virtual machine cluster management system.....................................562 21.4 Camlistore—a content addressable storage system................................................563 21.5 Other usages of the Go language..........................................................................563 APPENDICES...................................................................................................................567 (A) CODE REFERENCE...........................................................................................567 (B)CUTE GO QUOTES.............................................................................................571 GO QUOTES: TRUE BUT NOT SO CUTE....................................................572 (C) LIST OF CODE EXAMPLES (Listings)...............................................................572 (E) References in the text to Go—packages..................................................................583 (F) References in the text to Go—tools........................................................................586 (G) Answers to Questions............................................................................................586 (H) ANSWERS TO EXERCISES................................................................................590 (I) BIBLIOGRAPHY (Resources and References)........................................................593 Index..............................................................................................................................597 List of Illustrations Chapter 1—Origins, Context and Popularity of Go...............................................................1 Fig 1.1: The designers of Go: Griesemer, Thompson and Pike..........................................1 Fig 1.2: The logo’s of Go..................................................................................................3 Fig 1.3: Influences on Go.................................................................................................5 Chapter 3—Editors, IDE’s and Other tools.........................................................................28 Fig 3.1: LiteIDE and its AST-view..................................................................................33 Fig 3.2: GoClipse and its outline code-view...................................................................34 Chapter 4—Basic constructs and elementary data types.......................................................49 Fig 4.1: Value type..........................................................................................................67 Fig 4.2: Assignment of value types..................................................................................67 Fig 4.3: Reference types and assignment.........................................................................67 Fig 4.4: Pointers and memory usage...............................................................................98 Fig 4.5: Pointers and memory usage, 2...........................................................................99 Chapter 7—Arrays and Slices.............................................................................................157 Fig 7.1: Array in memory.............................................................................................158 Fig 7.2: Slice in memory..............................................................................................166 Chapter 9—Packages.........................................................................................................196 Fig 9.1: Package documentation with godoc.................................................................210 Chapter 10—Structs and Methods.....................................................................................224 Fig 10.1: Memory layout of a struct.............................................................................227 Fig 10.2: Memory layout of a struct of structs..............................................................229 Fig. 10.3: Linked list as recursive struct........................................................................230 Fig 10.4: Binary tree as recursive struct.........................................................................230 Chapter 11—Interfaces and reflection................................................................................263 Fig 11.1: Interface value in memory.............................................................................264 Chapter 14—Goroutines and Channels.............................................................................375 Fig 14.1: Channels and goroutines...............................................................................382 Fig 14.2: The sieve prime-algorithm.............................................................................397 Chapter 15—Networking, templating and web-applications..............................................436 Fig 15.1—Screen of exercise 15.6.................................................................................454 Chapter 19—Building a complete application....................................................................509 Fig 19.1: Handler functions in goto.............................................................................515 Fig 19.2: The Add handler...........................................................................................518 Fig 19.3: The response of the Add handler...................................................................519 Fig 19.4: The response of the Redirect handler.............................................................519 Fig 19.5: Distributing the work load over master- and slave computers........................529 Chapter 20—Go in Google App Engine............................................................................538 Fig 20.1: The Application Control Panel......................................................................558

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值