OpenOffice.org Forum at OOoForum.orgThe OpenOffice.org Forum
 
 [Home]   [FAQ]   [Search]   [Memberlist]   [Usergroups]   [Register
 [Profile]   [Log in to check your private messages]   [Log in

Some Introspection techniques (various languages)

 
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets
View previous topic :: View next topic  
Author Message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Tue Mar 23, 2004 7:51 am    Post subject: Some Introspection techniques (various languages) Reply with quote

This article addresses several facets of introspection.

In Java, Python, Visual Basic, etc. you do not have the convenient HasUnoInterfaces function provided in OOo Basic.

It is convenient to be able to use the supportsService() of the XServiceInfo interface. Problem is, if the service you are examining does not implemnent XServiceInfo, then you can't call supportsService(). So you would want to use a HasUnoInterfaces() function, as in OOo Basic, to first determine if the XServiceInfo interface is present.

Even without the XServiceInfo interface, you can still gather the methods, interfaces and properties of an object.


HasUnoInterfaces()

Here is my implementation of HasUnoInterfaces, written in OOo Basic. You can use this technique to implement a HasUnoInterfaces function in your programming language of choice.

Code:
' Here is one possible way to implement HasUnoInterfaces().
' There may be a more efficient method, but this works.
' This works by looking at every method that oObj has, and
'  then checking if *any* of those methods come from the
'  interface name that we are testing for.
Function DannysHasUnoInterface( oObj, cInterfaceName )
   DannysHasUnoInterface() = False
   
   ' Get the Introspection service.
   oIntrospection = createUnoService( "com.sun.star.beans.Introspection" )

   ' Now inspect the object to learn about it.   
   oObjInfo = oIntrospection.inspect( oObj )
   
   ' Obtain an array describing all methods of the object.
   oMethods = oObjInfo.getMethods( com.sun.star.beans.MethodConcept.ALL )
   ' Now look at every method.
   For i = LBound( oMethods ) To UBound( oMethods )
      oMethod = oMethods( i )
      ' Check the method's interface to see if
      '  these aren't the droids you're looking for.
      cMethodInterfaceName = oMethod.getDeclaringClass().getName()
      If cMethodInterfaceName = cInterfaceName Then
         DannysHasUnoInterface() = True
         Exit Function
      EndIf
   Next
End Function


Note this function is named in the singular not plural. You could trivially write a DannysHasUnoInterfaces() function wrapper around it to test for multiple interfaces.

In the past, I posted a similar implementation of the above in Python here...
http://www.oooforum.org/forum/viewtopic.php?t=6766

Code:
def hasUnoInterface( oObject, cInterfaceName ):
    """Similar to Basic's HasUnoInterfaces() function, but singular not plural."""

    # Get the Introspection service.
    oIntrospection = createUnoService( "com.sun.star.beans.Introspection" )

    # Now inspect the object to learn about it.   
    oObjInfo = oIntrospection.inspect( oObject )
   
    # Obtain an array describing all methods of the object.
    oMethods = oObjInfo.getMethods( uno.getConstantByName( "com.sun.star.beans.MethodConcept.ALL" ) )
    # Now look at every method.
    for oMethod in oMethods:
        # Check the method's interface to see if
        #  these aren't the droids you're looking for.
        cMethodInterfaceName = oMethod.getDeclaringClass().getName()
        if cMethodInterfaceName == cInterfaceName:
            return True
    return False


You need to go here
http://www.oooforum.org/forum/viewtopic.php?p=12909#12909
for some of my additional python functions, such as createUnoService() in order to make the previous python routine work.




SupportsService

OOo Basic programmers sometimes call the supportsService() method to test if a service exists. But sometimes this gives an error.

The reason for the error, as explained earlier is that the XServiceInfo interface may not be implemented on the object.

Using OOo Basic's HasUnoInterfaces (or re-implementing this function as described earlier, but in your favorite programming language) allows you to test for the XServiceInfo interface before attempting to call supportsService().



GetMethods() and GetProperties()

Here are a couple of functions that simulate the effect of two psuedo-properties that OOo Basic provides named Dbg_Methods and Dbg_Properties.

Code:
Function GetMethods( oObj )
   oIntrospection = createUnoService( "com.sun.star.beans.Introspection" )
   oObjInfo = oIntrospection.inspect( oObj )
   
   oMethods = oObjInfo.getMethods( com.sun.star.beans.MethodConcept.ALL )
   nNumMethods = UBound( oMethods ) - LBound( oMethods ) + 1

   cDscrpt = CSTR( nNumMethods ) + " methods"
   If nNumMethods > 0 Then
      cDscrpt = cDscrpt + "..."
   EndIf
   
   For i = LBound( oMethods ) To UBound( oMethods )
      oMethod = oMethods( i )
      cMethodName = oMethod.getName()
      cInterfaceName = oMethod.getDeclaringClass().getName()
      If Len( cDscrpt ) > 0 Then
         cDscrpt = cDscrpt + Chr(13)
      EndIf
      cDscrpt = cDscrpt + cInterfaceName + " --> " + cMethodName
   Next
   GetMethods() = cDscrpt
End Function

Function GetProperties( oObj )
   oIntrospection = createUnoService( "com.sun.star.beans.Introspection" )
   oObjInfo = oIntrospection.inspect( oObj )
   
   oProperties = oObjInfo.getProperties( com.sun.star.beans.PropertyConcept.ALL )
   nNumProperties = UBound( oProperties ) - LBound( oProperties ) + 1

   cDscrpt = CSTR( nNumProperties ) + " properties"
   If nNumProperties > 0 Then
      cDscrpt = cDscrpt + "..."
   EndIf
   
   For i = LBound( oProperties ) To UBound( oProperties )
      oProperty = oProperties( i )
      cPropertyName = oProperty.Name
      If Len( cDscrpt ) > 0 Then
         cDscrpt = cDscrpt + Chr(13)
      EndIf
      cDscrpt = cDscrpt + cPropertyName
   Next
   GetProperties() = cDscrpt
End Function



Here is a simple example of how you could create some object, and then describe its methods and properties in a MsgBox.
Code:
Sub Main
   ' Create some random object, and then show its methods and
   '  properties in a pair of MsgBox's.
   oObj = createUnoService( "com.sun.star.document.FilterFactory" )
   DescribeWithMsgBox( oObj )
End Sub


Sub DescribeWithMsgBox( oObj )
   cMethods = GetMethods( oObj )
   MsgBox( cMethods )
   
   cProperties = GetProperties( oObj )
   MsgBox( cProperties )
End Sub



Here is an example of how to create an object that has a large description, and then dump that description into a Writer document.
Code:
Sub Main
   ' Create a drawing, which has many methods and properties,
   '  and describe those into a new Writer document.   
   oObj = StarDesktop.loadComponentFromURL( "private:factory/sdraw", "_blank", 0, Array() )
   DescribeToWriterDoc( oObj )
   ' Close the drawing document.
   oObj.close( True )
End Sub


Sub DescribeToWriterDoc( oObj )
   cMethods = GetMethods( oObj )
   cProperties = GetProperties( oObj )
   
   ' Create a Writer document to hold the output.
   oDoc = StarDesktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, Array() )
   ' Print output into the writer doc.
   Writer_PrintLn( oDoc, cMethods )
   Writer_PrintLn( oDoc, cProperties )
End Sub


In order to make the previosu example work, you need these two auxiliary functions.
Code:
' This is a set of subroutines to make it easy to
'  generate lots of text output into a new Writer document.


' Sugar Coated way to Print into a Writer document.
' The oOutput parameter can be any of....
'   com.sun.star.text.TextDocument
'   com.sun.star.drawing.Text
'   com.sun.star.text.Text
'   com.sun.star.text.TextCursor
Sub Writer_Print( oOutput, cString )
   If oOutput.SupportsService( "com.sun.star.text.TextDocument" ) Then
      oText = oOutput.getText()
      oCursor = oText.createTextCursor()
   ElseIf oOutput.SupportsService( "com.sun.star.drawing.Text" ) Then
      oText = oOutput
      oCursor = oText.createTextCursor()
   ElseIf oOutput.SupportsService( "com.sun.star.text.Text" ) Then
      oText = oOutput
      oCursor = oText.createTextCursor()
   ElseIf oOutput.SupportsService( "com.sun.star.text.TextCursor" ) Then
      oCursor = oOutput
      oText = oCursor.getText()
   Else
      Exit Sub
   EndIf
   
   oCursor.gotoEnd( False )
   
   nLen = Len( cString )
   nStart = 1
   Do
      nPos = Instr( nStart, cString, Chr(13) )
      bCRFound = (nPos > 0)
      If Not bCRFound Then
         nPos = nLen + 1
      EndIf
      cSegment = Mid( cString, nStart, nPos-nStart )
      nStart = nPos + 1
      
      oText.insertString( oCursor, cSegment, False )
      
      If bCRFound Then
         oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
      EndIf
   Loop While bCRFound
End Sub

' Same as Writer_Print(), just adds a line ending.
Sub Writer_PrintLn( oOutput, Optional cString )
   If IsMissing( cString ) Then
      cString = ""
   EndIf
   Writer_Print( oOutput, cString + Chr(13) )
End Sub




In the past I posted some of the above code here...
http://www.oooforum.org/forum/viewtopic.php?t=3758
http://www.oooforum.org/forum/viewtopic.php?t=4802



Just for completeness, here is a description of how to walk through a list of all currently open windows, determine if a window is a document, what kind of document, and then perhaps even take action based on the contents of the document.
http://www.oooforum.org/forum/viewtopic.php?p=14057#14057
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Sat Dec 04, 2004 6:05 am    Post subject: Reply with quote

How many C++ code lines to obtain such introspection windows ?
http://perso.wanadoo.fr/moutou/Navigator.png
Answer in half an hour.
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Sat Dec 04, 2004 6:07 am    Post subject: Reply with quote

Here is the direct image corresponding to the previous post :

_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Sat Dec 04, 2004 7:01 am    Post subject: Reply with quote

This post takes code slightly modified from :
Calling XRay from C++
http://www.oooforum.org/forum/viewtopic.php?t=13751
I think it's a beter place here.

In fact I simply use the navigator to print out my introspection informations. This is not a great idea because an introspection opens a draw document but the result obtained is nicer than what is obtained with printf.
The code creates four pages in a draw document, it names them "Methods", "Interfaces", "Services" and "Properties". In each page it draws rectangle shapes (Positon=0, size=0) with constructed name corresponding to the information. When I open the navigator in this document, I obtain the result shown in previous post.
For the moment, I don't know how to manipulate the document navigator directly.
I have not resolved the problem of finding properties values : the Java code given with SDK :
<OpenOffice.org1.1_SDK>/examples/java/Inspector/InstanceInspector.java
resolves this problem. But I encouter sometimes difficulties to translate Java code....

The code use some procedures :
Code:

// Serge Moutou
// Don't forget to add : #include <com/sun/star/reflection/ParamMode.hpp>
// Don't forget to add "com.sun.star.reflection.ParamMode \" in the makefile
OUString getParamMode(ParamMode paramMode) {
// comes from <OpenOffice1.1_SDK>/examples/java/Inspector
  OUString toReturn;
  toReturn = OUString::createFromAscii("");
  if (paramMode == ParamMode_IN) toReturn = OUString::createFromAscii("IN"); else
    if (paramMode == ParamMode_OUT) toReturn = OUString::createFromAscii("OUT"); else
      if (paramMode == ParamMode_INOUT) toReturn = OUString::createFromAscii("INOUT");
  return toReturn;
}

// Christian Junker code
void MakePosition(sal_Int32 x, sal_Int32 y, ::com::sun::star::awt::Point *Pos)
{
   Pos->X = x;
   Pos->Y = y;
}

void MakeSize(sal_Int32 width, sal_Int32 height, ::com::sun::star::awt::Size *Size)
{
   Size->Width = width;
   Size->Height = height;
}

void DrawMe(Reference< XShape > &Shape, Reference< XDrawPage > &page, const OUString shapename)
{
   Reference< XShapes > Shapes(page, UNO_QUERY);
   Shapes->add(Shape);
   Reference< XPropertySet > shapeprops(Shape, UNO_QUERY);
   shapeprops->setPropertyValue(OUString::createFromAscii("Name"),
               makeAny(shapename));
}


The reflection's information and the draw document are managed in this listing :
Code:

void smallXRay(Any any,Reference< XMultiServiceFactory > rOServiceManager,Reference< XDesktop > theDesktop) {
   // create a drawing document : goal : use the navigator to see the results

   //query for the XComponentLoader interface
   Reference< XComponentLoader > rComponentLoader (theDesktop, UNO_QUERY);

   Reference< XComponent > xcomponent = rComponentLoader->loadComponentFromURL(
      OUString::createFromAscii("private:factory/sdraw"),
           OUString::createFromAscii("_blank"),
           0,
           Sequence < ::com::sun::star::beans::PropertyValue >());

// Don't forget to add : using namespace com::sun::star::drawing;
// Don't forget to add : #include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
// Don't forget to add "com.sun.star.drawing.XDrawPagesSupplier \" in the makefile
   Reference< XDrawPagesSupplier > rDrawDoc(xcomponent, UNO_QUERY);

// query the XDrawPages Interface
   Reference< XDrawPages > rDrawPages = rDrawDoc->getDrawPages();

// Don't forget to add : using namespace com::sun::star::container;
// Don't forget to add : #include <com/sun/star/container/XIndexAccess.hpp>
// Don't forget to add "com.sun.star.container.XIndexAccess \" in the makefile
// query the XIndexAccess Interface
   Reference< XIndexAccess > rPageIndexAccess(rDrawPages, UNO_QUERY);

   Any DrawPage = rPageIndexAccess->getByIndex(0);

// Don't forget to add : #include <com/sun/star/drawing/XDrawPage.hpp>
// Don't forget to add "com.sun.star.drawing.XDrawPage \" in the makefile
// Query the XDrawPage Interface
   Reference< XDrawPage > rDrawPage(DrawPage, UNO_QUERY);

// Don't forget to add : #include <com/sun/star/container/XNamed.hpp>
// Don't forget to add "com.sun.star.container.XNamed \" in the makefile
// query for the XNamed Interface
   Reference< XNamed > rNamed(rDrawPage, UNO_QUERY);
   rNamed->setName(OUString::createFromAscii("Methods"));

   Reference< XMultiServiceFactory > DocFactory(xcomponent, UNO_QUERY);

// ******** we have now our first Page in a Draw document

// translated in C++ from <OpenOffice1.1_SDK>/examples/java/Inspector

// Don't forget to add : using namespace com::sun::star::beans;
// Don't forget to add : #include <com/sun/star/beans/XIntrospection.hpp>
// Don't forget to add "com.sun.star.beans.XIntrospection \" in the makefile
   Reference< XIntrospection >xIntrospection = Reference< XIntrospection >
               ( rOServiceManager->createInstance(
                                      OUString( RTL_CONSTASCII_USTRINGPARAM(
                                          "com.sun.star.beans.Introspection" ))), UNO_QUERY );

// ********* get all methods for the given object *********************

   Reference< XIntrospectionAccess > xIntrospec = xIntrospection->inspect(any);

// Don't forget to add : #include <com/sun/star/beans/MethodConcept.hpp>
// Don't forget to add "com.sun.star.beans.MethodConcept \" in the makefile
   Sequence< Reference < XIdlMethod > > mMethods = xIntrospec -> getMethods(MethodConcept::ALL);
   printf("******** methods : (%d)\n",mMethods.getLength());
   for (int i=0;i<mMethods.getLength();i++){
      OUString params;
      params=OUString::createFromAscii("(");
      Sequence< ParamInfo > ParamInfos = mMethods[i]->getParameterInfos();
      if (ParamInfos.getLength() > 0) {
         for (int j=0;j<ParamInfos.getLength();j++){
            Reference< XIdlClass > xIdlClass = ParamInfos[j].aType;
            if (j == 0)
            // first parameter has no leading comma
            params += OUString::createFromAscii("[") + getParamMode(ParamInfos[j].aMode)+
            OUString::createFromAscii("]") +
            xIdlClass->getName();
            else
            params += OUString::createFromAscii(",[") + getParamMode(ParamInfos[j].aMode)+
            OUString::createFromAscii("]")+
            xIdlClass->getName();
         }
      }
      params += OUString::createFromAscii(")");
      OUString OUStr= mMethods[i]->getName()+params;

      Point *Pos = new (Point);
      Size *TheSize = new ( Size );

      Reference< XInterface > RectangleShape = DocFactory->createInstance(
                  OUString::createFromAscii("com.sun.star.drawing.RectangleShape") );
      Reference< XShape > rRectShape(RectangleShape, UNO_QUERY);
      MakePosition(0, 0, Pos);
      MakeSize(0, 0, TheSize);
      rRectShape->setPosition(*Pos);
      rRectShape->setSize(*TheSize);
      DrawMe(rRectShape, rDrawPage, OUStr);

   }

// Insert a new Page with name "Interfaces"
   // query for the XDrawPage Inteface
   rDrawPage = rDrawPages->insertNewByIndex(1);
// query for the XNamed Interface
   Reference< XNamed > rNamed2(rDrawPage, UNO_QUERY);
   rNamed2->setName(OUString::createFromAscii("Interfaces"));


// ********** get all Interfaces for the given object *********************

// Don't forget to add : #include <com/sun/star/lang/XTypeProvider.hpp>
// Don't forget to add "com.sun.star.lang.XTypeProvider \" in the makefile
   Reference< XTypeProvider > rTypeProvider(any,UNO_QUERY);
// Don't forget to add : #include <com/sun/star/uno/Type.hxx>
// But nothing in MakeFile : this hxx file is provided by SDK
   Sequence< Type > types = rTypeProvider->getTypes();
   printf("******** interfaces : (%d)\n",types.getLength());
   for (int i=0;i<types.getLength();i++){
      Point *Pos = new (Point);
      Size *TheSize = new ( Size );

      Reference< XInterface > RectangleShape = DocFactory->createInstance(
                  OUString::createFromAscii("com.sun.star.drawing.RectangleShape") );
      Reference< XShape > rRectShape(RectangleShape, UNO_QUERY);
      MakePosition(0, 0, Pos);
      MakeSize(0, 0, TheSize);
      rRectShape->setPosition(*Pos);
      rRectShape->setSize(*TheSize);
      DrawMe(rRectShape, rDrawPage, types[i].getTypeName());
   }

// Insert a new Page with name "Services"
   // query for the XDrawPage Inteface
   rDrawPage = rDrawPages->insertNewByIndex(2);
// query for the XNamed Interface
   Reference< XNamed > rNamed3(rDrawPage, UNO_QUERY);
   rNamed3->setName(OUString::createFromAscii("Services"));

// ********** get all services for the given object *********************

// Don't forget to add : #include <com/sun/star/lang/XServiceinfo.hpp>
// Don't forget to add "com.sun.star.lang.XServiceInfo \" in the makefile
   Reference< XServiceInfo > rServiceInfo(any,UNO_QUERY);

   Sequence< OUString > services = rServiceInfo->getSupportedServiceNames();
   printf("******** services : (%d)\n",services.getLength());
   for (int i=0;i<services.getLength();i++){
      Point *Pos = new (Point);
      Size *TheSize = new ( Size );

      Reference< XInterface > RectangleShape = DocFactory->createInstance(
                  OUString::createFromAscii("com.sun.star.drawing.RectangleShape") );
      Reference< XShape > rRectShape(RectangleShape, UNO_QUERY);
      MakePosition(0, 0, Pos);
      MakeSize(0, 0, TheSize);
      rRectShape->setPosition(*Pos);
      rRectShape->setSize(*TheSize);
      DrawMe(rRectShape, rDrawPage, services[i]);
   }

// Insert a new Page with name "Properties"
   // query for the XDrawPage Inteface
   rDrawPage = rDrawPages->insertNewByIndex(3);
// query for the XNamed Interface
   Reference< XNamed > rNamed4(rDrawPage, UNO_QUERY);
   rNamed4->setName(OUString::createFromAscii("Properties"));


// ********** get all properties for the given object *********************

// Don't forget to add : #include <com/sun/star/beans/PropertyConcept.hpp>
// Don't forget to add "com.sun.star.beans.PropertyConcept \" in the makefile
// Don't forget to add : #include <com/sun/star/beans/Property.hpp>
// Don't forget to add "com.sun.star.beans.Property \" in the makefile
// Don't forget to add : #include <com/sun/star/beans/XPropertySet.hpp>
// Don't forget to add "com.sun.star.beans.XPropertySet \" in the makefile

   Sequence< Property > Properties = xIntrospec -> getProperties(PropertyConcept::ALL);
   printf("******** properties : (%d)\n",Properties.getLength());
   for (int i=0;i<Properties.getLength();i++){
      OUString OUStr = Properties[i].Name + OUString::createFromAscii(" = (")+
         Properties[i].Type.getTypeName() + OUString::createFromAscii(")");
      Point *Pos = new (Point);
      Size *TheSize = new ( Size );

      Reference< XInterface > RectangleShape = DocFactory->createInstance(
                  OUString::createFromAscii("com.sun.star.drawing.RectangleShape") );
      Reference< XShape > rRectShape(RectangleShape, UNO_QUERY);
      MakePosition(0, 0, Pos);
      MakeSize(0, 0, TheSize);
      rRectShape->setPosition(*Pos);
      rRectShape->setSize(*TheSize);
      DrawMe(rRectShape, rDrawPage, OUStr);
   }
}


What we need now is an example to use all of that :
Code:

main( ) {
//retrieve an instance of the remote service manager
    Reference< XMultiServiceFactory > rOfficeServiceManager;
    rOfficeServiceManager = ooConnect();
    if( rOfficeServiceManager.is() ){
        printf( "Connected sucessfully to the office\n" );
    }

//get the desktop service using createInstance returns an XInterface type
    Reference< XInterface  > Desktop = rOfficeServiceManager->createInstance(
    OUString::createFromAscii( "com.sun.star.frame.Desktop" ));

//query for the XComponentLoader interface
    Reference< XComponentLoader > rComponentLoader (Desktop, UNO_QUERY);
    if( rComponentLoader.is() ){
           printf( "XComponentloader successfully instanciated\n" );

       }

   Reference< XDesktop > rDesktop(Desktop,UNO_QUERY);

   Any toInspect;
   //toInspect <<= rDesktop;
   toInspect <<= rOfficeServiceManager;
   smallXRay(toInspect,rOfficeServiceManager,rDesktop);
    return 0;
}


The priority of a future work in this direction is to obtain the properties values.
After I will search if it is possible to manage directly the navigator our use my own dialog Box ...
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide


Last edited by SergeM on Fri Dec 02, 2005 11:02 am; edited 1 time in total
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Mon Dec 20, 2004 10:10 am    Post subject: Reply with quote

As stated in previous post, I encounter difficulties to compute the properties' values. I finally find a solution.
My problem is to translate this Java Code (from <OpenOffice.org1.1_SDK>/examples/java/Inspector/InstanceInspector.java ) :
Code:

// Java
//  get the property set with help of the introspection access
XPropertySet xPropertySet = ( XPropertySet ) UnoRuntime.queryInterface(
  XPropertySet.class, xIntrospectionAccess.queryAdapter( new Type( XPropertySet.class ) ) );

and particularly the simple "new Type( XPropertySet.class ) "
I have tried many things until I discover again in the (Open) source code the solution :
Code:

// C++
// Done with two C++ code lines
Type typ =  getCppuType( (const Reference< XPropertySet > *)0);
Reference< XPropertySet > rPropertySet(xIntrospec->queryAdapter(typ),UNO_QUERY);

Have a look at the first line : here was my difficulties ! I have discover I have to use getCppuType but in such a maner ! perhaps in sevral years...

An other difficulty, later in Java code you can find :
Code:

// Java
if ( object != null ) {
//  creates a node for the property with his name, type, and value
  String stringTreeNodeName = myProperties[ n ].Name + " = (" +
   myProperties[ n ].Type.getTypeName() + ") " + object.toString();

Have a look to the beautiful "object.toString()"
So far as I know we haven't the corresponding C++ code : the Any type hasn't a toString method ! It's difficult for me to understand why the straightforward Java way hasn't a C++ counterpart !
Then I have written a function to do the job. I give it now even if I am sure we can do it in a simpler way (I have not discover at the moment) :
Code:

// C++
OUString getValueName(Any object){
   OUString OUStr;
   OUStr = OUString::createFromAscii("!! No computed value !!");
   if (object.hasValue()) {
        if (object.getValueTypeName() == OUString::createFromAscii("boolean")) {
         sal_Bool *MyBool;
         MyBool = (sal_Bool*) object.getValue();
         return OUStr.valueOf((sal_Bool) *MyBool);
        }else
      if (object.getValueTypeName() == OUString::createFromAscii("string")) {
         OUString *MyOUStr;
         MyOUStr = (OUString *) object.getValue();
         OUStr = OUString::createFromAscii("");
         return OUStr.concat(*MyOUStr);
      } else
      if (object.getValueTypeName() == OUString::createFromAscii("long")) {
         sal_Int32 *MyLong;
         MyLong = (sal_Int32*) object.getValue();
         return OUStr.valueOf((sal_Int32) *MyLong);
      } else
      if (object.getValueTypeName() == OUString::createFromAscii("short")) {
         sal_Int16 *MyShort;
         MyShort = (sal_Int16*) object.getValue();
         return OUStr.valueOf((sal_Int32) *MyShort);
      } else return OUStr;
   }
}

_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Tue Dec 21, 2004 7:50 am    Post subject: Reply with quote

I give a new code for getValueName
Code:

OUString getValueName(Any object){
   OUString OUStr;
   OUStr = OUString::createFromAscii("!! No computed value !!");
   if (object.hasValue()) {
      if (object.isExtractableTo(getCppuBooleanType())){
         sal_Bool MyBool;
         object >>= MyBool;
         return OUStr.valueOf((sal_Bool) MyBool);
      } else
      if (object.getValueTypeName() == OUString::createFromAscii("string")) {
         OUString *MyOUStr;
         MyOUStr = (OUString *) object.getValue();
         OUStr = OUString::createFromAscii("\"");
         return OUStr + *MyOUStr + OUString::createFromAscii("\"");
      } else
      if (object.getValueTypeName() == OUString::createFromAscii("long")) {
         sal_Int32 *MyLong;
         MyLong = (sal_Int32*) object.getValue();
         return OUStr.valueOf((sal_Int32) *MyLong);
      } else
      if (object.getValueTypeName() == OUString::createFromAscii("short")) {
         sal_Int16 *MyShort;
         MyShort = (sal_Int16*) object.getValue();
         return OUStr.valueOf((sal_Int32) *MyShort);
      } else
      if (object.getValueTypeName() == OUString::createFromAscii("[]byte")) {
         Sequence< sal_Int8 > SeqByte;
         object >>= SeqByte;
         OUStr = OUString::createFromAscii("Length:");
         OUStr=OUStr.concat(OUStr.valueOf((sal_Int32) SeqByte.getLength()));
// comments because I cannot use such constructed name as shapes's name
      //   for (sal_Int32 i=0; i<SeqByte.getLength()-1; i++){
      //      OUStr=OUStr.concat(OUStr.valueOf((sal_Int32) SeqByte[i],16);
      //      OUStr=OUStr.concat(OUString::createFromAscii(" "));
      //   }
         return OUStr;
      } else
      if (object.getValueTypeName() == OUString::createFromAscii("[]string")) {
         Sequence< OUString > SeqOUStr;
         object >>= SeqOUStr;
         OUStr = OUString::createFromAscii("Length:");
         OUStr=OUStr.concat(OUStr.valueOf((sal_Int32) SeqOUStr.getLength()));
         return OUStr;
      } else return OUStr;
   } else return OUStr;
}

I have completly rewrite the boolean case with reading the Any.hxx and Type.hxx file.
I have also rewrite the property part with the help of Bernard Marcelly XRayDelphi code (but he goes further than me)
Code:

// C++
// ********** get all properties for the given object *********************

   Sequence< Property > Properties = xIntrospec -> getProperties(PropertyConcept::ALL);

   for (int i=0;i<Properties.getLength();i++){

      Type typ =  getCppuType( (const Reference< XPropertySet > *)0);
      Reference< XPropertySet > rPropertySet(xIntrospec->queryAdapter(typ),UNO_QUERY);
      if (! rPropertySet.is()) printf("pb avec XPropertySet !!!!!\n");
      Reference< XPropertySetInfo > rPropertySetInfo=rPropertySet->getPropertySetInfo();
      Any object;
      if (rPropertySetInfo->hasPropertyByName(Properties[i].Name)){
         object <<= rPropertySet->getPropertyValue(Properties[i].Name);
         OUString OUStr = Properties[i].Name + OUString::createFromAscii(" = (")+
            Properties[i].Type.getTypeName() + OUString::createFromAscii(") ")
            + getValueName(object);
         Point *Pos = new (Point);
         Size *TheSize = new ( Size );

         Reference< XInterface > RectangleShape = DocFactory->createInstance(
                        OUString::createFromAscii("com.sun.star.drawing.RectangleShape") );
         Reference< XShape > rRectShape(RectangleShape, UNO_QUERY);
         MakePosition(0, 0, Pos);
         MakeSize(0, 0, TheSize);
         rRectShape->setPosition(*Pos);
         rRectShape->setSize(*TheSize);
         DrawMe(rRectShape, rDrawPage, OUStr);
      }
   }

We can see now some properties values.
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Wed Dec 22, 2004 6:50 am    Post subject: Reply with quote

I have post a Reflection Helper here : http://www.oooforum.org/forum/viewtopic.php?t=15366
where I have improved the information on the mehtods.
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Sat Jun 11, 2005 8:39 am    Post subject: Reply with quote

An other example is added in my document : how to print out the results of a reflection in a Dialog like this :

It's an other Reflection helper.
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Wed Jul 27, 2005 7:39 am    Post subject: Reply with quote

An other simpler way to use an inspector with C++ is to use the Java demo Inspector component. See
Using Inspector from OOoBasic/C++ http://www.oooforum.org/forum/viewtopic.phtml?t=22254
Here is the result :

_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Wed Jul 26, 2006 10:43 am    Post subject: Reply with quote

To go further http://wiki.services.openoffice.org/wiki/IDL_Files_and_Cpp#Core_reflection_service__and_its_Interfaces
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets All times are GMT - 8 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group