使用AXIS遇到 "'' is not a valid integer value错误?定位不到原因?

icelander 2007-10-16 03:08:28
请帮忙看看,这是什么问题,谢谢

WSDL2Java生成相关文件,调用的时候出现下面错误,所有的参数都根据axis生成的代码填充的,很奇怪~

AxisFault

faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server

faultSubcode:

faultString: '' is not a valid integer value

faultActor:

faultNode:

faultDetail:

{http://xml.apache.org/axis/}stackTrace:'' is not a valid integer value

at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)

at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)

at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)

at org.apache.crimson.parser.Parser2.maybeElement(Parser2.java:1712)

at org.apache.crimson.parser.Parser2.content(Parser2.java:1963)

at org.apache.crimson.parser.Parser2.maybeElement(Parser2.java:1691)

at org.apache.crimson.parser.Parser2.content(Parser2.java:1963)

at org.apache.crimson.parser.Parser2.maybeElement(Parser2.java:1691)

at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:667)

at org.apache.crimson.parser.Parser2.parse(Parser2.java:337)

at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:448)

at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)

at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)

at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)

at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)

at org.apache.axis.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62)

at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206)

at org.apache.axis.client.Call.invokeEngine(Call.java:2784)

at org.apache.axis.client.Call.invoke(Call.java:2767)

at org.apache.axis.client.Call.invoke(Call.java:2443)

at org.apache.axis.client.Call.invoke(Call.java:2366)

at org.apache.axis.client.Call.invoke(Call.java:1812)

at com.bankunion.sample.ISMSSVCbindingStub.smsSubmit(ISMSSVCbindingStub.java:188)

at com.bankunion.sample.SMSClientTest.main(SMSClientTest.java:71)



{http://xml.apache.org/axis/}hostname:wangzhi-pc



'' is not a valid integer value

at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)

at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)

at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)

at org.apache.crimson.parser.Parser2.maybeElement(Parser2.java:1712)

at org.apache.crimson.parser.Parser2.content(Parser2.java:1963)

at org.apache.crimson.parser.Parser2.maybeElement(Parser2.java:1691)

at org.apache.crimson.parser.Parser2.content(Parser2.java:1963)

at org.apache.crimson.parser.Parser2.maybeElement(Parser2.java:1691)

at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:667)

at org.apache.crimson.parser.Parser2.parse(Parser2.java:337)

at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:448)

at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)

at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)

at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)

at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)

at org.apache.axis.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62)

at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206)

at org.apache.axis.client.Call.invokeEngine(Call.java:2784)

at org.apache.axis.client.Call.invoke(Call.java:2767)

at org.apache.axis.client.Call.invoke(Call.java:2443)

at org.apache.axis.client.Call.invoke(Call.java:2366)

at org.apache.axis.client.Call.invoke(Call.java:1812)

at com.bankunion.sample.ISMSSVCbindingStub.smsSubmit(ISMSSVCbindingStub.java:188)

at com.bankunion.sample.SMSClientTest.main(SMSClientTest.java:71)
...全文
1577 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
we1www 2012-10-11
  • 打赏
  • 举报
回复
请问楼主问题如何解决的?请加我QQ告诉我,拜谢!qq:1181991582
chee003 2008-06-03
  • 打赏
  • 举报
回复
楼上兄弟的问题解决了没,我也碰到和你一模一样的问题了
sdk LCS/Telegraphics Wintab* Interface Specification 1.1: 16- and 32-bit API Reference By Rick Poyner Revised February 11, 2012 This specification was developed in response to a perceived need for a standardized programming inter-face to digitizing tablets, three dimensional position sensors, and other pointing devices by a group of lead-ing digitizer manufacturers and applications developers. The availability of drivers that support the features of the specification will simplify the process of developing Windows appli¬cation programs that in-corporate absolute coordinate input, and enhance the acceptance of ad¬vanced pointing de¬vices among users. This specification is intended to be an open standard, and as such the text and information contained herein may be freely used, copied, or distributed without compensation or licensing restrictions. This document is copyright 1991-2012 by LCS/Telegraphics.* Address questions and comments to: LCS/Telegraphics 150 Rogers St. Cambridge, MA 02142 (617)225-7970 (617)225-7969 FAX Compuserve: 76506,1676 Internet: wintab@pointing.com Note: sections marked with the “(1.1)” are new sections added for specification version 1.1. Sec-tions bearing the “(1.1 modified)” notation contain updated information for specification version 1.1. Version 1.1 Update Notation Conventions 1 1. Background Information 1 1.1. Features of Digitizers 1 1.2. The Windows Environment 1 2. Design Goals 2 2.1. User Control 2 2.2. Ease of Programming 2 2.3. Tablet Sharing 3 2.4. Tablet Feature Support 3 3. Design Concepts 3 3.1. Device Conventions 3 3.2. Device Information 4 3.3. Tablet Contexts 4 3.4. Event Packets 4 3.5. Tablet Managers 5 3.6. Extensions 5 3.7. Persistent Binding of Interface Features (1.1) 6 4. Interface Implementations 6 4.1. File and Module Conventions 6 4.2. Feature Support Options 6 5. Function Reference 7 5.1. Basic Functions 7 5.1.1. WTInfo 8 5.1.2. WTOpen 9 5.1.3. WTClose 10 5.1.4. WTPacketsGet 10 5.1.5. WTPacket 11 5.2. Visibility Functions 11 5.2.1. WTEnable 11 5.2.2. WTOverlap 12 5.3. Context Editing Functions 12 5.3.1. WTConfig 12 5.3.2. WTGet 13 5.3.3. WTSet (1.1 modified) 13 5.3.4. WTExtGet 14 5.3.5. WTExtSet 14 5.3.6. WTSave 15 5.3.7. WTRestore 15 5.4. Advanced Packet and Queue Functions 16 5.4.1. WTPacketsPeek 16 5.4.2. WTDataGet 17 5.4.3. WTDataPeek 17 5.4.4. WTQueuePackets (16-bit only) 18 5.4.5. WTQueuePacketsEx 18 5.4.6. WTQueueSizeGet 19 5.4.7. WTQueueSizeSet 19 5.5. Manager Handle Functions 19 5.5.1. WTMgrOpen 19 5.5.2. WTMgrClose 20 5.6. Manager Context Functions 20 5.6.1. WTMgrContextEnum 20 5.6.2. WTMgrContextOwner 21 5.6.3. WTMgrDefContext 22 5.6.4. WTMgrDefContextEx (1.1) 22 5.7. Manager Configuration Functions 23 5.7.1. WTMgrDeviceConfig 23 5.7.2. WTMgrConfigReplace (16-bit only) 24 5.7.3. WTMgrConfigReplaceEx 24 5.8. Manager Packet Hook Functions 25 5.8.1. WTMgrPacketHook (16-bit only) 26 5.8.2. WTMgrPacketHookEx 26 5.8.3. WTMgrPacketUnhook 29 5.8.4. WTMgrPacketHookDefProc (16-bit only) 30 5.8.5. WTMgrPacketHookNext 30 5.9. Manager Preference Data Functions 31 5.9.1. WTMgrExt 31 5.9.2. WTMgrCsrEnable 32 5.9.3. WTMgrCsrButtonMap 32 5.9.4. WTMgrCsrPressureBtnMarks (16-bit only) 33 5.9.5. WTMgrCsrPressureBtnMarksEx 33 5.9.6. WTMgrCsrPressureResponse 34 5.9.7. WTMgrCsrExt 35 6. Message Reference 36 6.1. Event Messages 36 6.1.1. WT_PACKET 36 6.1.2. WT_CSRCHANGE (1.1) 37 6.2. Context Messages 37 6.2.1. WT_CTXOPEN 37 6.2.2. WT_CTXCLOSE 37 6.2.3. WT_CTXUPDATE 38 6.2.4. WT_CTXOVERLAP 38 6.2.5. WT_PROXIMITY 38 6.3. Information Change Messages 39 6.3.1. WT_INFOCHANGE 39 7. Data Reference 39 7.1. Common Data Types (1.1 modified) 39 7.2. Information Data Structures 41 7.2.1. AXIS 41 7.2.2. Information Categories and Indices (1.1 modified) 42 7.3. Context Data Structures 50 7.3.1. LOGCONTEXT (1.1 modified) 50 7.4. Event Data Structures 55 7.4.1. PACKET (1.1 modified) 55 7.4.2. ORIENTATION 57 7.4.3. ROTATION (1.1) 58 Appendix A. Using PKTDEF.H 59 Appendix B. Extension Definitions 60 B.1. Extensions Programming 60 B.2. Out of Bounds Tracking 61 OBT Programming 61 Information Category 61 Turning OBT On and Off 61 B.3. Function Keys 62 FKEYS Programming 62 Information Category 62 B.4. Tilt 62 TILT Programming 63 Information Category 63 B.5. Cursor Mask 63 CSRMASK Programming 64 Information Category 64 B.6. Extended Button Masks 64 XBTNMASK Programming 64 Information Category 65 VERSION 1.1 UPDATE NOTATION CONVENTIONS Sections marked with the “(1.1)” are new sections added for specification version 1.1. Sections bearing the “(1.1 modified)” notation contain updated information for specification version 1.1. The “(1.1)” notation also marks the definitions of new functions, messages, and data structures. The nota-tion “1.1:” marks new text or commentaries explaining new functionality added to existing features. 1 BACKGROUND INFORMATION This document describes a programming interface for using digitizing tablets and other advanced pointing de¬vices with Microsoft Windows Version 3.0 and above. The design presented here is based on the input of numerous professionals from the pointing device manufacturing and Windows soft¬ware development industries. In this document, the words "tablet" and "digitizer" are used interchange¬ably to mean all absolute point¬ing or digitizing devices that can be made to work with this interface. The definition is not lim¬ited to de¬vices that use a physical tablet. In fact, this specification can support de¬vices that combine rela¬tive and absolute pointing as well as purely relative devices. The following sections describe features of tablets and of the Windows environment that helped mo¬tivate the design. 1.1 Features of Digitizers Digitizing tablets present several problems to device interface authors. • Many tablets have a very high report rate. • Many tablets have many configurable features and types of input information. • Tablets often control the system cursor, provide additional digitizing input, and provide template or macro functions. 1.2 The Windows Environment Programming for tablets in the Windows environment presents additional problems. • Multitasking means multiple applications may have to share the tablet. • The tablet must also be able to control the system cursor and/or the pen (in Pen Windows). • The tablet must work with legacy applications, and with applications written to take advan¬tage of tablet services. • The tablet driver must add minimal speed and memory overhead, so as many applications as possible can run as efficiently as possible. • The user should be able to control how applications use the tablet. The user interface must be ef-ficient, consistent, and customizable. 2 DESIGN GOALS While the tablet interface design must address the technical problems stated above, it must also be useful to the programmers who will write tablet programs, and ultimately, to the tablet users. Four design goals will help clarify these needs, and provide some criteria for evaluating the interface speci¬fication. The goals are user control, ease of programming, tablet sharing, and tablet feature support. 2.1 User Control The user should be able to use and control the tablet in as natural and easy a manner as possible. The user's preferences should take precedence over application requests, where possible. Here are questions to ask when thinking about user control as a design goal: • Can the user understand how applications use the tablet? • Is the interface for controlling tablet functions natural and unobtrusive? • Is the user allowed to change things that help to customize the work environment, but pre¬vented from changing things over which applications must have control? 2.2 Ease of Programming Programming is easiest when the amount of knowledge and effort required matches the task at hand. Writing simple programs should require only a few lines of code and a minimal understanding of the en-vironment. On the other hand, more advanced features and functions should be available to those who need them. The interface should accommodate three kinds of programmers: those who wish to write sim-ple tablet programs, programmers who wish to write complex applications that take full ad¬vantage of tab-let capabilities, and programmers who wish to provide tablet device control features. In addition, the inter-face should accommodate programmers in as many different programming lan¬guages, situations, and en-vironments as possible. Questions to ask when thinking about ease of programming include: • How hard is it to learn the interface and write a simple program that uses tablet input? • Can programmers of complex applications control the features they need? • Are more powerful tablet device control features available? • Can the interface be used in different programming environments? • Is the interface logical, consistent, and robust? 2.3 Tablet Sharing In the Windows environment, multiple applications that use the tablet may be running at once. Each ap-plication will require different services. Applications must be able to get the services they need without getting in each others' way. Questions to ask when thinking about tablet sharing include: • Can tablet applications use the tablet features they need, independent of other applications? • Does the interface prevent a rogue application from "hijacking" the tablet, or causing dead¬locks? • Does the sharing architecture promote efficiency? 2.4 Tablet Feature Support The interface gives standard access to as many features as possible, while leaving room for future ex¬ten-sions and vendor-specific customizations. Applications should be able to get the tablet informa¬tion and services they want, just the way they want them. Users should be able to use the tablet to set up an effi-cient, comfortable work environment. Questions to ask when thinking about tablet feature support include: • Does the interface provide the features applications need? Are any commonly available fea¬tures not supported? • Does the interface provide what users need? Is anything missing? • Are future extensions possible and fairly easy? • Are vendor-specific extensions possible? 3 DESIGN CONCEPTS The proposed interface design depends on several fundamental concepts. Devices and cursor types de-scribe physical hardware configurations. The interface publishes read-only information through a single information interface. Applications interact with the interface by setting up tablet contexts and consuming event packets. Applications may assume interface and hardware control functions by be¬coming tablet managers. The interface provides explicit support for future extensions. 3.1 Device Conventions The interface provides access to one or more devices that produce pointing input. Devices sup¬ported by this interface have some common characteristics. The device must define an absolute or relative coordi-nate space in at least two dimensions for which it can return position data. The device must have a point-ing ap¬para¬tus or method (such as a stylus, or a finger touching a touch pad), called the cursor, that de¬fines the current position. The cursor must be able to return at least one bit of additional state (via a but¬ton, touching a digitizing surface, etc.). Devices may have multiple cursor types that have different physical configurations, or that have differ¬ent numbers of buttons, or return auxiliary information, such as pressure information. Cursor types may also describe different optional hardware configurations. The interface defines a standard orientation for reporting device native coordinates. When the user is viewing the device in its normal position, the coordinate origin will be at the lower left of the device. The coordinate system will be right-handed, that is, the positive x axis points from left to right, and the posi¬tive y axis points either upward or away from the user. The z axis, if supported, points either to¬ward the user or upward. For devices that lay flat on a table top, the x-y plane will be horizontal and the z axis will point upward. For devices that are oriented vertically (for example, a touch screen on a conventional dis¬play), the x-y plane will be vertical, and the z axis will point toward the user. 3.2 Device Information Any program can get descriptive information about the tablet via the WTInfo function. The interface specifies certain information that must be available, but allows new implementations to add new types of information. The basic information includes device identifiers, version numbers, and overall ca¬pabilities. The information items are organized by category and index numbers. The combination of a category and index specifies a single information data item, which may be a scalar value, string, structure, or array. Applica¬tions may retrieve single items or whole categories at once. Some categories are multiplexed. A single category code represents the first of a group of identically in-dexed categories, one for each of a set of similar objects. Multiplexed categories in¬clude those for devices and cur¬sor types. One constructs the category number by adding the defined cate¬gory code to a zero-based device or cursor identification number. The information is read-only for normal tablet applications. Some information items may change during the course of a Windows session; tablet applications receive messages notifying them of changes in tablet information. 3.3 Tablet Contexts Tablet contexts play a central role in the interface; they are the objects that applications use to specify their use of the tablet. Con¬texts include not only the physical area of the tablet that the application will use, but also information about the type, con¬tents, and delivery method for tablet events, as well as other information. Tablet contexts are somewhat analo¬gous to display contexts in the GDI interface model; they contain context information about a spe¬cific application's use of the tablet. An application can open more than one context, but most only need one. Applications can customize their contexts, or they can open a context using a default context specification that is always available. The WTInfo function provides access to the default context specification. Opening a context requires a window handle. The window handle becomes the context's owner and will receive any window messages associated with the context. Contexts are remotely similar to screen windows in that they can physically overlap. The tablet inter¬face uses a combination of context overlap order and context attributes to decide which context will process a given event. The topmost context in the overlap order whose input context encompasses the event, and whose event masks select the event, will process the event. (Note that the notion of overlap order is sepa-rate from the notion of the physical z dimension.) Tablet managers (described below) provide a way to modify and overlap contexts. 3.4 Event Packets Tablet contexts generate and report tablet activity via event packets. Applications can control how they receive events, which events they receive, and what information they contain. Applications may receive events either by polling, or via Windows messages. • Polling: Any application that has opened a context can call the WTPacketsGet function to get the next state of the tablet for that context. • Window Messages: Applications that request messages will receive the WT_PACKET mes¬sage (described below), which indicates that something happened in the context and provides a refer-ence to more information. Applications can control which events they receive by using event masks. For example, some appli¬ca¬tions may only need to know when a button is pressed, while others may need to receive an event every time the cursor moves. Tablet context event masks implement this type of control. Applications can control the contents of the event packets they receive. Some tablets can return data that many applications will not need, like button pressure and three dimensional position and orien¬tation in-formation. The context object provides a way of specifying which data items the appli¬cation needs. This allows the driver to improve the efficiency of packet delivery to applications that only need a few items per packet. Packets are stored in context-specific packet queues and retrieved by explicit function calls. The interface provides ways to peek at and get packets, to query the size and contents of the queue, and to re-size the queue. 3.5 Tablet Managers The interface provides functions for tablet management. An application can become a tablet manager by opening a tablet manager handle. This handle allows the manager access to spe¬cial functions. These man-agement functions allow the application to arrange, overlap, and modify tablet contexts. Man¬agers may also perform other functions, such as changing default values used by applica¬tions, chang¬ing ergo¬nomic, preference, and configuration settings, controlling tablet behavior with non-tablet aware applica¬tions, modi¬fy¬ing user dialogs, and recording and playing back tablet packets. Opening a manager handle re¬quires a window handle. The window becomes a manager window and receives window messages about interface and con¬text activity. 3.6 Extensions The interface allows implementations to define additional features called extensions. Extensions can be made available to new applications without the need to modify ex¬isting applications. Extensions are sup-ported through the information categories, through the flexible definition of packets, and through special context and manager functions. Designing an extension involves defining the meaning and behavior of the extension packet and/or prefer-ence data, filling in the information category, defining the extension's interface with the special functions, and possibly defining additional functions to support the extension. Each extension will be assigned a unique tag for identification. Not all implementations will support all extensions. A multiplexed information category contains descriptive data about extensions. Note that applica¬tions must find their extensions by iterating through the categories and matching tags. While tags are fixed across all implementations, category numbers may vary among implementations. 3.7 Persistent Binding of Interface Features (1.1) The interface provides access to many of its features using consecutive numeric indices whose value is not guaranteed from session to session. However, sufficient information is provided to create unique identifi¬ers for devices, cursors, and interface extensions. Devices should be uniquely identified by the contents of their name strings. If multiple identical devices are present, implementation providers should provide unique, persistent id strings to the extent possible. Identical devices that return unique serial numbers are ideal. If supported by the hardware, cursors also may have a physical cursor id that uniquely identifies the cursor in a persistent and stable manner. Interface extensions are uniquely identified by their tag. 4 INTERFACE IMPLEMENTATIONS Implementations of this interface usually support one specific device, a class of similar devices, or a com-mon combination of devices. The following sections discuss guidelines for implementations. 4.1 File and Module Conventions For 16-bit implementations, the interface functions, and any additional vendor- or device-specific func-tions, reside in a dynamic link library with the file name "WINTAB.DLL" and module name "WINTAB"; 32-bit implementations use the file name "WINTAB32.DLL" and module name "WINTAB32." Any other file or module con¬ventions are implementation specific. Implementations may include other library mod-ules or data files as necessary. Installation processes are likewise implementa¬tion-specific. Wintab programs written in the C language require two header files. WINTAB.H contains definitions of all of the functions, constants, and fixed data types. PKTDEF.H contains a parameterized definition of the PACKET data structure, that can be tailored to fit the application. The Wintab Programmer's Kit con¬tains these and other files necessary for Wintab programming, plus several example programs with C-lan¬guage source files. The Wintab Programmer's Kit is available from the author. 4.2 Feature Support Options Some features of the interface are optional and may be left out by some implementations. Support of defined data items other than x, y, and buttons is optional. Many devices only report x, y, and button information. Support of system-cursor contexts is optional. This option relieves implementations of replacing the sys¬tem mouse driver in Windows versions before 3.1. Support of Pen Windows contexts is optional. Not all systems will have the Pen Windows hardware and software necessary. Support of external tablet manager applications is optional, and the number of manager handles is imple-mentation-dependent. However, the manager functions should be present in all implementa¬tions, return¬ing appropriate failure codes if not fully implemented. An implementation may provide context- and hardware-management support internally only, if desired. On the other hand, providing the external man-ager interface may relieve the implementation of a considerable amount of user in¬terface code, and make improvements to the manager interface easier to implement and distribute later. Support of extension data items is optional. Most extensions will be geared to unusual hardware features. 5 FUNCTION REFERENCE All tablet function names have the prefix "WT" and have attributes equivalent to WINAPI. Applica¬tions gain access to the tablet interface functions through a dynamic-link library with standard file and module names, as defined in the previous section. Applications may link to the functions by using the Windows functions LoadLibrary, FreeLibrary, and GetProcAddress, or use an import library. Specific to 32-bit Wintab: The functions WTInfo, WTOpen, WTGet, and WTSet have both ANSI and Unicode versions, using the same ANSI/Unicode porting conventions used in the Win32 API. Five non-portable functions, WTQueuePackets, WTMgrCsrPressureBtnMarks, WTMgrConfigReplace, WTMgrPacketHook, and WTMgrPacketHookDefProc are replaced by new portable functions WTQueuePacketsEx, WTMgrCsrPressureBtnMarksEx, WTMgrConfigReplaceEx, WTMgrPack-etHookEx, WTMgrPacketUnhook, and WTMgrPacketHookNext. WTMgrConfigReplaceEx and WTMgrPacketHookEx have both ANSI and Unicode versions. Table 5.1. Ordinal Function Numbers for Dynamic Linking Ordinal numbers for dynamic linking are defined in the table below. Where two ordinal entries appear, the first entry identifies the 16-bit and 32-bit ANSI versions of the function. The second entry identifies the 32-bit Unicode version. Function Name Ordinal Function Name Ordinal WTInfo 20, 1020 WTMgrOpen 100 WTOpen 21, 1021 WTMgrClose 101 WTClose 22 WTMgrContextEnum 120 WTPacketsGet 23 WTMgrContextOwner 121 WTPacket 24 WTMgrDefContext 122 WTEnable 40 WTMgrDefContextEx (1.1) 206 WTOverlap 41 WTMgrDeviceConfig 140 WTConfig 60 WTMgrConfigReplace 141 WTGet 61, 1061 WTMgrConfigReplaceEx 202, 1202 WTSet 62, 1062 WTMgrPacketHook 160 WTExtGet 63 WTMgrPacketHookEx 203, 1203 WTExtSet 64 WTMgrPacketUnhook 204 WTSave 65 WTMgrPacketHookDefProc 161 WTRestore 66 WTMgrPacketHookNext 205 WTPacketsPeek 80 WTMgrExt 180 WTDataGet 81 WTMgrCsrEnable 181 WTDataPeek 82 WTMgrCsrButtonMap 182 WTQueuePackets 83 WTMgrCsrPressureBtnMarks 183 WTQueuePacketsEx 200 WTMgrCsrPressureBtnMarksEx 201 WTQueueSizeGet 84 WTMgrCsrPressureResponse 184 WTQueueSizeSet 85 WTMgrCsrExt 185 5.1 Basic Functions The functions in the following section will be used by most tablet-aware applications. They include getting interface and device information, opening and closing contexts, and retrieving packets by polling or via Windows messages. 5.1.1 WTInfo Syntax UINT WTInfo(wCategory, nIndex, lpOutput) This function returns global information about the interface in an application-sup-plied buffer. Different types of information are specified by different index argu-ments. Applications use this function to receive information about tablet coordi-nates, physical dimensions, capabilities, and cursor types. Parameter Type/Description wCategory UINT Identifies the category from which information is being re-quested. nIndex UINT Identifies which information is being requested from within the category. lpOutput LPVOID Points to a buffer to hold the requested information. Return Value The return value specifies the size of the returned information in bytes. If the infor-mation is not supported, the function returns zero. If a tablet is not physi¬cally pres-ent, this function always returns zero. Comments Several important categories of information are available through this function. First, the function provides identification information, including specification and software version numbers, and tablet vendor and model information. Sec¬ond, the function provides general capability information, including dimensions, resolutions, optional features, and cursor types. Third, the function provides categories that give defaults for all tablet context attributes. Finally, the func¬tion may provide any other implementation- or vendor-specific information cat¬egories necessary. The information returned by this function is subject to change during a Win¬dows session. Applications cannot change the information returned here, but tablet man-ager applications or hardware changes or errors can. Applications can respond to information changes by fielding the WT_INFOCHANGE message. The parameters of the message indicate which information has changed. If the wCategory argument is zero, the function copies no data to the output buffer, but returns the size in bytes of the buffer necessary to hold the largest complete category. If the nIndex argument is zero, the function returns all of the information entries in the category in a single data structure. If the lpOutput argument is NULL, the function just returns the required buffer size. See Also Category and index definitions in tables 7.3 through 7.9, and the WT_INFOCHANGE message in section 6.3.1. 5.1.2 WTOpen Syntax HCTX WTOpen(hWnd, lpLogCtx, fEnable) This function establishes an active context on the tablet. On successful comple¬tion of this function, the application may begin receiving tablet events via mes¬sages (if they were requested), and may use the handle returned to poll the con¬text, or to per-form other context-related functions. Parameter Type/Description hWnd HWND Identifies the window that owns the tablet context, and receives messages from the context. lpLogCtx LPLOGCONTEXT Points to an application-provided LOGCONTEXT data structure describing the context to be opened. fEnable BOOL Specifies whether the new context will immediately begin processing input data. Return Value The return value identifies the new context. It is NULL if the context is not opened. Comments Opening a new context allows the application to receive tablet input or creates a context that controls the system cursor or Pen Windows pen. The owning window (and all manager windows) will immediately receive a WT_CTXOPEN message when the context has been opened. If the fEnable argument is zero, the context will be created, but will not process input. The context can be enabled using the WTEnable function. If tablet event messages were requested in the context specification, the owning window will receive them. The application can control the message numbers used the lcMsgBase field of the LOGCONTEXT structure. The window that owns the new context will receive context and information change messages even if event messages were not requested. It is not necessary to handle these in many cases, but some applications may wish to do so. The newly opened tablet context will be placed on the top of the context overlap or-der. Invalid or out-of-range attribute values in the logical context structure will ei¬ther be validated, or cause the open to fail, depending on the attributes involved. Upon a successful return from the function, the context specification pointed to by lpLogCtx will contain the validated values. See Also The WTEnable function in section 5.2.1, the LOGCONTEXT data structure in section 7.3.1, and the context and infor¬mation change messages in sections 6.2 and 6.3. 5.1.3 WTClose Syntax BOOL WTClose(hCtx) This function closes and destroys the tablet context object. Parameter Type/Description hCtx HCTX Identifies the context to be closed. Return Value The function returns a non-zero value if the context was valid and was destroyed. Otherwise, it returns zero. Comments After a call to this function, the passed handle is no longer valid. The owning win¬dow (and all manager windows) will receive a WT_CTXCLOSE message when the context has been closed. See Also The WTOpen function in section 5.1.2. 5.1.4 WTPacketsGet Syntax int WTPacketsGet(hCtx, cMaxPkts, lpPkts) This function copies the next cMaxPkts events from the packet queue of context hCtx to the passed lpPkts buffer and removes them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being returned. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. Return Value The return value is the number of packets copied in the buffer. Comments The exact structure of the returned packet is determined by the packet infor¬mation that was requested when the context was opened. The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. Applications may flush packets from the queue by calling this function with a NULL lpPkt argument. See Also The WTPacketsPeek function in section 5.4.1, and the descriptions of the LOGCONTEXT (section 7.3.1) and PACKET (section 7.4.1) data structures. 5.1.5 WTPacket Syntax BOOL WTPacket(hCtx, wSerial, lpPkt) This function fills in the passed lpPkt buffer with the context event packet having the specified serial number. The returned packet and any older packets are removed from the context's internal queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being returned. wSerial UINT Serial number of the tablet event to return. lpPkt LPVOID Points to a buffer to receive the event packet. Return Value The return value is non-zero if the specified packet was found and returned. It is zero if the specified packet was not found in the queue. Comments The exact structure of the returned packet is determined by the packet infor¬mation that was requested when the context was opened. The buffer pointed to by lpPkts must be at least sizeof(PACKET) bytes long to pre-vent overflow. Applications may flush packets from the queue by calling this function with a NULL lpPkts argument. See Also The descriptions of the LOGCONTEXT (section 7.3.1) and PACKET (section 7.4.1) data structures. 5.2 Visibility Functions The functions in this section allow applications to control contexts' visibility, whether or not they are pro-cessing input, and their overlap order. 5.2.1 WTEnable Syntax BOOL WTEnable(hCtx, fEnable) This function enables or disables a tablet context, temporarily turning on or off the processing of packets. Parameter Type/Description hCtx HCTX Identifies the context to be enabled or disabled. fEnable BOOL Specifies enabling if non-zero, disabling if zero. Return Value The function returns a non-zero value if the enable or disable request was satis¬fied, zero otherwise. Comments Calls to this function to enable an already enabled context, or to disable an al¬ready disabled context will return a non-zero value, but otherwise do nothing. The context’s packet queue is flushed on disable. Applications can determine whether a context is currently enabled by using the WTGet function and examining the lcStatus field of the LOGCONTEXT struc¬ture. See Also The WTGet function in section 5.3.2, and the LOGCONTEXT structure in sec¬tion 7.3.1. 5.2.2 WTOverlap Syntax BOOL WTOverlap(hCtx, fToTop) This function sends a tablet context to the top or bottom of the order of over¬lapping tablet contexts. Parameter Type/Description hCtx HCTX Identifies the context to move within the overlap order. fToTop BOOL Specifies sending the context to the top of the overlap or-der if non-zero, or to the bottom if zero. Return Value The function returns non-zero if successful, zero otherwise. Comments Tablet contexts' input areas are allowed to overlap. The tablet interface main¬tains an overlap order that helps determine which context will process a given event. The topmost context in the overlap order whose input context encom¬passes the event, and whose event masks select the event will process the event. This function is useful for getting access to input events when the application's con-text is overlapped by other contexts. The function will fail only if the context argument is invalid. 5.3 Context Editing Functions This group of functions allows applications to edit, save, and restore contexts. 5.3.1 WTConfig Syntax BOOL WTConfig(hCtx, hWnd) This function prompts the user for changes to the passed context via a dialog box. Parameter Type/Description hCtx HCTX Identifies the context that the user will modify via the dialog box. hWnd HWND Identifies the window that will be the parent window of the dialog box. Return Value The function returns a non-zero value if the tablet context was changed, zero oth-erwise. Comments Tablet applications can use this function to let the user choose context attributes that the application doesn't need to control. Applications can control the editing of con¬text attributes via the lcLocks logical context structure member. Applications should consider providing access to this function through a menu item or command. See Also The LOGCONTEXT structure in section 7.3.1 and the context lock values in table 7.13. 5.3.2 WTGet Syntax BOOL WTGet(hCtx, lpLogCtx) This function fills the passed structure with the current context attributes for the passed handle. Parameter Type/Description hCtx HCTX Identifies the context whose attributes are to be copied. lpLogCtx LPLOGCONTEXT Points to a LOGCONTEXT data structure to which the context attributes are to be copied. Return Value The function returns a non-zero value if the data is retrieved successfully. Oth¬er¬wise, it returns zero. See Also The LOGCONTEXT structure in section 7.3.1. 5.3.3 WTSet (1.1 modified) Syntax BOOL WTSet(hCtx, lpLogCtx) This function allows some of the context's attributes to be changed on the fly. Parameter Type/Description hCtx HCTX Identifies the context whose attributes are being changed. lpLogCtx LPLOGCONTEXT Points to a LOGCONTEXT data structure containing the new context attributes. Return Value The function returns a non-zero value if the context was changed to match the passed context specification; it returns zero if any of the requested changes could not be made. Comments If this function is called by the task or process that owns the context, any context attribute may be changed. Otherwise, the function can change attributes that do not affect the format or meaning of the context's event packets and that were not speci-fied as locked when the context was opened. Context lock values can only be changed by the context’s owner. 1.1: If the hCtx argument is a default context handle returned from WTMgrDef-Context or WTMgrDefContextEx, and the lpLogCtx argument is WTP_LPDEFAULT, the default context will be reset to its initial factory default values. See Also The LOGCONTEXT structure in section 7.3.1 and the context lock values in table 7.13. 5.3.4 WTExtGet Syntax BOOL WTExtGet(hCtx, wExt, lpData) This function retrieves any context-specific data for an extension. Parameter Type/Description hCtx HCTX Identifies the context whose extension attributes are being retrieved. wExt UINT Identifies the extension tag for which context-specific data is being retrieved. lpData LPVOID Points to a buffer to hold the retrieved data. Return Value The function returns a non-zero value if the data is retrieved successfully. Oth¬er¬wise, it returns zero. See Also The extension definitions in Appendix B. 5.3.5 WTExtSet Syntax BOOL WTExtSet(hCtx, wExt, lpData) This function sets any context-specific data for an extension. Parameter Type/Description hCtx HCTX Identifies the context whose extension attributes are being modified. wExt UINT Identifies the extension tag for which context-specific data is being modified. lpData LPVOID Points to the new data. Return Value The function returns a non-zero value if the data is modified successfully. Oth¬er¬wise, it returns zero. Comments Extensions may forbid their context-specific data to be changed during the life¬time of a context. For such extensions, calls to this function would always fail. Extensions may also limit context data editing to the task of the owning window, as with the context locks. See Also The extension definitions in Appendix B, the LOGCONTEXT data structure in section 7.3.1 and the context locking values in table 7.13. 5.3.6 WTSave Syntax BOOL WTSave(hCtx, lpSaveInfo) This function fills the passed buffer with binary save information that can be used to restore the equivalent context in a subsequent Windows session. Parameter Type/Description hCtx HCTX Identifies the context that is being saved. lpSaveInfo LPVOID Points to a buffer to contain the save information. Return Value The function returns non-zero if the save information is successfully retrieved. Oth-erwise, it returns zero. Comments The size of the save information buffer can be determined by calling the WTInfo function with category WTI_INTERFACE, index IFC_CTXSAVESIZE. The save information is returned in a private binary data format. Applications should store the information unmodified and recreate the context by passing the save information to the WTRestore function. Using WTSave and WTRestore allows applications to easily save and restore ex-tension data bound to contexts. See Also The WTRestore function in section 5.3.7. 5.3.7 WTRestore Syntax HCTX WTRestore(hWnd, lpSaveInfo, fEnable) This function creates a tablet context from save information returned from the WTSave function. Parameter Type/Description hWnd HWND Identifies the window that owns the tablet context, and receives messages from the context. lpSaveInfo LPVOID Points to a buffer containing save information. fEnable BOOL Specifies whether the new context will immediately begin processing input data. Return Value The function returns a valid context handle if successful. If a context equivalent to the save information could not be created, the function returns NULL. Comments The save information is in a private binary data format. Applications should only pass save information retrieved by the WTSave function. This function is much like WTOpen, except that it uses save in¬formation for input instead of a logical context. In particular, it will generate a WT_CTXOPEN mes¬sage for the new context. See Also The WTOpen function in section 5.1.2, the WTSave function in section 5.3.6, and the WT_CTXOPEN message in section 6.2.1. 5.4 Advanced Packet and Queue Functions These functions provide advanced packet retrieval and queue manipulation. The packet retrieval functions require the application to provide a packet output buffer. To prevent overflow, the buffer must be large enough to hold the requested number of packets from the specified context. It is up to the caller to deter¬mine the packet size (by interrogating the context, if necessary), and to allocate a large enough buffer. Ap¬plications may flush packets from the queue by passing a NULL buffer pointer. 5.4.1 WTPacketsPeek Syntax int WTPacketsPeek(hCtx, cMaxPkts, lpPkts) This function copies the next cMaxPkts events from the packet queue of context hCtx to the passed lpPkts buffer without removing them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being read. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. Return Value The return value is the number of packets copied in the buffer. Comments The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. See Also the WTPacketsGet function in section 5.1.4. 5.4.2 WTDataGet Syntax int WTDataGet(hCtx, wBegin, wEnd, cMaxPkts, lpPkts, lpNPkts) This function copies all packets with serial numbers between wBegin and wEnd in-clusive from the context's queue to the passed buffer and removes them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being returned. wBegin UINT Serial number of the oldest tablet event to return. wEnd UINT Serial number of the newest tablet event to return. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. lpNPkts LPINT Points to an integer to receive the number of packets ac-tually copied. Return Value The return value is the total number of packets found in the queue between wBegin and wEnd. Comments The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. See Also The WTDataPeek function in section 5.4.3, and the WTQueuePacketsEx function in section 5.4.5. 5.4.3 WTDataPeek Syntax int WTDataPeek(hCtx, wBegin, wEnd, cMaxPkts, lpPkts, lpNPkts) This function copies all packets with serial numbers between wBegin and wEnd in-clusive, from the context's queue to the passed buffer without removing them from the queue. Parameter Type/Description hCtx HCTX Identifies the context whose packets are being read. wBegin UINT Serial number of the oldest tablet event to return. wEnd UINT Serial number of the newest tablet event to return. cMaxPkts int Specifies the maximum number of packets to return. lpPkts LPVOID Points to a buffer to receive the event packets. lpNPkts LPINT Points to an integer to receive the number of packets ac-tually copied. Return Value The return value is the total number of packets found in the queue between wBegin and wEnd. Comments The buffer pointed to by lpPkts must be at least cMaxPkts * sizeof(PACKET) bytes long to prevent overflow. See Also The WTDataGet function in section 5.4.2, and the WTQueuePacketsEx function in section 5.4.5. 5.4.4 WTQueuePackets (16-bit only) Syntax DWORD WTQueuePackets(hCtx) This function returns the serial numbers of the oldest and newest packets cur¬rently in the queue. Parameter Type/Description hCtx HCTX Identifies the context whose queue is being queried. Return Value The high word of the return value contains the newest packet's serial number; the low word contains the oldest. Comments This function is non-portable and is superseded by WTQueuePacketsEx. See Also The WTQueuePacketsEx function in section 5.4.5. 5.4.5 WTQueuePacketsEx Syntax BOOL WTQueuePacketsEx(hCtx, lpOld, lpNew) This function returns the serial numbers of the oldest and newest packets cur¬rently in the queue. Parameter Type/Description hCtx HCTX Identifies the context whose queue is being queried. lpOld UINT FAR * Points to an unsigned integer to receive the oldest packet's serial number. lpNew UINT FAR * Points to an unsigned integer to receive the newest packet's serial number. Return Value The function returns non-zero if successful, zero otherwise. 5.4.6 WTQueueSizeGet Syntax int WTQueueSizeGet(hCtx) This function returns the number of packets the context's queue can hold. Parameter Type/Description hCtx HCTX Identifies the context whose queue size is being re¬turned. Return Value The return value is the number of packet the queue can hold. See Also The WTQueueSizeSet function in section 5.4.7. 5.4.7 WTQueueSizeSet Syntax BOOL WTQueueSizeSet(hCtx, nPkts) This function attempts to change the context's queue size to the value specified in nPkts. Parameter Type/Description hCtx HCTX Identifies the context whose queue size is being set. nPkts int Specifies the requested queue size. Return Value The return value is non-zero if the queue size was successfully changed. Other¬wise, it is zero. Comments If the return value is zero, the context has no queue because the function deletes the original queue before attempting to create a new one. The application must continue calling the function with a smaller queue size until the function returns a non-zero value. See Also The WTQueueSizeGet function in section 5.4.6. 5.5 Manager Handle Functions The functions described in this and subsequent sections are for use by tablet manager applications. The functions of this section create and destroy manager handles. These handles allow the interface code to limit the degree of simultaneous access to the powerful manager functions. Also, opening a manager handle lets the application receive messages about tablet interface activity. 5.5.1 WTMgrOpen Syntax HMGR WTMgrOpen(hWnd, wMsgBase) This function opens a tablet manager handle for use by tablet manager and con¬figu-ration applications. This handle is required to call the tablet management func¬tions. Parameter Type/Description hWnd HWND Identifies the window which owns the manager handle. wMsgBase UINT Specifies the message base number to use when notifying the manager window. Return Value The function returns a manager handle if successful, otherwise it returns NULL. Comments While the manager handle is open, the manager window will receive context mes-sages from all tablet contexts. Manager windows also receive information change messages. The number of manager handles available is interface implementation-dependent, and can be determined by calling the WTInfo function with category WTI_INTERFACE and index IFC_NMANAGERS. See Also The WTInfo function in section 5.1.1, the WTMgrClose function in section 5.5.2, the description of message base numbers in section 6 and the context and in¬for¬ma-tion change messages in sections 6.2 and 6.3. 5.5.2 WTMgrClose Syntax BOOL WTMgrClose(hMgr) This function closes a tablet manager handle. After this function returns, the passed manager handle is no longer valid. Parameter Type/Description hMgr HMGR Identifies the manager handle to close. Return Value The function returns non-zero if the handle was valid; otherwise, it returns zero. 5.6 Manager Context Functions These functions provide access to all open contexts and their owners, and allow changing context de¬faults. Only tablet managers are allowed to manipulate tablet contexts belonging to other applica¬tions. 5.6.1 WTMgrContextEnum Syntax BOOL WTMgrContextEnum(hMgr, lpEnumFunc, lParam) This function enumerates all tablet context handles by passing the handle of each context, in turn, to the callback function pointed to by the lpEnumFunc pa¬rameter. The enumeration terminates when the callback function returns zero. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. lpEnumFunc WTENUMPROC Is the procedure-instance address of the call-back function. See the following "Comments" section for details. lParam LPARAM Specifies the value to be passed to the callback func-tion for the application's use. Return Value The return value specifies the outcome of the function. It is non-zero if all con¬texts have been enumerated. Otherwise, it is zero. Comments The address passed as the lpEnumFunc parameter must be created by using the MakeProcInstance function. The callback function must have attributes equivalent to WINAPI. The callback function must have the following form: Callback BOOL WINAPI EnumFunc(hCtx, lParam) HCTX hCtx; LPARAM lParam; EnumFunc is a place holder for the application-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the applica-tion's module-definition file. Parameter Description hCtx Identifies the context. lParam Specifies the 32-bit argument of the WTMgrContextEnum func-tion. Return Value The function must return a non-zero value to continue enumeration, or zero to stop it. 5.6.2 WTMgrContextOwner Syntax HWND WTMgrContextOwner(hMgr, hCtx) This function returns the handle of the window that owns a tablet context. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. hCtx HCTX Identifies the context whose owner is to be returned. Return Value The function returns the context owner's window handle if the passed arguments are valid. Otherwise, it returns NULL. Comments This function allows the tablet manager to coordinate tablet context manage¬ment with the states of the context-owning windows. 5.6.3 WTMgrDefContext Syntax HCTX WTMgrDefContext(hMgr, fSystem) This function retrieves a context handle that allows setting values for the current default digit¬izing or system context. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fSystem BOOL Specifies retrieval of the default system context if non-zero, or the default digitizing context if zero. Return Value The return value is the context handle for the specified default context, or NULL if the arguments were invalid. Comments The default digitizing context is the context whose attributes are returned by the WTInfo function WTI_DEFCONTEXT category. The default system context is the context whose attributes are returned by the WTInfo function WTI_DEFSYSCTX category. Editing operations on the retrieved handles will fail if the new default contexts do not meet certain requirements. The digitizing context must include at least buttons, x, and y in its packet data, and must return absolute coordinates. 1.1: Editing the current default digitizing context will also update the device-spe¬cific default context for the device listed in the lcDevice field of the default con¬text’s LOGCONTEXT structure. See Also The WTInfo function in section 5.1.1 the WTMgrDefContextEx function in section 5.6.4, and the category and index definitions in tables 7.3 through 7.9. 5.6.4 WTMgrDefContextEx (1.1) Syntax HCTX WTMgrDefContextEx(hMgr, wDevice, fSystem) This function retrieves a context handle that allows setting values for the default digit¬izing or system context for a specified device. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. wDevice UINT Specifies the device for which a default context handle will be returned. fSystem BOOL Specifies retrieval of the default system context if non-zero, or the default digitizing context if zero. Return Value The return value is the context handle for the specified default context, or NULL if the arguments were invalid. Comments The default digitizing contexts are contexts whose attributes are returned by the WTInfo function WTI_DDCTXS multiplexed category. The default system con-texts are contexts whose attributes are returned by the WTInfo function WTI_DSCTXS multiplexed category. Editing operations on the retrieved handles will fail if the new default contexts do not meet certain requirements. The digitizing context must include at least buttons, x, and y in its packet data, and must return absolute coordinates. See Also The WTInfo function in section 5.1.1, and the category and index definitions in tables 7.3 through 7.9. 5.7 Manager Configuration Functions These functions allow manager applications to replace the default context configuration dialog and to display a configuration dialog for each hardware device. 5.7.1 WTMgrDeviceConfig Syntax UINT WTMgrDeviceConfig(hMgr, wDevice, hWnd) This function displays a custom modal tablet-hardware configuration dialog box, if one is supported. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. wDevice UINT Identifies the device that the user will configure via the dialog box. hWnd HWND Identifies the window that will be the parent window of the dialog box. If this argument is NULL, the function will return non-zero if the dialog is supported, or zero otherwise. Return Value The return value is zero if the dialog box is not supported. Otherwise, it is one of the following non-zero values. Value Meaning WTDC_CANCEL The user canceled the dialog without making any changes. WTDC_OK The user made and confirmed changes. WTDC_RESTART The user made and confirmed changes that require a sys-tem restart in order to take effect. The calling program should query the user to determine whether to restart. Restart Windows using the function call ExitWin-dows(EW_RESTARTWINDOWS, 0);. 5.7.2 WTMgrConfigReplace (16-bit only) Syntax BOOL WTMgrConfigReplace(hMgr, fInstall, lpConfigProc) This function allows a manager application to replace the default behavior of the WTConfig function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fInstall BOOL Specifies installation of a replacement function if non-zero, or removal of the current replacement if zero. lpConfigProc WTCONFIGPROC Is the procedure-instance address of the new configuration function. This argument is ignored during a re¬moval request. Return Value The function return non-zero if the installation or removal request succeeded. Oth-erwise, it returns zero. Comments This function is non-portable and is superseded by WTMgrConfigReplaceEx. See Also The WTConfig function in section 5.3.1, and for a description of the configuration callback function, see the WTMgrConfigReplaceEx function in section 5.7.3. 5.7.3 WTMgrConfigReplaceEx Syntax BOOL WTMgrConfigReplaceEx(hMgr, fInstall, lpszModule, lpszCfgProc) This function allows a manager application to replace the default behavior of the WTConfig function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fInstall BOOL Specifies installation of a replacement function if non-zero, or removal of the current replacement if zero. lpszModule LPCTSTR Points to a null-terminated string that names a DLL module containing the new configuration function. This argument is ignored during a re¬moval request lpszCfgProc LPCSTR Points to a null-terminated string that names the new configuration function. This argument is ignored during a re¬moval request. Return Value The function return non-zero if the installation or removal request succeeded. Oth-erwise, it returns zero. Comments The configuration callback function must have attributes equivalent to WINAPI. Only one callback function may be installed at a time. The manager handle passed with the removal request must match the handle passed with the corre¬sponding in-stallation request. Tablet managers that install a replacement context configuration function must re-move it before exiting. Callback BOOL WINAPI ConfigProc(hWnd, hCtx) HWND hWnd; HCTX hCtx; ConfigProc is a place holder for the application-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the applica-tion's module-definition file. Parameter Description hWnd Identifies the window that will be the parent window of the dialog box. hCtx Identifies the context that the user will modify via the dialog box. Return Value The function returns a non-zero value if the tablet context was changed, zero oth-erwise. Comments The configuration function and resulting dialog box should analyze the lcLocks context structure member, and only allow editing of unlocked context attributes. See Also The WTConfig function in section 5.3.1. 5.8 Manager Packet Hook Functions These functions allow manager applications to monitor, record, and play back sequences of tablet packets. 5.8.1 WTMgrPacketHook (16-bit only) Syntax WTHOOKPROC WTMgrPacketHook(hMgr, fInstall, nType, lpFunc) This function installs or removes a packet hook function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. fInstall BOOL Specifies installation of a hook function if non-zero, or removal of the specified hook if zero. nType int Specifies the packet hook to be installed. It can be any one of the following values: Value Meaning WTH_PLAYBACK Installs a packet playback hook. WTH_RECORD Installs a packet record hook. lpFunc WTHOOKPROC Is the procedure-instance address of the hook function to be installed. See the "Comments" section under WTMgrPacketHookEx for details. Return Value When installing a hook, the return value points to the procedure-instance ad¬dress of the previously installed hook (if any). It is NULL if there is no previous hook; it is negative one if the hook cannot be installed. The application or library that calls this func¬tion should save this return value in the library's data segment. The fourth argument of the WTPacketHookDefProc function points to the location in memory where the library saves this return value. When removing a hook, the return value is the passed lpFunc if successful, NULL otherwise. Comments This function is non-portable and is superseded by WTMgrPacketHookEx and WTMgrPacketUnhook. See Also the WTMgrPacketHookEx function in section 5.8.2, and the WTMgrPacketUn-hook function in section 5.8.3. 5.8.2 WTMgrPacketHookEx Syntax HWTHOOK WTMgrPacketHookEx(hMgr, nType, lpszModule, lpszHookProc) This function installs a packet hook function. Parameter Type/Description hMgr HMGR Is the valid manager handle that identifies the caller as a manager application. nType int Specifies the packet hook to be installed. It can be any one of the following values: Value Meaning WTH_PLAYBACK Installs a packet playback hook. WTH_RECORD Installs a packet record hook. lpszModule LPCTSTR Points to a null-terminated string that names a DLL module containing the new hook function. See the following "Comments" section for details. lpszHookProc LPCSTR Points to a null-terminated string that names the new hook function. See the following "Comments" section for details. Return Value If the function succeeds, the return value is the handle of the installed hook func-tion. Otherwise, the return value is NULL. Comments Packet hooks are a shared resource. Installing a hook affects all applications using the interface. All Wintab hook functions must be exported functions residing in a DLL module. The following section describes how to support the individual hook functions. WTH_PLAYBACK Wintab calls the WTH_PLAYBACK hook whenever a request for an event packet is made. The function is intended to be used to supply a previously recorded event packet for a compatible context. The hook function must have attributes equivalent to WINAPI. The filter function must have the following form: Hook Function LRESULT WINAPI HookFunc(nCode, wParam, lParam); int nCode; WPARAM wParam; LPARAM lParam; HookFunc is a place holder for the library-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the library's mod¬ule-definition file. Parameter Description nCode Specifies whether the hook function should process the mes¬sage or call the WTMgrPacketHookDefProc (if installed by WTMgrPacketHook)or WTMgrPacketHookNext (if installed by WTMgrPacketHookEx) function. If the nCode parame¬ter is less than zero, the hook function should pass the message to the appropriate function without further process¬ing. wParam Specifies the context handle whose event is being requested. lParam Points to the packet being processed by the hook function. Comments The WTH_PLAYBACK function should copy an event packet to the buffer pointed to by the lParam pa¬rameter. The packet must have been previously recorded by us-ing the WTH_RECORD hook. It should not modify the packet. The return value should be the amount of time (in milliseconds) Wintab should wait before pro¬cess¬ing the mes¬sage. This time can be computed by calculation the difference between the time stamps of the current and previous packets. If the function returns zero, the message is processed immediately. Once it returns control to Wintab, the packet continues to be processed. If the nCode parameter is WTHC_SKIP, the hook func-tion should prepare to return the next recorded event message on its next call. The packet pointed to by lParam will have the same structure as packets re¬trieved from the context normally. Wintab will validate the following packet items to en¬sure consistency: context handle, time stamp, and serial number. The remaining fields will be valid if the context used for playback is equivalent to the context from which the events were recorded. The WTH_PLAYBACK hook will not be called to notify it of the display or re¬moval of system modal dialog boxes. It is expected that applications playing back packets will also be playing back window event messages using Windows' own hook functions. While the WTH_PLAYBACK function is in effect, Wintab ignores all hardware in-put. WTH_RECORD The interface calls the WTH_RECORD hook whenever it processes a packet from a context event queue. The hook can be used to record the packet for later playback. The hook function must have attributes equivalent to WINAPI. The hook function must have the following form: Hook Function LRESULT WINAPI HookFunc(nCode, wParam, lParam); int nCode; WPARAM wParam; LPARAM lParam; HookFunc is a place holder for the library-supplied function name. The actual name must be exported by including it in an EXPORTS statement in the library's mod¬ule-definition file. Parameter Description nCode Specifies whether the hook function should process the mes¬sage or call the WTMgrPacketHookDefProc (if installed by WTMgrPacketHook)or WTMgrPacketHookNext (if installed by WTMgrPacketHookEx) function. If the nCode parame¬ter is less than zero, the hook function should pass the message to the appropriate function without further process¬ing. wParam Specifies the context handle whose event is being processed. lParam Points to the packet being processed by the hook function. Comments The WTH_RECORD function should save a copy of the packet for later play¬back. It should not modify the packet. Once it returns control to Wintab, the message con-tinues to be processed. The filter function does not require a return value. The packet pointed to by lParam will have the same structure as packets re¬trieved from the context normally. The WTH_RECORD hook will not be called to notify it of the display or re¬moval of system modal dialog boxes. It is expected that applications recording packets will also be recording window event messages using Windows' own hook functions. 5.8.3 WTMgrPacketUnhook Syntax BOOL WTMgrPacketUnhook(hHook) This function removes a hook function installed by the WTMgrPacketHookEx function. Parameter Type/Description hHook HWTHOOK Identifies the hook function to be removed. Return Value The function returns a non-zero value if successful, zero otherwise. See Also The WTMgrPacketHookEx function in section 5.8.2, and the WTMgrPack-etHookNext function in section 5.8.5. 5.8.4 WTMgrPacketHookDefProc (16-bit only) Syntax LRESULT WTMgrPacketHookDefProc(nCode, wParam, lParam, lplpFunc) This function calls the next function in a chain of packet hook functions. A packet hook function is a function that processes packets before they are re¬trieved from a context's queue. When applications define more than one hook function by using the WTMgrPacketHook function, Wintab places func¬tions of the same type in a chain. Parameter Type/Description nCode int Specifies a code used by the hook function to determine how to process the message. wParam WPARAM Specifies the word parameter of the message that the hook function is processing. lParam LPARAM Specifies the long parameter of the message that the hook function is processing. lplpFunc WTHOOKPROC FAR * Points to a memory location that con-tains the WTHOOKPROC returned by the WTMgrPacketHook function. Wintab changes the value at this location after an appli-cation unhooks the hook using the WTMgrPacketHook function. Return Value The return value specifies a value that is directly related to the nCode parameter. Comments This function is non-portable and is superseded by the WTMgrPacketHookNext function. See Also The WTMgrPacketHookNext function in section 5.8.5. 5.8.5 WTMgrPacketHookNext Syntax LRESULT WTMgrPacketHookNext(hHook, nCode, wParam, lParam) This function passes the hook information to the next hook function in the current hook chain. Parameter Type/Description hHook HWTHOOK Identifies the current hook. nCode int Specifies the hook code passed to the current hook function. wParam WPARAM Specifies the wParam value
Table of Contents Header Files The #define Guard Header File Dependencies Inline Functions The -inl.h Files Function Parameter Ordering Names and Order of Includes Scoping Namespaces Nested Classes Nonmember, Static Member, and Global Functions Local Variables Static and Global Variables Classes Doing Work in Constructors Default Constructors Explicit Constructors Copy Constructors Structs vs. Classes Inheritance Multiple Inheritance Interfaces Operator Overloading Access Control Declaration Order Write Short Functions Google-Specific Magic Smart Pointers cpplint Other C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and Predecrement Use of const Integer Types 64-bit Portability Preprocessor Macros 0 and NULL sizeof Boost C++0x Naming General Naming Rules File Names Type Names Variable Names Constant Names Function Names Namespace Names Enumerator Names Macro Names Exceptions to Naming Rules Comments Comment Style File Comments Class Comments Function Comments Variable Comments Implementation Comments Punctuation, Spelling and Grammar TODO Comments Deprecation Comments Formatting Line Length Non-ASCII Characters Spaces vs. Tabs Function Declarations and Definitions Function Calls Conditionals Loops and Switch Statements Pointer and Reference Expressions Boolean Expressions Return Values Variable and Array Initialization Preprocessor Directives Class Format Constructor Initializer Lists Namespace Formatting Horizontal Whitespace Vertical Whitespace Exceptions to the Rules Existing Non-conformant Code Windows Code Important Note Displaying Hidden Details in this Guide link ▶This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below. Hooray! Now you know you can expand points to get more details. Alternatively, there's an "expand all" at the top of this document. Background C++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain. The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively. Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting. One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency. Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted. Open-source projects developed by Google conform to the requirements in this guide. Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language. Header Files In general, every .cc file should have an associated .h file. There are some common exceptions, such as unittests and small .cc files containing just a main() function. Correct use of header files can make a huge difference to the readability, size and performance of your code. The following rules will guide you through the various pitfalls of using header files. The #define Guard link ▶All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be ___H_. To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file foo/src/bar/baz.h in project foo should have the following guard: #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_ ... #endif // FOO_BAR_BAZ_H_ Header File Dependencies link ▶Don't use an #include when a forward declaration would suffice. When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, we prefer to minimize includes, particularly includes of header files in other header files. You can significantly minimize the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having to #include "file/base/file.h". How can we use a class Foo in a header file without access to its definition? We can declare data members of type Foo* or Foo&. We can declare (but not define) functions with arguments, and/or return values, of type Foo. (One exception is if an argument Foo or const Foo& has a non-explicit, one-argument constructor, in which case we need the full definition to support automatic type conversion.) We can declare static data members of type Foo. This is because static data members are defined outside the class definition. On the other hand, you must include the header file for Foo if your class subclasses Foo or has a data member of type Foo. Sometimes it makes sense to have pointer (or better, scoped_ptr) members instead of object members. However, this complicates code readability and imposes a performance penalty, so avoid doing this transformation if the only purpose is to minimize includes in header files. Of course, .cc files typically do require the definitions of the classes they use, and usually have to include several header files. Note: If you use a symbol Foo in your source file, you should bring in a definition for Foo yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if Foo is used in myfile.cc, it's ok to #include (or forward-declare) Foo in myfile.h, instead of myfile.cc. Inline Functions link ▶Define functions inline only when they are small, say, 10 lines or less. Definition: You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism. Pros: Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions. Cons: Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. Decision: A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls! Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed). It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators. The -inl.h Files link ▶You may use file names with a -inl.h suffix to define complex inline functions when needed. The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sites. However, implementation code properly belongs in .cc files, and we do not like to have much actual code in .h files unless there is a readability or performance advantage. If an inline function definition is short, with very little, if any, logic in it, you should put the code in your .h file. For example, accessors and mutators should certainly be inside a class definition. More complex inline functions may also be put in a .h file for the convenience of the implementer and callers, though if this makes the .h file too unwieldy you can instead put that code in a separate -inl.h file. This separates the implementation from the class definition, while still allowing the implementation to be included where necessary. Another use of -inl.h files is for definitions of function templates. This can be used to keep your template definitions easy to read. Do not forget that a -inl.h file requires a #define guard just like any other header file. Function Parameter Ordering link ▶When defining a function, parameter order is: inputs, then outputs. Parameters to C/C++ functions are either input to the function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will be non-const pointers. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. Parameters that are both input and output (often classes/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule. Names and Order of Includes link ▶Use standard order for readability and to avoid hidden dependencies: C library, C++ library, other libraries' .h, your project's .h. All of a project's header files should be listed as descentants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory). For example, google-awesome-project/src/base/logging.h should be included as #include "base/logging.h" In dir/foo.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows: dir2/foo2.h (preferred location — see details below). C system files. C++ system files. Other libraries' .h files. Your project's .h files. The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The easiest way to achieve this is to make sure that every one of them is the first .h file #included in some .cc. dir/foo.cc and dir2/foo2.h are often in the same directory (e.g. base/basictypes_test.cc and base/basictypes.h), but can be in different directories too. Within each section it is nice to order the includes alphabetically. For example, the includes in google-awesome-project/src/foo/internal/fooserver.cc might look like this: #include "foo/public/fooserver.h" // Preferred location. #include #include #include #include #include "base/basictypes.h" #include "base/commandlineflags.h" #include "foo/public/bar.h" Scoping Namespaces link ▶Unnamed namespaces in .cc files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a using-directive. Definition: Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope. Pros: Namespaces provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. For example, if two different projects have a class Foo in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, project1::Foo and project2::Foo are now distinct symbols that do not collide. Cons: Namespaces can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. Use of unnamed spaces in header files can easily cause violations of the C++ One Definition Rule (ODR). Decision: Use namespaces according to the policy described below. Unnamed Namespaces Unnamed namespaces are allowed and even encouraged in .cc files, to avoid runtime naming conflicts: namespace { // This is in a .cc file. // The content of a namespace is not indented enum { kUnused, kEOF, kError }; // Commonly used tokens. bool AtEof() { return pos_ == kEOF; } // Uses our namespace's EOF. } // namespace However, file-scope declarations that are associated with a particular class may be declared in that class as types, static data members or static member functions rather than as members of an unnamed namespace. Terminate the unnamed namespace as shown, with a comment // namespace. Do not use unnamed namespaces in .h files. Named Namespaces Named namespaces should be used as follows: Namespaces wrap the entire source file after includes, gflags definitions/declarations, and forward declarations of classes from other namespaces: // In the .h file namespace mynamespace { // All declarations are within the namespace scope. // Notice the lack of indentation. class MyClass { public: ... void Foo(); }; } // namespace mynamespace // In the .cc file namespace mynamespace { // Definition of functions is within scope of the namespace. void MyClass::Foo() { ... } } // namespace mynamespace The typical .cc file might have more complex detail, including the need to reference classes in other namespaces. #include "a.h" DEFINE_bool(someflag, false, "dummy flag"); class C; // Forward declaration of class C in the global namespace. namespace a { class A; } // Forward declaration of a::A. namespace b { ...code for b... // Code goes against the left margin. } // namespace b Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file. You may not use a using-directive to make all names from a namespace available. // Forbidden -- This pollutes the namespace. using namespace foo; You may use a using-declaration anywhere in a .cc file, and in functions, methods or classes in .h files. // OK in .cc files. // Must be in a function, method or class in .h files. using ::foo::bar; Namespace aliases are allowed anywhere in a .cc file, anywhere inside the named namespace that wraps an entire .h file, and in functions and methods. // Shorten access to some commonly used names in .cc files. namespace fbz = ::foo::bar::baz; // Shorten access to some commonly used names (in a .h file). namespace librarian { // The following alias is available to all files including // this header (in namespace librarian): // alias names should therefore be chosen consistently // within a project. namespace pd_s = ::pipeline_diagnostics::sidetable; inline void my_inline_function() { // namespace alias local to a function (or method). namespace fbz = ::foo::bar::baz; ... } } // namespace librarian Note that an alias in a .h file is visible to everyone #including that file, so public headers (those available outside a project) and headers transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible. Nested Classes link ▶Although you may use public nested classes when they are part of an interface, consider a namespace to keep declarations out of the global scope. Definition: A class can define another class within it; this is also called a member class. class Foo { private: // Bar is a member class, nested within Foo. class Bar { ... }; }; Pros: This is useful when the nested (or member) class is only used by the enclosing class; making it a member puts it in the enclosing class scope rather than polluting the outer scope with the class name. Nested classes can be forward declared within the enclosing class and then defined in the .cc file to avoid including the nested class definition in the enclosing class declaration, since the nested class definition is usually only relevant to the implementation. Cons: Nested classes can be forward-declared only within the definition of the enclosing class. Thus, any header file manipulating a Foo::Bar* pointer will have to include the full class declaration for Foo. Decision: Do not make nested classes public unless they are actually part of the interface, e.g., a class that holds a set of options for some method. Nonmember, Static Member, and Global Functions link ▶Prefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely. Pros: Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace. Cons: Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies. Decision: Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead. Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library. If you must define a nonmember function and it is only needed in its .cc file, use an unnamed namespace or static linkage (eg static int Foo() {...}) to limit its scope. Local Variables link ▶Place a function's variables in the narrowest scope possible, and initialize variables in the declaration. C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g. int i; i = f(); // Bad -- initialization separate from declaration. int j = g(); // Good -- declaration has initialization. Note that gcc implements for (int i = 0; i < 10; ++i) correctly (the scope of i is only the scope of the for loop), so you can then reuse i in another for loop in the same scope. It also correctly scopes declarations in if and while statements, e.g. while (const char* p = strchr(str, '/')) str = p + 1; There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope. // Inefficient implementation: for (int i = 0; i < 1000000; ++i) { Foo f; // My ctor and dtor get called 1000000 times each. f.DoSomething(i); } It may be more efficient to declare such a variable used in a loop outside that loop: Foo f; // My ctor and dtor get called once each. for (int i = 0; i < 1000000; ++i) { f.DoSomething(i); } Static and Global Variables link ▶Static or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and destruction. Objects with static storage duration, including global variables, static variables, static class member variables, and function static variables, must be Plain Old Data (POD): only ints, chars, floats, or pointers, or arrays/structs of POD. The order in which class constructors and initializers for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class type, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals. Likewise, the order in which destructors are called is defined to be the reverse of the order in which the constructors were called. Since constructor order is indeterminate, so is destructor order. For example, at program-end time a static variable might have been destroyed, but code still running -- perhaps in another thread -- tries to access it and fails. Or the destructor for a static 'string' variable might be run prior to the destructor for another variable that contains a reference to that string. As a result we only allow static variables to contain POD data. This rule completely disallows vector (use C arrays instead), or string (use const char []). If you need a static or global variable of a class type, consider initializing a pointer (which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw pointer, not a "smart" pointer, since the smart pointer's destructor will have the order-of-destructor issue that we are trying to avoid. Classes Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class. Doing Work in Constructors link ▶In general, constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. Definition: It is possible to perform initialization in the body of the constructor. Pros: Convenience in typing. No need to worry about whether the class has been initialized or not. Cons: The problems with doing work in constructors are: There is no easy way for constructors to signal errors, short of using exceptions (which are forbidden). If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state. If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion. If someone creates a global variable of this type (which is against the rules, but still), the constructor code will be called before main(), possibly breaking some implicit assumptions in the constructor code. For instance, gflags will not yet have been initialized. Decision: If your object requires non-trivial initialization, consider having an explicit Init() method. In particular, constructors should not call virtual functions, attempt to raise errors, access potentially uninitialized global variables, etc. Default Constructors link ▶You must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly. Definition: The default constructor is called when we new a class object with no arguments. It is always called when calling new[] (for arrays). Pros: Initializing structures by default, to hold "impossible" values, makes debugging much easier. Cons: Extra work for you, the code writer. Decision: If your class defines member variables and has no other constructors you must define a default constructor (one that takes no arguments). It should preferably initialize the object in such a way that its internal state is consistent and valid. The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly. If your class inherits from an existing class but you add no new member variables, you are not required to have a default constructor. Explicit Constructors link ▶Use the C++ keyword explicit for constructors with one argument. Definition: Normally, if a constructor takes one argument, it can be used as a conversion. For instance, if you define Foo::Foo(string name) and then pass a string to a function that expects a Foo, the constructor will be called to convert the string into a Foo and will pass the Foo to your function for you. This can be convenient but is also a source of trouble when things get converted and new objects created without you meaning them to. Declaring a constructor explicit prevents it from being invoked implicitly as a conversion. Pros: Avoids undesirable conversions. Cons: None. Decision: We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the class definition: explicit Foo(string name); The exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments. Copy Constructors link ▶Provide a copy constructor and assignment operator only when necessary. Otherwise, disable them with DISALLOW_COPY_AND_ASSIGN. Definition: The copy constructor and assignment operator are used to create copies of objects. The copy constructor is implicitly invoked by the compiler in some situations, e.g. passing objects by value. Pros: Copy constructors make it easy to copy objects. STL containers require that all contents be copyable and assignable. Copy constructors can be more efficient than CopyFrom()-style workarounds because they combine construction with copying, the compiler can elide them in some contexts, and they make it easier to avoid heap allocation. Cons: Implicit copying of objects in C++ is a rich source of bugs and of performance problems. It also reduces readability, as it becomes hard to track which objects are being passed around by value as opposed to by reference, and therefore where changes to an object are reflected. Decision: Few classes need to be copyable. Most should have neither a copy constructor nor an assignment operator. In many situations, a pointer or reference will work just as well as a copied value, with better performance. For example, you can pass function parameters by reference or pointer instead of by value, and you can store pointers rather than objects in an STL container. If your class needs to be copyable, prefer providing a copy method, such as CopyFrom() or Clone(), rather than a copy constructor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your class needs to be stored by value in an STL container), provide both a copy constructor and assignment operator. If your class does not need a copy constructor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy constructor and assignment operator in the private: section of your class, but do not provide any corresponding definition (so that any attempt to use them results in a link error). For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used: // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) Then, in class Foo: class Foo { public: Foo(int f); ~Foo(); private: DISALLOW_COPY_AND_ASSIGN(Foo); }; Structs vs. Classes link ▶Use a struct only for passive objects that carry data; everything else is a class. The struct and class keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-type you're defining. structs should be used for passive objects that carry data, and may have associated constants, but lack any functionality other than access/setting the data members. The accessing/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., constructor, destructor, Initialize(), Reset(), Validate(). If more functionality is required, a class is more appropriate. If in doubt, make it a class. For consistency with STL, you can use struct instead of class for functors and traits. Note that member variables in structs and classes have different naming rules. Inheritance link ▶Composition is often more appropriate than inheritance. When using inheritance, make it public. Definition: When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and interface inheritance, in which only method names are inherited. Pros: Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API. Cons: For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. The base class may also define some data members, so that specifies physical layout of the base class. Decision: All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead. Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: Bar subclasses Foo if it can reasonably be said that Bar "is a kind of" Foo. Make your destructor virtual if necessary. If your class has virtual methods, its destructor should be virtual. Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that data members should be private. When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived class. Rationale: If virtual is omitted, the reader has to check all ancestors of the class in question to determine if the function is virtual or not. Multiple Inheritance link ▶Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be pure interface classes tagged with the Interface suffix. Definition: Multiple inheritance allows a sub-class to have more than one base class. We distinguish between base classes that are pure interfaces and those that have an implementation. Pros: Multiple implementation inheritance may let you re-use even more code than single inheritance (see Inheritance). Cons: Only very rarely is multiple implementation inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution. Decision: Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are pure interfaces. In order to ensure that they remain pure interfaces, they must end with the Interface suffix. Note: There is an exception to this rule on Windows. Interfaces link ▶Classes that satisfy certain conditions are allowed, but not required, to end with an Interface suffix. Definition: A class is a pure interface if it meets the following requirements: It has only public pure virtual ("= 0") methods and static methods (but see below for destructor). It may not have non-static data members. It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected. If it is a subclass, it may only be derived from classes that satisfy these conditions and are tagged with the Interface suffix. An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed correctly, they must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See Stroustrup, The C++ Programming Language, 3rd edition, section 12.4 for details. Pros: Tagging a class with the Interface suffix lets others know that they must not add implemented methods or non static data members. This is particularly important in the case of multiple inheritance. Additionally, the interface concept is already well-understood by Java programmers. Cons: The Interface suffix lengthens the class name, which can make it harder to read and understand. Also, the interface property may be considered an implementation detail that shouldn't be exposed to clients. Decision: A class may end with Interface only if it meets the above requirements. We do not require the converse, however: classes that meet the above requirements are not required to end with Interface. Operator Overloading link ▶Do not overload operators except in rare, special circumstances. Definition: A class can define that operators such as + and / operate on the class as if it were a built-in type. Pros: Can make code appear more intuitive because a class will behave in the same way as built-in types (such as int). Overloaded operators are more playful names for functions that are less-colorfully named, such as Equals() or Add(). For some template functions to work correctly, you may need to define operators. Cons: While operator overloading can make code more intuitive, it has several drawbacks: It can fool our intuition into thinking that expensive operations are cheap, built-in operations. It is much harder to find the call sites for overloaded operators. Searching for Equals() is much easier than searching for relevant invocations of ==. Some operators work on pointers too, making it easy to introduce bugs. Foo + 4 may do one thing, while &Foo + 4 does something totally different. The compiler does not complain for either of these, making this very hard to debug. Overloading also has surprising ramifications. For instance, if a class overloads unary operator&, it cannot safely be forward-declared. Decision: In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them. Likewise, avoid the dangerous unary operator& at all costs, if there's any possibility the class might be forward-declared. However, there may be rare cases where you need to overload an operator to interoperate with templates or "standard" C++ classes (such as operator<<(ostream&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container. Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why. See also Copy Constructors and Function Overloading. Access Control link ▶Make data members private, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class to be protected when using Google Test). Typically a variable would be called foo_ and the accessor function foo(). You may also want a mutator function set_foo(). Exception: static const data members (typically called kFoo) need not be private. The definitions of accessors are usually inlined in the header file. See also Inheritance and Function Names. Declaration Order link ▶Use the specified order of declarations within a class: public: before private:, methods before data members (variables), etc. Your class definition should start with its public: section, followed by its protected: section and then its private: section. If any of these sections are empty, omit them. Within each section, the declarations generally should be in the following order: Typedefs and Enums Constants (static const data members) Constructors Destructor Methods, including static methods Data Members (except static const data members) Friend declarations should always be in the private section, and the DISALLOW_COPY_AND_ASSIGN macro invocation should be at the end of the private: section. It should be the last thing in the class. See Copy Constructors. Method definitions in the corresponding .cc file should be the same as the declaration order, as much as possible. Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See Inline Functions for more details. Write Short Functions link ▶Prefer small and focused functions. We recognize that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program. Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code. You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces. Google-Specific Magic There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere. Smart Pointers link ▶If you actually need pointer semantics, scoped_ptr is great. You should only use std::tr1::shared_ptr under very specific conditions, such as when objects need to be held by STL containers. You should never use auto_ptr. "Smart" pointers are objects that act like pointers but have added semantics. When a scoped_ptr is destroyed, for instance, it deletes the object it's pointing to. shared_ptr is the same way, but implements reference-counting so only the last pointer to an object deletes it. Generally speaking, we prefer that we design code with clear object ownership. The clearest object ownership is obtained by using an object directly as a field or local variable, without using pointers at all. On the other extreme, by their very definition, reference counted pointers are owned by nobody. The problem with this design is that it is easy to create circular references or other strange conditions that cause an object to never be deleted. It is also slow to perform atomic operations every time a value is copied or assigned. Although they are not recommended, reference counted pointers are sometimes the simplest and most elegant way to solve a problem. cpplint link ▶Use cpplint.py to detect style errors. cpplint.py is a tool that reads a source file and identifies many style errors. It is not perfect, and has both false positives and false negatives, but it is still a valuable tool. False positives can be ignored by putting // NOLINT at the end of the line. Some projects have instructions on how to run cpplint.py from their project tools. If the project you are contributing to does not, you can download cpplint.py separately. Other C++ Features Reference Arguments link ▶All parameters passed by reference must be labeled const. Definition: In C, if a function needs to modify a variable, the parameter must use a pointer, eg int foo(int *pval). In C++, the function can alternatively declare a reference parameter: int foo(int &val). Pros: Defining a parameter as reference avoids ugly code like (*pval)++. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that NULL is not a possible value. Cons: References can be confusing, as they have value syntax but pointer semantics. Decision: Within function parameter lists all references must be const: void Foo(const string &in, string *out); In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters. One case when you might want an input parameter to be a const pointer is if you want to emphasize that the argument is not copied, so it must exist for the lifetime of the object; it is usually best to document this in comments as well. STL adapters such as bind2nd and mem_fun do not permit reference parameters, so you must declare functions with pointer parameters in these cases, too. Function Overloading link ▶Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called. Definition: You may write a function that takes a const string& and overload it with another that takes const char*. class MyClass { public: void Analyze(const string &text); void Analyze(const char *text, size_t textlen); }; Pros: Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors. Cons: If a function is overloaded by the argument types alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function. Decision: If you want to overload a function, consider qualifying the name with some information about the arguments, e.g., AppendString(), AppendInt() rather than just Append(). Default Arguments link ▶We do not allow default function parameters, except in a few uncommon situations explained below. Pros: Often you have a function that uses lots of default values, but occasionally you want to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions. Cons: People often figure out how to use an API by looking at existing code that uses it. Default parameters are more difficult to maintain because copy-and-paste from previous code may not reveal all the parameters. Copy-and-pasting of code segments can cause major problems when the default arguments are not appropriate for the new code. Decision: Except as described below, we require all arguments to be explicitly specified, to force programmers to consider the API and the values they are passing for each argument rather than silently accepting defaults they may not be aware of. One specific exception is when default arguments are used to simulate variable-length argument lists. // Support up to 4 params by using a default empty AlphaNum. string StrCat(const AlphaNum &a, const AlphaNum &b = gEmptyAlphaNum, const AlphaNum &c = gEmptyAlphaNum, const AlphaNum &d = gEmptyAlphaNum); Variable-Length Arrays and alloca() link ▶We do not allow variable-length arrays or alloca(). Pros: Variable-length arrays have natural-looking syntax. Both variable-length arrays and alloca() are very efficient. Cons: Variable-length arrays and alloca are not part of Standard C++. More importantly, they allocate a data-dependent amount of stack space that can trigger difficult-to-find memory overwriting bugs: "It ran fine on my machine, but dies mysteriously in production". Decision: Use a safe allocator instead, such as scoped_ptr/scoped_array. Friends link ▶We allow use of friend classes and functions, within reason. Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of friend is to have a FooBuilder class be a friend of Foo so that it can construct the inner state of Foo correctly, without exposing this state to the world. In some cases it may be useful to make a unittest class a friend of the class it tests. Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is better than making a member public when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members. Exceptions link ▶We do not use C++ exceptions. Pros: Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes. Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with. Some third-party C++ libraries use exceptions, and turning them off internally makes it harder to integrate with those libraries. Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an Init() method, but these require heap allocation or a new "invalid" state, respectively. Exceptions are really handy in testing frameworks. Cons: When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program terminating as a result. For instance, if f() calls g() calls h(), and h throws an exception that f catches, g has to be careful or it may not clean up properly. More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don't expect. This causes maintainability and debugging difficulties. You can minimize this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand. Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it. Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure. The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document these restrictions! Decision: On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions. Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden. Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch. There is an exception to this rule (no pun intended) for Windows code. Run-Time Type Information (RTTI) link ▶We do not use Run Time Type Information (RTTI). Definition: RTTI allows a programmer to query the C++ class of an object at run time. Pros: It is useful in some unittests. For example, it is useful in tests of factory classes where the test has to verify that a newly created object has the expected dynamic type. In rare circumstances, it is useful even outside of tests. Cons: A query of type during run-time typically means a design problem. If you need to know the type of an object at runtime, that is often an indication that you should reconsider the design of your class. Decision: Do not use RTTI, except in unittests. If you find yourself in need of writing code that behaves differently based on the class of an object, consider one of the alternatives to querying the type. Virtual methods are the preferred way of executing different code paths depending on a specific subclass type. This puts the work within the object itself. If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system. If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. :-) Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags. Casting link ▶Use C++ casts like static_cast(). Do not use other cast formats like int y = (int)x; or int y = int(x);. Definition: C++ introduced a different cast system from C that distinguishes the types of cast operations. Pros: The problem with C casts is the ambiguity of the operation; sometimes you are doing a conversion (e.g., (int)3.5) and sometimes you are doing a cast (e.g., (int)"hello"); C++ casts avoid this. Additionally C++ casts are more visible when searching for them. Cons: The syntax is nasty. Decision: Do not use C-style casts. Instead, use these C++-style casts. Use static_cast as the equivalent of a C-style cast that does value conversion, or when you need to explicitly up-cast a pointer from a class to its superclass. Use const_cast to remove the const qualifier (see const). Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if you know what you are doing and you understand the aliasing issues. Do not use dynamic_cast except in test code. If you need to know type information at runtime in this way outside of a unittest, you probably have a design flaw. Streams link ▶Use streams only for logging. Definition: Streams are a replacement for printf() and scanf(). Pros: With streams, you do not need to know the type of the object you are printing. You do not have problems with format strings not matching the argument list. (Though with gcc, you do not have that problem with printf either.) Streams have automatic constructors and destructors that open and close the relevant files. Cons: Streams make it difficult to do functionality like pread(). Some formatting (particularly the common format string idiom %.*s) is difficult if not impossible to do efficiently using streams without using printf-like hacks. Streams do not support operator reordering (the %1s directive), which is helpful for internationalization. Decision: Do not use streams, except where required by a logging interface. Use printf-like routines instead. There are various pros and cons to using streams, but in this case, as in many other cases, consistency trumps the debate. Do not use streams in your code. Extended Discussion There has been debate on this issue, so this explains the reasoning in greater depth. Recall the Only One Way guiding principle: we want to make sure that whenever we do a certain type of I/O, the code looks the same in all those places. Because of this, we do not want to allow users to decide between using streams or using printf plus Read/Write/etc. Instead, we should settle on one or the other. We made an exception for logging because it is a pretty specialized application, and for historical reasons. Proponents of streams have argued that streams are the obvious choice of the two, but the issue is not actually so clear. For every advantage of streams they point out, there is an equivalent disadvantage. The biggest advantage is that you do not need to know the type of the object to be printing. This is a fair point. But, there is a downside: you can easily use the wrong type, and the compiler will not warn you. It is easy to make this kind of mistake without knowing when using streams. cout << this; // Prints the address cout << *this; // Prints the contents The compiler does not generate an error because << has been overloaded. We discourage overloading for just this reason. Some say printf formatting is ugly and hard to read, but streams are often no better. Consider the following two fragments, both with the same typo. Which is easier to discover? cerr << "Error connecting to '" hostname.first << ":" hostname.second << ": " hostname.first, foo->bar()->hostname.second, strerror(errno)); And so on and so forth for any issue you might bring up. (You could argue, "Things would be better with the right wrappers," but if it is true for one scheme, is it not also true for the other? Also, remember the goal is to make the language smaller, not add yet more machinery that someone has to learn.) Either path would yield different advantages and disadvantages, and there is not a clearly superior solution. The simplicity doctrine mandates we settle on one of them though, and the majority decision was on printf + read/write. Preincrement and Predecrement link ▶Use prefix form (++i) of the increment and decrement operators with iterators and other template objects. Definition: When a variable is incremented (++i or i++) or decremented (--i or i--) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement). Pros: When the return value is ignored, the "pre" form (++i) is never less efficient than the "post" form (i++), and is often more efficient. This is because post-increment (or decrement) requires a copy of i to be made, which is the value of the expression. If i is an iterator or other non-scalar type, copying i could be expensive. Since the two types of increment behave the same when the value is ignored, why not just always pre-increment? Cons: The tradition developed, in C, of using post-increment when the expression value is not used, especially in for loops. Some find post-increment easier to read, since the "subject" (i) precedes the "verb" (++), just like in English. Decision: For simple scalar (non-object) values there is no reason to prefer one form and we allow either. For iterators and other template types, use pre-increment. Use of const link ▶We strongly recommend that you use const whenever it makes sense to do so. Definition: Declared variables and parameters can be preceded by the keyword const to indicate the variables are not changed (e.g., const int foo). Class functions can have the const qualifier to indicate the function does not change the state of the class member variables (e.g., class Foo { int Bar(char c) const; };). Pros: Easier for people to understand how variables are being used. Allows the compiler to do better type checking, and, conceivably, generate better code. Helps people convince themselves of program correctness because they know the functions they call are limited in how they can modify your variables. Helps people know what functions are safe to use without locks in multi-threaded programs. Cons: const is viral: if you pass a const variable to a function, that function must have const in its prototype (or the variable will need a const_cast). This can be a particular problem when calling library functions. Decision: const variables, data members, methods and arguments add a level of compile-time type checking; it is better to detect errors as soon as possible. Therefore we strongly recommend that you use const whenever it makes sense to do so: If a function does not modify an argument passed by reference or by pointer, that argument should be const. Declare methods to be const whenever possible. Accessors should almost always be const. Other methods should be const if they do not modify any data members, do not call any non-const methods, and do not return a non-const pointer or non-const reference to a data member. Consider making data members const whenever they do not need to be modified after construction. However, do not go crazy with const. Something like const int * const * const x; is likely overkill, even if it accurately describes how const x is. Focus on what's really useful to know: in this case, const int** x is probably sufficient. The mutable keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first. Where to put the const Some people favor the form int const *foo to const int* foo. They argue that this is more readable because it's more consistent: it keeps the rule that const always follows the object it's describing. However, this consistency argument doesn't apply in this case, because the "don't go crazy" dictum eliminates most of the uses you'd have to be consistent with. Putting the const first is arguably more readable, since it follows English in putting the "adjective" (const) before the "noun" (int). That said, while we encourage putting const first, we do not require it. But be consistent with the code around you! Integer Types link ▶Of the built-in C++ integer types, the only one used is int. If a program needs a variable of a different size, use a precise-width integer type from , such as int16_t. Definition: C++ does not specify the sizes of its integer types. Typically people assume that short is 16 bits, int is 32 bits, long is 32 bits and long long is 64 bits. Pros: Uniformity of declaration. Cons: The sizes of integral types in C++ can vary based on compiler and architecture. Decision: defines types like int16_t, uint32_t, int64_t, etc. You should always use those in preference to short, unsigned long long and the like, when you need a guarantee on the size of an integer. Of the C integer types, only int should be used. When appropriate, you are welcome to use standard types like size_t and ptrdiff_t. We use int very often, for integers we know are not going to be too big, e.g., loop counters. Use plain old int for such things. You should assume that an int is at least 32 bits, but don't assume that it has more than 32 bits. If you need a 64-bit integer type, use int64_t or uint64_t. For integers we know can be "big", use int64_t. You should not use the unsigned integer types such as uint32_t, unless the quantity you are representing is really a bit pattern rather than a number, or unless you need defined twos-complement overflow. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this. On Unsigned Integers Some people, including some textbook authors, recommend using unsigned types to represent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider: for (unsigned int i = foo.Length()-1; i >= 0; --i) ... This code will never terminate! Sometimes gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variables. Basically, C's type-promotion scheme causes unsigned types to behave differently than one might expect. So, document that a variable is non-negative using assertions. Don't use an unsigned type. 64-bit Portability link ▶Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing, comparisons, and structure alignment. printf() specifiers for some types are not cleanly portable between 32-bit and 64-bit systems. C99 defines some portable format specifiers. Unfortunately, MSVC 7.1 does not understand some of these specifiers and the standard is missing a few, so we have to define our own ugly versions in some cases (in the style of the standard include file inttypes.h): // printf macros for size_t, in the style of inttypes.h #ifdef _LP64 #define __PRIS_PREFIX "z" #else #define __PRIS_PREFIX #endif // Use these macros after a % in a printf format string // to get correct 32/64 bit behavior, like this: // size_t size = records.size(); // printf("%"PRIuS"\n", size); #define PRIdS __PRIS_PREFIX "d" #define PRIxS __PRIS_PREFIX "x" #define PRIuS __PRIS_PREFIX "u" #define PRIXS __PRIS_PREFIX "X" #define PRIoS __PRIS_PREFIX "o" Type DO NOT use DO use Notes void * (or any pointer) %lx %p int64_t %qd, %lld %"PRId64" uint64_t %qu, %llu, %llx %"PRIu64", %"PRIx64" size_t %u %"PRIuS", %"PRIxS" C99 specifies %zu ptrdiff_t %d %"PRIdS" C99 specifies %zd Note that the PRI* macros expand to independent strings which are concatenated by the compiler. Hence if you are using a non-constant format string, you need to insert the value of the macro into the format, rather than the name. It is still possible, as usual, to include length specifiers, etc., after the % when using the PRI* macros. So, e.g. printf("x = %30"PRIuS"\n", x) would expand on 32-bit Linux to printf("x = %30" "u" "\n", x), which the compiler will treat as printf("x = %30u\n", x). Remember that sizeof(void *) != sizeof(int). Use intptr_t if you want a pointer-sized integer. You may need to be careful with structure alignments, particularly for structures being stored on disk. Any class/structure with a int64_t/uint64_t member will by default end up being 8-byte aligned on a 64-bit system. If you have such structures being shared on disk between 32-bit and 64-bit code, you will need to ensure that they are packed the same on both architectures. Most compilers offer a way to alter structure alignment. For gcc, you can use __attribute__((packed)). MSVC offers #pragma pack() and __declspec(align()). Use the LL or ULL suffixes a
实现 图片的放大,缩小,左右屏幕滑动 。 直接贴代码吧。。 public class ViewPager extends ViewGroup { private static final String TAG = "ViewPager"; private static final boolean DEBUG = false; private static final boolean USE_CACHE = false; private static final int DEFAULT_OFFSCREEN_PAGES = 1; private static final int MAX_SETTLE_DURATION = 600; // ms private static final int PAGER_NEXT_MARGIN_DP = 40; static class ItemInfo { Object object; int position; boolean scrolling; } private static final Comparator COMPARATOR = new Comparator() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return lhs.position - rhs.position; } }; private static final Interpolator sInterpolator = new Interpolator() { public float getInterpolation(float t) { // _o(t) = t * t * ((tension + 1) * t + tension) // o(t) = _o(t - 1) + 1 t -= 1.0f; return t * t * t + 1.0f; } }; private final ArrayList mItems = new ArrayList(); private PagerAdapter mAdapter; private int mCurItem; // Index of currently displayed page. private int mRestoredCurItem = -1; private Parcelable mRestoredAdapterState = null; private ClassLoader mRestoredClassLoader = null; private Scroller mScroller; private PagerAdapter.DataSetObserver mObserver; private int mPageMargin; private Drawable mMarginDrawable; private int mChildWidthMeasureSpec; private int mChildHeightMeasureSpec; private boolean mInLayout; private boolean mScrollingCacheEnabled; private boolean mPopulatePending; private boolean mScrolling; private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES; private boolean mIsBeingDragged; private boolean mIsUnableToDrag; private int mTouchSlop; private float mInitialMotionX; /** * Position of the last motion event. */ private float mLastMotionX; private float mLastMotionY; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ private int mActivePointerId = INVALID_POINTER; /** * Sentinel value for no current active pointer. Used by * {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; /** * Determines speed during touch scrolling */ private VelocityTracker mVelocityTracker; private int mMinimumVelocity; private int mMaximumVelocity; private float mBaseLineFlingVelocity; private float mFlingVelocityInfluence; private int mPagerNextMarginPixels; private boolean mFakeDragging; private long mFakeDragBeginTime; private EdgeEffectCompat mLeftEdge; private EdgeEffectCompat mRightEdge; private boolean mFirstLayout = true; private OnPageChangeListener mOnPageChangeListener; /** * Indicates that the pager is in an idle, settled state. The current page * is fully in view and no animation is in progress. */ public static final int SCROLL_STATE_IDLE = 0; /** * Indicates that the pager is currently being dragged by the user. */ public static final int SCROLL_STATE_DRAGGING = 1; /** * Indicates that the pager is in the process of settling to a final * position. */ public static final int SCROLL_STATE_SETTLING = 2; private int mScrollState = SCROLL_STATE_IDLE; /** * Callback interface for responding to changing state of the selected page. */ public interface OnPageChangeListener { /** * This method will be invoked when the current page is scrolled, either * as part of a programmatically initiated smooth scroll or a user * initiated touch scroll. * * @param position * Position index of the first page currently being * displayed. Page position+1 will be visible if * positionOffset is nonzero. * @param positionOffset * Value from [0, 1) indicating the offset from the page at * position. * @param positionOffsetPixels * Value in pixels indicating the offset from position. */ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); /** * This method will be invoked when a new page becomes selected. * Animation is not necessarily complete. * * @param position * Position index of the new selected page. */ public void onPageSelected(int position, int prePosition); /** * Called when the scroll state changes. Useful for discovering when the * user begins dragging, when the pager is automatically settling to the * current page, or when it is fully stopped/idle. * * @param state * The new scroll state. * @see ViewPager#SCROLL_STATE_IDLE * @see ViewPager#SCROLL_STATE_DRAGGING * @see ViewPager#SCROLL_STATE_SETTLING */ public void onPageScrollStateChanged(int state); } /** * Simple implementation of the {@link OnPageChangeListener} interface with * stub implementations of each method. Extend this if you do not intend to * override every method of {@link OnPageChangeListener}. */ public static class SimpleOnPageChangeListener implements OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // This space for rent } @Override public void onPageSelected(int position, int prePosition) { // This space for rent } @Override public void onPageScrollStateChanged(int state) { // This space for rent } } public ViewPager(Context context) { super(context); initViewPager(); } public ViewPager(Context context, AttributeSet attrs) { super(context, attrs); initViewPager(); } void initViewPager() { setWillNotDraw(false); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setFocusable(true); final Context context = getContext(); mScroller = new Scroller(context, sInterpolator); final ViewConfiguration configuration = ViewConfiguration.get(context); mTouchSlop = ViewConfigurationCompat .getScaledPagingTouchSlop(configuration); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mLeftEdge = new EdgeEffectCompat(context); mRightEdge = new EdgeEffectCompat(context); float density = context.getResources().getDisplayMetrics().density; mBaseLineFlingVelocity = 2500.0f * density; mFlingVelocityInfluence = 0.4f; final float scale = getResources().getDisplayMetrics().density; mPagerNextMarginPixels = (int) (PAGER_NEXT_MARGIN_DP * scale + 0.5f); } private void setScrollState(int newState) { if (mScrollState == newState) { return; } mScrollState = newState; if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrollStateChanged(newState); } } public void setAdapter(PagerAdapter adapter) { if (mAdapter != null) { mAdapter.setDataSetObserver(null); mAdapter.startUpdate(this); for (int i = 0; i < mItems.size(); i++) { final ItemInfo ii = mItems.get(i); mAdapter.destroyItem(this, ii.position, ii.object); } mAdapter.finishUpdate(this); mItems.clear(); removeAllViews(); mCurItem = 0; scrollTo(0, 0); } mAdapter = adapter; if (mAdapter != null) { if (mObserver == null) { mObserver = new DataSetObserver(); } mAdapter.setDataSetObserver(mObserver); mPopulatePending = false; if (mRestoredCurItem >= 0) { mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader); setCurrentItemInternal(mRestoredCurItem, false, true); mRestoredCurItem = -1; mRestoredAdapterState = null; mRestoredClassLoader = null; } else { populate(); } } } public PagerAdapter getAdapter() { return mAdapter; } /** * Set the currently selected page. If the ViewPager has already been * through its first layout there will be a smooth animated transition * between the current item and the specified item. * * @param item * Item index to select */ public void setCurrentItem(int item) { mPopulatePending = false; setCurrentItemInternal(item, !mFirstLayout, false); } /** * Set the currently selected page. * * @param item * Item index to select * @param smoothScroll * True to smoothly scroll to the new item, false to transition * immediately */ public void setCurrentItem(int item, boolean smoothScroll) { mPopulatePending = false; setCurrentItemInternal(item, smoothScroll, false); } public int getCurrentItem() { return mCurItem; } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { setCurrentItemInternal(item, smoothScroll, always, 0); } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) { int preItem = mCurItem; if (mAdapter == null || mAdapter.getCount() <= 0) { setScrollingCacheEnabled(false); return; } if (!always && mCurItem == item && mItems.size() != 0) { setScrollingCacheEnabled(false); return; } if (item < 0) { item = 0; } else if (item >= mAdapter.getCount()) { item = mAdapter.getCount() - 1; } final int pageLimit = mOffscreenPageLimit; if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) { // We are doing a jump by more than one page. To avoid // glitches, we want to keep all current pages in the view // until the scroll ends. for (int i = 0; i < mItems.size(); i++) { mItems.get(i).scrolling = true; } } final boolean dispatchSelected = mCurItem != item; mCurItem = item; populate(); final int destX = (getWidth() + mPageMargin) * item; if (smoothScroll) { smoothScrollTo(destX, 0, velocity); if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item, preItem); } } else { if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item, preItem); } completeScroll(); scrollTo(destX, 0); } } public void setOnPageChangeListener(OnPageChangeListener listener) { mOnPageChangeListener = listener; } /** * Returns the number of pages that will be retained to either side of the * current page in the view hierarchy in an idle state. Defaults to 1. * * @return How many pages will be kept offscreen on either side * @see #setOffscreenPageLimit(int) */ public int getOffscreenPageLimit() { return mOffscreenPageLimit; } /** * Set the number of pages that should be retained to either side of the * current page in the view hierarchy in an idle state. Pages beyond this * limit will be recreated from the adapter when needed. * *

* This is offered as an optimization. If you know in advance the number of * pages you will need to support or have lazy-loading mechanisms in place * on your pages, tweaking this setting can have benefits in perceived * smoothness of paging animations and interaction. If you have a small * number of pages (3-4) that you can keep active all at once, less time * will be spent in layout for newly created view subtrees as the user pages * back and forth. *

* *

* You should keep this limit low, especially if your pages have complex * layouts. This setting defaults to 1. *

* * @param limit * How many pages will be kept offscreen in an idle state. */ public void setOffscreenPageLimit(int limit) { if (limit < DEFAULT_OFFSCREEN_PAGES) { Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + DEFAULT_OFFSCREEN_PAGES); limit = DEFAULT_OFFSCREEN_PAGES; } if (limit != mOffscreenPageLimit) { mOffscreenPageLimit = limit; populate(); } } /** * Set the margin between pages. * * @param marginPixels * Distance between adjacent pages in pixels * @see #getPageMargin() * @see #setPageMarginDrawable(Drawable) * @see #setPageMarginDrawable(int) */ public void setPageMargin(int marginPixels) { final int oldMargin = mPageMargin; mPageMargin = marginPixels; final int width = getWidth(); recomputeScrollPosition(width, width, marginPixels, oldMargin); requestLayout(); } /** * Return the margin between pages. * * @return The size of the margin in pixels */ public int getPageMargin() { return mPageMargin; } /** * Set a drawable that will be used to fill the margin between pages. * * @param d * Drawable to display between pages */ public void setPageMarginDrawable(Drawable d) { mMarginDrawable = d; if (d != null) refreshDrawableState(); setWillNotDraw(d == null); invalidate(); } /** * Set a drawable that will be used to fill the margin between pages. * * @param resId * Resource ID of a drawable to display between pages */ public void setPageMarginDrawable(int resId) { setPageMarginDrawable(getContext().getResources().getDrawable(resId)); } @Override protected boolean verifyDrawable(Drawable who) { return super.verifyDrawable(who) || who == mMarginDrawable; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); final Drawable d = mMarginDrawable; if (d != null && d.isStateful()) { d.setState(getDrawableState()); } } // We want the duration of the page snap animation to be influenced by the // distance that // the screen has to travel, however, we don't want this duration to be // effected in a // purely linear fashion. Instead, we use this method to moderate the effect // that the distance // of travel has on the overall snap duration. float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. f *= 0.3f * Math.PI / 2.0f; return (float) Math.sin(f); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x * the number of pixels to scroll by on the X axis * @param y * the number of pixels to scroll by on the Y axis */ void smoothScrollTo(int x, int y) { smoothScrollTo(x, y, 0); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x * the number of pixels to scroll by on the X axis * @param y * the number of pixels to scroll by on the Y axis * @param velocity * the velocity associated with a fling, if applicable. (0 * otherwise) */ void smoothScrollTo(int x, int y, int velocity) { if (getChildCount() == 0) { // Nothing to do. setScrollingCacheEnabled(false); return; } int sx = getScrollX(); int sy = getScrollY(); int dx = x - sx; int dy = y - sy; if (dx == 0 && dy == 0) { completeScroll(); setScrollState(SCROLL_STATE_IDLE); return; } setScrollingCacheEnabled(true); mScrolling = true; setScrollState(SCROLL_STATE_SETTLING); final float pageDelta = (float) Math.abs(dx) / (getWidth() + mPageMargin); int duration = (int) (pageDelta * 100); velocity = Math.abs(velocity); if (velocity > 0) { duration += (duration / (velocity / mBaseLineFlingVelocity)) * mFlingVelocityInfluence; } else { duration += 100; } duration = Math.min(duration, MAX_SETTLE_DURATION); mScroller.startScroll(sx, sy, dx, dy, duration); invalidate(); } void addNewItem(int position, int index) { ItemInfo ii = new ItemInfo(); ii.position = position; ii.object = mAdapter.instantiateItem(this, position); if (index < 0) { mItems.add(ii); } else { mItems.add(index, ii); } } void dataSetChanged() { // This method only gets called if our observer is attached, so mAdapter // is non-null. boolean needPopulate = mItems.size() < 3 && mItems.size() < mAdapter.getCount(); int newCurrItem = -1; for (int i = 0; i < mItems.size(); i++) { final ItemInfo ii = mItems.get(i); final int newPos = mAdapter.getItemPosition(ii.object); if (newPos == PagerAdapter.POSITION_UNCHANGED) { continue; } if (newPos == PagerAdapter.POSITION_NONE) { mItems.remove(i); i--; mAdapter.destroyItem(this, ii.position, ii.object); needPopulate = true; if (mCurItem == ii.position) { // Keep the current item in the valid range newCurrItem = Math.max(0, Math.min(mCurItem, mAdapter.getCount() - 1)); } continue; } if (ii.position != newPos) { if (ii.position == mCurItem) { // Our current item changed position. Follow it. newCurrItem = newPos; } ii.position = newPos; needPopulate = true; } } Collections.sort(mItems, COMPARATOR); if (newCurrItem >= 0) { // TODO This currently causes a jump. setCurrentItemInternal(newCurrItem, false, true); needPopulate = true; } if (needPopulate) { populate(); requestLayout(); } } void populate() { if (mAdapter == null) { return; } // Bail now if we are waiting to populate. This is to hold off // on creating views from the time the user releases their finger to // fling to a new position until we have finished the scroll to // that position, avoiding glitches from happening at that point. if (mPopulatePending) { if (DEBUG) Log.i(TAG, "populate is pending, skipping for now..."); return; } // Also, don't populate until we are attached to a window. This is to // avoid trying to populate before we have restored our view hierarchy // state and conflicting with what is restored. if (getWindowToken() == null) { return; } mAdapter.startUpdate(this); final int pageLimit = mOffscreenPageLimit; final int startPos = Math.max(0, mCurItem - pageLimit); final int N = mAdapter.getCount(); final int endPos = Math.min(N - 1, mCurItem + pageLimit); if (DEBUG) Log.v(TAG, "populating: startPos=" + startPos + " endPos=" + endPos); // Add and remove pages in the existing list. int lastPos = -1; for (int i = 0; i < mItems.size(); i++) { ItemInfo ii = mItems.get(i); if ((ii.position < startPos || ii.position > endPos) && !ii.scrolling) { if (DEBUG) Log.i(TAG, "removing: " + ii.position + " @ " + i); mItems.remove(i); i--; mAdapter.destroyItem(this, ii.position, ii.object); } else if (lastPos < endPos && ii.position > startPos) { // The next item is outside of our range, but we have a gap // between it and the last item where we want to have a page // shown. Fill in the gap. lastPos++; if (lastPos < startPos) { lastPos = startPos; } while (lastPos <= endPos && lastPos < ii.position) { if (DEBUG) Log.i(TAG, "inserting: " + lastPos + " @ " + i); addNewItem(lastPos, i); lastPos++; i++; } } lastPos = ii.position; } // Add any new pages we need at the end. lastPos = mItems.size() > 0 ? mItems.get(mItems.size() - 1).position : -1; if (lastPos < endPos) { lastPos++; lastPos = lastPos > startPos ? lastPos : startPos; while (lastPos <= endPos) { if (DEBUG) Log.i(TAG, "appending: " + lastPos); addNewItem(lastPos, -1); lastPos++; } } if (DEBUG) { Log.i(TAG, "Current page list:"); for (int i = 0; i < mItems.size(); i++) { Log.i(TAG, "#" + i + ": page " + mItems.get(i).position); } } ItemInfo curItem = null; for (int i = 0; i < mItems.size(); i++) { if (mItems.get(i).position == mCurItem) { curItem = mItems.get(i); break; } } mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null); mAdapter.finishUpdate(this); if (hasFocus()) { View currentFocused = findFocus(); ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null; if (ii == null || ii.position != mCurItem) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { if (child.requestFocus(FOCUS_FORWARD)) { break; } } } } } } public static class SavedState extends BaseSavedState { int position; Parcelable adapterState; ClassLoader loader; public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(position); out.writeParcelable(adapterState, flags); } @Override public String toString() { return "FragmentPager.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " position=" + position + "}"; } public static final Parcelable.Creator CREATOR = ParcelableCompat .newCreator(new ParcelableCompatCreatorCallbacks() { @Override public SavedState createFromParcel(Parcel in, ClassLoader loader) { return new SavedState(in, loader); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }); SavedState(Parcel in, ClassLoader loader) { super(in); if (loader == null) { loader = getClass().getClassLoader(); } position = in.readInt(); adapterState = in.readParcelable(loader); this.loader = loader; } } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.position = mCurItem; if (mAdapter != null) { ss.adapterState = mAdapter.saveState(); } return ss; } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (mAdapter != null) { mAdapter.restoreState(ss.adapterState, ss.loader); setCurrentItemInternal(ss.position, false, true); } else { mRestoredCurItem = ss.position; mRestoredAdapterState = ss.adapterState; mRestoredClassLoader = ss.loader; } } @Override public void addView(View child, int index, LayoutParams params) { if (mInLayout) { addViewInLayout(child, index, params); child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec); } else { super.addView(child, index, params); } if (USE_CACHE) { if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(mScrollingCacheEnabled); } else { child.setDrawingCacheEnabled(false); } } } ItemInfo infoForChild(View child) { for (int i = 0; i < mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (mAdapter.isViewFromObject(child, ii.object)) { return ii; } } return null; } ItemInfo infoForAnyChild(View child) { ViewParent parent; while ((parent = child.getParent()) != this) { if (parent == null || !(parent instanceof View)) { return null; } child = (View) parent; } return infoForChild(child); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mFirstLayout = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // For simple implementation, or internal size is always 0. // We depend on the container to specify the layout size of // our view. We can't really know what it is since we will be // adding and removing different arbitrary views and do not // want the layout to change as this happens. setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); // Children are just made to fill our space. mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY); mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec( getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY); // Make sure we have created all fragments that we need to have shown. mInLayout = true; populate(); mInLayout = false; // Make sure all children have been properly measured. final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { if (DEBUG) Log.v(TAG, "Measuring #" + i + " " + child + ": " + mChildWidthMeasureSpec); child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec); } } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Make sure scroll position is set correctly. if (w != oldw) { recomputeScrollPosition(w, oldw, mPageMargin, mPageMargin); } } private void recomputeScrollPosition(int width, int oldWidth, int margin, int oldMargin) { final int widthWithMargin = width + margin; if (oldWidth > 0) { final int oldScrollPos = getScrollX(); final int oldwwm = oldWidth + oldMargin; final int oldScrollItem = oldScrollPos / oldwwm; final float scrollOffset = (float) (oldScrollPos % oldwwm) / oldwwm; final int scrollPos = (int) ((oldScrollItem + scrollOffset) * widthWithMargin); scrollTo(scrollPos, getScrollY()); if (!mScroller.isFinished()) { // We now return to your regularly scheduled scroll, already in // progress. final int newDuration = mScroller.getDuration() - mScroller.timePassed(); mScroller.startScroll(scrollPos, 0, mCurItem * widthWithMargin, 0, newDuration); } } else { int scrollPos = mCurItem * widthWithMargin; if (scrollPos != getScrollX()) { completeScroll(); scrollTo(scrollPos, getScrollY()); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; populate(); mInLayout = false; final int count = getChildCount(); final int width = r - l; for (int i = 0; i < count; i++) { View child = getChildAt(i); ItemInfo ii; if (child.getVisibility() != GONE && (ii = infoForChild(child)) != null) { int loff = (width + mPageMargin) * ii.position; int childLeft = getPaddingLeft() + loff; int childTop = getPaddingTop(); if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth() + "x" + child.getMeasuredHeight()); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } mFirstLayout = false; } @Override public void computeScroll() { if (DEBUG) Log.i(TAG, "computeScroll: finished=" + mScroller.isFinished()); if (!mScroller.isFinished()) { if (mScroller.computeScrollOffset()) { if (DEBUG) Log.i(TAG, "computeScroll: still scrolling"); int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); } if (mOnPageChangeListener != null) { final int widthWithMargin = getWidth() + mPageMargin; final int position = x / widthWithMargin; final int offsetPixels = x % widthWithMargin; final float offset = (float) offsetPixels / widthWithMargin; mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); } // Keep on drawing until the animation has finished. invalidate(); return; } } // Done with scroll, clean up state. completeScroll(); } private void completeScroll() { boolean needPopulate = mScrolling; if (needPopulate) { // Done with scroll, no longer want to cache view drawing. setScrollingCacheEnabled(false); mScroller.abortAnimation(); int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); } setScrollState(SCROLL_STATE_IDLE); } mPopulatePending = false; mScrolling = false; for (int i = 0; i < mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (ii.scrolling) { needPopulate = true; ii.scrolling = false; } } if (needPopulate) { populate(); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; // Always take care of the touch gesture being complete. if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { // Release the drag. if (DEBUG) Log.v(TAG, "Intercept done!"); mIsBeingDragged = false; mIsUnableToDrag = false; mActivePointerId = INVALID_POINTER; return false; } // Nothing more to do here if we have decided whether or not we // are dragging. if (action != MotionEvent.ACTION_DOWN) { if (mIsBeingDragged) { if (DEBUG) Log.v(TAG, "Intercept returning true!"); return true; } if (mIsUnableToDrag) { if (DEBUG) Log.v(TAG, "Intercept returning false!"); return false; } } switch (action) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have * caught it. Check whether the user has moved far enough from his * original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value of * the down event. */ final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on // content. break; } final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float dx = x - mLastMotionX; final float xDiff = Math.abs(dx); final float y = MotionEventCompat.getY(ev, pointerIndex); final float yDiff = Math.abs(y - mLastMotionY); final int scrollX = getScrollX(); final boolean atEdge = (dx > 0 && scrollX == 0) || (dx < 0 && mAdapter != null && scrollX >= (mAdapter .getCount() - 1) * getWidth() - 1); if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); if (canScroll(this, false, (int) dx, (int) x, (int) y)) { // Nested view has scrollable area under this point. Let it be // handled there. mInitialMotionX = mLastMotionX = x; mLastMotionY = y; return false; } if (xDiff > mTouchSlop && xDiff > yDiff) { if (DEBUG) Log.v(TAG, "Starting drag!"); mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); mLastMotionX = x; setScrollingCacheEnabled(true); } else { if (yDiff > mTouchSlop) { // The finger has moved enough in the vertical // direction to be counted as a drag... abort // any attempt to drag horizontally, to work correctly // with children that have scrolling containers. if (DEBUG) Log.v(TAG, "Starting unable to drag!"); mIsUnableToDrag = true; } } break; } case MotionEvent.ACTION_DOWN: { /* * Remember location of down touch. ACTION_DOWN always refers to * pointer index 0. */ mLastMotionX = mInitialMotionX = ev.getX(); mLastMotionY = ev.getY(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); if (mScrollState == SCROLL_STATE_SETTLING) { // Let the user 'catch' the pager as it animates. mIsBeingDragged = true; mIsUnableToDrag = false; setScrollState(SCROLL_STATE_DRAGGING); } else { completeScroll(); mIsBeingDragged = false; mIsUnableToDrag = false; } if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY + " mIsBeingDragged=" + mIsBeingDragged + "mIsUnableToDrag=" + mIsUnableToDrag); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mIsBeingDragged; } @Override public boolean onTouchEvent(MotionEvent ev) { if (mFakeDragging) { // A fake drag is in progress already, ignore this real one // but still eat the touch events. // (It is likely that the user is multi-touching the screen.) return true; } if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { // Don't handle edge touches immediately -- they may actually belong // to one of our // descendants. return false; } if (mAdapter == null || mAdapter.getCount() == 0) { // Nothing to present or scroll; nothing to touch. return false; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); boolean needsInvalidate = false; switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ completeScroll(); // Remember where the motion event started mLastMotionX = mInitialMotionX = ev.getX(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); break; } case MotionEvent.ACTION_MOVE: if (!mIsBeingDragged) { final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float xDiff = Math.abs(x - mLastMotionX); final float y = MotionEventCompat.getY(ev, pointerIndex); final float yDiff = Math.abs(y - mLastMotionY); if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); if (xDiff > mTouchSlop && xDiff > yDiff) { if (DEBUG) Log.v(TAG, "Starting drag!"); mIsBeingDragged = true; mLastMotionX = x; setScrollState(SCROLL_STATE_DRAGGING); setScrollingCacheEnabled(true); } } if (mIsBeingDragged) { // Scroll to follow the motion event final int activePointerIndex = MotionEventCompat .findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final float deltaX = mLastMotionX - x; mLastMotionX = x; float oldScrollX = getScrollX(); float scrollX = oldScrollX + deltaX; final int width = getWidth(); final int widthWithMargin = width + mPageMargin; final int lastItemIndex = mAdapter.getCount() - 1; final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin); final float rightBound = Math.min(mCurItem + 1, lastItemIndex) * widthWithMargin; if (scrollX < leftBound) { if (leftBound == 0) { float over = -scrollX; needsInvalidate = mLeftEdge.onPull(over / width); } scrollX = leftBound; } else if (scrollX > rightBound) { if (rightBound == lastItemIndex * widthWithMargin) { float over = scrollX - rightBound; needsInvalidate = mRightEdge.onPull(over / width); } scrollX = rightBound; } // Don't lose the rounded component mLastMotionX += scrollX - (int) scrollX; scrollTo((int) scrollX, getScrollY()); if (mOnPageChangeListener != null) { final int position = (int) scrollX / widthWithMargin; final int positionOffsetPixels = (int) scrollX % widthWithMargin; final float positionOffset = (float) positionOffsetPixels / widthWithMargin; mOnPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( velocityTracker, mActivePointerId); mPopulatePending = true; final int widthWithMargin = getWidth() + mPageMargin; final int scrollX = getScrollX(); // 澧炲姞杈硅窛鍒ゆ柇 int currentPage = scrollX / widthWithMargin; int leftPageScorll = scrollX % widthWithMargin; int nextPage = currentPage; float chargeVelocity = initialVelocity; if (chargeVelocity > 0) { // 鍚戝彸 if (widthWithMargin - leftPageScorll > mPagerNextMarginPixels) { nextPage = currentPage; } else { nextPage = currentPage + 1; } } else { // 鍚戝乏 if (leftPageScorll > mPagerNextMarginPixels) { nextPage = currentPage + 1; } else { nextPage = currentPage; } } // nextPage = chargeVelocity > 0 ? currentPage // : currentPage + 1; // Log.d(TAG, "initialVelocity:" + initialVelocity // + ", currentPage: " + (scrollX / widthWithMargin) // + ", widthWithMargin: " + widthWithMargin // + ", scrollX: " + scrollX + ", chargeVelocity: " // + chargeVelocity + ", nextPage: " + nextPage); setCurrentItemInternal(nextPage, true, true, initialVelocity); mActivePointerId = INVALID_POINTER; endDrag(); needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); } break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged) { setCurrentItemInternal(mCurItem, true, true); mActivePointerId = INVALID_POINTER; endDrag(); needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); } break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); final float x = MotionEventCompat.getX(ev, index); mLastMotionX = x; mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); break; } if (needsInvalidate) { invalidate(); } return true; } @Override public void draw(Canvas canvas) { super.draw(canvas); boolean needsInvalidate = false; final int overScrollMode = ViewCompat.getOverScrollMode(this); if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS || (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && mAdapter != null && mAdapter.getCount() > 1)) { if (!mLeftEdge.isFinished()) { final int restoreCount = canvas.save(); final int height = getHeight() - getPaddingTop() - getPaddingBottom(); canvas.rotate(270); canvas.translate(-height + getPaddingTop(), 0); mLeftEdge.setSize(height, getWidth()); needsInvalidate |= mLeftEdge.draw(canvas); canvas.restoreToCount(restoreCount); } if (!mRightEdge.isFinished()) { final int restoreCount = canvas.save(); final int width = getWidth(); final int height = getHeight() - getPaddingTop() - getPaddingBottom(); final int itemCount = mAdapter != null ? mAdapter.getCount() : 1; canvas.rotate(90); canvas.translate(-getPaddingTop(), -itemCount * (width + mPageMargin) + mPageMargin); mRightEdge.setSize(height, width); needsInvalidate |= mRightEdge.draw(canvas); canvas.restoreToCount(restoreCount); } } else { mLeftEdge.finish(); mRightEdge.finish(); } if (needsInvalidate) { // Keep animating invalidate(); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Draw the margin drawable if needed. if (mPageMargin > 0 && mMarginDrawable != null) { final int scrollX = getScrollX(); final int width = getWidth(); final int offset = scrollX % (width + mPageMargin); if (offset != 0) { // Pages fit completely when settled; we only need to draw when // in between final int left = scrollX - offset + width; mMarginDrawable.setBounds(left, 0, left + mPageMargin, getHeight()); mMarginDrawable.draw(canvas); } } } /** * Start a fake drag of the pager. * *

* A fake drag can be useful if you want to synchronize the motion of the * ViewPager with the touch scrolling of another view, while still letting * the ViewPager control the snapping motion and fling behavior. (e.g. * parallax-scrolling tabs.) Call {@link #fakeDragBy(float)} to simulate the * actual drag motion. Call {@link #endFakeDrag()} to complete the fake drag * and fling as necessary. * *

* During a fake drag the ViewPager will ignore all touch events. If a real * drag is already in progress, this method will return false. * * @return true if the fake drag began successfully, false if it could not * be started. * * @see #fakeDragBy(float) * @see #endFakeDrag() */ public boolean beginFakeDrag() { if (mIsBeingDragged) { return false; } mFakeDragging = true; setScrollState(SCROLL_STATE_DRAGGING); mInitialMotionX = mLastMotionX = 0; if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } else { mVelocityTracker.clear(); } final long time = SystemClock.uptimeMillis(); final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0); mVelocityTracker.addMovement(ev); ev.recycle(); mFakeDragBeginTime = time; return true; } /** * End a fake drag of the pager. * * @see #beginFakeDrag() * @see #fakeDragBy(float) */ public void endFakeDrag() { Log.d(TAG, "endFakeDrag"); if (!mFakeDragging) { throw new IllegalStateException( "No fake drag in progress. Call beginFakeDrag first."); } final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getYVelocity( velocityTracker, mActivePointerId); mPopulatePending = true; Log.d(TAG, "initialVelocity: " + initialVelocity + ", Math.abs(mInitialMotionX - mLastMotionX): " + Math.abs(mInitialMotionX - mLastMotionX)); if ((Math.abs(initialVelocity) > mMinimumVelocity) || Math.abs(mInitialMotionX - mLastMotionX) >= (getWidth() / 3)) { if (mLastMotionX > mInitialMotionX) { setCurrentItemInternal(mCurItem - 1, true, true); } else { setCurrentItemInternal(mCurItem + 1, true, true); } } else { setCurrentItemInternal(mCurItem, true, true); } endDrag(); mFakeDragging = false; } /** * Fake drag by an offset in pixels. You must have called * {@link #beginFakeDrag()} first. * * @param xOffset * Offset in pixels to drag by. * @see #beginFakeDrag() * @see #endFakeDrag() */ public void fakeDragBy(float xOffset) { if (!mFakeDragging) { throw new IllegalStateException( "No fake drag in progress. Call beginFakeDrag first."); } mLastMotionX += xOffset; float scrollX = getScrollX() - xOffset; final int width = getWidth(); final int widthWithMargin = width + mPageMargin; final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin); final float rightBound = Math .min(mCurItem + 1, mAdapter.getCount() - 1) * widthWithMargin; if (scrollX < leftBound) { scrollX = leftBound; } else if (scrollX > rightBound) { scrollX = rightBound; } // Don't lose the rounded component mLastMotionX += scrollX - (int) scrollX; scrollTo((int) scrollX, getScrollY()); if (mOnPageChangeListener != null) { final int position = (int) scrollX / widthWithMargin; final int positionOffsetPixels = (int) scrollX % widthWithMargin; final float positionOffset = (float) positionOffsetPixels / widthWithMargin; mOnPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } // Synthesize an event for the VelocityTracker. final long time = SystemClock.uptimeMillis(); final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE, mLastMotionX, 0, 0); mVelocityTracker.addMovement(ev); ev.recycle(); } /** * Returns true if a fake drag is in progress. * * @return true if currently in a fake drag, false otherwise. * * @see #beginFakeDrag() * @see #fakeDragBy(float) * @see #endFakeDrag() */ public boolean isFakeDragging() { return mFakeDragging; } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } private void endDrag() { mIsBeingDragged = false; mIsUnableToDrag = false; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private void setScrollingCacheEnabled(boolean enabled) { if (mScrollingCacheEnabled != enabled) { mScrollingCacheEnabled = enabled; if (USE_CACHE) { final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(enabled); } } } } } /** * Tests scrollability within child views of v given a delta of dx. * * @param v * View to test for horizontal scrollability * @param checkV * Whether the view v passed should itself be checked for * scrollability (true), or just its children (false). * @param dx * Delta scrolled in pixels * @param x * X coordinate of the active touch point * @param y * Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dx. */ protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) { if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int scrollX = v.getScrollX(); final int scrollY = v.getScrollY(); final int count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance // first. for (int i = count - 1; i >= 0; i--) { // TODO: Add versioned support here for transformed views. // This will not work for transformed views in Honeycomb+ final View child = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && canScroll(child, true, dx, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && ViewCompat.canScrollHorizontally(v, -dx); } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event * The key event to execute. * @return Return true if the event was handled, else false. */ public boolean executeKeyEvent(KeyEvent event) { boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: handled = arrowScroll(FOCUS_LEFT); break; case KeyEvent.KEYCODE_DPAD_RIGHT: handled = arrowScroll(FOCUS_RIGHT); break; case KeyEvent.KEYCODE_TAB: if (KeyEventCompat.hasNoModifiers(event)) { handled = arrowScroll(FOCUS_FORWARD); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { handled = arrowScroll(FOCUS_BACKWARD); } break; } } return handled; } public boolean arrowScroll(int direction) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; boolean handled = false; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == View.FOCUS_LEFT) { // If there is nothing to the left, or this is causing us to // jump to the right, then what we really want to do is page // left. if (currentFocused != null && nextFocused.getLeft() >= currentFocused.getLeft()) { handled = pageLeft(); } else { handled = nextFocused.requestFocus(); } } else if (direction == View.FOCUS_RIGHT) { // If there is nothing to the right, or this is causing us to // jump to the left, then what we really want to do is page // right. if (currentFocused != null && nextFocused.getLeft() <= currentFocused.getLeft()) { handled = pageRight(); } else { handled = nextFocused.requestFocus(); } } } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) { // Trying to move left and nothing there; try to page. handled = pageLeft(); } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) { // Trying to move right and nothing there; try to page. handled = pageRight(); } if (handled) { playSoundEffect(SoundEffectConstants .getContantForFocusDirection(direction)); } return handled; } boolean pageLeft() { if (mCurItem > 0) { setCurrentItem(mCurItem - 1, true); return true; } return false; } boolean pageRight() { if (mAdapter != null && mCurItem < (mAdapter.getCount() - 1)) { setCurrentItem(mCurItem + 1, true); return true; } return false; } /** * We only want the current page that is being shown to be focusable. */ @Override public void addFocusables(ArrayList views, int direction, int focusableMode) { final int focusableCount = views.size(); final int descendantFocusability = getDescendantFocusability(); if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) { for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { child.addFocusables(views, direction, focusableMode); } } } } // we add ourselves (if focusable) in all cases except for when we are // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. // this is // to avoid the focus search finding layouts when a more precise search // among the focusable children would be more interesting. if (descendantFocusability != FOCUS_AFTER_DESCENDANTS || // No focusable descendants (focusableCount == views.size())) { // Note that we can't call the superclass here, because it will // add all views in. So we need to do the same thing View does. if (!isFocusable()) { return; } if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE && isInTouchMode() && !isFocusableInTouchMode()) { return; } if (views != null) { views.add(this); } } } /** * We only want the current page that is being shown to be touchable. */ @Override public void addTouchables(ArrayList views) { // Note that we don't call super.addTouchables(), which means that // we don't call View.addTouchables(). This is okay because a ViewPager // is itself not touchable. for (int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { child.addTouchables(views); } } } } /** * We only want the current page that is being shown to be focusable. */ @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { int index; int increment; int end; int count = getChildCount(); if ((direction & FOCUS_FORWARD) != 0) { index = 0; increment = 1; end = count; } else { index = count - 1; increment = -1; end = -1; } for (int i = index; i != end; i += increment) { View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem) { if (child.requestFocus(direction, previouslyFocusedRect)) { return true; } } } } return false; } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { // ViewPagers should only report accessibility info for the current // page, // otherwise things get very confusing. // TODO: Should this note something about the paging container? final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { final ItemInfo ii = infoForChild(child); if (ii != null && ii.position == mCurItem && child.dispatchPopulateAccessibilityEvent(event)) { return true; } } } return false; }

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧