texts
stringlengths
0
1.24M
names
stringlengths
13
33
ComAggregate Example This example shows how aggregation is implemented using the COM compiler. The example is described in detail in chapter two of the book "Inside OLE". With aggregation, an object which implements one or several interfaces is reused without modification and without the need to forward each method of the reused interfaces. The reused object is called the inner one, and the object which reuses the inner object is called the outer object. The inner object delegates all calls to QueryInterface to the outer object, and the outer object has a reference to the inner object's IUnknown interface. This latter interface must not forward the QueryInterface calls, otherwise this would produce an infinite recursion. This implies that an aggregatable object must provide a separate implementation of the IUnknown interface, i.e. an aggregatable object consists of at least two records which both implement the IUnknown interface, where one QueryInterface method is forwarded, while the other is not. These two records will be linked by references from one to the other. The interface which is reused has the IAnimal interface, IAnimal = POINTER TO ABSTRACT RECORD ["{00021143-0000-0000-C000-000000000046}"] (COM.IUnknown) (this: IAnimal) Eat (): COM.RESULT, NEW, ABSTRACT; (this: IAnimal) Sleep (): COM.RESULT, NEW, ABSTRACT; (this: IAnimal) Procreate (): COM.RESULT, NEW, ABSTRACT; END; and the two objects which implement the aggregatable implementation of this interface are defined below. CAnimal = POINTER TO RECORD (COM.IUnknown) impl: CImpIAnimal END; CImpIAnimal = POINTER TO RECORD (IAnimal) obj: CAnimal END; The CAnimal record implements the IUnknown interface and the CImplAnimal record implements the IAnimal interface. If the object is aggregated, the calls to the QueryInterface method of the latter record are forwarded to the outer object. Since objects are created inside-out, the outer object is passed as a parameter to the procedure which creates an IAnimal object. If the reference to the outer object is not NIL, then the IAnimal object is aggregated. It is a convention of COM that then the IUnknown interface of the aggregated object must be requested upon object creation. As the outer object has a reference to the inner one, and the inner one a reference to the outer one, there is a cycle of references which would prevent garbage collection. To avoid this, the reference from the inner to the outer object is a special reference which is not reference counted. Such references can be generated with the two-argument NEW. The default implementation of QueryInterface then automatically forwards the requests to the outer object. If the object is not aggregated, we use the CAnimal record as "outer" object for the CImplAnimal object. This is the same pattern as in the ComObject example, i.e. a COM object which implements several interfaces. The whole procedure to create an IAnimal object is given below. The first parameter (outer) determines whether the object is aggregated or not. PROCEDURE CreateAnimal (outer: COM.IUnknown; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR new: CAnimal; BEGIN IF (outer # NIL) & (iid # COM.ID(COM.IUnknown)) THEN RETURN WinApi.CLASS_E_NOAGGREGATION END; NEW(new); IF new # NIL THEN IF outer = NIL THEN NEW(new.impl, new) ELSE NEW(new.impl, outer) END; IF new.impl # NIL THEN new.impl.obj := new; StdLog.String("Animal allocated"); StdLog.Ln; RETURN new.QueryInterface(iid, int) END END; RETURN WinApi.E_OUTOFMEMORY END CreateAnimal; The inner object's explicit IUnknown interface must control the inner object's reference count and implement the QueryInterface behavior for only the inner object. The procedure which is doing this has the following form: PROCEDURE (this: CAnimal) QueryInterface (IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; BEGIN IF COM.QUERY(this, iid, int) OR COM.QUERY(this.impl, iid, int) THEN RETURN WinApi.S_OK ELSE RETURN WinApi.E_NOINTERFACE END END QueryInterface; Note that the COM.QUERY command on the CImplAnimal interface is not forwarded. It succeeds if the IAnimal interface is requested. Note that in the example, the outer object which implements the IKoala interface is also designed to support aggregation. The object is separated into two records, one implementing the IUnknown interface and the other the IKoala interface. This design is easy to extend if additional interfaces have to be supported. The example finally provides some commands which allow to test the functionality of the IKoala-IAnimal implementation. ComAggregatesources
Com/Docu/Aggregate.odc
ComConnect Example This example shows how connectable objects are implemented using the COM compiler. The example is described in detail in chapter four of the book "Inside OLE". Connectable objects offer an interface which allows to install interfaces which can be called back by the connectable object. A connectable object has to implement the interface IConnectionPointContainer with the two methods FindConnectionPoint and EnumConnectionPoints. With the first method, the connectable object can be asked for a specific outgoing interface. If the interface is supported, then a pointer to the IConnectionPoint is returned, the interface through which the callback interface can be installed. With the method EnumConnectionPoints the supported outgoing interfaces can be requested. The list of supported interfaces is returned in the form of an enumeration interface, IEnumConnectionPoints. In our example, the connectable object keeps a list of the supported interfaces as an instance variable. The IConnectionPoint interface allows to establish a connection between the connectable object and the client through the Advise method. A cookie (key) is returned as result. A connection point can support any number of connections. In our example, the constant connMax defines the number of connections that can be established. With the Unadvise method a connection can be terminated. The connection cookie must be passed as argument. As argument of the Advise method the sink object's IUnknown interface is passed. From this interface the outgoing interface is requested and stored in the connection (the object implementing IConnectionPoint). Besides these two methods, the IConnectionPoint interface supports the methods EnumConnections, GetConnectionPointContainer and GetConnectionInterface. The implementation of the latter two functions is straight-forward. The EnumConnections function returns an enumeration of all the currently installed connections. This enumeration interface is implemented with CEnumConnections. The implementation of IConnectionPoint has the following instance variables: CConnectionPoint = POINTER TO RECORD (WinOle.IConnectionPoint) obj: CConnObject; iid: COM.GUID; unk: ARRAY connMax OF COM.IUnknown; cookies: ARRAY connMax OF INTEGER; conn: INTEGER; next: INTEGER END; The obj reference refers to the connectable object, i.e. to the object implementing the IConnectionPointContainer interface. The GUID of the outgoing interface, which is supported by the concrete connection, is stored in the field iid. In our example this is always COM.GUID(IDuckEvents). All installed connections are stored in the unk array. If an event is distributed through all conected interfaces, then the necessary interface is requested though the IUnknown interfaces installed in the unk array. The cookies corresponding to the connections are stored in the cookies array. They are necessary to search a connection when Unadvise is called. The conn field counts the number of installed connections, and the next field finally contains the last distributed cookie. The IDuckEvents interface is used in this example as the outgoing interface. This interface supports the following three functions: IDuckEvents = POINTER TO ABSTRACT RECORD ["{00021145-0000-0000-C000-000000000046}"] (COM.IUnknown) (this: IDuckEvents) Quack (): COM.RESULT, NEW, ABSTRACT; (this: IDuckEvents) Flap (): COM.RESULT, NEW, ABSTRACT; (this: IDuckEvents) Paddle (): COM.RESULT, NEW, ABSTRACT; END; In its instance variable, the concrete implementation of this interface keeps an identifier and the cookie which is obtained when the interface is installed in the connectable object. The implementation of the methods write a text to the log indicating that they have been called. They also write their identifier into the log. In our example, the connectable object CConnObject offers the additional method TriggerEvent. With this method, an event can be sent through all registered IDuckEvents interfaces. The module ComConnect offers the following commands Init creates two objects which implement the IDuckEvents interface Release disconnects all connections and frees the connectable object and the sink objects ObjectCreate creates the connectable object ObjectRelease releases the connectable object SinkXConnect connects a sink object to the connectable object SinkXDisconnect disconnects a sink object from the connectable object TriggerQuack calls the Quack method of all connected IDuckEvents interfaces TriggerFlap calls the Flap method of all connected IDuckEvents interfaces TriggerPaddle calls the Paddle method of all connected IDuckEvents interfaces This example is coded rather in a general way. It would be easy to extend the implementation to support more connections or more outgoing interfaces. If only one outgoing interface were supported, the code could be simplified at several places. ComConnectsources
Com/Docu/Connect.odc
DevComDebug see documentationoftheDirect-To-COMCompilerenvironment.
Com/Docu/Debug.odc
Direct-To-COM Compiler The Component Object Model The Component Object Model (COM) is an object model which allows independently developed binary software components to connect to and communicate with each other in a well-defined manner. COM defines a binary standard for object interoperability which is programming-language and compiler independent. The primary architectural feature of COM is that an object exposes a set of interfaces to a client. An interface is a set of semantically related functions. Every object can provide multiple interfaces. COM objects can only be accessed through pointers to interfaces (interface pointers). Direct access to an object's internal variables is not possible. This allows for encapsulation of data and processing, a fundamental requirement of a true component software standard. Another fundamental concept of the COM model is reference counting. Reference counting allows objects to track their own lifetime and delete themselves when appropriate. The following figure visualizes a COM object as large black box, which is accessible from the outside only via pointers to its exported interfaces. Internally, a COM object typically contains a large number of simpler objects, which constitute its hidden implementation. Note that there are pointers from each interface record of the COM object to each other interface record, directly or indirectly. Also, every implementation object is connected to the interfaces through one or several pointer chains. Pointer chains may contain cycles. Binary Standard COM defines a standardized way to layout the concrete implementation of interfaces. Every COM object provides the implementation of each method specified in the interface. The pointers to the method implementations are stored in an array, a so called virtual function table (vtable). The interface record is a structure whose first entry is a pointer to a vtable; it may contain additional private object data. COM clients only interact with a COM object through pointers to interfaces, i.e. with pointers to pointers to vtables. It is through such a pointer that the client accesses the object's implementation of the interface. Therefore, any language that can call functions via pointers (using the StdCall calling conventions) can be used to write and use COM components. interface pointer interface vtable Reference Counting in COM COM uses reference counting as a simple form of (manual) garbage collection. Reference counting is performed through two standard methods called AddRef and Release. Whenever a new reference to an interface is established, AddRef must be called. When the interface is no longer needed, Release must be called. Reference counting is done at the interface level, i.e., every interface must support the two methods AddRef and Release. They are defined in the interface IUnknown which is the base interface of every COM interface. Internally, the interface implementation counts the number of AddRef and Release calls, and thereby knows when it is safe to free the memory that it occupies. Conceptually, reference counting is performed at the interface level. However, as a COM object can support several interfaces, it is free to implement one central reference count per object, instead of one reference count per interface. However, a client should never assume that an object uses the same counter for several interfaces; i.e., it should increment the reference count always through the interface which is about to be used. The following two simple rules define how reference counts have to be managed. Interface pointer variables are variables which hold interface pointers. Such variables may be located in memory or in processor registers. 1) Whenever an interface pointer is stored in an interface pointer variable, AddRef must be called through this interface pointer. 2) Immediately before an interface pointer variable is cleared, overwritten, or destroyed, Release must be called on the interface pointer presently in the variable. Rule 1 implies that a function that returns an interface pointer must call AddRef on this interface, as it stores a new interface pointer in a register or in memory (i.e., at a place where access is still possible). Examples of such functions are IUnknown.QueryInterface and IFactory.CreateInstance. Rule 2 implies that Release must be called on old values of an interface pointer variable before assigning a new value, and on local interface pointers before leaving the scope. The example below demonstrates the use of these two rules: IFactory* pFactory; HRESULT hr = GetFactory(IID_IFactory, (void**)&pFactory); if (SUCCEEDED(hr)) // Reference count of factory has been incremented by GetFactory { IAnimal* pAnimal1; hr = pFactory->CreateInstance(0, IID_IAnimal, (void**)&pAnimal1); // (2) if (SUCCEEDED(hr)) // Reference count of pAnimal1 incremented by CreateInstance { IAnimal* pAnimal2 = pAnimal1; pAnimal2->AddRef(); // Increment Reference Count (1) pAnimal2->Sleep(); // Do something through pAnimal2 pAnimal1->Release(); // Release Interface before assigning a new animal (1) (3) hr = factory->CreateInstance(0, IID_IAnimal, (void**)&pAnimal1); if (SUCCEEDED(hr)) // Reference count of pAnimal1 incremented by CreateInstance { pAnimal1->Eat(); // Do something with second animal pAnimal1->Release(); // scope in which pAnimal1 is declared will be closed soon } pAnimal2->Release(); // scope in which pAnimal2 is declared will be closed } pFactory->Release(); // scope in which pFactory is declared wil be closed soon } In principle, every assignment to an interface pointer must be accompanied by a Release call (except for NULL or uninitialized interface pointers) and an AddRef call. However, in some special situations, AddRef and Release pairs can be omitted safely. Unfortunately, the COM specification defines some special rules for interface parameters of methods. An interface may specify that some arguments of its methods are passed only in one direction; i.e., only from the client to the server or vice versa. This minimizes communication overhead for calls across process or machine boundaries (remote procedure calls), but it complicates the rules for the COM programmer.
Com/Docu/DTC-COM.odc
Direct-To-COM Compiler Contents COMCompilerExtensions COMSysflagsforInterfaceStructures COMsysflagsforVARparameters TheModuleCOM NewPredefinedProcedures Unions COMProgrammingHints CompilerImplementationRestrictions The Direct-To-COM (DTC) compiler is a Component Pascal compiler that supports Microsoft's Component Object Model (COM) binary interface standard. In DTC Component Pascal, COM objects are declared and implemented in a superset of the Component Pascal language. They can be used from any other language, and COM objects implemented in any language can be used from Component Pascal. In Component Pascal, COM interfaces are mapped to special Component Pascal records. Interface pointers are pointers to such records. The virtual function table is the method table of the Component Pascal type descriptor. It is hidden from the programmer. A COM interface can be defined in the following way: ILookup* = POINTER TO ABSTRACT RECORD ["{C4910D71-BA7D-11CD-94E8-08001701A8A3}"] (COM.IUnknown) END; PROCEDURE (this: ILookup) LookupByName*( name: WinApi.PtrWSTR; OUT number: WinApi.PtrWSTR): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: ILookup) LookupByNumber*( number: WinApi.PtrWSTR; OUT name: WinApi.PtrWSTR): COM.RESULT, NEW, ABSTRACT; Interface definitions can be derived from one another using Component Pascal subtyping. The above interface is a subtype of the interface COM.IUnknown. The interface identifier (IID) is specified in the declaration of the interface. The interface is declared to be abstract and cannot be instantiated. Concrete implementations of interface objects are extensions of interface records. In contrast to the interface records which are referenced through (reference-counted) interface pointers, the implementation records are referenced through regular Component Pascal pointers. The COM standard uses reference counting as its memory management strategy. Reference counting errors, however, are the most difficult and dangerous errors when programming to the OLE interfaces. The "Safer OLE" technology of the DTC compiler adds automatic memory management to COM objects. In contrast to C and C++, programmers using the DTC Component Pascal compiler do not need to worry about reference counting. The compiler automatically generates calls of an object's AddRef and Release methods where necessary, and the compiler also automatically implements the AddRef and Release methods for interfaces implemented in Component Pascal. When a COM object is no longer used, it is automatically removed from memory. Components written in DTC Component Pascal become more reliable and maintainable. In Component Pascal, the above example looks as follows: VAR factory: IFactory; animal1, animal2: IAnimal; hr: COM.RESULT; BEGIN hr := GetFactory(COM.ID(IFactory), factory); IF hr >= 0 THEN hr := factory.CreateInstance(NIL, COM.ID(animal1), animal1); IF hr >= 0 THEN animal2 := animal1; animal2.Sleep(); hr := factory.CreateInstance(NIL, COM.ID(animal1), animal1); IF hr >= 0 THEN animal1.Eat() END END END END Calls to the reference counting methods are generated for assignments to interface pointer variables. The garbage collector recognizes COM interface implementations and does not remove such objects with a reference count greater than zero. If the garbage collector finds a COM interface object with reference count zero, then all interface pointers stored in this object are released before the object is collected. The same holds for local variables if the scope is left and for global variables that are stored in a component to be unloaded. This automatic garbage collection mechanism just generates code that would have to be written manually in any case. Thus it does not require any extra run time and is fully compatible with other components, created with other tools. The DTC compiler is integrated in the development environment BlackBox. The debugger allows to inspect components and objects on a symbolic level. In order to browse through dynamic memory, you use hypertext links to follow pointers. Effective support for COM in Component Pascal requires special language constructs, e.g. to specify the unique id of a COM interface. We clearly separate these language extensions from the core language. The reason is that such interfacing features should and need not be used in normal Component Pascal modules, and moreover, COM is only one of an increasing number of object models which could be supported. Modules using the special language constructs must flag this fact in the module header. If you look at the beginning of a module source, it should immediately be clear whether this is an (unportable) module and whether it is unsafe or not. We already have followed this principle in earlier products: system flags and other similar features are only allowed in modules which import the pseudo-module SYSTEM. This module and the necessary compiler extensions are not considered part of the language definition proper. In a similar vein, a pseudo-module COM needs to be imported in order to make the special COM features available in a module. This module is not considered a part of Component Pascal itself. To quote Prof. N. Wirth from the ETH technical report #82 (From Modula to Oberon): "It appears preferrable to drop the pretense of portability of programs that import a "standard", yet system-specific module. Both, the module SYSTEM and the type transfer functions are therefore eliminated, and with them also the types ADDRESS and WORD. Individual implementations are free to provide system-dependent modules, but they do not belong to the general language definition. Their use then declares a program to be patently implementation-specific, and thereby non-portable." In this spirit, procedural DLLs and COM DLLs are system-specific. A software system should minimize the number and size of modules directly using them, and encapsulate the latter such that their module interfaces only use the core Component Pascal features wherever possible (abstraction!). For this reason it is considered good software engineering practice to structure the implementation of a complex COM object such that the number of objects (and their modules) that contain references to interfaces are minimized and they are concentrated at the "top" and "bottom" of the module hierarchy, so that the intermediate layer consists of pure Component Pascal modules which don't use any special COM features: This leads to a module structure such as the following, where the top-level module implements the COM interfaces (export), the bottom-level modules implement access to existing COM interfaces (import), while the intermediate modules are implemented in portable, safe, and non-COM-specific modules: COM Compiler Extensions The compiler features added in order to support COM are modest. In particular, new sysflags for interface records and VAR parameters have been defined and union records are provided. Some additional types and functions are defined in the pseudo module COM. In order to access these extended facilities, the pseudo module COM must be imported. In the following, the special COM extensions are explained. COM Sysflags for Interface Structures Interface records are marked by the interface sysflag or by a GUID (globally unique identifier) flag. The GUID string must be a valid GUID constant spelled out in hex and wrapped in braces. TYPE IExample = POINTER TO ABSTRACT RECORD ["{91C074A1-C2D7-11CF-A4A1-444553540000}"] (COM.IUnknown) END; PROCEDURE (e: IExample) MethodA(): COM.RESULT, NEW, ABSTRACT; Instead of an explicit GUID, an interface record can also be marked with the interface sysflag. Such interfaces however cannot be requested through a QueryInterfacecall as they have no identifier. They can be used to implement outgoing interfaces which are not explicitely requested. TYPE IExample = POINTER TO ABSTRACT RECORD [interface] (COM.IUnknown) END; PROCEDURE (e: IExample) MethodA(): COM.RESULT, NEW, ABSTRACT Interface records and interface pointers must be (direct or indirect) extensions of COM.IUnknown. Interface records must be abstract and therefore must not contain any fields. Procedures bound to interface records must also be abstract. Abstract records cannot be allocated. The only legal usage of an interface record is as a record or pointer base type or as type of an interface pointer variable. An implementation extension of an interface must overwrite all abstract procedures bound to the interface record. Exceptions are the procedures defined by COM.IUnknown: The following example defines an implementation of the IExample interface. By convention, type names of interface pointers start with an I, and type names of (implementing) classes with a C. TYPE CExample = POINTER TO RECORD (IExample) END; PROCEDURE (e: CExample) MethodA(): COM.RESULT; BEGIN RETURN WinApi.E_NOTIMPL END MethodA; COM Sysflags for VAR Parameters [nil] The nil flag for VAR parameters indicates that NIL may also be used as an actual parameter. With the function VALID (see below) it can be tested whether an actual VAR parameter is valid, i.e. is not NIL. If the actual parameter is not valid (i.e. is NIL), then it must neither be read nor written. It may only be passed as actual parameter for another nil-parameter. Attempts to read or write an invalid nil parameter leads to a NIL dereference trap. [new] [iid] The iid and new VAR parameter flags allow to specify polymorphic out parameters. They allow to implement QueryInterface-like operations. The new and iid parameters must always be paired in a parameter list. A new parameter must be followed by a corresponding iid parameter or vice versa. A parameter list may contain only one new-iid pair. The iid parameter must be an IN parameter of type GUID, and the new parameter must be an OUT parameter of an interface type. The type passed as iid parameter defines the static type of the polymorphic out parameter. The dynamic type of the out parameter can be a subtype of the asserted static type. The actual parameter passed for the interface parameter may be a base type of the asserted static type and may be an extension of the formal parameter. In other words, the following relation must be satisfied for the actual parameters of a polymorphic out parameter (<= refers to the subtype relation) type of formal new parameter <= static type of actual new parameter <= type specified through iid parameter <= dynamic type of actual new parameter (on return) The following program fragment shows some examples of the use of polymorphic out parameters. TYPE IExample = POINTER TO ABSTRACT RECORD ["{91C074A1-C2D7-11CF-A4A1-444553540000}"] (COM.IUnknown) END; IExample2 = POINTER TO ABSTRACT RECORD ["{91C074A2-C2D7-11CF-A4A1-444553540000}"] (IExample) END; PROCEDURE GetInterface(IN [iid] id: COM.GUID; OUT [new] int: COM.IUnknown); END GetInterface; PROCEDURE Test; VAR i0: COM.IUnknown; i1: IExample; i2: IExample2; BEGIN GetInterface(COM.ID(i1), i0); (* valid *) GetInterface(COM.ID(i1), i1); (* valid *) GetInterface(COM.ID(i1), i2); (* compiler error: wrong [iid] - [new] pair *) END Test; A procedure like PROCEDURE QueryInterface (IN [iid] id: COM.GUID; OUT [new] int: COM.IUnknown); can be called in four different ways: - QueryInterface(COM.ID(p1), p0) where p0 is an extension of COM.IUnknown and p1 is an extension of p0. VAR i1: IExample; i2: IExample2; QueryInterface(COM.ID(i2), i1); - QueryInterface(COM.ID(T), p) where p is an extension of COM.IUnknown and T is a subtype of the type of p. VAR i1: IExample; QueryInterface(COM.ID(IExample2), i1); - QueryInterface(id, p) where id is an arbitrary GUID and p is of type COM.IUnknown. VAR p: COM.IUnknown; QueryInterface("{91C074A1-C2D7-11CF-A4A1-444553540000}", p); - QueryInterface(id, int) where id and int are another [iid], [new] pair. PROCEDURE P (IN [iid] id: COM.GUID; OUT [new] int: COM.IUnknown); BEGIN QueryInterface(id, int) END P; In a procedure with an iid-new parameter pair, the interface parameter cannot be assigned directly, but id and int can be used as formal parameters to another [new], [iid] pair or to COM.QUERY (see below). The Module COM The module COM contains certain types and procedures that are necessary to implement COM components. As module SYSTEM, module COM is a pseudo module, i.e., no symbol file exists for module COM. If module COM is imported, this is only a declaration for the compiler. A pseudo description of the interface is shown below: DEFINITION COM; TYPE RESULT = INTEGER; GUID = ARRAY 16 OF BYTE; (* modified compare semantics *) IUnknown = POINTER TO ABSTRACT RECORD ["{00000000-0000-0000-C000-000000000046}"] (this: IUnknown) QueryInterface (IN [iid] iid: GUID; OUT [new] int: IUnknown): RESULT, NEW, ABSTRACT; (this: IUnknown) AddRef, NEW, ABSTRACT; (* hidden, can neither be called nor overwritten *) (this: IUnknown) Release, NEW, ABSTRACT; (* hidden, can neither be caled nor overwritten *) (this: IUnknown) RELEASE-, NEW, EXTENSIBLE; END; PROCEDURE QUERY (p: IUnknown; IN [iid] id: GUID; OUT [new] ip: IUnknown): BOOLEAN; PROCEDURE ID (t: INTERFACETYPE): GUID; PROCEDURE ID (p: IUnknown): GUID; PROCEDURE ID (s: ARRAY OF CHAR): GUID; END COM. TYPE RESULT Result type of most COM operations (alias of INTEGER). The error translator of the Direct-To-COM development environment can be used to obtain a meaningful description from such a result. TYPE GUID Type for globally unique identifiers (GUIDs). A GUID is a 128 bit identifier. String constant expressions representing a valid GUID can be assigned to a GUID variable. VAR id: COM.GUID; id := "{12345678-1000-11cf-adf0-444553540000}"; TYPE IUnknown COM Interface, ABSTRACT The type IUnknown is the base type of all COM interfaces. IUnknown is a pointer to an abstract record. PROCEDURE (this: IUnknown) AddRef; NEW, HIDDEN PROCEDURE (this: IUnknown) Release; NEW, HIDDEN The AddRef and Release methods are necessary to control the reference count of a COM object. AddRef and Release are always handled implicitly, they can neither be overwritten nor called. PROCEDURE (this: IUnknown) QueryInterface (IN [iid] iid: GUID; OUT [new] int: IUnknown): RESULT; NEW, DEFAULT QueryInterface is used to ask for interfaces a COM object supports. It is implemented by default but may be overwritten if special behaviour is needed (e.g. for objects which support several interfaces). For an example see module ComObject. The default implementation of QueryInterface has the following form. The pointer this.outer is a hidden reference to another COM object which can be specified with the two-argument NEW procedure (see below). PROCEDURE (this: IUnknown) QueryInterface ( IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; BEGIN IF this.outer # NIL THEN RETURN this.outer.QueryInterface(iid, int) ELSE IF COM.QUERY(this, iid, int) THEN RETURN WinApi.S_OK ELSE RETURN WinApi.E_NOINTERFACE END END END QueryInterface; PROCEDURE (this: IUnknown) RELEASE-; NEW, EMPTY The RELEASE method is called whenever the reference cout drops from one to zero. Note that if the system calls the RELEASE method, the interface is not necessarily removed by the garbage collector as Component Pascal pointer references to the object may still exist. RELEASE gives additional control over COM objects besides the FINALIZE method which is provided for all (tagged) Component Pascal records. In contrast to the FINALIZE method, the RELEASE method may be called several times. PROCEDURE ID (t: INTERFACETYPE): GUID The actual parameter must be the name of a type. Returns the GUID associated with interface type t (pointer or record). PROCEDURE ID (p: IUnknown): GUID Returns the GUID associated with the static type of the actual parameter passed for p. PROCEDURE ID (s: ARRAY OF CHAR): GUID Returns the GUID from a textual representation (string constant). PROCEDURE QUERY (p: COM.IUnknown; IN [iid] id: COM.GUID, OUT [new] ip: COM.IUnknown): BOOLEAN; QUERY allows safe assignments to polymorphic out parameters. If there exists a type t with the following properties: - t is an interface type - p points to an extension of t - ID(t) = id then p is assigned to ip and the function returns TRUE. Otherwise ip remains unchanged and the function returns FALSE. COM.QUERY allows safe and simple implementations of QueryInterface without any restrictions. New Predefined Procedures In the Direct-To-COM compiler the following additional predefined procedures are available. Function procedures VALID (v: VARPAR): BOOLEAN; v (a VAR [nil] parameter) is not nil Proper procedures NEW(VAR p: COM.IUnknown); allocates p^ NEW(VAR p: COM.IUnknown; outer: COM.IUnknown); allocates p^ as subobject of outer The two-argument version of NEW is used when implementing aggregation (see example ComAggregate) or to implement COM objects supporting several interfaces (see example ComObject). AddRef, Release, and QueryInterface calls are forwarded to the outer object. If AddRef or Release of p is called, then both the reference count of p and of the outer interface are incremented or decremented respectively. Unions In order to simplify the mapping of C data structures, the Direct-To-COM compiler supports union records. In a union record all fields are aligned at offset 0. The size of a union record is the maximal size of its fields. The semantics of union records are the one of C union structures and not the one of Pascal-like variant records. With nested records and union records, Pascal-like variant records can be simulated also. A union record is marked with the union sysflag. Example: TYPE Complex = RECORD type: SHORTINT; u: RECORD [union] cart: RECORD x, y: LONGREAL END; polar: RECORD phi, rho: LONGREAL END END END Warning: pointers in union records are unsafe and are ignored by the garbage collector! COM Programming Hints If you want to free an interface explicitly for some reason, just assign NIL to the interface pointer. This will call Release() on the pointer and additionally prevents you from using the (no longer valid) pointer accidentally. The golden rule of COM programming in Component Pascal: Never use an interface pointer if you can use a Component Pascal pointer instead. Although interface pointers are safely handled by the compiler, there are still unsafe constructs which must be handled carefully. This specifically applies to C pointers which are not interface pointers, like pointers to strings. The lifecycle of such pointers must be controlled by explicit Allocate and Deallocate calls. It also applies to structures containing C-style unions. Pointers in such structures (including interface pointers) must be handled manually. See the ComTools documentation for an example of how such a structure can be used safely. Compiler Implementation Restrictions - Untagged open arrays (arrays with unspecified length) containing interface pointers may not be assigned as a whole. Workaround: Assign the individual elements. - The array supplied for an out parameter of type "untagged array of interface pointer" may not be open. Workaround: Use an array with defined length. - Out parameters of type "untagged open array of pointer" are not initialized to NIL. Workaround: Initialize them manually.
Com/Docu/DTC-Comp.odc
Direct-To-COM Compiler The Integrated Development Environment Contents Linker InterfaceBrowser COMInterfaceInspector OtherCOMCommands Besides the compiler (which is described in COM Compiler Extension documentation), the DTC development environment offers some special facilities. Most of them are accessible through the COM menu. Linker With the linker Component Pascal modules can be linked to DLL (in process servers) or to EXE (out of process servers) files. Furthermore it can be decided whether a dynamic module loader should be added or not. This leads to the following four link commands: EXE DLL unextensible DevLinker.LinkExe DevLinker.LinkDll extensible DevLinker.Link DevLinker.LinkDynDll For further information about the linker we also refer to the DevLinker Documentation. DevLinker.Link This command links a module set containing a dynamic module loader to an EXE file. At startup the body of the main module is called. Initialization and termination of the dynamically loaded modules must be done by the runtime system. DevLinker.LinkExe This command links an nonextensible module set to an EXE file. At startup the bodies of all modules are called in the correct order. If the last body terminates, the terminators of all modules are called in reverse order. No runtime system is needed for initialization and termination. For an example see ComKoalaExe. DevLinker.LinkDll This command links a non-extensible module set to a DLL file. When the DLL is attached to a process, the bodies of all modules are called in the correct order. When the DLL is released from the process, the terminators of all modules are called in reverse order. No runtime system is needed for initialization and termination. For an example see ComKoalaDll. DevLinker.LinkDynDll (rarely used, present for completeness) Links a module set containing a dynamic module loader to a DLL file. When the DLL is attached to a process, the body of the main module is called. When the DLL is released from the process, the terminator of the main module is called. Initialization and termination of the dynamically loaded modules must be done by the runtime system. Interface Browser To quickly retrieve the actual definition of an interface, a special interface browser is available under the menu command COM->Interface Info. In contrast to the BlackBox browser, the COM interface browser displays additional information such as the number of the functions in the interface. Note that the first three entries of every interface are used by the functions of the IUnknown interface. If you select WinOle.IEnumUnknown and execute COM->Interface Info the following window is opened: COM Interface Inspector The COM interface inspector is the most important tool for the development of COM objects. It allows to inspect all currently allocated interface records. The browser is opened with the command COM->Show Interfaces. For every interface the actual value of its reference count is displayed. After the name and the address of an interface, a diamond mark allows to follow the pointer to the record to which it points (by clicking on the diamond mark). If the interface is anchored globally through a Component Pascal reference, the global anchor is also shown. With the Update link the interface inspector can be updated, and the All link allows to toggle between the display of all interfaces and of only the non-BlackBox-internal ones. Interfaces with reference count zero are no longer referenced through an interface pointer, however they might still be referenced by a Component Pascal pointer. Interfaces which are neither referenced through an interface pointer nor through a Component Pascal pointer are garbage collected upon the next run of the garbage collector. The run of the garbage collector can be enforced through the menu command COM->Collect. The collected interfaces disappear when the interface inspector is updated. Note: If you look at the ComObject example, you will see that every ComObject.Object interface contains Component Pascal pointers to the three interfaces ComObject.IOleObject, ComObject.IDataObject and ComObject.IPersistStorage, i.e. they are not removed by the garbage collector as long as interface pointers refer to a ComObject.Object. Other COM Commands Show Error Almost all COM and OLE API functions and nearly every interface method returns a value of type COM.RESULT. COM.RESULT is an alias type to INTEGER. A result code consists of a severity bit (success or error), a facility code and an error code. If result >= 0, then it is a success code, otherwise it is an error code. The menu command COM->Show Error can be used to obtain a full text description of the selected result. As input a selected integer is taken. The integer may be given in decimal or hexadecimal notation. E.g. if you select 1236 and execute COM->Show Error, the following window is opened: For the use in programs the most common error codes are defined in module WinApi. New GUID The command COM->New GUID generates a text which contains 10 interface GUIDs. It calls the OLE procedure CoCreateGuid. Collect The command COM->Collect explicitly calls the garbage collector.
Com/Docu/DTC-Env.odc
Map to the Direct-To-COM Compiler Documentation Introduction Direct-To-COM Compiler Tutorials TheComponentObjectModel HowtoDevelopnewCOMObjects TheDirect-To-COMCompiler Direct-To-COMExamples TheDevelopmentEnvironment Related Documentation ComponentPascelLanguageReport Platform-SpecificIssues BlackBoxDocumentation WindowsProgrammingInterfaces
Com/Docu/DTC-Help.odc
Direct-To-COM Compiler How to Develop new COM Objects This text gives an overview of the typical way in which new OLE objects are developed. It summarizes the most important aspects of what is detailed in the BlackBox user's guide. BlackBox is the integrated development environment (IDE) for the Direct-To-COM Component Pascal compiler with Safer OLE technology. In a first step, a subsystem name for the project is chosen, and a suitable directory created (with its Code, Mod, and Sym directories). This directory must be in the BlackBox directory itself, i.e. at the same location where the System, Std, etc. directories are. Note that there are no environment variables or path name lists in BlackBox. File lookup is static and determined by module names, not by configurable search paths or similar constructs. It can be convenient to provide a subsystem for private software, like test modules or personal tool commands, e.g. a subsystem Priv. It is helpful to set up a text document which contains the names of all the subsystem's modules, starting with the one lowest in the module hierarchy. Such a tool text can be used as input to the Dev->OpenModuleList command. This command opens the source file of the module whose name is selected. This is convenient since it can almost eliminate the need to navigate through the directory hierarchy. As a mnemonic aid, the keyboard equivalent for Dev->OpenModuleList is the digit "0", while the keyboard equivalent of the File->Open... command is the letter "O". Dev->OpenModuleList even allows to open several files at the same time, if the selection includes several module names. Now you are ready to create the module sources, which should be placed in your subsystem's Mod directory. In order to take advantage of autoindentation, you should use tab characters for indentation. You can directly compile the module on which you are working with the Dev->Compile command. This command compiles, but does not yet load, the module. The command Dev->CompileModuleList takes a list of module names and compiles them all. In order to load the module, you can execute one of its exported parameterless procedures, either by executing the Dev->Execute menu command on the command's name (e.g. on Dialog.Beep), or you can augment your tool text with commanders, e.g. Dialog.Beep (execute Tools->InsertCommander). Once loaded, a module remains loaded, unless you explicitly unload it. Unloading can be done by executing Unload when the source code is focused, or by selecting a module name and calling Dev->UnloadModuleList. This command also works on a sequence of module names, similar to Dev->CompileModuleList. Note that modules must be unloaded from top to bottom, since only modules which are not imported anymore may be unloaded. The loaded modules are displayed in the correct order by the command Info->Loaded Moules. This command opens a text which lists all loaded modules. The command Dev->Unload Module List may directly be called on a selection in this text. In this text, top-level modules, i.e. modules which are not imported by other modules, have a clients count of 0. For the unloading of top-level modules, there is a shortcut if you use a commander: ctrl-click on the commander first unloads the old version of the module, then loads the new version, and then calls the procedure. In order to get quick access to a module's definition or documentation, you can use the commands Info->Interface, or Info->Documentation, respectively. Info->Interface calls the browser to construct a definition text out of a module's symbol file. Note that in this text you can select further module names (or names of imported constants, variables, types, or procedures) and get the interface of those by calling the same command again. If there is a documentation file available for a module, you can execute Info->Documentation after selecting the module's name. This command opens the documentation text. If you have selected not only the module name (e.g. Math) but an object of this module (e.g. Math.Sin), the command tries to find the first occurence of the object's name which is written in boldface. The name is selected, and the window scrolls to the selection's position. In the rare cases where this first occurence is not the one you need, you may call Text->FindAgain to search for the next occurence. In order to test a module, you can use module Out to write debugging output into the Log window. In order to set breakpoints, you can introduce HALT statements and recompile the module. The trap text which is opened when the HALT is reached gives you information about the call chain (stack) as it has been at the moment the command was interrupted. Note that at no point in time the normal BlackBox environment is left; debugging takes place completely inside BlackBox. It is recommended to check preconditions and important invariants systematically in all programs, using the ASSERT statement. This debugging strategy is called static debugging, since error conditions are specified statically (even though they can be checked only at run-time). In an object-oriented environment, where the control flow tends to become too convoluted to follow step-by-step, the systematic application of assertions proves to keep debugging times shorter than any interactive debugging ever could. There is a global menu configuration text. It can be opened with command Info->Menus, edited, and then made the current configuration by calling Info->UpdateMenus. A menu item may not only have an action command, but also a guard command. Guards mainly determine whether a menu item is currently enabled or disabled. Distribution of a COM object basically consists of distributing a linked EXE file (application) or a linked DLL (e.g. a control). How does the dynamic loading facility of BlackBox, as described above, relate to COM binaries? Basically, dynamic loading of individual modules is convenient during development, so you don't need a separate linking step every time before trying out a new version of your code. Only before distributing the code you need to link it into an EXE or DLL. For example, if you develop an OLE object as one Component Pascal module, you typically load the module by executing its command that registers the object with OLE. Then you switch to some other application which is an OLE client (i.e. a container), such as MS Word. There you can insert the new object and try it out. If you detect some erroneous behavior, close the document and return to BlackBox, i.e. to the OLE server. Unload the module, correct the error in the Component Pascal module(s), recompile, and then continue again with loading the new version of the module. When working in this way, in principle you can use all BlackBox features for debugging, e.g. the Out module which writes into the Log text, or the symbolic debugger of BlackBox. Only when you're completely satisfied with the object's behavior, you link it together into a DLL. Unfortunately, for historical reasons ActiveX controls are treated somewhat differently than ordinary OLE objects. For example, controls require the existence of a DLL. For you, this means that you need to link the program into a DLL after each modification and compilation of the sources. Furthermore, for testing you need a program which is a control container; normal OLE containers are not sufficient.
Com/Docu/DTC-HowTo.odc
Direct-To-COM Compiler Introduction COM Microsoft's Component Object Model (COM) is a language and compiler independent interface standard for object interoperability on the binary level. COM specifies how objects implemented in one component can access services provided by objects implemented in another component. The services provided by objects are grouped in interfaces, which are sets of semantically related functions. For example, an ActiveX control is a COM object that extends OLE, by implementing concrete implementations of the necessary OLE interfaces. COM makes it possible that an extended software component can be updated without invalidating extending components, e.g., a new release of OLE can be introduced without breaking existing ActiveX controls. In such an evolving, decentrally constructed system it is difficult to decide whether an object is still used or whether it can be removed from the system. The client of an object does not know whether other clients still have access to the same object, and a server does not know whether a client passed its reference to other clients. This lack of global knowledge can make it hard to determine whether an object is no longer referenced, and thus could be released. If an object is released prematurely, then unpredictable errors will occur. The problem is critical in component software environments, because an erroneous component of one vendor may destroy objects implemented by other vendors' components. It may even take some time until the destroyed objects begin to visibly malfunction. For the end user, it is next to impossible to determine which vendor is to blame. As a consequence, some form of automatic garbage collection mechanism must be provided. In contrast to closed systems, this is a necessity with component software, and not merely an option or a convenience feature. COM uses reference counting as a rather simple form of garbage collection. Whenever a client gets access to a COM object, it must inform the object that a new reference exists. As soon as the client releases the COM object, it must inform the object that a reference will disappear. A COM object counts its references and thus can control its own lifetime. Direct-To-COM Compiler The problem with reference counting is that it depends on the discipline of the programmer. The situation is aggravated by additional subtle rules about who is responsible for the management of the reference counts if COM objects are passed as function arguments. Reliable software construction requires the management of reference counts to be automated. The Direct-To-COM compiler for Component Pascal completely automates memory management. The compiler and its small run-time system (module Kernel) hides the reference counting mechanism, i.e., a program need not call nor implement the AddRef and Release methods. For programmers, the integration of COM into a strongly typed, garbage-collected language has two major advantages. Firstly, it brings all the amenities of automatic garbage collection to COM. Secondly, it makes the handling of COM interfaces typesafe. Getting Started How should you start to get acquainted with this product? Note that all documentation is available on-line, and can be reached from the help screen. After the Installation of the BlackBox Component Builder, we suggest that you start with the introduction text ABriefHistoryofPascal. Then move on to the chapters of the user guide which deal with text editing and with the development tools (TextSubsystem and DevSubsystem). After you thus have gained a working knowledge of BlackBox, it is time to delve into the COM-specific parts of the IDE and the Component Pascal compiler extensions for COM. The section HowtoDevelopnewCOMobjects (p. 20) summarizes the main points of the user guide as far as it pertains to COM development. Then proceed with the various example implementations of COM objects, which demonstrate all basic aspects of COM programming. Knowledge of the Windows APIs (e.g. OLE) is assumed. Further Reading We recommend the following books on COM, OLE and ActiveX: Kraig Brockschmidt, Inside OLE, 2nd Edition, Microsoft Press, 1995. David Chappell, Understanding ActiveX and OLE, Microsoft Press, 1996, ISBN 1-57231-216-5. Adam Denning, OLE Controls Inside Out, Microsoft Press, 1995. Dale Rogerson, Inside COM, Microsoft Press, 1997, ISBN 1-57231-349-8, Don Box, Creating Components with DCOM and C++, Addison Wesley, 1997. Microsoft COM Home Page, http://www.microsoft.com/com
Com/Docu/DTC-Intro.odc
ComEnum ComEnum is a library containing implementations for the following standard enumerators: - IEnumUnknown - IEnumString - IEnumFormatEtc - IEnumOleVerb To use one of the enumerators, import the corresponding creation procedure and call it with your actual data. PROCEDURE CreateIEnumFORMATETC (num: INTEGER; IN format: ARRAY OF INTEGER; IN aspect, tymed: ARRAY OF SET; OUT enum: WinOle.IEnumFORMATETC); Creates an IEnumFormatEtc enumerator with num entries. The enumerated entries (of type FORMATETC) are initialized from the values in format[i], aspect[i], and tymed[i]. PROCEDURE CreateIEnumOLEVERB (num: INTEGER; IN verb: ARRAY OF INTEGER; IN name: ARRAY OF ARRAY OF CHAR; IN flags, attribs: ARRAY OF SET; OUT enum: WinOle.IEnumOLEVERB); Creates an IEnumOleVerb enumerator with num entries. The enumerated entries (of type OLEVERB) are initialized from the values in verb[i], name[i], flags[i], and attribs[i]. PROCEDURE CreateIEnumString (num: INTEGER; IN data: ARRAY OF ARRAY OF CHAR; OUT enum: WinOle.IEnumString); Creates an IEnumFormatEtc enumerator with num entries. The enumerated entries (of type WinApi.PtrWSTR) are initialized from the strings in data[i]. PROCEDURE CreateIEnumUnknown (num: INTEGER; IN data: ARRAY OF COM.IUnknown; OUT enum: WinOle.IEnumUnknown); Creates an IEnumFormatEtc enumerator with num entries. The enumerated entries (of type IUnknown) are initialized from the values in data[i]. Alternatively, the source code of the module can be used as a starting point for customized implementations or implementations of other enumerators. ComEnumsources
Com/Docu/Enum.odc
ComEnumRect Example This is a simple example adapted form the same example in the book "Inside OLE". The interface IEnumRECT (an enumerator for rectangles) is defined and implemented in this module. The interface consists of the following four methods: IEnumRECT = POINTER TO ABSTRACT RECORD ["{00021140-0000-0000-C000-000000000046}"] (COM.IUnknown) (this: IEnumRECT) Next (num: INTEGER; OUT elem: ARRAY [untagged] OF WinApi.RECT; OUT [nil] fetched: INTEGER): COM.RESULT, NEW, ABSTRACT; (this: IEnumRECT) Skip (num: INTEGER): COM.RESULT, NEW, ABSTRACT (this: IEnumRECT) Reset (): COM.RESULT, NEW, ABSTRACT; (this: IEnumRECT) Clone (OUT enum: IEnumRECT): COM.RESULT, NEW, ABSTRACT; END; For the implementation, an array of length 15 is used. As the interface is implemented in one record (EnumRECT), the default implementation for QueryInterface can be used. ComEnumRectsources
Com/Docu/EnumRect.odc
DevComInterfaceGen DEFINITION DevComInterfaceGen; IMPORT Dialog; VAR dialog: RECORD library: Dialog.List; fileName: ARRAY 256 OF CHAR; modName: ARRAY 64 OF CHAR END; PROCEDURE Browse; PROCEDURE GenAutomationInterface; PROCEDURE GenCustomInterface; PROCEDURE BrowseTypeLib; PROCEDURE InitDialog; PROCEDURE Open; PROCEDURE Close; PROCEDURE ListBoxNotifier (op, from, to: INTEGER); PROCEDURE TextFieldNotifier (op, from, to: INTEGER); ... plus some private items ... END DevComInterfaceGen. Module DevComInterfaceGen provides services to automatically generate COM interface modules. Interface modules are used by BlackBox to access COM components in several different ways. One of them is Automation. Any application (server) supporting Automation can be controlled from within another application (controller). The interface of a server application, i.e., the objects provided by the application and the operations on these objects, are described in a COM type library. In order to write a controller in BlackBox, an interface module is used which contains a Component Pascal object for each COM object in the type library. These objects can be accessed like other Component Pascal objects in a convenient and typesafe way. They hide the details of the Automation standard. The Ctl subsystem includes several such Automation interface modules. (Basically for MS Office Automation servers.) Module DevComInterfaceGen provides services to automatically generate Automation interfaces from the corresponding type libraries. In certain situations, however, the automatically generated interface module does not compile without errors. Here some minimal manual work is required. So far we have encountered three kinds of difficulties that may occur: 1. Formal parameter name is equal to parameter type name. Solution: Change the formal parameter name in the parameter list and procedure body. 2. Formal parameter name is equal to return type name. Solution: Change the formal parameter name in the parameter list and procedure body. 3. Constant name is equal to some type name. Solution: Change constant name. VAR dialog: RECORD The interactor for the Generate Automation Interface dialog. library: Dialog.List A list representing all type library entries that are registered in the system's registration database. fileName: ARRAY 256 OF CHAR Complete path name of the type library. modName: ARRAY 64 OF CHAR Module name of the Automation interface module to be generated from the corresponding type library. PROCEDURE Browse Open a standard open file dialog box, to let the user choose a type library or DLL file. PROCEDURE GenAutomationInterface Generates the automation interface module according to the parameters in dialog. PROCEDURE GenCustomInterface Generates the custom interface module according to the parameters in dialog. PROCEDURE BrowseTypeLib Generates an interface module suitable for browsing the contents of the type library according to the parameters in dialog. PROCEDURE InitDialog Initializes the dialog interactor. PROCEDURE Open Calls InitDialog and opens the dialog if it was closed. Otherwise brings the dialog to front. PROCEDURE Close Closes the dialog and clears the state. PROCEDURE ListBoxNotifier (op, from, to: INTEGER) PROCEDURE TextFieldNotifier (op, from, to: INTEGER) Notifiers used by the Generate Automation Interface dialog.
Com/Docu/InterfaceGen.odc
ComKoala Example This example is one of the simplest COM examples. It provides a component which implements the IUnknown interface. In DTC Component Pascal, a concrete extension of the base interface must be defined. The two methods AddRef and Release are implemented by the compiler, and for QueryInterface, the default implementation can be taken. Thus, only the following two lines are necessary to implement this simple interface. TYPE Koala = POINTER TO RECORD (COM.IUnknown) END; A set of interfaces is implemented in a COM class. A COM class may be identified by a unique class identifier (CLSID) which is also a GUID. A run-time instantiation of a COM class is called a COM object. Each COM class is implemented in a COM server. The server is a piece of code compiled into an executable (EXE file) or into a dynamic link library (DLL file). For every COM class, the server must provide a factory object through which a new instance can be constructed. This factory object can be registered in the Windows registry. CONST KoalaId = "{00021146-0000-0000-C000-000000000046}"; (* the CLSID *) TYPE KoalaFactory = POINTER TO RECORD (WinOle.IClassFactory) END; The interface of the factory supports two methods: CreateInstance and LockServer. The methods of the IUnknown interface are again implemented by the compiler. Through CreateInstance new Koala objects are requested. The required interface of the new object is passed as parameter iid. The implementation simply creates a new Koala object (using NEW) and asks QueryInterface of the newly generated object to return the requested interface. PROCEDURE (this: KoalaFactory) CreateInstance (outer: COM.IUnknown; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR res: COM.RESULT; new: Koala; BEGIN IF outer # NIL THEN RETURN WinApi.CLASS_E_NOAGGREGATION END; NEW(new); IF new # NIL THEN RETURN new.QueryInterface(iid, int) ELSE RETURN WinApi.E_OUTOFMEMORY END END CreateInstance; In module ComKoalaTst some test routines are implemented which demonstrate the use of ComKoala and which in particular illustrate the usual szenario when creating COM objects. First, the ComKoala server must instantiate a class factory and register it with the command WinOle.CoRegisterClassObject under its CLSID. This is implemented in the command ComKoala.Register If you now look at the interface inspector you see that interface ComKoala.KoalaFactory is allocated and has a reference count of one (the reference in the registry). Now the client can request a pointer to the class factory by calling WinOle.CoGetClassObject. As second argument we specify that the local server (i.e. BlackBox) has to be used. Now the reference count of the factory has been incremented to two (the reference in the registry and the reference we just created). ComKoalaTst.CreateClass Through the factory object a Koala object can now be generated. The factory creates an instance of ComKoala.Koala and returns a pointer to the IUnknown interface. The interface browser now shows a new allocated interface. ComKoalaTst.CreateInstance With the commands ComKoalaTst.AddRef and ComKoalaTst.Release the number of references can be incremented or decremented. Look at the updated interface browser from time to time. Whenever the command CreateInstance is called again, a new instance is created. ComKoalaTst.AddRef ComKoalaTst.Release The factory reference which is held by module ComKoalaTst can be released with the command ComKoalaTst.ReleaseClass and the reference in the Windows registry is removed by calling WinOle.CoRevokeClassObject. The latter operation is implemented in the command ComKoala.Release Note that the two references to the factory can be released in any order. As soon as the registry reference is released, no new classes can be generated through WinOle.CoGetClassObject, and as soon as the factory reference in module ComKoalaTst is released, no new instances can be created. The implementation can also be tested with the ObjUser.exe program which is provided in the Inside OLE book. Before you can use it, you must register the factory (ComKoala.Register) and you must set the ObjUser.exe program in EXE mode. ComKoalasources ComKoalaTstsources
Com/Docu/Koala.odc
ComKoalaDll Example This version of the Koala example can be linked as an independent DLL. It can be tested with the ObjUser.exe program which is provided with the book "Inside OLE". Note that you have to set the ObjUser.exe program into DLL mode. The implementation of the DLL only slightly differs from the first ComKoala implementation. One difference is that a counter is provided which counts the number of instances. This counter is incremented whenever a new object is created (CreateInstance method), and it is decremented if the last interface reference is removed (RELEASE finalizer). Every in-process server must provide the two functions DllGetClassObject and DllCanUnloadNow. The first procedure is called whenever a factory is required, and with the second command it is tested whether the DLL can be unloaded. The DLL can be unloaded if no object generated by a factory of the DLL is referenced through an interface pointer and if no factory of the DLL was locked with the factory's LockServer method. This ComKoalaDll example can be linked to DKoala1.dll with the following command: DevLinker.LinkDll "Com/DKoala1.dll" := Kernel+ ComKoalaDll# ~ The registry must be informed about which DLL to launch if a IKoala factory is required. The necessary registry file Com/Reg/DKoala1.reg is given below. Use the REGEDIT tool to update the registry. Adjust path names if necessary! REGEDIT HKEY_CLASSES_ROOT\Koala1.0 = Koala Object Chapter 5 HKEY_CLASSES_ROOT\Koala1.0\CLSID = {00021146-0000-0000-C000-000000000046} HKEY_CLASSES_ROOT\Koala = Koala Object Chapter 5 HKEY_CLASSES_ROOT\Koala\CurVer = Koala1.0 HKEY_CLASSES_ROOT\Koala\CLSID = {00021146-0000-0000-C000-000000000046} HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046} = Koala Object Chapter 5 HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\ProgID = Koala1.0 HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\VersionIndependentProgID = Koala HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\InprocServer32 = C:\BlackBox\Com\DKoala1.dll HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\NotInsertable ComKoalaDllsources
Com/Docu/KoalaDll.odc
ComKoalaExe Example This version of the Koala example can be linked as an independent exe. It can be tested with the ObjUser.exe program which is provided with the book "Inside OLE". Note that you have to set the ObjUser.exe program into EXE mode. The EXE file opens its application window which is closed as soon as the last interface pointer is released. It also must implement a main loop which polls and dispatches all Windows events. Additionally, the body of the module must register the factory upon start up and remove the factory from the registry as soon as the EXE is unloaded. The ComKoalaExe example can be linked to EKoala1.EXE with the following command: DevLinker.LinkExe "Com/EKoala1.exe" := Kernel+ ComKoalaExe ~ The registry must be informed about which program to start if a local server for our IKoala factory ({00021146-0000-0000-C000-000000000046}) is requested. The necessary registry fileCom/Reg/EKoala1.reg is given below. Use the REGEDIT tool to update the registry. Adjust path names if necessary! REGEDIT HKEY_CLASSES_ROOT\Koala1.0 = Koala Object Chapter 5 HKEY_CLASSES_ROOT\Koala1.0\CLSID = {00021146-0000-0000-C000-000000000046} HKEY_CLASSES_ROOT\Koala = Koala Object Chapter 5 HKEY_CLASSES_ROOT\Koala\CurVer = Koala1.0 HKEY_CLASSES_ROOT\Koala\CLSID = {00021146-0000-0000-C000-000000000046} HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046} = Koala Object Chapter 5 HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\ProgID = Koala1.0 HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\VersionIndependentProgID = Koala HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\LocalServer32 = C:\BlackBox\Com\Ekoala1.exe HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\NotInsertable ComKoalaExesources
Com/Docu/KoalaExe.odc
ComKoala Example: ComKoalaTst Test program for ComKoala. There is no separate documentation.
Com/Docu/KoalaTst.odc
ComObject Example This example implements a simple OLE server which provides the following OLE object: This object implements the four interfaces IUnknown, IOleObject, IDataObject and IPersistStorage and uses several other interfaces. Beside of this, the module also implements a factory object which can be registered and which provides the creation of new objects of the above type. In order to implement the four interfaces, four Component Pascal records are defined as subtypes of the particular interface records. These objects refer to each other in the following way: The record which implements the IUnknown interface contains the object data. The references to the other interface records are necessary in order to implement the QueryInterface method. The other interfaces need a reference to the IUnknown object to access the object data as well as to implement their QueryInterface. Note that other definitions would be possible also. Instead of such a symmetric approach, the interface IOleObject could play the role of the main interface and administrate the object's instance variables. Object = POINTER TO RECORD (COM.IUnknown) ioo: IOleObject; ido: IDataObject; ips: IPersistStorage; (* and other fields *) END; IOleObject = POINTER TO RECORD (WinOle.IOleObject) obj: Object END; IDataObject = POINTER TO RECORD (WinOle.IDataObject) obj: Object END; IPersistStorage = POINTER TO RECORD (WinOle.IPersistStorage) obj: Object END; Object creation New objects are created through the method CreateInstance of the class factory. This method allocates the objects, defines the relation between the involved interfaces and returns a pointer to the requested interface. The implementation of the QueryInterface method of the three interfaces IOleObject, IDataObject and IPersistStorage is simplified by using hidden references to the main record. These hidden references are generated with the two-argument NEW. VAR new: Object; NEW(new); NEW(new.ioo, new); NEW(new.ido, new); NEW(new.ips, new); new.ioo.obj := new; new.ido.obj := new; new.ips.obj := new; All QueryInterface calls are thus forwarded to the QueryInterface method of Object. The explicit references to Object are only used to access the instance variables of the object. Instance variables which would be used by the implementation of one interface only could also be stored in the corresponding record directly. If one of the interfaces IOleObject, IDataObject or IPersistStorage is requested through QueryInterface, then the reference count of the particular record as well as the reference count of the main object is incremented. The latter one is incremented since the requested interface contains a (hidden) reference to the main object. As an alternative, the four records could also be allocated with the one-argument NEW, but then QueryInterface calls would have to be forwarded to the main object by hand for the implementations of the interfaces IOleObject, IDataObject and IPersistStorage. The following procedure shows how that would be done. PROCEDURE (this: IOleObject) QueryInterface (VAR iid: COM.GUID; VAR int: COM.IUnknown): COM.RESULT; BEGIN RETURN this.obj.QueryInterface(iid, int) END QueryInterface; QueryInterface The second interesting aspect is the implementation of QueryInterface of Object. For all the interfaces that the object supports, the COM.QUERY function is called one by one. If the IUnknown interface is requested, then always the same interface pointer is returned, although all involved interfaces support the IUnknown methods. This is a requirement of the COM specification. PROCEDURE (this: Object) QueryInterface (IN iid: COM.GUID; OUT int: COM.IUnknown): COM.RESULT; BEGIN IF COM.QUERY(this, iid, int) OR COM.QUERY(this.ioo, iid, int) OR COM.QUERY(this.ido, iid, int) OR COM.QUERY(this.ips, iid, int) THEN RETURN WinApi.S_OK ELSE RETURN WinApi.E_NOINTERFACE END Registry With the command ComObject.Register the factory can be registered. As soon as it is registered it can be requested with a call to the procedure CoGetClassObject (it has to be requested from a local server, namely the running BlackBox). VAR factory: WinOle.IClassFactory; res: COM.RESULT; res := WinOle.CoGetClassObject("{00010001-1000-11cf-adf0-444553540000}", WinOle.CLSCTX_LOCAL_SERVER, 0, COM.ID(factory), factory) If the object is also registered in the Windows registry, then the object can be inserted in any OLE container using the Insert Object menu entry, provided that the factory has been registered using the command ComObject.Register. The necessary registry file Com/Reg/Object.reg is given below. Use the REGEDIT tool to update the registry. Adjust path names if necessary! Note that you cannot insert it into a BlackBox document of the BlackBox which is the server for this object, because then the object would be inserted in-process, and thus the in-process handler would not be used. However, you can insert this object in a document of another running BlackBox. Once the smiley object has successfully been inserted into an OLE container, you can inspect with the interface inspector how many interfaces the client has requested. REGEDIT HKEY_CLASSES_ROOT\BlackBox.Object = BlackBox Object HKEY_CLASSES_ROOT\BlackBox.Object\CLSID = {00010001-1000-11cf-adf0-444553540000} HKEY_CLASSES_ROOT\BlackBox.Object\Insertable HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000} = BlackBox Object HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\ProgID = BlackBox.Object HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\LocalServer32 = C:\BlackBox\BlackBox.exe HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\InProcHandler32 = ole32.dll HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\Insertable HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\DefaultIcon = C:\BlackBox\BlackBox.exe,0 HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\DataFormats\GetSet\0 = 3,1,32,1 HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\MiscStatus = 16 HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\AuxUserType\2 = BlackBox Object HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\AuxUserType\3 = BlackBox It would also be possible to generate a new executable which acts as server for this BlackBox object. You find a similar example in ComKoalaExe. In particular, the main event loop has to be implemented. If you intend to link this object implementation into a DLL, then the additional interfaces IViewObject2, IOleCache2, and IRunnableObject would have to be implemented. ComObjectsources
Com/Docu/Object.odc
ComPhoneBook Example In this example we show the implementation of a COM component which implements a simple phone directory database that manages customer names and telephone numbers. This database can be queried by name and by number. For our phone directory service we define the interface ILookup. This interface contains the methods LookupByName and LookupByNumber, which return a phone number for a given name, and vice versa. Clients of the phonebook component can access the component's services through this interface only. The interface identifier (IID) of this interface is {C4910D71-BA7D-11CD-94E8-08001701A8A3}. This IID is a globally unique identifier (GUID), i.e., unique in time and space. The definition of this interface ILookup.idl in the Microsoft interface definition language (MIDL) is shown below: [ object, uuid(c4910d71-ba7d-11cd-94e8-08001701a8a3), pointer_default(unique) ] interface ILookup : IUnknown { import "unknwn.idl"; HRESULT LookupByName([in] LPTSTR lpName, [out, string] WCHAR **lplpNumber); HRESULT LookupByNumber([in] LPTSTR lpNumber, [out, string] WCHAR **lplpName); } In the DTC Component Pascal, this interface is defined as an abstract extension of COM.IUnknown marked by its IID. The compiler does prohibit instantiation of objects of this type, and it does also prohibit implementation of the abstract methods, but variables of type ILookup can be used as interface pointers as we will see later. TYPE ILookup* = POINTER TO ABSTRACT RECORD ["{C4910D71-BA7D-11CD-94E8-08001701A8A3}"] (COM.IUnknown) END; PROCEDURE (this: ILookup) LookupByName*( name: WinApi.PtrWSTR; OUT number: WinApi.PtrWSTR): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: ILookup) LookupByNumber*( number: WinApi.PtrWSTR; OUT name: WinApi.PtrWSTR): COM.RESULT, NEW, ABSTRACT; The implementation of the phone book directory interface is an extension of the abstract interface record ILookup. The phone book is represented as a linear list. The root of the list is stored as private data in the interface record. The two methods LookupByName and LookupByNumber implement a simple linear search. If no entry is found, a special error code is returned. Module ComTools offers auxiliary routines to convert e.g. strings from and to Windows data structures. TYPE CLookup = POINTER TO RECORD (ILookup) phoneBook: Entry END; Entry = POINTER TO RECORD next: Entry; name, number: ARRAY 32 OF CHAR END; To allow access to instances of this COM class, a factory object needs to be provided. The CreateInstance method creates a new object, initializes it and returns the requested interface (in this example this might be the interface IUnknown or ILookup). Note, that the implementation of the interface is usually not exported, only the CLSID must be known in order to create new instances of this class. The procedures ComPhoneBook.Register and ComPhoneBook.Unregister can be used to register a reference of the factory object in the COM library, from where it can be requested using the CLSID. CONST CLSID* = "{E67D346C-2A5B-11D0-ADBA-00C01500554E}"; TYPE LookupFactory = POINTER TO RECORD (WinOle.IClassFactory) END; In module ComPhoneBookClient the implementation of a simple client of the phone directory is given. With the Windows procedure CoCreateInstance a new instance of the phone directory object is created. If the creation is successful, a pointer to the interface ILookup is assigned to the interface pointer phoneBook, through which the methods LookupByName and LookupByNumber can be called. The combo box shown in the figure below can be opened with the command "StdCmds.OpenToolDialog('Com/Rsrc/PhoneBook', 'PhoneBook')" Through this mask, the phone directory can be accessed. It is also possible to use this interface across process boundaries. For this purpose, however, marshalling code must be provided in proxy and stub objects, and the reference to the DLL which implements the proxy and stub objects must be registered in the Windows registry. The proxy and stub code can be generated with the MIDL compiler based on the interface description in the Microsoft interface definition language. The MIDL compiler generates C source code. For the ILookup interface all necessary files are provided in the directory Com/Interfaces/Lookup. The generated DLL is a self registering DLL, i.e., you have to execute the program REGSVR32 on this DLL in order to register it. Once the proxy and stub DLLs have been registered, it is possible to communicate across process boundaries. You can test this if you start BlackBox in two separate processes, register the factory object in one process using the command ComPhoneBook.Register and look for phone book entries in the other process through the dialog "StdCmds.OpenToolDialog('Com/Rsrc/PhoneBook', 'PhoneBook')". If you have DCOM installed, then the two Component Pascal programs can even run on two different machines. The parameter in the call of procedure WinOle.CoCreateInstance needs then to be adjusted. ComPhoneBooksources
Com/Docu/PhoneBook.odc
ComPhoneBookActiveX Example In this example a simple ActiveX control is implemented. The control offers the same functionality as the phone book in the ComPhoneBook example, but in this example, clients communicate through a dispatch interface. The control will be linked into a DLL and can be used as an ActiveX control from any client which properly supports the ActiveX standard. The dispatch interface also has to be described in a MIDL definition. This definition is stored in file Phone.idl and shown below: [ uuid(C4910D73-BA7D-11CD-94E8-08001701A8A3), version(1.0), helpstring("PhoneBook ActiveX Control") ] library PhoneBookLib { importlib("stdole32.tlb"); [ uuid(C4910D72-BA7D-11CD-94E8-08001701A8A3), helpstring("Dispatch interface for PhoneBook ActiveX Control") ] dispinterface DPhoneBook { properties: methods: [id(1)] BSTR LookupByName(BSTR name); [id(2)] BSTR LookupByNumber(BSTR number); }; [ uuid(E67D346B-2A5B-11D0-ADBA-00C01500554E), helpstring("PhoneBook ActiveX Control") ] coclass PhoneBook { [default] dispinterface DPhoneBook; }; } With the MIDL compiler, a type library is generated. Once this library has been registered in the Windows registry it can be inspected with the OLE ITypeLib Viewer. In DTC Component Pascal, this interface is defined as an abstract extension of WinOleAut.IDispatch, the base type of all dispatch interface. This interface contains the following four methods which must be implemented: TYPE IDispatch = POINTER TO ABSTRACT RECORD ["{00020400-0000-0000-C000-000000000046}"] (COM.IUnknown) (this: IDispatch) GetIDsOfNames (IN [nil] riid: COM.GUID; IN [nil] rgszNames: WinApi.PtrWSTR; cNames: INTEGER; lcid: WinOle.LCID; OUT [nil] rgDispId: WinOleAut.DISPID): COM.RESULT, NEW, ABSTRACT; (this: IDispatch) GetTypeInfo (iTInfo: INTEGER; lcid: WinOle.LCID; OUT [nil] ppTInfo: WinOleAut.ITypeInfo): COM.RESULT, NEW, ABSTRACT; (this: IDispatch) GetTypeInfoCount (OUT [nil] pctinfo: INTEGER): COM.RESULT, NEW, ABSTRACT; (this: IDispatch) Invoke (dispIdMember: WinOleAut.DISPID; IN riid: COM.GUID; lcid: WinOle.LCID; wFlags: SHORTINT; VAR [nil] pDispParams: WinOleAut.DISPPARAMS; OUT [nil] pVarResult: WinOleAut.VARIANT; OUT [nil] pExcepInfo: WinOleAut.EXCEPINFO; OUT [nil] puArgErr: INTEGER): COM.RESULT, NEW, ABSTRACT END; The implementation of this interface is a concrete extension of the abstract dispatch interface. The main method is the Invoke method. Through this method the functions of the interface are called. The number of the function to be invoced is passed in parameter dispIdMember, and the parameters are passed in the array pDispParams as variant records. The result is returned through parameter pVarResult, a variant record as well. The other three methods of this interface provide information about the interface itself. They can easily be implemented if a type library is available. Besides the implementation of the dispatch interface, a factory object must be provided. Furthermore, the two global functions DllGetClassObject and DllCanUnloadNow have to be implemented. These two routines are called by the COM library. If the DLL is loaded it is asked to return a reference to the factory object, and with the function DllCanUnloadNow the COM library tests whether the DLL can be unloaded. If module ComPhoneBookActiveX has been compiled, a DLL can be linked with the command DevLinker.LinkDll "Com/phone.dll" := Kernel+ ComTools ComPhoneBookActiveX# ~ This command generates a DLL with a size of 40KBytes only. In order to load this DLL it must be registered in the Windows registry. Note, that the CLSID for this implementation is different than the CLSID of example ComPhoneBook. Besides the CLSID, the information about the type library must be stored in the registry, and in particular the CLSID entry must contain a reference to the GUID under which the type library is referenced. The necessary registry file Com/Interfaces/DPhoneBook/Phone.reg is given below. Use the REGEDIT tool to update the registry. Adjust path names if necessary! REGEDIT HKEY_CLASSES_ROOT\PhoneBook = PhoneBook ActiveX Control HKEY_CLASSES_ROOT\PhoneBook\CLSID = {E67D346B-2A5B-11D0-ADBA-00C01500554E} HKEY_CLASSES_ROOT\PhoneBook\TypeLib = {C4910D73-BA7D-11CD-94E8-08001701A8A3} HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E} = PhoneBook ActiveX Control HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\ProgID = PhoneBook1.0 HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\Control HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\Version = 1.0 HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\VersionIndependentProgID = PhoneBook HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\TypeLib = {C4910D73-BA7D-11CD-94E8-08001701A8A3} HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\InprocServer32 = C:\BlackBox\Com\phone.dll HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\NotInsertable HKEY_CLASSES_ROOT\TypeLib\{C4910D73-BA7D-11CD-94E8-08001701A8A3}\1.0 = PhoneBook ActiveX Control HKEY_CLASSES_ROOT\TypeLib\{C4910D73-BA7D-11CD-94E8-08001701A8A3}\1.0\0\win32 = C:\BlackBox\Com\Interfaces\DPhoneBook\phone.tlb HKEY_CLASSES_ROOT\TypeLib\{C4910D73-BA7D-11CD-94E8-08001701A8A3}\1.0\FLAGS = 0 HKEY_CLASSES_ROOT\TypeLib\{C4910D73-BA7D-11CD-94E8-08001701A8A3}\1.0\HELPDIR = C:\BlackBox\Com\Interfaces\DPhoneBook Once this information has been stored, the phonebook ActiveX control is ready to be used. As an example we demonstrate how it can be used through the Internet Explorer. With the <OBJECT> tag an ActiveX control can be embedded in any HTML page. As an example the html page Com/Rsrc/phone.html is provided. Note, that the only reference to the ActiveX control is its CLSID. The phone book is accessed in the two VBScript commands PhoneBook.LookupByName(NameField.value) and PhoneBook.LookupByNumber(NameField.value). <HTML> <HEAD> <TITLE>ActiveX Demo - Phonebook</TITLE> </HEAD> <BODY> <H1>BlackBox Phone Book Example</H1> <OBJECT CLASSID="CLSID:E67D346B-2A5B-11D0-ADBA-00C01500554E" ID=PhoneBook > </OBJECT> This page uses a small (40K) non-visual control which provides access to a phone book which also might run on a remote computer. This ActiveX control has been implemented with the DTC Component Pascal compiler. <P> Enter a name or a phone number and press the corresponding button: <P> <INPUT TYPE="text" NAME = "NameField" SIZE=20> <INPUT TYPE=BUTTON VALUE="Lookup by Name" NAME="NameBtn" > <INPUT TYPE=BUTTON VALUE="Lookup by Number" NAME="NumberBtn"> <SCRIPT LANGUAGE=VBScript> Sub NameBtn_Onclick alert "Phone number of " & NameField.value & ": " & PhoneBook.LookupByName(NameField.value) End Sub Sub NumberBtn_Onclick alert "Name of line " & NameField.value & ": " & PhoneBook.LookupByNumber(NameField.value) End Sub </SCRIPT> </BODY> </HTML> The following figure shows a screen dump of Internet Explorer if this html page is inspected. ComPhoneBookActiveXsources
Com/Docu/PhoneBookActiveX.odc
ComPhoneBook Example: ComPhoneBookClient Phonebook client program. There is no separate documentation.
Com/Docu/PhoneBookClient.odc
Map to the Direct-To-COM Examples COM Interface Usage ComEnumRectdocu ComEnumRectsources simple COM object ComObjectdocu ComObjectsources minimal OLE server ComConnectdocu ComConnectsources connection points ComAggregatedocu ComAggregatesources usage of aggregation Inprocess and Local Servers ComKoaladocu ComKoalasources local server in BlackBox ComKoalaTstsources test program for ComKoala ComKoalaExedocu ComKoalaExesources independent local server ComKoalaDlldocu ComKoalaDllsources in process server Tool Libraries ComToolsdocu ComToolssources tools for unsafe structures ComEnumdocu ComEnumsources standard enumerators Sample Control ComPhoneBookdocu ComPhoneBooksources simple phonebook ComPhoneBookActiveX ComPhoneBookActiveX phonebook as ActiveX ComPhoneBookClient phonebook client
Com/Docu/Sys-Map.odc
ComTools ComTools is a library containing routines for the handling of often used and partially unsafe data structures. These data structures are unsafe because they contain C unions or C pointers (not interface pointers) or both. ComTools can be imported as a tool package or its source can be used as starting point for customized implementations. String handling Strings are pointers to arrays of unspecified length. They must be allocated and deallocated manually. PROCEDURE NewString (IN str: ARRAY [untagged] OF CHAR): WinApi.PtrWSTR; PROCEDURE NewEmptyString (length: INTEGER): WinApi.PtrWSTR; PROCEDURE FreeString (VAR p: WinApi.PtrWSTR); PROCEDURE NewSString (IN str: ARRAY [untagged] OF SHORTCHAR): WinApi.PtrSTR; PROCEDURE NewEmptySString (length: INTEGER): WinApi.PtrSTR; PROCEDURE FreeSString (VAR p: WinApi.PtrSTR); STGMEDIUM The STGMEDIUM structure contains a C union and various pointers. The following procedures can be used to properly initialize one of the seven possible STGMEDIUM variants: PROCEDURE GenBitmapMedium (bitmap: WinApi.HBITMAP; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM); PROCEDURE GenEMetafileMedium (emf: WinApi.HENHMETAFILE; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM); PROCEDURE GenFileMedium (name: ARRAY OF CHAR; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM); PROCEDURE GenGlobalMedium (hg: WinApi.HGLOBAL; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM); PROCEDURE GenMetafileMedium (mf: WinApi.HMETAFILEPICT; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM); PROCEDURE GenStorageMedium (stg: WinOle.IStorage; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM); PROCEDURE GenStreamMedium (stm: WinOle.IStream; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM); Safe access to the variable part of the structure should be done by one of these functions: PROCEDURE MediumBitmap (IN sm: WinOle.STGMEDIUM): WinApi.HBITMAP; PROCEDURE MediumEnhMetafile (IN sm: WinOle.STGMEDIUM): WinApi.HENHMETAFILE; PROCEDURE MediumFile (IN sm: WinOle.STGMEDIUM): WinApi.PtrWSTR; PROCEDURE MediumGlobal (IN sm: WinOle.STGMEDIUM): WinApi.HGLOBAL; PROCEDURE MediumMetafile (IN sm: WinOle.STGMEDIUM): WinApi.HMETAFILEPICT; PROCEDURE MediumStorage (IN sm: WinOle.STGMEDIUM): WinOle.IStorage; PROCEDURE MediumStream (IN sm: WinOle.STGMEDIUM): WinOle.IStream; STGMEDIUM structures must be released manually. Use the OLE library procedure WinOle.ReleaseStgMedium for that purpose: PROCEDURE ReleaseStgMedium (VAR [nil] sm: WinOle.STGMEDIUM); FORMATETC generation This procedure can be used to quickly initialize a FORMATETC structure. PROCEDURE GenFormatEtc (format: SHORTINT; aspect, tymed: SET; OUT f: WinOle.FORMATETC); ComToolssources
Com/Docu/Tools.odc
DevTypeLibs Module DevTypeLibs deals with information provided by COM type libraries. This module has a private interface, it is only used internally.
Com/Docu/TypeLibs.odc
MODULE ComAggregate; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" references = "adapted from Reuse sample in "Inside OLE", 2nd ed." changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinApi, StdLog; TYPE IAnimal = POINTER TO ABSTRACT RECORD ["{00021143-0000-0000-C000-000000000046}"] (COM.IUnknown) END; CAnimal = POINTER TO RECORD (COM.IUnknown) impl: CImpIAnimal END; CImpIAnimal = POINTER TO RECORD (IAnimal) obj: CAnimal END; IKoala = POINTER TO ABSTRACT RECORD ["{00021144-0000-0000-C000-000000000046}"] (COM.IUnknown) END; CKoala = POINTER TO RECORD (COM.IUnknown) impl: CImpIKoala; animal: COM.IUnknown END; CImpIKoala = POINTER TO RECORD (IKoala) obj: CKoala END; VAR koala: COM.IUnknown; (* ---------- IAnimal ---------- *) PROCEDURE (this: IAnimal) Eat (): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: IAnimal) Sleep (): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: IAnimal) Procreate (): COM.RESULT, NEW, ABSTRACT; (* ---------- CAnimal ---------- *) PROCEDURE (this: CAnimal) QueryInterface (IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; BEGIN IF COM.QUERY(this, iid, int) OR COM.QUERY(this.impl, iid, int) THEN RETURN WinApi.S_OK ELSE RETURN WinApi.E_NOINTERFACE END END QueryInterface; (* ---------- CImpIAnimal ---------- *) PROCEDURE (this: CImpIAnimal) Eat (): COM.RESULT; BEGIN StdLog.String("Animal's IAnimal.Eat called"); StdLog.Ln; RETURN WinApi.S_OK END Eat; PROCEDURE (this: CImpIAnimal) Sleep (): COM.RESULT; BEGIN StdLog.String("Animal's IAnimal.Sleep called"); StdLog.Ln; RETURN WinApi.S_OK END Sleep; PROCEDURE (this: CImpIAnimal) Procreate (): COM.RESULT; BEGIN StdLog.String("Animal's IAnimal.Procreate called"); StdLog.Ln; RETURN WinApi.S_OK END Procreate; (* ---------- Animal creation ---------- *) PROCEDURE CreateAnimal (outer: COM.IUnknown; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR new: CAnimal; BEGIN IF (outer # NIL) & (iid # COM.ID(COM.IUnknown)) THEN RETURN WinApi.CLASS_E_NOAGGREGATION END; NEW(new); IF new # NIL THEN IF outer = NIL THEN NEW(new.impl, new) ELSE NEW(new.impl, outer) END; IF new.impl # NIL THEN new.impl.obj := new; StdLog.String("Animal allocated"); StdLog.Ln; RETURN new.QueryInterface(iid, int) END END; RETURN WinApi.E_OUTOFMEMORY END CreateAnimal; (* ---------- IKoala ---------- *) PROCEDURE (this: IKoala) ClimbEucalyptusTrees (): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: IKoala) PouchOpensDown (): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: IKoala) SleepForHoursAfterEating (): COM.RESULT, NEW, ABSTRACT; (* ---------- CKoala ---------- *) PROCEDURE (this: CKoala) QueryInterface (IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; BEGIN IF COM.QUERY(this, iid, int) OR COM.QUERY(this.impl, iid, int) THEN RETURN WinApi.S_OK ELSIF iid = COM.ID(IAnimal) THEN RETURN this.animal.QueryInterface(iid, int) ELSE RETURN WinApi.E_NOINTERFACE END END QueryInterface; (* ---------- CImpIKoala ---------- *) PROCEDURE (this: CImpIKoala) ClimbEucalyptusTrees (): COM.RESULT; BEGIN StdLog.String("Koala's IKoala.ClimbEucalyptusTrees called"); StdLog.Ln; RETURN WinApi.S_OK END ClimbEucalyptusTrees; PROCEDURE (this: CImpIKoala) PouchOpensDown (): COM.RESULT; BEGIN StdLog.String("Koala's IKoala.PouchOpensDown called"); StdLog.Ln; RETURN WinApi.S_OK END PouchOpensDown; PROCEDURE (this: CImpIKoala) SleepForHoursAfterEating (): COM.RESULT; BEGIN StdLog.String("Koala's IKoala.SleepForHoursAfterEating called"); StdLog.Ln; RETURN WinApi.S_OK END SleepForHoursAfterEating; (* ---------- Koala creation ---------- *) PROCEDURE CreateKoalaAggregation (OUT unk: COM.IUnknown): BOOLEAN; VAR obj: CKoala; res: COM.RESULT; BEGIN NEW(obj); IF obj # NIL THEN NEW(obj.impl, obj); IF obj.impl # NIL THEN obj.impl.obj := obj; res := CreateAnimal(obj, COM.ID(obj.animal), obj.animal); IF res >= 0 THEN StdLog.String("Koala allocated"); StdLog.Ln; RETURN obj.QueryInterface(COM.ID(unk), unk) >= 0 END END END; RETURN FALSE END CreateKoalaAggregation; (* ---------- user interface ---------- *) PROCEDURE CreateKoala*; BEGIN IF CreateKoalaAggregation(koala) THEN StdLog.String("Koala created") ELSE StdLog.String("Koala creation failed") END; StdLog.Ln END CreateKoala; PROCEDURE ReleaseKoala*; BEGIN IF koala # NIL THEN koala := NIL; StdLog.String("Koala released") ELSE StdLog.String("no object") END; StdLog.Ln END ReleaseKoala; PROCEDURE AnimalEat*; VAR a: IAnimal; res: COM.RESULT; BEGIN IF koala # NIL THEN res := koala.QueryInterface(COM.ID(a), a); IF res >= 0 THEN res := a.Eat(); StdLog.String("IAnimal.Eat called") ELSE StdLog.String("no IAnimal interface") END ELSE StdLog.String("no object") END; StdLog.Ln END AnimalEat; PROCEDURE AnimalSleep*; VAR a: IAnimal; res: COM.RESULT; BEGIN IF koala # NIL THEN res := koala.QueryInterface(COM.ID(a), a); IF res >= 0 THEN res := a.Sleep(); StdLog.String("IAnimal.Sleep called") ELSE StdLog.String("no IAnimal interface") END ELSE StdLog.String("no object") END; StdLog.Ln END AnimalSleep; PROCEDURE AnimalProcreate*; VAR a: IAnimal; res: COM.RESULT; BEGIN IF koala # NIL THEN res := koala.QueryInterface(COM.ID(a), a); IF res >= 0 THEN res := a.Procreate(); StdLog.String("IAnimal.Procreate called") ELSE StdLog.String("no IAnimal interface") END ELSE StdLog.String("no object") END; StdLog.Ln END AnimalProcreate; PROCEDURE KoalaClimbEucalyptusTrees*; VAR a: IKoala; res: COM.RESULT; BEGIN IF koala # NIL THEN res := koala.QueryInterface(COM.ID(a), a); IF res >= 0 THEN res := a.ClimbEucalyptusTrees(); StdLog.String("IKoala.ClimbEucalyptusTrees called") ELSE StdLog.String("no IKoala interface") END ELSE StdLog.String("no object") END; StdLog.Ln END KoalaClimbEucalyptusTrees; PROCEDURE KoalaPouchOpensDown*; VAR a: IKoala; res: COM.RESULT; BEGIN IF koala # NIL THEN res := koala.QueryInterface(COM.ID(a), a); IF res >= 0 THEN res := a.PouchOpensDown(); StdLog.String("IKoala.PouchOpensDown called") ELSE StdLog.String("no IKoala interface") END ELSE StdLog.String("no object") END; StdLog.Ln END KoalaPouchOpensDown; PROCEDURE KoalaSleepForHoursAfterEating*; VAR a: IKoala; res: COM.RESULT; BEGIN IF koala # NIL THEN res := koala.QueryInterface(COM.ID(a), a); IF res >= 0 THEN res := a.SleepForHoursAfterEating(); StdLog.String("IKoala.SleepForHoursAfterEating called") ELSE StdLog.String("no IKoala interface") END ELSE StdLog.String("no object") END; StdLog.Ln END KoalaSleepForHoursAfterEating; END ComAggregate. ComAggregate.CreateKoala ComAggregate.ReleaseKoala ComAggregate.AnimalEat ComAggregate.AnimalSleep ComAggregate.AnimalProcreate ComAggregate.KoalaClimbEucalyptusTrees ComAggregate.KoalaPouchOpensDown ComAggregate.KoalaSleepForHoursAfterEating
Com/Mod/Aggregate.odc
MODULE ComConnect; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" references = "adapted from Connect sample in "Inside OLE", 2nd ed." changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinApi, WinOle, StdLog; CONST connPoints = 1; connMax = 2; eventQuack = 1; eventFlap = 2; eventPaddle = 3; SINK1 = 0; SINK2 = 1; TYPE IDuckEvents = POINTER TO ABSTRACT RECORD ["{00021145-0000-0000-C000-000000000046}"] (COM.IUnknown) END; CEnumConnectionPoints = POINTER TO RECORD (WinOle.IEnumConnectionPoints) cur: INTEGER; num: INTEGER; data: ARRAY connPoints OF WinOle.IConnectionPoint END; CEnumConnections = POINTER TO RECORD (WinOle.IEnumConnections) cur: INTEGER; num: INTEGER; data: ARRAY connMax OF WinOle.CONNECTDATA END; CConnectionPoint = POINTER TO RECORD (WinOle.IConnectionPoint) obj: CConnObject; iid: COM.GUID; unk: ARRAY connMax OF COM.IUnknown; cookies: ARRAY connMax OF INTEGER; conn: INTEGER; next: INTEGER END; CConnObject = POINTER TO RECORD (WinOle.IConnectionPointContainer) connPt: ARRAY connPoints OF CConnectionPoint END; CDuckEvents = POINTER TO RECORD (IDuckEvents) id: INTEGER; cookie: INTEGER END; VAR sink: ARRAY 2 OF CDuckEvents; obj: CConnObject; (* ---------- IDuckEvents ---------- *) PROCEDURE (this: IDuckEvents) Quack (): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: IDuckEvents) Flap (): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: IDuckEvents) Paddle (): COM.RESULT, NEW, ABSTRACT; (* ---------- CDuckEvents ---------- *) PROCEDURE CreateCDuckEvents (id: INTEGER; OUT new: CDuckEvents); BEGIN NEW(new); IF new # NIL THEN new.id := id; new.cookie := 0 END END CreateCDuckEvents; PROCEDURE (this: CDuckEvents) Quack (): COM.RESULT; BEGIN StdLog.String("Sink "); StdLog.Int(this.id + 1); StdLog.String(" received Quack"); StdLog.Ln; RETURN WinApi.S_OK END Quack; PROCEDURE (this: CDuckEvents) Flap (): COM.RESULT; BEGIN StdLog.String("Sink "); StdLog.Int(this.id + 1); StdLog.String(" received Flap"); StdLog.Ln; RETURN WinApi.S_OK END Flap; PROCEDURE (this: CDuckEvents) Paddle (): COM.RESULT; BEGIN StdLog.String("Sink "); StdLog.Int(this.id + 1); StdLog.String(" received Paddle"); StdLog.Ln; RETURN WinApi.S_OK END Paddle; (* ---------- CEnumConnections ---------- *) PROCEDURE CreateCEnumConnections (num: INTEGER; VAR data: ARRAY OF WinOle.CONNECTDATA; OUT new: CEnumConnections); VAR i: INTEGER; BEGIN NEW(new); IF new # NIL THEN new.cur := 0; new.num := num; i := 0; WHILE i < num DO new.data[i] := data[i]; INC(i) END END END CreateCEnumConnections; PROCEDURE (this: CEnumConnections) Next (num: INTEGER; OUT elem: ARRAY [untagged] OF WinOle.CONNECTDATA; OUT [nil] fetched: INTEGER): COM.RESULT; VAR n: INTEGER; BEGIN n := 0; IF VALID(fetched) THEN fetched := 0 ELSIF num # 1 THEN RETURN WinApi.E_POINTER END; IF this.cur < this.num THEN WHILE (this.cur < this.num) & (num > 0) DO elem[n] := this.data[this.cur]; INC(this.cur); INC(n); DEC(num) END; IF VALID(fetched) THEN fetched := n END; RETURN WinApi.S_OK END; RETURN WinApi.S_FALSE END Next; PROCEDURE (this: CEnumConnections) Skip (num: INTEGER): COM.RESULT; BEGIN IF this.cur + num < this.num THEN INC(this.cur, num); RETURN WinApi.S_OK ELSE RETURN WinApi.S_FALSE END END Skip; PROCEDURE (this: CEnumConnections) Reset (): COM.RESULT; BEGIN this.cur := 0; RETURN WinApi.S_OK END Reset; PROCEDURE (this: CEnumConnections) Clone (OUT enum: WinOle.IEnumConnections): COM.RESULT; VAR new: CEnumConnections; BEGIN CreateCEnumConnections(this.num, this.data, new); IF new # NIL THEN new.cur := this.cur; enum := new; RETURN WinApi.S_OK ELSE RETURN WinApi.E_OUTOFMEMORY END END Clone; (* ---------- CConnectionPoint ---------- *) PROCEDURE CreateCConnectionPoint (obj: CConnObject; IN iid: COM.GUID; OUT new: CConnectionPoint); VAR i: INTEGER; BEGIN NEW(new); IF new # NIL THEN new.iid := iid; new.obj := obj; new.conn := 0; new.next := 100 END END CreateCConnectionPoint; PROCEDURE (this: CConnectionPoint) GetConnectionInterface (OUT iid: COM.GUID): COM.RESULT; BEGIN iid := this.iid; RETURN WinApi.S_OK END GetConnectionInterface; PROCEDURE (this: CConnectionPoint) GetConnectionPointContainer (OUT cpc: WinOle.IConnectionPointContainer): COM.RESULT; BEGIN RETURN this.obj.QueryInterface(COM.ID(cpc), cpc) END GetConnectionPointContainer; PROCEDURE (this: CConnectionPoint) Advise (sink: COM.IUnknown; OUT cookie: INTEGER): COM.RESULT; VAR res: COM.RESULT; unk: COM.IUnknown; i: INTEGER; BEGIN IF this.conn < connMax THEN res := sink.QueryInterface(this.iid, unk); IF res >= 0 THEN i := 0; WHILE this.unk[i] # NIL DO INC(i) END; this.unk[i] := unk; INC(this.next); this.cookies[i] := this.next; cookie := this.next; INC(this.conn); RETURN WinApi.S_OK ELSE RETURN WinApi.CONNECT_E_CANNOTCONNECT END ELSE RETURN WinApi.CONNECT_E_ADVISELIMIT END END Advise; PROCEDURE (this: CConnectionPoint) Unadvise (cookie: INTEGER): COM.RESULT; VAR i: INTEGER; BEGIN IF cookie # 0 THEN i := 0; WHILE (i < connMax) & (this.cookies[i] # cookie) DO INC(i) END; IF i < connMax THEN this.unk[i] := NIL; this.cookies[i] := 0; DEC(this.conn); RETURN WinApi.S_OK ELSE RETURN WinApi.CONNECT_E_NOCONNECTION END ELSE RETURN WinApi.E_INVALIDARG END END Unadvise; PROCEDURE (this: CConnectionPoint) EnumConnections ( OUT enum: WinOle.IEnumConnections): COM.RESULT; VAR p: ARRAY connMax OF WinOle.CONNECTDATA; i, j: INTEGER; c: CEnumConnections; BEGIN IF this.conn > 0 THEN i := 0; j := 0; WHILE i < connMax DO IF this.unk[i] # NIL THEN p[j].pUnk := this.unk[i]; p[j].dwCookie := this.cookies[i]; INC(j) END; INC(i) END; CreateCEnumConnections(this.conn, p, c); IF c # NIL THEN enum := c; RETURN WinApi.S_OK ELSE RETURN WinApi.E_OUTOFMEMORY END ELSE RETURN WinApi.OLE_E_NOCONNECTION END END EnumConnections; (* ---------- CEnumConnectionPoints ---------- *) PROCEDURE CreateCEnumConnectionPoints (num: INTEGER; VAR data: ARRAY OF WinOle.IConnectionPoint; VAR new: CEnumConnectionPoints); VAR i: INTEGER; BEGIN NEW(new); IF new # NIL THEN new.cur := 0; new.num := num; i := 0; WHILE i < num DO new.data[i] := data[i]; INC(i) END END END CreateCEnumConnectionPoints; PROCEDURE (this: CEnumConnectionPoints) Next (num: INTEGER; OUT elem: ARRAY [untagged] OF WinOle.IConnectionPoint; OUT [nil] fetched: INTEGER): COM.RESULT; VAR n: INTEGER; BEGIN n := 0; IF VALID(fetched) THEN fetched := 0 ELSIF num # 1 THEN RETURN WinApi.E_POINTER END; IF this.cur < this.num THEN WHILE (this.cur < this.num) & (num > 0) DO elem[n] := this.data[this.cur]; INC(this.cur); INC(n); DEC(num) END; IF VALID(fetched) THEN fetched := n END; RETURN WinApi.S_OK END; RETURN WinApi.S_FALSE END Next; PROCEDURE (this: CEnumConnectionPoints) Skip (num: INTEGER): COM.RESULT; BEGIN IF this.cur + num < this.num THEN INC(this.cur, num); RETURN WinApi.S_OK ELSE RETURN WinApi.S_FALSE END END Skip; PROCEDURE (this: CEnumConnectionPoints) Reset (): COM.RESULT; BEGIN this.cur := 0; RETURN WinApi.S_OK END Reset; PROCEDURE (this: CEnumConnectionPoints) Clone ( OUT enum: WinOle.IEnumConnectionPoints): COM.RESULT; VAR new: CEnumConnectionPoints; BEGIN CreateCEnumConnectionPoints(this.num, this.data, new); IF new # NIL THEN new.cur := this.cur; enum := new; RETURN WinApi.S_OK ELSE RETURN WinApi.E_OUTOFMEMORY END END Clone; (* ---------- CConnObject ---------- *) PROCEDURE CreateCConnObject (VAR new: CConnObject); VAR i, n: INTEGER; BEGIN NEW(new); IF new # NIL THEN i := 0; WHILE i < connPoints DO CreateCConnectionPoint(new, COM.ID(IDuckEvents), new.connPt[i]); INC(i) END END END CreateCConnObject; PROCEDURE (this: CConnObject) EnumConnectionPoints (OUT enum: WinOle.IEnumConnectionPoints): COM.RESULT; VAR i: INTEGER; cp: ARRAY connPoints OF WinOle.IConnectionPoint; ce: CEnumConnectionPoints; BEGIN i := 0; WHILE i < connPoints DO cp[i] := this.connPt[i]; INC(i) END; CreateCEnumConnectionPoints(connPoints, cp, ce); IF ce # NIL THEN enum := ce; RETURN WinApi.S_OK ELSE RETURN WinApi.E_OUTOFMEMORY END END EnumConnectionPoints; PROCEDURE (this: CConnObject) FindConnectionPoint (IN iid: COM.GUID; OUT conn: WinOle.IConnectionPoint): COM.RESULT; VAR BEGIN IF iid = COM.ID(IDuckEvents) THEN conn := this.connPt[0]; RETURN WinApi.S_OK ELSE RETURN WinApi.E_NOINTERFACE END END FindConnectionPoint; PROCEDURE (this: CConnObject) TriggerEvent (event: INTEGER): BOOLEAN, NEW; VAR enum: WinOle.IEnumConnections; cd: ARRAY 1 OF WinOle.CONNECTDATA; duck: IDuckEvents; n: INTEGER; BEGIN IF this.connPt[0].EnumConnections(enum) >= 0 THEN WHILE enum.Next(1, cd, NIL) = WinApi.S_OK DO IF cd[0].pUnk.QueryInterface(COM.ID(duck), duck) >= 0 THEN CASE event OF | eventQuack: n := duck.Quack() | eventFlap: n := duck.Flap() | eventPaddle: n := duck.Paddle() END END END; RETURN TRUE ELSE RETURN FALSE END END TriggerEvent; (* ---------- commands ---------- *) PROCEDURE GetConnectionPoint (): WinOle.IConnectionPoint; VAR res: COM.RESULT; cont: WinOle.IConnectionPointContainer; cp: WinOle.IConnectionPoint; BEGIN res := obj.QueryInterface(COM.ID(cont), cont); IF res >= 0 THEN res := cont.FindConnectionPoint(COM.ID(IDuckEvents), cp); RETURN cp ELSE RETURN NIL END END GetConnectionPoint; PROCEDURE Connect (id: INTEGER); VAR cp: WinOle.IConnectionPoint; res: COM.RESULT; BEGIN IF obj # NIL THEN IF sink[id].cookie = 0 THEN cp := GetConnectionPoint(); IF cp # NIL THEN res := cp.Advise(sink[id], sink[id].cookie); IF res < 0 THEN StdLog.String("Connection failed"); StdLog.Ln ELSE StdLog.String("Connection complete"); StdLog.Ln END ELSE StdLog.String("Failed to get IConnectionPoint"); StdLog.Ln END ELSE StdLog.String("Sink already connected"); StdLog.Ln END ELSE StdLog.String("No object"); StdLog.Ln END END Connect; PROCEDURE Disconnect (id: INTEGER); VAR cp: WinOle.IConnectionPoint; res: COM.RESULT; BEGIN IF obj # NIL THEN IF sink[id].cookie # 0 THEN cp := GetConnectionPoint(); IF cp # NIL THEN res := cp.Unadvise(sink[id].cookie); IF res < 0 THEN StdLog.String("Disconnection failed"); StdLog.Ln ELSE StdLog.String("Disconnection complete"); StdLog.Ln; sink[id].cookie := 0 END ELSE StdLog.String("Failed to get IConnectionPoint"); StdLog.Ln END ELSE StdLog.String("Sink not connected"); StdLog.Ln END ELSE StdLog.String("No object"); StdLog.Ln END END Disconnect; PROCEDURE Init*; BEGIN CreateCDuckEvents(SINK1, sink[SINK1]); CreateCDuckEvents(SINK2, sink[SINK2]); END Init; PROCEDURE Release*; BEGIN obj := NIL; Disconnect(SINK1); Disconnect(SINK2); sink[SINK1] := NIL; sink[SINK2] := NIL END Release; PROCEDURE ObjectCreate*; BEGIN CreateCConnObject(obj); IF obj # NIL THEN StdLog.String(" Object created"); StdLog.Ln END END ObjectCreate; PROCEDURE ObjectRelease*; BEGIN IF obj # NIL THEN obj := NIL; StdLog.String("Object released"); StdLog.Ln ELSE StdLog.String("No object"); StdLog.Ln END END ObjectRelease; PROCEDURE Sink1Connect*; BEGIN Connect(SINK1) END Sink1Connect; PROCEDURE Sink1Disconnect*; BEGIN Disconnect(SINK1) END Sink1Disconnect; PROCEDURE Sink2Connect*; BEGIN Connect(SINK2) END Sink2Connect; PROCEDURE Sink2Disconnect*; BEGIN Disconnect(SINK2) END Sink2Disconnect; PROCEDURE TriggerQuack*; BEGIN IF obj # NIL THEN IF ~obj.TriggerEvent(eventQuack) THEN StdLog.String("No connected sinks"); StdLog.Ln END ELSE StdLog.String("No object"); StdLog.Ln END END TriggerQuack; PROCEDURE TriggerFlap*; BEGIN IF obj # NIL THEN IF ~obj.TriggerEvent(eventFlap) THEN StdLog.String("No connected sinks"); StdLog.Ln END ELSE StdLog.String("No object"); StdLog.Ln END END TriggerFlap; PROCEDURE TriggerPaddle*; BEGIN IF obj # NIL THEN IF ~obj.TriggerEvent(eventPaddle) THEN StdLog.String("No connected sinks"); StdLog.Ln END ELSE StdLog.String("No object"); StdLog.Ln END END TriggerPaddle; END ComConnect. ComConnect.Init ComConnect.Release ComConnect.ObjectCreate ComConnect.ObjectRelease ComConnect.Sink1Connect ComConnect.Sink1Disconnect ComConnect.Sink2Connect ComConnect.Sink2Disconnect ComConnect.TriggerFlap ComConnect.TriggerPaddle ComConnect.TriggerQuack
Com/Mod/Connect.odc
MODULE ComDebug; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - 20070205, bh, Unicode support - 20141027, center #19, full Unicode support for Component Pascal identifiers added - 20160110, center #60, fix for underlined white space - 20160324, center #111, code cleanups " issues = " - ... " **) IMPORT SYSTEM, COM, WinApi, WinOle, Kernel, Strings, Dialog, Fonts, Ports, Stores, Models, Views, Properties, Containers, Documents, Windows, TextModels, TextRulers, TextViews, TextControllers, TextMappers, DevDebug, DevHeapSpy, StdLog, StdLinks; TYPE Block = POINTER TO RECORD [untagged] tag: Kernel.Type; size: INTEGER; (* size of free blocks *) ref: INTEGER; unk: INTEGER END; Cluster = POINTER TO RECORD [untagged] size: INTEGER; (* total size *) next: Cluster; END; VAR all: BOOLEAN; PROCEDURE NewRuler (): TextRulers.Ruler; CONST mm = Ports.mm; VAR p: TextRulers.Prop; BEGIN NEW(p); p.valid := {TextRulers.right, TextRulers.tabs, TextRulers.opts}; p.opts.val := {TextRulers.rightFixed}; p.opts.mask := p.opts.val; p.right := 130 * mm; p.tabs.len := 4; p.tabs.tab[0].stop := 15 * mm; p.tabs.tab[1].stop := 70 * mm; p.tabs.tab[2].stop := 85 * mm; p.tabs.tab[3].stop := 95 * mm; RETURN TextRulers.dir.NewFromProp(p) END NewRuler; PROCEDURE OpenViewer (t: TextModels.Model; title: Views.Title; ruler:TextRulers.Ruler); VAR v: TextViews.View; c: Containers.Controller; BEGIN Dialog.MapString(title, title); v := TextViews.dir.New(t); IF ruler # NIL THEN v.SetDefaults(ruler, TextViews.dir.defAttr) END; c := v.ThisController(); IF c # NIL THEN c.SetOpts(c.opts - {Containers.noFocus, Containers.noSelection} + {Containers.noCaret}) END; Views.OpenAux(v, title) END OpenViewer; PROCEDURE OpenInfoViewer (t: TextModels.Model; title: Views.Title); VAR v: TextViews.View; c: Containers.Controller; p: Properties.BoundsPref; BEGIN Dialog.MapString(title, title); v := TextViews.dir.New(t); c := v.ThisController(); IF c # NIL THEN c.SetOpts(c.opts - {Containers.noFocus, Containers.noSelection} + {Containers.noCaret}) END; p.w := Views.undefined; p.h := Views.undefined; Views.HandlePropMsg(v, p); Views.OpenAux(Documents.dir.New(v, p.w, p.h), title) END OpenInfoViewer; PROCEDURE Next (b: Block): Block; (* next block in same cluster *) VAR size: INTEGER; tag: Kernel.Type; BEGIN tag := SYSTEM.VAL(Kernel.Type, SYSTEM.VAL(INTEGER, b.tag) DIV 4 * 4); size := tag.size + 4; IF ODD(SYSTEM.VAL(INTEGER, b.tag) DIV 2) THEN size := b.size - SYSTEM.ADR(b.size) + size END; size := (size + 15) DIV 16 * 16; RETURN SYSTEM.VAL(Block, SYSTEM.VAL(INTEGER, b) + size) END Next; PROCEDURE ShowInterfaces (VAR out: TextMappers.Formatter); VAR adr, end: INTEGER; modName, name, anchor: Kernel.Name; a0, a1: TextModels.Attributes; cluster: Cluster; blk: Block; BEGIN out.WriteString("Referenced Interface Records:"); out.WriteTab; out.WriteTab; a0 := out.rider.attr; out.rider.SetAttr(TextModels.NewStyle(out.rider.attr, {Fonts.underline})); out.rider.SetAttr(TextModels.NewColor(out.rider.attr, Ports.blue)); a1 := out.rider.attr; out.WriteView(StdLinks.dir.NewLink("ComDebug.ToggleAllInterfaces")); IF all THEN out.WriteString("New") ELSE out.WriteString("All") END; out.WriteView(StdLinks.dir.NewLink("")); out.rider.SetAttr(a0); out.WriteTab; out.rider.SetAttr(a1); out.WriteView(StdLinks.dir.NewLink("ComDebug.UpdateInterfaceRecords")); out.WriteString("Update"); out.WriteView(StdLinks.dir.NewLink("")); out.rider.SetAttr(a0); out.WriteLn; out.WriteLn; cluster := SYSTEM.VAL(Cluster, Kernel.Root()); WHILE cluster # NIL DO blk := SYSTEM.VAL(Block, SYSTEM.VAL(INTEGER, cluster) + 12); end := SYSTEM.VAL(INTEGER, blk) + (cluster.size - 12) DIV 16 * 16; WHILE SYSTEM.VAL(INTEGER, blk) < end DO IF ~(1 IN SYSTEM.VAL(SET, blk.tag)) & (SYSTEM.VAL(INTEGER, blk.tag) # SYSTEM.ADR(blk.size)) & (blk.tag.base[0] = NIL) THEN Kernel.GetModName(blk.tag.mod, modName); IF (all OR (modName # "HostMechanisms") & (modName # "OleServer") & (modName # "OleClient") & (modName # "OleStorage") & (modName # "OleData")) THEN adr := SYSTEM.ADR(blk.size); out.WriteString("ref: "); out.WriteInt(blk.ref); out.WriteTab; out.WriteString(modName); out.WriteChar("."); IF (blk.tag.id DIV 256 # 0) & (blk.tag.mod.refcnt >= 0) THEN Kernel.GetTypeName(blk.tag, name); out.WriteString(name) ELSE out.WriteString("RECORD"); END; out.WriteTab; out.WriteChar("["); out.WriteIntForm(adr, TextMappers.hexadecimal, 9, "0", TextMappers.showBase); out.WriteChar("]"); out.WriteChar(" "); out.WriteView(DevDebug.HeapRefView(adr, "Interface")); DevHeapSpy.GetAnchor(adr, anchor); IF anchor # "" THEN out.WriteTab; out.WriteTab; out.WriteChar("("); out.WriteString(anchor); out.WriteChar(")") END; out.WriteLn END; END; blk := Next(blk) END; cluster := cluster.next END END ShowInterfaces; PROCEDURE ShowInterfaceRecords*; VAR out: TextMappers.Formatter; BEGIN out.ConnectTo(TextModels.CloneOf(StdLog.buf)); ShowInterfaces(out); OpenViewer(out.rider.Base(), "Interfaces", NewRuler()); out.ConnectTo(NIL) END ShowInterfaceRecords; PROCEDURE UpdateInterfaceRecords*; VAR t, t0: TextModels.Model; out: TextMappers.Formatter; BEGIN t0 := TextViews.FocusText(); Models.BeginModification(Models.notUndoable, t0); t0.Delete(0, t0.Length()); (* removes old object references from text *) Views.Update(TextViews.Focus(), Views.rebuildFrames); Windows.dir.Update(Windows.dir.First()); (* remove frame references *) Kernel.Collect; t := TextModels.CloneOf(t0); (*Stores.InitDomain(t, t0.domain);*) Stores.Join(t, t0); out.ConnectTo(t); ShowInterfaces(out); t0.Insert(0, t, 0, t.Length()); Models.EndModification(Models.notUndoable, t0); out.ConnectTo(NIL) END UpdateInterfaceRecords; PROCEDURE ToggleAllInterfaces*; BEGIN all := ~all; UpdateInterfaceRecords END ToggleAllInterfaces; PROCEDURE ShowError*; VAR res: INTEGER; c: TextControllers.Controller; r: TextModels.Reader; f: TextMappers.Formatter; beg, end, i: INTEGER; str: ARRAY 1024 OF CHAR; ch: CHAR; s: ARRAY 64 OF CHAR; BEGIN c := TextControllers.Focus(); IF (c # NIL) & c.HasSelection() THEN c.GetSelection(beg, end); r := c.text.NewReader(NIL); r.SetPos(beg); i := 0; r.ReadChar(ch); WHILE (beg + i < end) & (i < LEN(s) - 1) & (ch >= " ") DO s[i] := ch; INC(i); r.ReadChar(ch) END; s[i] := 0X; Strings.StringToInt(s, i, res); IF res = 0 THEN f.ConnectTo(TextModels.CloneOf(StdLog.buf)); f.WriteString("Error Code: "); f.WriteIntForm(i, TextMappers.hexadecimal, 9, "0", TRUE); f.WriteLn; f.WriteString("(Facility: "); CASE i DIV 10000H MOD 2000H OF | 0: f.WriteString("NULL, ") | 1: f.WriteString("RPC, ") | 2: f.WriteString("DISPATCH, ") | 3: f.WriteString("STORAGE, ") | 4: f.WriteString("ITF, ") | 7: f.WriteString("WIN32, ") | 8: f.WriteString("WINDOWS, ") | 10: f.WriteString("CONTROL, ") ELSE f.WriteString("unknown, ") END; f.WriteString("Severity: "); IF i < 0 THEN f.WriteString("Error, ") ELSE f.WriteString("Success, ") END; f.WriteString("Code: "); f.WriteInt(i MOD 10000H); f.WriteChar(")"); f.WriteLn; f.WriteString("Description:"); f.WriteLn; i := WinApi.FormatMessageW({12}, 0, i, 0, str, LEN(str), NIL); IF i > 0 THEN REPEAT DEC(i) UNTIL (i < 0) OR (str[i] >= " "); str[i + 1] := 0X; ELSE str := "" END; f.WriteString(str); f.WriteLn; OpenInfoViewer(f.rider.Base(), "Show Error"); f.ConnectTo(NIL) END END END ShowError; PROCEDURE Hex (VAR f: TextMappers.Formatter; x, n: INTEGER); BEGIN IF n > 1 THEN Hex(f, x DIV 16, n - 1) END; x := x MOD 16; IF x >= 10 THEN f.WriteChar(CHR(x + ORD("A") - 10)) ELSE f.WriteChar(CHR(x + ORD("0"))) END END Hex; PROCEDURE NewGuid*; VAR f: TextMappers.Formatter; g: COM.GUID; res: COM.RESULT; n: INTEGER; BEGIN f.ConnectTo(TextModels.CloneOf(StdLog.buf)); n := 10; WHILE n > 0 DO res := WinOle.CoCreateGuid(g); f.WriteChar("{"); Hex(f, g[2] MOD 256 + 256 * g[3] MOD 256, 4); Hex(f, g[0] MOD 256 + 256 * g[1] MOD 256, 4); f.WriteChar("-"); Hex(f, g[4] MOD 256 + 256 * g[5] MOD 256, 4); f.WriteChar("-"); Hex(f, g[6] MOD 256 + 256 * g[7] MOD 256, 4); f.WriteChar("-"); Hex(f, g[8] MOD 256, 2); Hex(f, g[9] MOD 256, 2); f.WriteChar("-"); Hex(f, g[10] MOD 256, 2); Hex(f, g[11] MOD 256, 2); Hex(f, g[12] MOD 256, 2); Hex(f, g[13] MOD 256, 2); Hex(f, g[14] MOD 256, 2); Hex(f, g[15] MOD 256, 2); f.WriteChar("}"); f.WriteLn; DEC(n) END; OpenInfoViewer(f.rider.Base(), "Guids"); f.ConnectTo(NIL) END NewGuid; END ComDebug.
Com/Mod/Debug.odc
MODULE ComEnum; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinApi, WinOle, ComTools; TYPE IEnumUnknown = POINTER TO RECORD (WinOle.IEnumUnknown) cur: INTEGER; num: INTEGER; data: POINTER TO ARRAY OF COM.IUnknown END; IEnumString = POINTER TO RECORD (WinOle.IEnumString) cur: INTEGER; num: INTEGER; data: POINTER TO ARRAY OF ARRAY OF CHAR END; IEnumFORMATETC = POINTER TO RECORD (WinOle.IEnumFORMATETC) cur: INTEGER; num: INTEGER; format: POINTER TO ARRAY OF INTEGER; aspect, tymed: POINTER TO ARRAY OF SET END; IEnumOLEVERB = POINTER TO RECORD (WinOle.IEnumOLEVERB) cur: INTEGER; num: INTEGER; verb: POINTER TO ARRAY OF INTEGER; name: POINTER TO ARRAY OF ARRAY OF CHAR; flags, attribs: POINTER TO ARRAY OF SET END; (* IEnumUnknown *) PROCEDURE CreateIEnumUnknown* (num: INTEGER; IN data: ARRAY OF COM.IUnknown; OUT enum: WinOle.IEnumUnknown); VAR i, n: INTEGER; new: IEnumUnknown; BEGIN NEW(new); IF new # NIL THEN new.cur := 0; new.num := num; NEW(new.data, num); i := 0; WHILE i < num DO new.data[i] := data[i]; INC(i) END; enum := new END END CreateIEnumUnknown; PROCEDURE (this: IEnumUnknown) Next (num: INTEGER; OUT elem: ARRAY [untagged] OF COM.IUnknown; OUT [nil] fetched: INTEGER): COM.RESULT; VAR n: INTEGER; BEGIN n := 0; IF VALID(fetched) THEN fetched := 0 ELSIF num # 1 THEN RETURN WinApi.E_POINTER END; IF this.cur < this.num THEN WHILE (this.cur < this.num) & (num > 0) DO elem[n] := this.data[this.cur]; INC(this.cur); INC(n); DEC(num) END; IF VALID(fetched) THEN fetched := n END; RETURN WinApi.S_OK END; RETURN WinApi.S_FALSE END Next; PROCEDURE (this: IEnumUnknown) Skip (num: INTEGER): COM.RESULT; BEGIN IF this.cur + num < this.num THEN INC(this.cur, num); RETURN WinApi.S_OK ELSE RETURN WinApi.S_FALSE END END Skip; PROCEDURE (this: IEnumUnknown) Reset (): COM.RESULT; BEGIN this.cur := 0; RETURN WinApi.S_OK END Reset; PROCEDURE (this: IEnumUnknown) Clone (OUT enum: WinOle.IEnumUnknown): COM.RESULT; VAR new: IEnumUnknown; BEGIN NEW(new); IF new # NIL THEN new.num := this.num; new.cur := this.cur; new.data := this.data; enum := new; RETURN WinApi.S_OK ELSE RETURN WinApi.E_OUTOFMEMORY END END Clone; (* IEnumString *) PROCEDURE CreateIEnumString* (num: INTEGER; IN data: ARRAY OF ARRAY OF CHAR; OUT enum: WinOle.IEnumString); VAR i, n: INTEGER; new: IEnumString; BEGIN NEW(new); IF new # NIL THEN new.cur := 0; new.num := num; NEW(new.data, num, LEN(data, 1)); i := 0; WHILE i < num DO new.data[i] := data[i]$; INC(i) END; enum := new END END CreateIEnumString; PROCEDURE (this: IEnumString) Next (num: INTEGER; OUT elem: ARRAY [untagged] OF WinApi.PtrWSTR; OUT [nil] fetched: INTEGER): COM.RESULT; VAR n: INTEGER; BEGIN n := 0; IF VALID(fetched) THEN fetched := 0 ELSIF num # 1 THEN RETURN WinApi.E_POINTER END; IF this.cur < this.num THEN WHILE (this.cur < this.num) & (num > 0) DO elem[n] := ComTools.NewString(this.data[this.cur]); INC(this.cur); INC(n); DEC(num) END; IF VALID(fetched) THEN fetched := n END; RETURN WinApi.S_OK END; RETURN WinApi.S_FALSE END Next; PROCEDURE (this: IEnumString) Skip (num: INTEGER): COM.RESULT; BEGIN IF this.cur + num < this.num THEN INC(this.cur, num); RETURN WinApi.S_OK ELSE RETURN WinApi.S_FALSE END END Skip; PROCEDURE (this: IEnumString) Reset (): COM.RESULT; BEGIN this.cur := 0; RETURN WinApi.S_OK END Reset; PROCEDURE (this: IEnumString) Clone (OUT enum: WinOle.IEnumString): COM.RESULT; VAR new: IEnumString; BEGIN NEW(new); IF new # NIL THEN new.num := this.num; new.cur := this.cur; new.data := this.data; enum := new; RETURN WinApi.S_OK ELSE RETURN WinApi.E_OUTOFMEMORY END END Clone; (* IEnumFORMATETC *) PROCEDURE CreateIEnumFORMATETC* (num: INTEGER; IN format: ARRAY OF INTEGER; IN aspect, tymed: ARRAY OF SET; OUT enum: WinOle.IEnumFORMATETC); VAR i, n: INTEGER; new: IEnumFORMATETC; BEGIN NEW(new); IF new # NIL THEN new.cur := 0; new.num := num; NEW(new.format, num); NEW(new.aspect, num); NEW(new.tymed, num); i := 0; WHILE i < num DO new.format[i] := format[i]; new.aspect[i] := aspect[i]; new.tymed[i] := tymed[i]; INC(i) END; enum := new END END CreateIEnumFORMATETC; PROCEDURE (this: IEnumFORMATETC) Next (num: INTEGER; OUT elem: ARRAY [untagged] OF WinOle.FORMATETC; OUT [nil] fetched: INTEGER): COM.RESULT; VAR n: INTEGER; BEGIN n := 0; IF VALID(fetched) THEN fetched := 0 ELSIF num # 1 THEN RETURN WinApi.E_POINTER END; IF this.cur < this.num THEN WHILE (this.cur < this.num) & (num > 0) DO ComTools.GenFormatEtc(SHORT(this.format[this.cur]), this.aspect[this.cur], this.tymed[this.cur], elem[n]); INC(this.cur); INC(n); DEC(num) END; IF VALID(fetched) THEN fetched := n END; RETURN WinApi.S_OK END; RETURN WinApi.S_FALSE END Next; PROCEDURE (this: IEnumFORMATETC) Skip (num: INTEGER): COM.RESULT; BEGIN IF this.cur + num < this.num THEN INC(this.cur, num); RETURN WinApi.S_OK ELSE RETURN WinApi.S_FALSE END END Skip; PROCEDURE (this: IEnumFORMATETC) Reset (): COM.RESULT; BEGIN this.cur := 0; RETURN WinApi.S_OK END Reset; PROCEDURE (this: IEnumFORMATETC) Clone (OUT enum: WinOle.IEnumFORMATETC): COM.RESULT; VAR new: IEnumFORMATETC; BEGIN NEW(new); IF new # NIL THEN new.num := this.num; new.cur := this.cur; new.format := this.format; new.aspect := this.aspect; new.tymed := this.tymed; enum := new; RETURN WinApi.S_OK ELSE RETURN WinApi.E_OUTOFMEMORY END END Clone; (* IEnumOLEVERB *) PROCEDURE CreateIEnumOLEVERB* (num: INTEGER; IN verb: ARRAY OF INTEGER; IN name: ARRAY OF ARRAY OF CHAR; IN flags, attribs: ARRAY OF SET; OUT enum: WinOle.IEnumOLEVERB); VAR i, n: INTEGER; new: IEnumOLEVERB; BEGIN NEW(new); IF new # NIL THEN new.cur := 0; new.num := num; NEW(new.verb, num); NEW(new.name, num, LEN(name, 1)); NEW(new.flags, num); NEW(new.attribs, num); i := 0; WHILE i < num DO new.verb[i] := verb[i]; new.name[i] := name[i]$; new.flags[i] := flags[i]; new.attribs[i] := attribs[i]; INC(i) END; enum := new END END CreateIEnumOLEVERB; PROCEDURE (this: IEnumOLEVERB) Next (num: INTEGER; OUT elem: ARRAY [untagged] OF WinOle.OLEVERB; OUT [nil] fetched: INTEGER): COM.RESULT; VAR n: INTEGER; BEGIN n := 0; IF VALID(fetched) THEN fetched := 0 ELSIF num # 1 THEN RETURN WinApi.E_POINTER END; IF this.cur < this.num THEN WHILE (this.cur < this.num) & (num > 0) DO elem[n].lVerb := this.verb[this.cur]; elem[n].lpszVerbName := ComTools.NewString(this.name[this.cur]); elem[n].fuFlags := this.flags[this.cur]; elem[n].grfAttribs := this.attribs[this.cur]; INC(this.cur); INC(n); DEC(num) END; IF VALID(fetched) THEN fetched := n END; RETURN WinApi.S_OK END; RETURN WinApi.S_FALSE END Next; PROCEDURE (this: IEnumOLEVERB) Skip (num: INTEGER): COM.RESULT; BEGIN IF this.cur + num < this.num THEN INC(this.cur, num); RETURN WinApi.S_OK ELSE RETURN WinApi.S_FALSE END END Skip; PROCEDURE (this: IEnumOLEVERB) Reset (): COM.RESULT; BEGIN this.cur := 0; RETURN WinApi.S_OK END Reset; PROCEDURE (this: IEnumOLEVERB) Clone (OUT enum: WinOle.IEnumOLEVERB): COM.RESULT; VAR new: IEnumOLEVERB; BEGIN NEW(new); IF new # NIL THEN new.num := this.num; new.cur := this.cur; new.verb := this.verb; new.name := this.name; new.flags := this.flags; new.attribs := this.attribs; enum := new; RETURN WinApi.S_OK ELSE RETURN WinApi.E_OUTOFMEMORY END END Clone; END ComEnum.
Com/Mod/Enum.odc
MODULE ComEnumRect; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" references = "adapted from EnumRect sample in "Inside OLE", 2nd ed." changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinApi; CONST rects = 15; TYPE IEnumRECT* = POINTER TO ABSTRACT RECORD ["{00021140-0000-0000-C000-000000000046}"] (COM.IUnknown) END; EnumRECT = POINTER TO RECORD (IEnumRECT) cur: INTEGER; data: ARRAY rects OF WinApi.RECT; END; (* ---------- abstract interface methods ---------- *) (* QueryInterface, AddRef, Release inherited from COM.IUnknown *) PROCEDURE (this: IEnumRECT) Next* (num: INTEGER; OUT elem: ARRAY [untagged] OF WinApi.RECT; OUT [nil] fetched: INTEGER): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: IEnumRECT) Skip* (num: INTEGER): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: IEnumRECT) Reset* (): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: IEnumRECT) Clone* (OUT enum: IEnumRECT): COM.RESULT, NEW, ABSTRACT; (* ---------- interface implementation ---------- *) (* use default QueryInterface implementation *) (* AddRef & Release implemented implicitly by the compiler *) PROCEDURE (this: EnumRECT) Next (num: INTEGER; OUT elem: ARRAY [untagged] OF WinApi.RECT; OUT [nil] fetched: INTEGER): COM.RESULT; VAR n: INTEGER; BEGIN n := 0; IF VALID(fetched) THEN fetched := 0 ELSIF num # 1 THEN RETURN WinApi.S_FALSE END; IF this.cur < rects THEN WHILE (this.cur < rects) & (num > 0) DO elem[n] := this.data[this.cur]; INC(this.cur); INC(n); DEC(num) END; IF VALID(fetched) THEN fetched := n END; RETURN WinApi.S_OK END; RETURN WinApi.S_FALSE END Next; PROCEDURE (this: EnumRECT) Skip (num: INTEGER): COM.RESULT; BEGIN IF this.cur + num < rects THEN INC(this.cur, num); RETURN WinApi.S_OK ELSE RETURN WinApi.S_FALSE END END Skip; PROCEDURE (this: EnumRECT) Reset (): COM.RESULT; BEGIN this.cur := 0; RETURN WinApi.S_OK END Reset; PROCEDURE (this: EnumRECT) Clone (OUT enum: IEnumRECT): COM.RESULT; VAR new: EnumRECT; BEGIN NEW(new); IF new # NIL THEN new.cur := this.cur; new.data := this.data; enum := new; RETURN WinApi.S_OK ELSE RETURN WinApi.E_OUTOFMEMORY END END Clone; PROCEDURE CreateRectEnumerator* (OUT enum: IEnumRECT); VAR new: EnumRECT; i: INTEGER; BEGIN NEW(new); IF new # NIL THEN new.cur := 0; i := 0; WHILE i < rects DO new.data[i].left := i; new.data[i].top := i * 2; new.data[i].right := i * 3; new.data[i].bottom := i * 4; INC(i) END; enum := new END END CreateRectEnumerator; END ComEnumRect.
Com/Mod/EnumRect.odc
MODULE ComInterfaceGen; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - 20070205, bh, Unicode support - 20160110, center #92, Office automation " issues = " - ... " **) IMPORT COM, WinApi, WinOle, WinOleAut, Files, (* HostFiles, *) Strings, Dialog, StdDialog, Views, TextModels, TextViews, ComTypeLibs, StdCmds; TYPE Entry = POINTER TO RECORD (* registry typelib entry *) next: Entry; index: INTEGER; guid: COM.GUID; major, minor: SHORTINT; lcid: WinApi.LCID; title: ARRAY 256 OF CHAR; file: ARRAY 256 OF CHAR END; VAR dialog*: RECORD library*: Dialog.List; fileName*: ARRAY 256 OF CHAR; modName*: ARRAY 64 OF CHAR; list, current: Entry END; PROCEDURE GetName (tlib: WinOleAut.ITypeLib; VAR name: ARRAY OF CHAR); VAR res: INTEGER; s: WinOle.BSTR; BEGIN res := tlib.GetDocumentation(-1, s, NIL, NIL, NIL); name := s$; IF (name[0] >= "a") & (name[0] <= "z") THEN name[0] := CAP(name[0]) END; name := "Ctl" + name; WinOleAut.SysFreeString(s) END GetName; PROCEDURE GenAutomationInterface*; VAR fn: Files.Name; loc: Files.Locator; t: TextModels.Model; BEGIN t := ComTypeLibs.AutomationInterface(dialog.fileName$, dialog.modName$); StdDialog.GetSubLoc(dialog.modName, "Mod", loc, fn); loc.res := 77; Views.Open(TextViews.dir.New(t), loc, fn, NIL) END GenAutomationInterface; PROCEDURE GenCustomInterface*; VAR fn: Files.Name; loc: Files.Locator; t: TextModels.Model; BEGIN t := ComTypeLibs.CustomInterface(dialog.fileName$, dialog.modName$); StdDialog.GetSubLoc(dialog.modName, "Mod", loc, fn); loc.res := 77; Views.Open(TextViews.dir.New(t), loc, fn, NIL) END GenCustomInterface; PROCEDURE BrowseTypeLib*; VAR fn: Files.Name; loc: Files.Locator; t: TextModels.Model; BEGIN t := ComTypeLibs.Browse(dialog.fileName$, dialog.modName$); StdDialog.GetSubLoc(dialog.modName, "Mod", loc, fn); loc.res := 77; Views.Open(TextViews.dir.New(t), loc, fn, NIL) END BrowseTypeLib; PROCEDURE Browse*; VAR loc: Files.Locator; name: Files.Name; res: INTEGER; tlib: WinOleAut.ITypeLib; n: ARRAY 256 OF CHAR; BEGIN Dialog.GetIntSpec("*", loc, name); IF loc # NIL THEN (* dialog.fileName := loc(HostFiles.Locator).path$ + "\" + name$; *) Dialog.GetLocPath(loc, dialog.fileName); res := WinOleAut.LoadTypeLib(dialog.fileName, tlib); IF res >= 0 THEN GetName(tlib, n); dialog.modName := n$ ELSE dialog.modName := "" END; dialog.library.index := 0; Dialog.Update(dialog) END END Browse; PROCEDURE TextFieldNotifier* (op, from, to: INTEGER); VAR res: INTEGER; tlib: WinOleAut.ITypeLib; n: ARRAY 256 OF CHAR; BEGIN IF op = Dialog.changed THEN res := WinOleAut.LoadTypeLib(dialog.fileName, tlib); IF res >= 0 THEN GetName(tlib, n); dialog.modName := n$ ELSE dialog.modName := "" END; dialog.library.index := 0; Dialog.Update(dialog) END END TextFieldNotifier; PROCEDURE ListBoxNotifier* (op, from, to: INTEGER); VAR name: ARRAY 260 OF CHAR; res: INTEGER; e: Entry; tlib: WinOleAut.ITypeLib; n: ARRAY 256 OF CHAR; BEGIN IF op = Dialog.changed THEN IF dialog.library.index # dialog.current.index THEN e := dialog.list; WHILE e.index # dialog.library.index DO e := e.next END; dialog.current := e; dialog.fileName := e.file$ END; res := WinOleAut.LoadTypeLib(dialog.fileName, tlib); IF res >= 0 THEN GetName(tlib, n); dialog.modName := n$ ELSE dialog.modName := ""; dialog.library.index := 0 END; Dialog.Update(dialog) END END ListBoxNotifier; PROCEDURE InitDialog*; VAR tlKey, gKey, vKey, lidKey, fKey: WinApi.HKEY; guid: COM.GUID; e: Entry; i, j, k, res, idx, lcid, len: INTEGER; ver: REAL; wstr: ARRAY 256 OF CHAR; nstr: ARRAY 16 OF CHAR; BEGIN NEW(dialog.list); dialog.list.next := NIL; dialog.list.index := 0; dialog.list.title := " "; dialog.list.file := ""; dialog.current := dialog.list; res := WinApi.RegOpenKeyW(WinApi.HKEY_CLASSES_ROOT, "TypeLib", tlKey); idx := 1; i := 0; res := WinApi.RegEnumKeyW(tlKey, i, wstr, LEN(wstr)); WHILE res = 0 DO res := WinOle.CLSIDFromString(wstr, guid); IF res = 0 THEN res := WinApi.RegOpenKeyW(tlKey, wstr, gKey); j := 0; res := WinApi.RegEnumKeyW(gKey, j, wstr, LEN(wstr)); WHILE res = 0 DO Strings.StringToReal(wstr, ver, res); IF res = 0 THEN res := WinApi.RegOpenKeyW(gKey, wstr, vKey); k := 0; res := WinApi.RegEnumKeyW(vKey, k, wstr, LEN(wstr)); WHILE res = 0 DO Strings.StringToInt(wstr, lcid, res); IF res = 0 THEN res := WinApi.RegOpenKeyW(vKey, wstr, lidKey); res := WinApi.RegOpenKeyW(lidKey, "Win32", fKey); IF res # 0 THEN res := WinApi.RegOpenKeyW(lidKey, "Win16", fKey) END; IF res = 0 THEN NEW(e); e.next := dialog.list; dialog.list := e; e.index := idx; INC(idx); e.guid := guid; e.major := SHORT(SHORT(ENTIER(ver))); e.minor := SHORT(SHORT(ENTIER(ver * 100)) MOD 100); e.lcid := lcid; len := LEN(e.title); res := WinApi.RegQueryValueW(vKey, NIL, e.title, len); Strings.RealToString(ver, wstr); Strings.IntToString(lcid, nstr); e.title := e.title + " (" + wstr + ", " + nstr + ")"; len := LEN(e.file); res := WinApi.RegQueryValueW(fKey, NIL, e.file, len) END END; INC(k); res := WinApi.RegEnumKeyW(vKey, k, wstr, LEN(wstr)) END END; INC(j); res := WinApi.RegEnumKeyW(gKey, j, wstr, LEN(wstr)) END END; INC(i); res := WinApi.RegEnumKeyW(tlKey, i, wstr, LEN(wstr)) END; dialog.library.SetLen(idx); e := dialog.list; WHILE e # NIL DO dialog.library.SetItem(e.index, e.title); e := e.next END; IF dialog.list.next # NIL THEN dialog.library.index := 1 ELSE dialog.library.index := 0 END; ListBoxNotifier(Dialog.changed, 0, 0) END InitDialog; PROCEDURE Open*; BEGIN IF dialog.list = NIL THEN InitDialog END ; StdCmds.OpenAuxDialog('Com/Rsrc/InterfaceGen', '#Com:Type Libraries') END Open; PROCEDURE Close*; BEGIN dialog.list := NIL; dialog.current := NIL; dialog.library.SetLen(0); StdCmds.CloseDialog; END Close; END ComInterfaceGen. ComInterfaceGen.Open
Com/Mod/InterfaceGen.odc
MODULE ComKoala; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" references = "adapted from Koala sample in "Inside OLE", 2nd ed." changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinApi, WinOle; CONST KoalaId = "{00021146-0000-0000-C000-000000000046}"; TYPE Koala = POINTER TO RECORD (COM.IUnknown) END; KoalaFactory = POINTER TO RECORD (WinOle.IClassFactory) END; VAR locks: INTEGER; token: INTEGER; (* ---------- Koala ---------- *) (* use default QueryInterface implementation *) (* AddRef & Release implemented implicitly by the compiler *) (* ---------- KoalaFactory ---------- *) (* use default QueryInterface implementation *) (* AddRef & Release implemented implicitly by the compiler *) PROCEDURE (this: KoalaFactory) CreateInstance (outer: COM.IUnknown; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR res: COM.RESULT; new: Koala; BEGIN IF outer # NIL THEN RETURN WinApi.CLASS_E_NOAGGREGATION END; NEW(new); IF new # NIL THEN RETURN new.QueryInterface(iid, int) ELSE RETURN WinApi.E_OUTOFMEMORY END END CreateInstance; PROCEDURE (this: KoalaFactory) LockServer (lock: WinApi.BOOL): COM.RESULT; BEGIN IF lock # 0 THEN INC(locks) ELSE DEC(locks) END; RETURN WinApi.S_OK END LockServer; (* ---------- registration ---------- *) PROCEDURE Register*; VAR res: COM.RESULT; factory: KoalaFactory; BEGIN NEW(factory); res := WinOle.CoRegisterClassObject(KoalaId, factory, WinOle.CLSCTX_LOCAL_SERVER, WinOle.REGCLS_MULTIPLEUSE, token) END Register; PROCEDURE Unregister*; VAR res: COM.RESULT; BEGIN IF (locks = 0) & (token # 0) THEN res := WinOle.CoRevokeClassObject(token) END END Unregister; BEGIN locks := 0 END ComKoala. ComKoala.Register ComKoala.Unregister
Com/Mod/Koala.odc
MODULE ComKoalaDll; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" references = "adapted from Koala sample in "Inside OLE", 2nd ed." changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinApi, WinOle; CONST KoalaId = "{00021146-0000-0000-C000-000000000046}"; TYPE Koala = POINTER TO RECORD (COM.IUnknown) END; KoalaFactory = POINTER TO RECORD (WinOle.IClassFactory) END; VAR locks: INTEGER; objects: INTEGER; (* ---------- Koala ---------- *) (* use default QueryInterface implementation *) (* AddRef & Release implemented implicitly by the compiler *) PROCEDURE (this: Koala) RELEASE; (* called when last com reference is removed *) BEGIN DEC(objects) END RELEASE; (* ---------- KoalaFactory ---------- *) (* use default QueryInterface implementation *) (* AddRef & Release implemented implicitly by the compiler *) PROCEDURE (this: KoalaFactory) CreateInstance (outer: COM.IUnknown; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR res: COM.RESULT; new: Koala; BEGIN IF outer # NIL THEN RETURN WinApi.CLASS_E_NOAGGREGATION END; NEW(new); IF new # NIL THEN res := new.QueryInterface(iid, int); IF res >= 0 THEN INC(objects) END; RETURN res ELSE RETURN WinApi.E_OUTOFMEMORY END END CreateInstance; PROCEDURE (this: KoalaFactory) LockServer (lock: WinApi.BOOL): COM.RESULT; BEGIN IF lock # 0 THEN INC(locks) ELSE DEC(locks) END; RETURN WinApi.S_OK END LockServer; (* ---------- dll interface ---------- *) PROCEDURE DllGetClassObject* (IN clsid: COM.GUID; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR obj: KoalaFactory; BEGIN IF clsid = KoalaId THEN NEW(obj); IF obj # NIL THEN RETURN obj.QueryInterface(iid, int) ELSE RETURN WinApi.E_OUTOFMEMORY; END ELSE RETURN WinApi.E_FAIL END END DllGetClassObject; PROCEDURE DllCanUnloadNow* (): COM.RESULT; BEGIN IF (objects = 0) & (locks = 0) THEN RETURN WinApi.S_OK ELSE RETURN WinApi.S_FALSE END END DllCanUnloadNow; BEGIN locks := 0; objects := 0 END ComKoalaDll. DevLinker.LinkDll DKoala1.dll := Kernel+ ComKoalaDll# ~ ----------------------------------------------------------------------------------------------------------------- REGEDIT HKEY_CLASSES_ROOT\Koala1.0 = Koala Object Chapter 5 HKEY_CLASSES_ROOT\Koala1.0\CLSID = {00021146-0000-0000-C000-000000000046} HKEY_CLASSES_ROOT\Koala = Koala Object Chapter 5 HKEY_CLASSES_ROOT\Koala\CurVer = Koala1.0 HKEY_CLASSES_ROOT\Koala\CLSID = {00021146-0000-0000-C000-000000000046} HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046} = Koala Object Chapter 5 HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\ProgID = Koala1.0 HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\VersionIndependentProgID = Koala HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\InprocServer32 = C:\BlackBox\Com\DKoala1.dll HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\NotInsertable -----------------------------------------------------------------------------------------------------------------
Com/Mod/KoalaDll.odc
MODULE ComKoalaExe; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - 20070205, bh, Unicode support " issues = " - ... " **) IMPORT S := SYSTEM, COM, WinApi, WinOle; CONST KoalaId = "{00021146-0000-0000-C000-000000000046}"; TYPE Koala = POINTER TO RECORD (COM.IUnknown) END; KoalaFactory = POINTER TO RECORD (WinOle.IClassFactory) END; VAR instance: WinApi.HMODULE; mainWnd: WinApi.HWND; locks: INTEGER; objects: INTEGER; (* ---------- Koala ---------- *) (* use default QueryInterface implementation *) (* AddRef & Release implemented implicitly by the compiler *) PROCEDURE (this: Koala) RELEASE; (* called when last com reference is removed *) VAR res: INTEGER; BEGIN DEC(objects); IF objects = 0 THEN res := WinApi.PostMessageW(mainWnd, WinApi.WM_CLOSE, 0, 0); END END RELEASE; (* ---------- KoalaFactory ---------- *) (* use default QueryInterface implementation *) (* AddRef & Release implemented implicitly by the compiler *) PROCEDURE (this: KoalaFactory) CreateInstance (outer: COM.IUnknown; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR res: COM.RESULT; new: Koala; BEGIN IF outer # NIL THEN RETURN WinApi.CLASS_E_NOAGGREGATION END; NEW(new); IF new # NIL THEN res := new.QueryInterface(iid, int); IF res >= 0 THEN INC(objects) END; RETURN res ELSE RETURN WinApi.E_OUTOFMEMORY END END CreateInstance; PROCEDURE (this: KoalaFactory) LockServer (lock: WinApi.BOOL): COM.RESULT; VAR res: INTEGER; BEGIN IF lock # 0 THEN INC(locks) ELSE DEC(locks) END; IF locks = 0 THEN res := WinApi.PostMessageW(mainWnd, WinApi.WM_CLOSE, 0, 0); END; RETURN WinApi.S_OK END LockServer; (* ---------- window handler ---------- *) PROCEDURE WndHandler (wnd: WinApi.HWND; message, wParam, lParam: INTEGER): INTEGER; VAR res: INTEGER; ps: WinApi.PAINTSTRUCT; dc: WinApi.HDC; BEGIN IF message = WinApi.WM_CLOSE THEN IF (locks > 0) OR (objects > 0) THEN RETURN 0 END ELSIF message = WinApi.WM_DESTROY THEN WinApi.PostQuitMessage(0); RETURN 0 ELSIF message = WinApi.WM_PAINT THEN dc := WinApi.BeginPaint(wnd, ps); res := WinApi.TextOutW(dc, 50, 50, "Koala Server", 12); res := WinApi.EndPaint(wnd, ps); RETURN 0 END; RETURN WinApi.DefWindowProcW(wnd, message, wParam, lParam) END WndHandler; PROCEDURE OpenWindow; VAR class: WinApi.WNDCLASSW; res: INTEGER; BEGIN class.hCursor := WinApi.LoadCursorW(0, S.VAL(WinApi.PtrWSTR, WinApi.IDC_ARROW)); class.hIcon := WinApi.LoadIconW(0, S.VAL(WinApi.PtrWSTR, WinApi.IDI_APPLICATION)); class.lpszMenuName := NIL; class.lpszClassName := "Koala"; class.hbrBackground := WinApi.GetStockObject(WinApi.WHITE_BRUSH); class.style := WinApi.CS_HREDRAW + WinApi.CS_VREDRAW; class.hInstance := instance; class.lpfnWndProc := WndHandler; class.cbClsExtra := 0; class.cbWndExtra := 0; res := WinApi.RegisterClassW(class); mainWnd := WinApi.CreateWindowExW({}, "Koala", "Koala", WinApi.WS_OVERLAPPEDWINDOW, WinApi.CW_USEDEFAULT, WinApi.CW_USEDEFAULT, WinApi.CW_USEDEFAULT, WinApi.CW_USEDEFAULT, 0, 0, instance, 0); res := WinApi.ShowWindow(mainWnd, 10); res := WinApi.UpdateWindow(mainWnd); END OpenWindow; (* ---------- main loop ---------- *) PROCEDURE Main; VAR msg: WinApi.MSG; res: COM.RESULT; factory: KoalaFactory; token: INTEGER; BEGIN instance := WinApi.GetModuleHandleW(NIL); res := WinOle.CoInitialize(0); NEW(factory); res := WinOle.CoRegisterClassObject(KoalaId, factory, WinOle.CLSCTX_LOCAL_SERVER, WinOle.REGCLS_MULTIPLEUSE, token); OpenWindow; WHILE WinApi.GetMessageW(msg, 0, 0, 0) # 0 DO res := WinApi.TranslateMessage(msg); res := WinApi.DispatchMessageW(msg); END; res := WinOle.CoRevokeClassObject(token); WinOle.CoUninitialize; WinApi.ExitProcess(msg.wParam) END Main; BEGIN Main END ComKoalaExe. DevLinker.LinkExe EKoala1.exe := Kernel+ ComKoalaExe ~ ----------------------------------------------------------------------------------------------------------------- REGEDIT HKEY_CLASSES_ROOT\Koala1.0 = Koala Object Chapter 5 HKEY_CLASSES_ROOT\Koala1.0\CLSID = {00021146-0000-0000-C000-000000000046} HKEY_CLASSES_ROOT\Koala = Koala Object Chapter 5 HKEY_CLASSES_ROOT\Koala\CurVer = Koala1.0 HKEY_CLASSES_ROOT\Koala\CLSID = {00021146-0000-0000-C000-000000000046} HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046} = Koala Object Chapter 5 HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\ProgID = Koala1.0 HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\VersionIndependentProgID = Koala HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\LocalServer32 = C:\BlackBox\Com\Ekoala1.exe HKEY_CLASSES_ROOT\CLSID\{00021146-0000-0000-C000-000000000046}\NotInsertable -----------------------------------------------------------------------------------------------------------------
Com/Mod/KoalaExe.odc
MODULE ComKoalaTst; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinApi, WinOle, StdLog; CONST KoalaId = "{00021146-0000-0000-C000-000000000046}"; nMax = 10; VAR factory: WinOle.IClassFactory; koala: ARRAY nMax OF COM.IUnknown; n: INTEGER; PROCEDURE CreateClass*; VAR res: INTEGER; BEGIN res := WinOle.CoGetClassObject(KoalaId, WinOle.CLSCTX_LOCAL_SERVER, 0, COM.ID(factory), factory); IF res = WinApi.S_OK THEN StdLog.String("Class creation succeeded"); StdLog.Ln ELSE StdLog.String("Class creation failed, error = "); StdLog.Int(res); StdLog.Ln END END CreateClass; PROCEDURE ReleaseClass*; BEGIN factory := NIL END ReleaseClass; PROCEDURE CreateInstance*; VAR res: INTEGER; BEGIN IF factory # NIL THEN res := factory.CreateInstance(NIL, COM.ID(COM.IUnknown), koala[0]); n := 1; IF res = WinApi.S_OK THEN StdLog.String("Instance creation succeeded"); StdLog.Ln ELSE StdLog.String("Instance creation failed, error = "); StdLog.Int(res); StdLog.Ln END ELSE StdLog.String("Creation failed, class not yet created."); StdLog.Ln END END CreateInstance; PROCEDURE AddRef*; BEGIN IF (n > 0) & (n < nMax) THEN koala[n] := koala[n-1]; INC(n) END END AddRef; PROCEDURE Release*; BEGIN IF n > 0 THEN DEC(n); koala[n] := NIL END END Release; END ComKoalaTst. ComKoala.Register ComKoala.Unregister ComKoalaTst.CreateClass ComKoalaTst.ReleaseClass ComKoalaTst.CreateInstance ComKoalaTst.AddRef ComKoalaTst.Release
Com/Mod/KoalaTst.odc
MODULE ComObject; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - 20070205, bh, Unicode support " issues = " - ... " **) IMPORT SYSTEM, COM, WinApi, WinOle, ComTools; CONST ObjectID = "{00010001-1000-11cf-adf0-444553540000}"; streamStr = "CONTENTS"; cbFormat = 200H; TYPE IClassFactory = POINTER TO RECORD (WinOle.IClassFactory) END; Object = POINTER TO RECORD (COM.IUnknown) ioo: IOleObject; ido: IDataObject; ips: IPersistStorage; ics: WinOle.IOleClientSite; idah: WinOle.IDataAdviseHolder; ioah: WinOle.IOleAdviseHolder; isg: WinOle.IStorage; ism: WinOle.IStream; w, h: INTEGER END; IOleObject = POINTER TO RECORD (WinOle.IOleObject) obj: Object END; IDataObject = POINTER TO RECORD (WinOle.IDataObject) obj: Object END; IPersistStorage = POINTER TO RECORD (WinOle.IPersistStorage) obj: Object END; VAR locks: INTEGER; token: INTEGER; PROCEDURE PictureOf (obj: Object): WinApi.HMETAFILEPICT; VAR dc: WinApi.HDC; mf: WinApi.HMETAFILE; mp: WinApi.PtrMETAFILEPICT; rc: WinApi.RECT; res: INTEGER; h: WinApi.HMETAFILEPICT; oldb, oldp: WinApi.HGDIOBJ; BEGIN dc := WinApi.CreateMetaFileW(NIL); IF dc # 0 THEN res := WinApi.SetMapMode(dc, WinApi.MM_ANISOTROPIC); res := WinApi.SetWindowOrgEx(dc, 0, 0, NIL); res := WinApi.SetWindowExtEx(dc, 20, 20, NIL); oldb := WinApi.SelectObject(dc, WinApi.GetStockObject(WinApi.NULL_BRUSH)); oldp := WinApi.SelectObject(dc, WinApi.CreatePen(WinApi.PS_SOLID, 1, 0)); res := WinApi.Ellipse(dc, 2, 2, 18, 18); res := WinApi.Ellipse(dc, 6, 6, 8, 8); res := WinApi.Ellipse(dc, 12, 6, 14, 8); res := WinApi.Ellipse(dc, 8, 8, 12, 12); res := WinApi.Ellipse(dc, 6, 14, 14, 16); res := WinApi.SelectObject(dc, oldb); res := WinApi.DeleteObject(WinApi.SelectObject(dc, oldp)); mf := WinApi.CloseMetaFile(dc); IF mf # 0 THEN h := WinApi.GlobalAlloc(WinApi.GMEM_DDESHARE + WinApi.GMEM_MOVEABLE, SIZE(WinApi.METAFILEPICT)); IF h # 0 THEN mp := SYSTEM.VAL(WinApi.PtrMETAFILEPICT, WinApi.GlobalLock(h)); mp.hMF := mf; mp.mm := WinApi.MM_ANISOTROPIC; mp.xExt := obj.w; mp.yExt := obj.h; res := WinApi.GlobalUnlock(h); RETURN h ELSE res := WinApi.DeleteMetaFile(mf) END END END; RETURN 0 END PictureOf; (* ---------- IClassFactory ---------- *) PROCEDURE (this: IClassFactory) CreateInstance (outer: COM.IUnknown; IN iid: COM.GUID; OUT int: COM.IUnknown): COM.RESULT; VAR res: COM.RESULT; new: Object; BEGIN IF outer = NIL THEN NEW(new); IF new # NIL THEN NEW(new.ioo, new); NEW(new.ido, new); NEW(new.ips, new); IF (new.ioo # NIL) & (new.ido # NIL) & (new.ips # NIL) THEN new.ioo.obj := new; new.ido.obj := new; new.ips.obj := new; res := new.QueryInterface(iid, int) ELSE res := WinApi.E_OUTOFMEMORY END ELSE res := WinApi.E_OUTOFMEMORY END ELSE res := WinApi.CLASS_E_NOAGGREGATION END; RETURN res END CreateInstance; PROCEDURE (this: IClassFactory) LockServer (lock: WinApi.BOOL): COM.RESULT; BEGIN IF lock # 0 THEN INC(locks) ELSE DEC(locks) END; RETURN WinApi.S_OK END LockServer; (* ---------- Object ---------- *) PROCEDURE (this: Object) QueryInterface (IN iid: COM.GUID; OUT int: COM.IUnknown): COM.RESULT; BEGIN IF COM.QUERY(this, iid, int) OR COM.QUERY(this.ioo, iid, int) OR COM.QUERY(this.ido, iid, int) OR COM.QUERY(this.ips, iid, int) THEN RETURN WinApi.S_OK ELSE RETURN WinApi.E_NOINTERFACE END END QueryInterface; (* ---------- IOleObject ---------- *) PROCEDURE (this: IOleObject) SetClientSite (site: WinOle.IOleClientSite): COM.RESULT; BEGIN this.obj.ics := site; RETURN WinApi.S_OK END SetClientSite; PROCEDURE (this: IOleObject) GetClientSite (OUT site: WinOle.IOleClientSite): COM.RESULT; BEGIN site := this.obj.ics; RETURN WinApi.S_OK END GetClientSite; PROCEDURE (this: IOleObject) SetHostNames (app, obj: WinApi.PtrWSTR): COM.RESULT; BEGIN RETURN WinApi.S_OK END SetHostNames; PROCEDURE (this: IOleObject) Close (saveOption: INTEGER): COM.RESULT; BEGIN RETURN WinApi.S_OK END Close; PROCEDURE (this: IOleObject) SetMoniker (which: INTEGER; mk: WinOle.IMoniker): COM.RESULT; BEGIN RETURN WinApi.E_NOTIMPL END SetMoniker; PROCEDURE (this: IOleObject) GetMoniker (assign, which: INTEGER; OUT mk: WinOle.IMoniker): COM.RESULT; BEGIN RETURN WinApi.E_NOTIMPL END GetMoniker; PROCEDURE (this: IOleObject) InitFromData (obj: WinOle.IDataObject; creation: WinApi.BOOL; reserved: INTEGER): COM.RESULT; BEGIN RETURN WinApi.E_NOTIMPL END InitFromData; PROCEDURE (this: IOleObject) GetClipboardData (reserved: INTEGER; OUT obj: WinOle.IDataObject): COM.RESULT; BEGIN RETURN WinApi.E_NOTIMPL END GetClipboardData; PROCEDURE (this: IOleObject) DoVerb (verb: INTEGER; IN msg: WinApi.MSG; activeSite: WinOle.IOleClientSite; index: INTEGER; parent: WinApi.HWND; IN posRect: WinApi.RECT): COM.RESULT; BEGIN IF verb < 0 THEN RETURN WinApi.S_OK ELSE RETURN WinApi.OLEOBJ_E_NOVERBS END END DoVerb; PROCEDURE (this: IOleObject) EnumVerbs (OUT enum: WinOle.IEnumOLEVERB): COM.RESULT; BEGIN RETURN WinApi.OLEOBJ_E_NOVERBS END EnumVerbs; PROCEDURE (this: IOleObject) Update (): COM.RESULT; BEGIN RETURN WinApi.S_OK END Update; PROCEDURE (this: IOleObject) IsUpToDate (): COM.RESULT; BEGIN RETURN WinApi.S_OK END IsUpToDate; PROCEDURE (this: IOleObject) GetUserClassID (OUT id: COM.GUID): COM.RESULT; BEGIN id := ObjectID; RETURN WinApi.S_OK END GetUserClassID; PROCEDURE (this: IOleObject) GetUserType (form: INTEGER; OUT type: WinApi.PtrWSTR): COM.RESULT; BEGIN RETURN WinApi.OLE_S_USEREG END GetUserType; PROCEDURE (this: IOleObject) SetExtent (aspect: SET; IN size: WinApi.SIZE): COM.RESULT; VAR res: COM.RESULT; BEGIN IF aspect * WinOle.DVASPECT_CONTENT # {} THEN this.obj.w := size.cx; this.obj.h := size.cy; RETURN WinApi.S_OK ELSE RETURN WinApi.E_FAIL END END SetExtent; PROCEDURE (this: IOleObject) GetExtent (aspect: SET; OUT size: WinApi.SIZE): COM.RESULT; BEGIN IF aspect * WinOle.DVASPECT_CONTENT # {} THEN size.cx := this.obj.w; size.cy := this.obj.h; RETURN WinApi.S_OK ELSE RETURN WinApi.E_FAIL END END GetExtent; PROCEDURE (this: IOleObject) Advise (sink: WinOle.IAdviseSink; OUT connection: INTEGER): COM.RESULT; VAR res: COM.RESULT; BEGIN IF this.obj.ioah = NIL THEN res := WinOle.CreateOleAdviseHolder(this.obj.ioah); IF res < 0 THEN RETURN res END END; RETURN this.obj.ioah.Advise(sink, connection) END Advise; PROCEDURE (this: IOleObject) Unadvise (connection: INTEGER): COM.RESULT; BEGIN IF this.obj.ioah # NIL THEN RETURN this.obj.ioah.Unadvise(connection) ELSE RETURN WinApi.E_FAIL END END Unadvise; PROCEDURE (this: IOleObject) EnumAdvise (OUT enum: WinOle.IEnumSTATDATA): COM.RESULT; BEGIN IF this.obj.ioah # NIL THEN RETURN this.obj.ioah.EnumAdvise(enum) ELSE RETURN WinApi.E_FAIL END END EnumAdvise; PROCEDURE (this: IOleObject) GetMiscStatus (aspect: SET; OUT status: SET): COM.RESULT; BEGIN RETURN WinApi.OLE_S_USEREG END GetMiscStatus; PROCEDURE (this: IOleObject) SetColorScheme (IN pal: WinApi.LOGPALETTE): COM.RESULT; BEGIN RETURN WinApi.E_NOTIMPL END SetColorScheme; (* ---------- IDataObject ---------- *) PROCEDURE (this: IDataObject) GetData (IN format: WinOle.FORMATETC; OUT medium: WinOle.STGMEDIUM): COM.RESULT; VAR res: COM.RESULT; BEGIN res := this.QueryGetData(format); IF res = WinApi.S_OK THEN ComTools.GenMetafileMedium(PictureOf(this.obj), NIL, medium); RETURN WinApi.S_OK ELSE RETURN res END END GetData; PROCEDURE (this: IDataObject) GetDataHere (IN format: WinOle.FORMATETC; VAR medium: WinOle.STGMEDIUM): COM.RESULT; BEGIN RETURN WinApi.DV_E_FORMATETC END GetDataHere; PROCEDURE (this: IDataObject) QueryGetData (IN format: WinOle.FORMATETC): COM.RESULT; BEGIN IF format.dwAspect * WinOle.DVASPECT_CONTENT = {} THEN RETURN WinApi.DV_E_DVASPECT ELSIF format.cfFormat # WinApi.CF_METAFILEPICT THEN RETURN WinApi.DV_E_FORMATETC ELSIF format.tymed * WinOle.TYMED_MFPICT = {} THEN RETURN WinApi.DV_E_TYMED ELSE RETURN WinApi.S_OK END END QueryGetData; PROCEDURE (this: IDataObject) GetCanonicalFormatEtc (IN formatIn: WinOle.FORMATETC; OUT formatOut: WinOle.FORMATETC): COM.RESULT; BEGIN RETURN WinApi.DATA_S_SAMEFORMATETC END GetCanonicalFormatEtc; PROCEDURE (this: IDataObject) SetData (IN format: WinOle.FORMATETC; IN medium: WinOle.STGMEDIUM; release: WinApi.BOOL): COM.RESULT; BEGIN RETURN WinApi.DV_E_FORMATETC END SetData; PROCEDURE (this: IDataObject) EnumFormatEtc (direction: SET; OUT enum: WinOle.IEnumFORMATETC): COM.RESULT; BEGIN RETURN WinApi.OLE_S_USEREG END EnumFormatEtc; PROCEDURE (this: IDataObject) DAdvise (IN format: WinOle.FORMATETC; flags: SET; advSink: WinOle.IAdviseSink; OUT connection: INTEGER): COM.RESULT; VAR res: COM.RESULT; BEGIN IF this.obj.idah = NIL THEN res := WinOle.CreateDataAdviseHolder(this.obj.idah); IF res < 0 THEN RETURN res END END; RETURN this.obj.idah.Advise(this, format, flags, advSink, connection) END DAdvise; PROCEDURE (this: IDataObject) DUnadvise (connection: INTEGER): COM.RESULT; BEGIN IF this.obj.idah # NIL THEN RETURN this.obj.idah.Unadvise(connection) ELSE RETURN WinApi.E_FAIL END END DUnadvise; PROCEDURE (this: IDataObject) EnumDAdvise (OUT enum: WinOle.IEnumSTATDATA): COM.RESULT; BEGIN IF this.obj.idah # NIL THEN RETURN this.obj.idah.EnumAdvise(enum) ELSE RETURN WinApi.E_FAIL END END EnumDAdvise; (* ---------- IPersistStorage ---------- *) PROCEDURE (this: IPersistStorage) GetClassID (OUT id: COM.GUID): COM.RESULT; BEGIN id := ObjectID; RETURN WinApi.S_OK END GetClassID; PROCEDURE (this: IPersistStorage) IsDirty (): COM.RESULT; BEGIN RETURN WinApi.S_FALSE END IsDirty; PROCEDURE (this: IPersistStorage) InitNew (stg: WinOle.IStorage): COM.RESULT; VAR res: COM.RESULT; ps: WinApi.PtrWSTR; BEGIN IF stg # NIL THEN res := stg.CreateStream(streamStr, WinOle.STGM_DIRECT + WinOle.STGM_CREATE + WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE, 0, 0, this.obj.ism); IF res >= 0 THEN res := WinOle.OleRegGetUserType(ObjectID, WinOle.USERCLASSTYPE_SHORT, ps); res := WinOle.WriteFmtUserTypeStg(stg, cbFormat, ps); ComTools.FreeString(ps); this.obj.isg := stg; this.obj.w := 5000; this.obj.h := 5000; RETURN WinApi.S_OK ELSE RETURN res END ELSE RETURN WinApi.E_POINTER END END InitNew; PROCEDURE (this: IPersistStorage) Load (stg: WinOle.IStorage): COM.RESULT; VAR res: COM.RESULT; BEGIN IF stg # NIL THEN res := stg.OpenStream(streamStr, 0, WinOle.STGM_DIRECT + WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE, 0, this.obj.ism); IF res >= 0 THEN res := this.obj.ism.Read(SYSTEM.ADR(this.obj.w), 4, NIL); res := this.obj.ism.Read(SYSTEM.ADR(this.obj.h), 4, NIL); IF res >= 0 THEN this.obj.isg := stg; RETURN WinApi.S_OK END END; RETURN WinApi.STG_E_READFAULT ELSE RETURN WinApi.E_POINTER END END Load; PROCEDURE (this: IPersistStorage) Save (stg: WinOle.IStorage; sameAsLoad: WinApi.BOOL): COM.RESULT; VAR stm: WinOle.IStream; res: COM.RESULT; ps: WinApi.PtrWSTR; BEGIN IF sameAsLoad # 0 THEN stm := this.obj.ism; res := stm.Seek(0, WinOle.STREAM_SEEK_SET, NIL) ELSIF stg # NIL THEN res := stg.CreateStream(streamStr, WinOle.STGM_DIRECT + WinOle.STGM_CREATE + WinOle.STGM_WRITE + WinOle.STGM_SHARE_EXCLUSIVE, 0, 0, stm); IF res < 0 THEN RETURN res END; res := WinOle.OleRegGetUserType(ObjectID, WinOle.USERCLASSTYPE_SHORT, ps); res := WinOle.WriteFmtUserTypeStg(stg, cbFormat, ps); ComTools.FreeString(ps); ELSE RETURN WinApi.E_POINTER END; res := stm.Write(SYSTEM.ADR(this.obj.w), 4, NIL); res := stm.Write(SYSTEM.ADR(this.obj.h), 4, NIL); IF res < 0 THEN RETURN WinApi.STG_E_WRITEFAULT ELSE RETURN WinApi.S_OK END END Save; PROCEDURE (this: IPersistStorage) SaveCompleted (new: WinOle.IStorage): COM.RESULT; VAR res: COM.RESULT; BEGIN IF new # NIL THEN res := new.OpenStream(streamStr, 0, WinOle.STGM_DIRECT + WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE, 0, this.obj.ism); IF res >= 0 THEN this.obj.isg := new; ELSE RETURN res END END; IF this.obj.ioah # NIL THEN res := this.obj.ioah.SendOnSave() END; RETURN WinApi.S_OK END SaveCompleted; PROCEDURE (this: IPersistStorage) HandsOffStorage (): COM.RESULT; BEGIN this.obj.ism := NIL; this.obj.isg := NIL; RETURN WinApi.S_OK END HandsOffStorage; (* ---------- commands ---------- *) PROCEDURE Register*; VAR res: COM.RESULT; factory: IClassFactory; BEGIN NEW(factory); res := WinOle.CoRegisterClassObject(ObjectID, factory, WinOle.CLSCTX_LOCAL_SERVER, WinOle.REGCLS_MULTIPLEUSE, token); END Register; PROCEDURE Unregister*; VAR res: COM.RESULT; BEGIN IF (token # 0) & (locks = 0) THEN res := WinOle.CoRevokeClassObject(token) END END Unregister; END ComObject. ComObject.Register ComObject.Unregister ----------------------------------------------------------------------------------------------------------------- REGEDIT HKEY_CLASSES_ROOT\BlackBox.Object = BlackBox Object HKEY_CLASSES_ROOT\BlackBox.Object\CLSID = {00010001-1000-11cf-adf0-444553540000} HKEY_CLASSES_ROOT\BlackBox.Object\Insertable HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000} = BlackBox Object HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\ProgID = BlackBox.Object HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\LocalServer32 = C:\BlackBox\BlackBox.exe HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\InProcHandler32 = ole32.dll HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\Insertable HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\DefaultIcon = C:\BlackBox\BlackBox.exe,0 HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\DataFormats\GetSet\0 = 3,1,32,1 HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\MiscStatus = 16 HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\AuxUserType\2 = BlackBox Object HKEY_CLASSES_ROOT\CLSID\{00010001-1000-11cf-adf0-444553540000}\AuxUserType\3 = BlackBox -----------------------------------------------------------------------------------------------------------------
Com/Mod/Object.odc
MODULE ComPhoneBook; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinApi, WinOle, ComTools; CONST CLSID* = "{E67D346C-2A5B-11D0-ADBA-00C01500554E}"; E_NotFound* = 80004005H; TYPE ILookup* = POINTER TO ABSTRACT RECORD ["{C4910D71-BA7D-11CD-94E8-08001701A8A3}"] (COM.IUnknown) END; CLookup = POINTER TO RECORD (ILookup) phoneBook: Entry END; LookupFactory = POINTER TO RECORD (WinOle.IClassFactory) END; Entry = POINTER TO RECORD next: Entry; name, number: ARRAY 32 OF CHAR END; VAR locks: INTEGER; token: INTEGER; phoneBook: Entry; (* ---------- ILookup ---------- *) PROCEDURE (this: ILookup) LookupByName*( name: WinApi.PtrWSTR; OUT number: WinApi.PtrWSTR): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: ILookup) LookupByNumber*( number: WinApi.PtrWSTR; OUT name: WinApi.PtrWSTR): COM.RESULT, NEW, ABSTRACT; (* ---------- CLookup ---------- *) PROCEDURE (this: CLookup) LookupByName(name: WinApi.PtrWSTR; OUT number: WinApi.PtrWSTR): COM.RESULT; VAR e: Entry; BEGIN e := this.phoneBook; WHILE (e # NIL) & (e.name # name^) DO e := e.next END; IF e # NIL THEN number := ComTools.NewString(e.number); RETURN WinApi.S_OK ELSE RETURN E_NotFound END END LookupByName; PROCEDURE (this: CLookup) LookupByNumber(number: WinApi.PtrWSTR; OUT name: WinApi.PtrWSTR): COM.RESULT; VAR e: Entry; BEGIN e := this.phoneBook; WHILE (e # NIL) & (e.number # number^) DO e := e.next END; IF e # NIL THEN name := ComTools.NewString(e.name); RETURN WinApi.S_OK ELSE RETURN E_NotFound END END LookupByNumber; (* ---------- LookupFactory ---------- *) PROCEDURE (this: LookupFactory) CreateInstance (outer: COM.IUnknown; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR new: CLookup; BEGIN IF outer # NIL THEN RETURN WinApi.CLASS_E_NOAGGREGATION END; NEW(new); IF new # NIL THEN new.phoneBook := phoneBook;RETURN new.QueryInterface(iid, int) ELSE RETURN WinApi.E_OUTOFMEMORY END END CreateInstance; PROCEDURE (this: LookupFactory) LockServer (lock: WinApi.BOOL): COM.RESULT; BEGIN IF lock # 0 THEN INC(locks) ELSE DEC(locks) END; RETURN WinApi.S_OK END LockServer; (* ---------- registration ---------- *) PROCEDURE Register*; VAR res: COM.RESULT; factory: LookupFactory; BEGIN NEW(factory); res := WinOle.CoRegisterClassObject(CLSID, factory, WinOle.CLSCTX_LOCAL_SERVER, WinOle.REGCLS_MULTIPLEUSE, token) END Register; PROCEDURE Unregister*; VAR res: COM.RESULT; BEGIN IF (locks = 0) & (token # 0) THEN res := WinOle.CoRevokeClassObject(token); token := 0 END END Unregister; PROCEDURE NewEntry(name, number: ARRAY 32 OF CHAR); VAR e: Entry; BEGIN NEW(e); e.next := phoneBook; phoneBook := e; e.name := name$; e.number := number$ END NewEntry; BEGIN locks := 0; NewEntry("Daffy Duck", "310-555-1212"); NewEntry("Wile E. Coyote", "408-555-1212"); NewEntry("Scrogge McDuck", "206-555-1212"); NewEntry("Huey Lewis", "415-555-1212"); NewEntry("Thomas Dewey", "617-555-1212") END ComPhoneBook.
Com/Mod/PhoneBook.odc
MODULE ComPhoneBookActiveX; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinApi, WinOle, ComTools, WinOleAut; CONST CLSID* = "{E67D346B-2A5B-11D0-ADBA-00C01500554E}"; E_NotFound = -2147467259; typelibrary = "C:\BlackBox\Com\Interfaces\DPhoneBook\phone.tlb"; TYPE ILookup* = POINTER TO ABSTRACT RECORD ["{C4910D72-BA7D-11CD-94E8-08001701A8A3}"] (WinOleAut.IDispatch) END; CLookup = POINTER TO RECORD (ILookup) END; LookupFactory = POINTER TO RECORD (WinOle.IClassFactory) END; Entry = POINTER TO EntryDesc; EntryDesc = RECORD next: Entry; name, number: ARRAY 32 OF CHAR END; VAR locks: INTEGER; objects: INTEGER; phoneBook: Entry; (* ---------- ILookup ---------- *) PROCEDURE (this: ILookup) LookupByName*( name: WinApi.PtrWSTR; OUT number: WinApi.PtrWSTR): COM.RESULT, NEW, ABSTRACT; PROCEDURE (this: ILookup) LookupByNumber*( number: WinApi.PtrWSTR; OUT name: WinApi.PtrWSTR): COM.RESULT, NEW, ABSTRACT; (* ---------- CLookup ---------- *) (* use default QueryInterface implementation *) (* AddRef & Release implemented implicitly by the compiler *) PROCEDURE (this: CLookup) LookupByName(name: WinApi.PtrWSTR; OUT number: WinApi.PtrWSTR): COM.RESULT; VAR e: Entry; ustr: ARRAY [untagged] 32 OF CHAR; i: INTEGER; BEGIN e := phoneBook; WHILE (e # NIL) & (e.name # name^) DO e := e.next END; IF e # NIL THEN i := 0; REPEAT ustr[i] := e.number[i]; INC(i) UNTIL e.number[i-1] = 0X; number := ComTools.NewString(ustr); RETURN WinApi.S_OK ELSE RETURN E_NotFound END END LookupByName; PROCEDURE (this: CLookup) LookupByNumber(number: WinApi.PtrWSTR; OUT name: WinApi.PtrWSTR): COM.RESULT; VAR e: Entry; ustr: ARRAY [untagged] 32 OF CHAR; i: INTEGER; BEGIN e := phoneBook; WHILE (e # NIL) & (e.number # number^) DO e := e.next END; IF e # NIL THEN i := 0; REPEAT ustr[i] := e.name[i]; INC(i) UNTIL e.name[i-1] = 0X; name := ComTools.NewString(ustr); RETURN WinApi.S_OK ELSE RETURN E_NotFound END END LookupByNumber; PROCEDURE (this: CLookup) Invoke (dispIdMember: WinOleAut.DISPID; IN riid: COM.GUID; lcid: WinOle.LCID; wFlags: SHORTINT; VAR [nil] pDispParams: WinOleAut.DISPPARAMS; OUT [nil] pVarResult: WinOleAut.VARIANT; OUT [nil] pExcepInfo: WinOleAut.EXCEPINFO; OUT [nil] puArgErr: INTEGER ): COM.RESULT; VAR wstr: WinApi.PtrWSTR; res: INTEGER; (* bstr: WinOle.BSTR; *) BEGIN IF (dispIdMember = 1) OR (dispIdMember = 2) THEN IF pDispParams.cArgs = 1 THEN IF pDispParams.rgvarg[0].vt = WinOle.VT_BSTR THEN IF dispIdMember = 1 THEN res := this.LookupByName(pDispParams.rgvarg[0].u.bstrVal, wstr) ELSE res := this.LookupByNumber(pDispParams.rgvarg[0].u.bstrVal, wstr) END; IF res = 0 THEN pVarResult.vt := WinOle.VT_BSTR; pVarResult.u.bstrVal := WinOleAut.SysAllocString(wstr^); RETURN WinApi.S_OK ELSE pExcepInfo.wCode := 0; pExcepInfo.wReserved := 0; pExcepInfo.bstrSource := WinOleAut.SysAllocString("PhoneBook.Lookup"); pExcepInfo.bstrDescription := WinOleAut.SysAllocString("Entry not found"); pExcepInfo.bstrHelpFile := NIL; pExcepInfo.pfnDeferredFillIn := NIL; pExcepInfo.scode := res; RETURN WinApi.DISP_E_EXCEPTION END ELSE RETURN WinApi.DISP_E_BADVARTYPE END ELSE RETURN WinApi.DISP_E_BADPARAMCOUNT END; ELSE RETURN WinApi.DISP_E_MEMBERNOTFOUND END END Invoke; PROCEDURE (this: CLookup) GetIDsOfNames (IN [nil] riid: COM.GUID (* NULL *); IN [nil] rgszNames: WinApi.PtrWSTR; cNames: INTEGER; lcid: WinOle.LCID; OUT [nil] rgDispId: WinOleAut.DISPID ): COM.RESULT; VAR lib: WinOleAut.ITypeLib; ptinfo: WinOleAut.ITypeInfo; names: WinApi.PtrWSTR;res: INTEGER; BEGIN res := WinOleAut.LoadTypeLib(ComTools.NewString(typelibrary), lib); res := lib.GetTypeInfoOfGuid(COM.ID(ILookup), ptinfo); names := ComTools.NewString(rgszNames^); res := WinOleAut.DispGetIDsOfNames(ptinfo, names, cNames, rgDispId); RETURN 0 END GetIDsOfNames; PROCEDURE (this: CLookup) GetTypeInfo (iTInfo: INTEGER; lcid: WinOle.LCID; OUT [nil] ppTInfo: WinOleAut.ITypeInfo): COM.RESULT; VAR lib: WinOleAut.ITypeLib; res: INTEGER; BEGIN res := WinOleAut.LoadTypeLib(ComTools.NewString(typelibrary), lib); RETURN lib.GetTypeInfo(iTInfo, ppTInfo) END GetTypeInfo; PROCEDURE (this: CLookup) GetTypeInfoCount (OUT [nil] pctinfo: INTEGER): COM.RESULT; BEGIN pctinfo := 1; (* type info available *) RETURN 0 END GetTypeInfoCount; PROCEDURE (this: CLookup) RELEASE; (* called when last com reference is removed *) BEGIN DEC(objects) END RELEASE; (* ---------- LookupFactory ---------- *) (* use default QueryInterface implementation *) (* AddRef & Release implemented implicitly by the compiler *) PROCEDURE (this: LookupFactory) CreateInstance (outer: COM.IUnknown; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR res: COM.RESULT; new: CLookup; BEGIN IF outer # NIL THEN RETURN WinApi.CLASS_E_NOAGGREGATION END; NEW(new); IF new # NIL THEN res := new.QueryInterface(iid, int); IF res >= 0 THEN INC(objects) END; RETURN res ELSE RETURN WinApi.E_OUTOFMEMORY END END CreateInstance; PROCEDURE (this: LookupFactory) LockServer (lock: WinApi.BOOL): COM.RESULT; BEGIN IF lock # 0 THEN INC(locks) ELSE DEC(locks) END; RETURN WinApi.S_OK END LockServer; (* ---------- dll interface ---------- *) PROCEDURE DllGetClassObject* (IN clsid: COM.GUID; IN [iid] iid: COM.GUID; OUT [new] int: COM.IUnknown): COM.RESULT; VAR obj: LookupFactory; BEGIN IF clsid = CLSID THEN NEW(obj); IF obj # NIL THEN RETURN obj.QueryInterface(iid, int) ELSE RETURN WinApi.E_OUTOFMEMORY; END ELSE RETURN WinApi.E_FAIL END END DllGetClassObject; PROCEDURE DllCanUnloadNow* (): COM.RESULT; BEGIN IF (objects = 0) & (locks = 0) THEN RETURN WinApi.S_OK ELSE RETURN WinApi.S_FALSE END END DllCanUnloadNow; PROCEDURE NewEntry(name, number: ARRAY OF CHAR); VAR e: Entry; BEGIN NEW(e); e.next := phoneBook; phoneBook := e; e.name := name$; e.number := number$ END NewEntry; BEGIN locks := 0; objects := 0; NewEntry("Daffy Duck", "310-555-1212"); NewEntry("Wile E. Coyote", "408-555-1212"); NewEntry("Scrooge McDuck", "206-555-1212"); NewEntry("Huey Lewis", "415-555-1212"); NewEntry("Thomas Dewey", "617-555-1212"); END ComPhoneBookActiveX. DevLinker.LinkDll "Com/phone.dll" := Kernel+ ComTools ComPhoneBookActiveX# ~ REGEDIT HKEY_CLASSES_ROOT\PhoneBook = PhoneBook ActiveX Control HKEY_CLASSES_ROOT\PhoneBook\CLSID = {E67D346B-2A5B-11D0-ADBA-00C01500554E} HKEY_CLASSES_ROOT\PhoneBook\TypeLib = {C4910D73-BA7D-11CD-94E8-08001701A8A3} HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E} = PhoneBook ActiveX Control HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\ProgID = PhoneBook1.0 HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\Control HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\Version = 1.0 HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\VersionIndependentProgID = PhoneBook HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\TypeLib = {C4910D73-BA7D-11CD-94E8-08001701A8A3} HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\InprocServer32 = C:\BlackBox\Com\phone.dll HKEY_CLASSES_ROOT\CLSID\{E67D346B-2A5B-11D0-ADBA-00C01500554E}\NotInsertable HKEY_CLASSES_ROOT\TypeLib\{C4910D73-BA7D-11CD-94E8-08001701A8A3}\1.0 = PhoneBook ActiveX Control HKEY_CLASSES_ROOT\TypeLib\{C4910D73-BA7D-11CD-94E8-08001701A8A3}\1.0\0\win32 = C:\BlackBox\Com\Interfaces\DPhoneBook\phone.tlb HKEY_CLASSES_ROOT\TypeLib\{C4910D73-BA7D-11CD-94E8-08001701A8A3}\1.0\FLAGS = 0 HKEY_CLASSES_ROOT\TypeLib\{C4910D73-BA7D-11CD-94E8-08001701A8A3}\1.0\HELPDIR = C:\BlackBox\Com\Interfaces\DPhoneBook
Com/Mod/PhoneBookActiveX.odc
MODULE ComPhoneBookClient; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = " - YYYYMMDD, nn, ... " issues = " - ... " **) IMPORT COM, WinOle, WinApi, ComTools, StdLog, ComPhoneBook, Dialog; VAR para*: RECORD name*: Dialog.Combo; number*: ARRAY 32 OF CHAR END; PROCEDURE GetNumber*; VAR phoneBook: ComPhoneBook.ILookup; res: INTEGER; str: WinApi.PtrWSTR; BEGIN res := WinOle.CoCreateInstance(ComPhoneBook.CLSID, NIL, WinOle.CLSCTX_SERVER, COM.ID(phoneBook), phoneBook); IF res = WinApi.S_OK THEN res := phoneBook.LookupByName(para.name.item, str); IF res = WinApi.S_OK THEN para.number := str$; ComTools.FreeString(str) ELSE StdLog.String("GetNumber failed, error = "); StdLog.Int(res); StdLog.Ln; para.number := "" END; Dialog.Update(para) ELSE StdLog.String("Instance creation failed, error = "); StdLog.Int(res); StdLog.Ln END; END GetNumber; BEGIN para.name.SetLen(5); para.name.SetItem(0, "Daffy Duck"); para.name.SetItem(1, "Wile E. Coyote"); para.name.SetItem(2, "Scrogge McDuck"); para.name.SetItem(3, "Huey Lewis"); para.name.SetItem(4, "Thomas Dewey"); END ComPhoneBookClient. ComPhoneBook.Register ComPhoneBook.Unregister "StdCmds.OpenToolDialog('Com/Rsrc/PhoneBook', 'PhoneBook')"
Com/Mod/PhoneBookClient.odc
README.md exists but content is empty.
Downloads last month
5