Date: prev next · Thread: first prev next last
2011 Archives by date, by thread · List index


Hi all

Thanks to Thorsten pointing the old (2004) pyUno

I revived it recently and made it workable again, removing some
unnecessary things but it is in
my plans to make it cleaner as a lot of things is outdated (eg. old OOo
links to idl reference - need to be updated). I hope to find time in a
near future

btw, here is the version i'm actally using

the basic use to instrospect an object at runtime is rather simple

inside a pyUNo script :

from pyXray import XrayBox
XrayBox(self.ctx, theUnoObject)

self.ctx, is the context

Feel free to include it in LibreOffice sources if you find it usefull,
provided the licence is ok (otherwise, i may ask my old employer,
but there should be no problem, just let me know)

I really hope that it will be usefull for someone (as an introspection
tool or sample of pyUno script). Let me know and feel free to ask if any
question

HTH

Laurent


# (C) Copyright 2004 Indesko SARL <http://indesko.com>
# Author: Laurent Godard <lgodard@indesko.com> (old email)
#         Laurent Godard <lgodard.libre@laposte.net>
# based on Xray Basic macro from Bernard Marcelly
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
#

import uno, unohelper

# UNO GUI toolkit
from com.sun.star.awt.WindowClass import TOP, SIMPLE
from com.sun.star.awt.PushButtonType import STANDARD as standard
from com.sun.star.awt.PushButtonType import OK as ok
from com.sun.star.awt.PushButtonType import CANCEL as cancel
from com.sun.star.awt.PushButtonType import HELP as help
from com.sun.star.awt.TextAlign import CENTER as center
from com.sun.star.awt.TextAlign import LEFT as left
from com.sun.star.awt.TextAlign import RIGHT as right

# used UNO listeners
from com.sun.star.awt import XActionListener
from com.sun.star.awt import XItemListener
from com.sun.star.awt import XMouseListener

# UNO typeClass handling for instrospection
from com.sun.star.uno.TypeClass import VOID as unoVoid
from com.sun.star.uno.TypeClass import CHAR as unoChar
from com.sun.star.uno.TypeClass import BOOLEAN as unoBoolean
from com.sun.star.uno.TypeClass import BYTE as unoByte
from com.sun.star.uno.TypeClass import SHORT as unoShort
from com.sun.star.uno.TypeClass import UNSIGNED_SHORT as unoUnsignedShort
from com.sun.star.uno.TypeClass import LONG as unoLong
from com.sun.star.uno.TypeClass import UNSIGNED_LONG as unoUnsignedLong
from com.sun.star.uno.TypeClass import HYPER as unoHyper
from com.sun.star.uno.TypeClass import UNSIGNED_HYPER as unoUnsignedHyper
from com.sun.star.uno.TypeClass import FLOAT as unoFloat
from com.sun.star.uno.TypeClass import DOUBLE as unoDouble
from com.sun.star.uno.TypeClass import STRING as unoString
from com.sun.star.uno.TypeClass import TYPE as unoType
from com.sun.star.uno.TypeClass import ANY as unoAny
from com.sun.star.uno.TypeClass import ENUM as unoEnum
from com.sun.star.uno.TypeClass import TYPEDEF as unoTypeDef
from com.sun.star.uno.TypeClass import STRUCT as unoStruct
from com.sun.star.uno.TypeClass import UNION as unoUnion
from com.sun.star.uno.TypeClass import EXCEPTION as unoException
from com.sun.star.uno.TypeClass import SEQUENCE as unoSequence
from com.sun.star.uno.TypeClass import ARRAY as unoArray
from com.sun.star.uno.TypeClass import INTERFACE as unoInterface
from com.sun.star.uno.TypeClass import SERVICE as unoService
from com.sun.star.uno.TypeClass import MODULE as unoModule
from com.sun.star.uno.TypeClass import INTERFACE_METHOD as unoInterfaceMethod
from com.sun.star.uno.TypeClass import INTERFACE_ATTRIBUTE as unoInterfaceAttribute
from com.sun.star.uno.TypeClass import UNKNOWN as unoUnknown
from com.sun.star.uno.TypeClass import PROPERTY as unoProperty
from com.sun.star.uno.TypeClass import CONSTANT as unoConstant
from com.sun.star.uno.TypeClass import CONSTANTS as unoConstants
from com.sun.star.uno.TypeClass import SINGLETON as unoSingleton

# file utilities
from os import sep
from os import mkdir

# path logo
from os import path
from sys import modules
logo_path = path.dirname (path.abspath (modules["pyXray"].__file__))
#logo_path = logo_path + sep + 'logo.jpg'
logo_path=""

#Browser for SDK Querying
from os import environ as OS_ENVIRON
#if sep == '/':
    # problem on invoking konqueror
    # http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/2184915
#    if OS_ENVIRON['BROWSER']=='kfmclient openProfile webbrowsing':
#        OS_ENVIRON['BROWSER']='konqueror'
import webbrowser
my_browser = webbrowser.get()

#####################################################
#                                                   #
#               pyXray                              #
#                                                   #
# XrayBox (context, object)                         #
#                                                   #
#####################################################

# USER PARAMETERS to UPDATE

# Gui language
# supported : fr, en
GUI_LANGUAGE = 'fr'

# path to SDK IDL reference
if sep == '/':
    # Linux
    #SDK_ADDRESS = '/home/laurent/OpenOffice.org1.1.0/OpenOffice.org1.1_SDK/docs/common/ref/'
    #TODO : enable web IDL browsing
    SDK_ADDRESS = 'http://api.openoffice.org/docs/common/ref/'
else:
    #windows
    SDK_ADDRESS = 'C:\\Program 
Files\\Applications\\OOO\\OpenOffice.org1.1_Beta_2_SDK\\docs\\common\\ref\\'

#####################################################

class XrayBox(unohelper.Base):
    """Inspect UNO object, link to sdk and recusrsive calls"""

    def __init__(self, aContext, UNO_Object):
        """acontext : a Valid UNO context
        UNO_Object : the object to inspect
        """
        self.VERSION = '0.6 beta'
        self.ctx = aContext
        self.smgr = aContext.ServiceManager
        # UI Dialog object
        self.dialog=None
        # List of openned Listeners
        self.lst_listeners={}
        # What is currently handled :
        # 'property', 'method', 'interface', 'service' or 'listener'
        self.cur_display=''
        # History management
        self.nb_histo_obj = -1
        self.lst_histo_obj = {}
        self.lst_histo_name={}

        # Create GUI
        self._setTranslation(GUI_LANGUAGE)
        self.dialog=self._createBox()
        self._addListeners()

        self._initializeObject(UNO_Object)

        #execute the dialog --> blocking call
        self.dialog.execute()

        #end --> release listeners and dispose dialog
        self._removeListeners()
        self.dialog.dispose()

    #####################################################
    #                 GUI definition                    #
    #####################################################
    def _createBox(self):
        """Create Xray User Interface"""
    #create the dialog model and set the properties
        dialog_model = self.smgr.createInstanceWithContext(
                                    'com.sun.star.awt.UnoControlDialogModel',
                                    self.ctx)
        dialog_model.PositionX = 50
        dialog_model.Step = 1
        dialog_model.TabIndex = 7
        dialog_model.Width = 270
        dialog_model.Height = 261
        dialog_model.PositionY = 63
        dialog = self.smgr.createInstanceWithContext(
                                'com.sun.star.awt.UnoControlDialog',
                                self.ctx)

    # Frame Afficher : FrameControl1
        frame = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlGroupBoxModel')
        frame.PositionX = 3
        frame.TabIndex = 0
        frame.Height = 64
        frame.Width = 104
        frame.PositionY = 2
        dialog_model.insertByName('FrameControl1', frame)
        frame.Label = self.gui_rsc['FrameControl1']
        frame = None

    # Radio Button group : None
        radiogroup = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlGroupBoxModel')
        dialog_model.insertByName('None', radiogroup)

    # Radio Button Interfaces : BtnSuppInterf
        radio = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlRadioButtonModel')
        radio.PositionX = 7
        radio.TabIndex = 1
        radio.Height = 10
        radio.Width = 89
        radio.PositionY = 43
        radio.State = False
        radio.Label = self.gui_rsc['BtnSuppInterf']
        dialog_model.insertByName('BtnSuppInterf', radio )

    # Radio Button Modeles : BtnMethods
        radio = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlRadioButtonModel')
        radio.PositionX = 7
        radio.TabIndex = 2
        radio.Height = 10
        radio.Width = 46
        radio.PositionY = 23
        radio.Label = self.gui_rsc['BtnMethods']
        radio.State = False
        dialog_model.insertByName('BtnMethods', radio )

    # Radio Button Proprietes : BtnProperties
        radio = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlRadioButtonModel')
        radio.PositionX = 7
        radio.TabIndex = 3
        radio.Height = 10
        radio.Width = 45
        radio.PositionY = 13
        radio.State = True
        radio.Label = self.gui_rsc['BtnProperties']
        dialog_model.insertByName('BtnProperties', radio )

    # Radio Button Services : BtnServices
        radio = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlRadioButtonModel')
        radio.PositionX = 7
        radio.TabIndex = 4
        radio.Height = 10
        radio.Width = 89
        radio.PositionY = 33
        radio.Label = self.gui_rsc['BtnServices']
        radio.State = False
        dialog_model.insertByName('BtnServices', radio )

    # Radio Button Listeners : BtnListeners
        radio = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlRadioButtonModel')
        radio.PositionX = 7
        radio.TabIndex = 4
        radio.Height = 10
        radio.Width = 89
        radio.PositionY = 53
        radio.State = False
        radio.Label = self.gui_rsc['BtnListeners']
        dialog_model.insertByName('BtnListeners', radio )

    # List detailled : ListInspect
        a_list= dialog_model.createInstance(
                                  'com.sun.star.awt.UnoControlListBoxModel')
        a_list.PositionX = 1
        a_list.TabIndex = 7
        a_list.Width = 130
        a_list.Height = 173
        a_list.PositionY = 86
        a_list.HelpText = self.gui_rsc['ListInspect']
        a_list.Dropdown=  False
        dialog_model.insertByName('ListInspect', a_list )

    # Text information on line selected in ListInspect 'TxtObjInfosDetail'
        texte_right=a_list
        textfield = dialog_model.createInstance(
                                    'com.sun.star.awt.UnoControlEditModel')
        textfield.PositionX = texte_right.Width + 2
        textfield.TabIndex = 8
        textfield.Width = dialog_model.Width - textfield .PositionX - 1
        textfield.PositionY = texte_right.PositionY + 12
        textfield.Height = texte_right.Height - (textfield.PositionY
                                                    - texte_right.PositionY)
        textfield.VScroll = True
        textfield.HScroll = False
        textfield.MultiLine = True
        textfield.ReadOnly = True
        dialog_model.insertByName('TxtObjInfosDetail', textfield )

    # label Label0
        label = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlFixedTextModel')
        label.PositionX =  textfield.PositionX
        label.TabIndex = 9
        label.Width = textfield.Width
        label.Height = textfield.PositionY - texte_right.PositionY
        label.PositionY = texte_right.PositionY
        label.Align = 1
        label.Label = self.gui_rsc['Label0']
        dialog_model.insertByName('Label0', label)

    # Button Exit : BtnExit
        button = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlButtonModel')
        button.PositionX = 210
        button.TabIndex = 8
        button.Height = 12
        button.Width = 53
        button.PositionY = 40
        button.PushButtonType =  cancel
        button.DefaultButton =  True
        button.Label = self.gui_rsc['BtnExit']
        dialog_model.insertByName('BtnExit', button )

    # label Label1
        label = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlFixedTextModel')
        label.PositionX = 111
        label.TabIndex = 9
        label.Width = 155
        label.Height = 12
        label.PositionY = 57
        label.Align = 1
        label.Label = self.gui_rsc['Label1']
        dialog_model.insertByName('Label1', label)

    # label Author
        label = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlFixedTextModel')
        label.PositionX = 203
        label.TabIndex = 11
        label.Width = 67
        label.Height = 16
        label.PositionY = 19
        label.Align = 1
        label.MultiLine = True
        label.TextColor = 0x000000
        #label.BackgroundColor = -1 #Transparent
     #   label.Label = u"Laurent Godard\n lgodard@indesko.com"
        dialog_model.insertByName('LabelAuteur', label)

    # Logo
        image = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlImageControlModel')
        image.PositionX = 210
        image.Width = 53
        image.Height = 15
        image.PositionY = 3
        image.ScaleImage = True
        image.ImageURL = "" # unohelper.systemPathToFileUrl(logo_path)
        image.Enabled = True
        image.Border = 1 #3D
        dialog_model.insertByName('ImageLogo', image)

    # Button Xray : recusive call : DeeperBtn
        button = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlButtonModel')
        button.PositionX = 111
        button.Step = 1
        button.TabIndex = 12
        button.Height = 12
        button.Width = 90
        button.PositionY = 40
        button.Label = self.gui_rsc['DeeperBtn']
        dialog_model.insertByName('DeeperBtn', button )

    # Button SDK : SDKBtn2 - proprietes et methodes
        button = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlButtonModel')
        button.PositionX = 111
        button.TabIndex = 13
        button.Height = 12
        button.Width = 90
        button.PositionY = 24
        button.Label = self.gui_rsc['SDKBtn2']
        dialog_model.insertByName('SDKBtn2', button )

    # List Historical examinated objects : ListObj
        a_list= dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlListBoxModel')
        a_list.PositionX = 38
        a_list.TabIndex = 14
        a_list.Width = 230
        a_list.Height = 10
        a_list.PositionY = 73
        a_list.HelpText = self.gui_rsc['ListObj']
        a_list.Dropdown =  True
        a_list.LineCount = 15
        a_list.Tag = ''
        dialog_model.insertByName('ListObj', a_list )


    # label Label2
        label = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlFixedTextModel')
        label.PositionX = 3
        label.TabIndex = 16
        label.Height = 10
        label.Width = 35
        label.PositionY = 73
        label.Label = self.gui_rsc['Label2']
        dialog_model.insertByName('Label2', label)


    # text Object Name : OriginName
        textfield = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlEditModel')
        textfield.PositionX = 111
        textfield.TabIndex = 15
        textfield.BackgroundColor = 0xccffff
        textfield.Width = 90
        textfield.Height = 10
        textfield.PositionY = 6
        textfield.Align =  center
        textfield.ReadOnly =  True
        textfield.Tabstop =  False
        dialog_model.insertByName('OriginName', textfield )

    # End of objects definition

        if not dialog.getModel():
            dialog.setModel(dialog_model)

    #UNO toolkit definition
        toolkit = self.smgr.createInstanceWithContext(
                                'com.sun.star.awt.Toolkit',
                                self.ctx)
        a_rect = uno.createUnoStruct( 'com.sun.star.awt.Rectangle' )
        a_rect.X = 50
        dialog.setTitle ( "pyXray - " + self.VERSION )
        a_rect.Width = 270
        a_rect.Height = 261
        a_rect.Y = 63
        win_descriptor = uno.createUnoStruct('com.sun.star.awt.WindowDescriptor')
        win_descriptor.Type = TOP
        win_descriptor.ParentIndex = -1
        win_descriptor.Bounds = a_rect
        peer = toolkit.createWindow( win_descriptor )
        dialog.createPeer( toolkit, peer )

        return dialog

#    ##########################

    def _addListeners(self):
        """Add listeners to dialog"""
        a_control = self.dialog.getControl('DeeperBtn')
        the_listener = ButtonXrayListener(self)
        a_control.addActionListener(the_listener)
        self.lst_listeners['DeeperBtn'] = the_listener

        a_control = self.dialog.getControl('BtnMethods')
        the_listener = OptMethodListener(self)
        a_control.addActionListener(the_listener)
        self.lst_listeners['BtnMethods']=the_listener

        a_control = self.dialog.getControl('BtnProperties')
        the_listener = OptPropertyListener(self)
        a_control.addActionListener(the_listener)
        self.lst_listeners['BtnProperties']=the_listener

        a_control = self.dialog.getControl('BtnSuppInterf')
        the_listener = OptInterfaceListener(self)
        a_control.addActionListener(the_listener)
        self.lst_listeners['BtnSuppInterf']=the_listener

        a_control = self.dialog.getControl('BtnServices')
        the_listener = OptServiceListener(self)
        a_control.addActionListener(the_listener)
        self.lst_listeners['BtnServices']=the_listener

        a_control = self.dialog.getControl('BtnListeners')
        the_listener = OptListenListener(self)
        a_control.addActionListener(the_listener)
        self.lst_listeners['BtnListeners']=the_listener

        a_control=self.dialog.getControl('ListInspect')
        the_listener = ListInspectListener(self)
        a_control.addItemListener(the_listener)
        self.lst_listeners['ListInspect']=the_listener

        a_control=self.dialog.getControl('ListObj')
        the_listener = ListHistoListener(self)
        a_control.addItemListener(the_listener)
        self.lst_listeners['ListObj']=the_listener

        a_control = self.dialog.getControl('SDKBtn2')
        the_listener = ButtonSDKListener(self)
        a_control.addActionListener(the_listener)
        self.lst_listeners['SDKBtn2']=the_listener

        a_control = self.dialog.getControl('LabelAuteur')
        the_listener = MouseAuthorListener(self)
        a_control.addMouseListener(the_listener)
        self.lst_listeners['LabelAuteur']=the_listener

        a_control = self.dialog.getControl('ImageLogo')
        the_listener = MouseAuthorListener(self)
        a_control.addMouseListener(the_listener)
        self.lst_listeners['ImageLogo']=the_listener

        return

#    ###########################

    def _removeListeners(self):
        """ remove listeners on exiting"""
        a_control = self.dialog.getControl('DeeperBtn')
        a_control.removeActionListener(self.lst_listeners['DeeperBtn'])
        a_control = self.dialog.getControl('BtnMethods')
        a_control.removeActionListener(self.lst_listeners['BtnMethods'])
        a_control = self.dialog.getControl('BtnProperties')
        a_control.removeActionListener(self.lst_listeners['BtnProperties'])
        a_control = self.dialog.getControl('BtnSuppInterf')
        a_control.removeActionListener(self.lst_listeners['BtnSuppInterf'])
        a_control = self.dialog.getControl('BtnServices')
        a_control.removeActionListener(self.lst_listeners['BtnServices'])
        a_control = self.dialog.getControl('BtnListeners')
        a_control.removeActionListener(self.lst_listeners['BtnListeners'])
        a_control = self.dialog.getControl('ListInspect')
        a_control.removeItemListener(self.lst_listeners['ListInspect'])
        a_control = self.dialog.getControl('ListObj')
        a_control.removeItemListener(self.lst_listeners['ListObj'])
        a_control = self.dialog.getControl('SDKBtn2')
        a_control.removeActionListener(self.lst_listeners['SDKBtn2'])
        a_control = self.dialog.getControl('LabelAuteur')
        a_control.removeMouseListener(self.lst_listeners['LabelAuteur'])
        a_control = self.dialog.getControl('ImageLogo')
        a_control.removeMouseListener(self.lst_listeners['ImageLogo'])

        return

    #####################################################
    #            Translation                            #
    #####################################################

    def _setTranslation(self, language):
        self.gui_rsc = {}
        if language == 'fr':
            self._setLanguage_fr()
        else:
            self._setLanguage_en()

        return

    def _setLanguage_fr(self):
        """French translation strings"""

        self.gui_rsc['FrameControl1'] = u" Afficher "
        self.gui_rsc['BtnSuppInterf'] = u"Interfaces supportees"
        self.gui_rsc['BtnMethods'] = u"Methodes"
        self.gui_rsc['BtnProperties'] = u"Proprietes"
        self.gui_rsc['BtnServices'] = u"Services"
        self.gui_rsc['BtnListeners'] = u"Listeners supportes"
        self.gui_rsc['ListInspect'] = "Selectionner une ligne pour avoir le detail"
        self.gui_rsc['Label0'] = u"Detail de la selection"
        self.gui_rsc['BtnExit'] = u"Fermer"
        self.gui_rsc['Label1'] = u"Vous pouvez selectionner et copier le detail affiche"
        self.gui_rsc['DeeperBtn'] = u"Xray sur la selection"
        self.gui_rsc['SDKBtn2'] = u"Documentation du SDK"
        self.gui_rsc['ListObj'] = "Afficher un objet deja analyse"
        self.gui_rsc['Label2'] = u"Objet affiche"
        self.gui_rsc['origin'] = "Origine"
        self.gui_rsc['no_name'] = "( Pas de Nom )"
        self.gui_rsc['value'] = "Valeur :"
        self.gui_rsc['return'] = "Retourne : "
        self.gui_rsc['arg'] = "Arguments :"
        self.gui_rsc['no_result'] = "Aucun Resultat"
        self.gui_rsc['need_XRay'] = "Xray Necessaire"

        return

    def _setLanguage_en(self):
        """English translation strings"""
        self.gui_rsc['FrameControl1'] = u" Display "
        self.gui_rsc['BtnSuppInterf'] = u"Supported Interfaces"
        self.gui_rsc['BtnMethods'] = u"Methods"
        self.gui_rsc['BtnProperties'] = u"Properties"
        self.gui_rsc['BtnServices'] = u"Services"
        self.gui_rsc['BtnListeners'] = u"Supported Listeners"
        self.gui_rsc['ListInspect'] = "Select a line to see detail"
        self.gui_rsc['Label0'] = u"Selection detail"
        self.gui_rsc['BtnExit'] = u"Close"
        self.gui_rsc['Label1'] = u"You can select and copy the displayed detail"
        self.gui_rsc['DeeperBtn'] = u"Recursive Xray"
        self.gui_rsc['SDKBtn2'] = u"SDK documentation"
        self.gui_rsc['ListObj'] = "Display an already analyzed object"
        self.gui_rsc['Label2'] = u"Current object"
        self.gui_rsc['origin'] = "Origin"
        self.gui_rsc['no_name'] = "( No name )"
        self.gui_rsc['value'] = "Value :"
        self.gui_rsc['return'] = "Return : "
        self.gui_rsc['arg'] = "Arguments :"
        self.gui_rsc['no_result'] = "No result"
        self.gui_rsc['need_XRay'] = "Recursive Xray needed"

        return

    #####################################################
    #            Work functions                         #
    #####################################################

    def _initializeObject(self, obj, obj_name = '', obj_rank = -1 ):
        self.cur_obj = obj
        # Update historical list
        obj_rank_int = int(obj_rank)
        self.nb_histo_obj = self.nb_histo_obj + 1
        self.lst_histo_obj[self.nb_histo_obj] = obj
        if obj_rank_int == -1:
            # add an object
            if self.nb_histo_obj == 0:
                self.lst_histo_name[0]=self.gui_rsc['origin']
            else:
                self.lst_histo_name[self.nb_histo_obj] = \
                        self.lst_histo_name[self.nb_histo_obj - 1 ] \
                        + '.' + obj_name
        else:
            self.lst_histo_name[self.nb_histo_obj] = \
                        self.lst_histo_name[obj_rank_int] \
                        + '.' + obj_name

        ctrl_lst_histo=self.dialog.getControl('ListObj')

        if ctrl_lst_histo.getItemCount() > 0:
            ctrl_lst_histo.removeItems(0,ctrl_lst_histo.getItemCount())

        for i in range(len(self.lst_histo_name)):
            ctrl_lst_histo.addItem( self.lst_histo_name[i].encode('utf-8'), i )

        ctrl_lst_histo.selectItemPos(self.nb_histo_obj, True)

        # update object name
        ctrl_lbl_name = self.dialog.getControl('OriginName')
        try:
            the_value = obj.ImplementationName
        except:
            the_value = self.gui_rsc['no_name']
        ctrl_lbl_name.setText(the_value)

        # switch to properties list
        ctrl_radio = self.dialog.getControl('BtnProperties')
        ctrl_radio.State = True

        return

#    ###########################

    def _displayObjects(self, lst):
        """ Display the list built in listeners"""
        ctrl_lst_inspect = self.dialog.getControl('ListInspect')
        ctrl_lst_inspect.removeItems(0,ctrl_lst_inspect.getItemCount())
        if len(lst) > 0:
            lst.sort()
            for i in range(len(lst)):
                ctrl_lst_inspect.addItem( lst[i].encode('utf-8'), i )

        return

#    ###########################

    def _displayInfos(self, analyze):
        """ Display informations in the right text box """

        ctrl_lst_inspect = self.dialog.getControl('ListInspect')
        ctrl_txt_detail = self.dialog.getControl('TxtObjInfosDetail')
        ctrl_txt_detail.setText('')
        obj = self.cur_obj
        ctx = self.ctx

        # The introsection object
        introspection = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.beans.Introspection',
                                            ctx )
        inspect = introspection.inspect( obj )

        # the examinated topic is a property
        if self.cur_display == 'property':
            my_prop = inspect.getProperty(analyze, unohelper.METHOD_CONCEPT_ALL)
            info =  '\t' + my_prop.Type.typeName + '\n\n'
            info += '\t'
            info += unohelper._propertymode_to_str(my_prop.Attributes)
            #Content
            the_value=''
            the_value=self._getOjbectValue(obj, my_prop)
            info = info + '\n\n' + self.gui_rsc['value']
            info = info + '\n' + str(the_value)

        # the examinated topic is a method
        if self.cur_display == 'method':
            my_method = inspect.getMethod(analyze, unohelper.METHOD_CONCEPT_ALL)
            arguments = my_method.ParameterTypes
            informations = my_method.ParameterInfos
            info = '\n' + self.gui_rsc['return'] + my_method.ReturnType.Name
            info = info + '\n\n' + self.gui_rsc['arg']
            #arguments
            for i in range(0, len(arguments)):
                info = info + '\n\n\t' \
                            + unohelper._mode_to_str( informations[i].aMode ) \
                            + '  ' + informations[i].aName
                info = info+ '\n\t' + arguments[i].Name
            # content
            uno_class = my_method.ReturnType.TypeClass
            if (uno_class != unoVoid) and (len(arguments) == 0):
                the_value = self._getOjbectValue(obj, my_method)
                info = info + '\n\n' + self.gui_rsc['value']
                info = info + '\n'+the_value

        # the examinated topic is a service --> no Info
        if self.cur_display == 'service':
            info = ''

        # the examinated topic is an interface --> no Info
        if self.cur_display == 'interface':
            info = ''

        # the examinated topic is a listener --> no Info
        if self.cur_display == 'listener':
            info = ''

        if info != '':
            detail = analyze + '\n'

        final_text = detail + info
        ctrl_txt_detail.setText(final_text)

        return

#    ###########################

    def _getOjbectValue( self, obj, element):

        # Introspection
        ctx = self.ctx
        introspection = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.beans.Introspection',
                                            ctx)
        inspect = introspection.inspect(obj)
        the_value = ()

        # Retreives Value and type
        if self.cur_display == 'property':
            prop_name=element.Name
            # Invocation object
            invocation = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.script.Invocation',
                                            ctx)
            invoc = invocation.createInstanceWithArguments((obj,))
            inspect = introspection.inspect( invoc )
            #retreive the value
            method = inspect.getMethod( 'getValue' , unohelper.METHOD_CONCEPT_ALL )
            the_value, dummy = method.invoke(invoc,(prop_name,))
            type_name = element.Type.typeName

        if self.cur_display == 'method':
            the_value, dummy = element.invoke(obj, () )
            #uno_class = element.ReturnType.TypeClass
            type_name = element.ReturnType.Name

        returned_value = self._getParsedValue(type_name, the_value)

        return returned_value

#    ###########################

    def _getXRayObject(self, obj, name):
        """ Performs the recusive call of name on obj"""
        ctx = self.ctx
        introspection = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.beans.Introspection',
                                            ctx)
        inspect = introspection.inspect(obj)

        if self.cur_display =='method':
            if inspect.hasMethod( name , unohelper.METHOD_CONCEPT_ALL):
                method = inspect.getMethod(name ,unohelper.METHOD_CONCEPT_ALL)
                the_value, dummy = method.invoke(obj, () )

        if self.cur_display =='property':
            invocation = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.script.Invocation',
                                            ctx)
            invoc = invocation.createInstanceWithArguments( (obj,) )
            inspect = introspection.inspect(invoc)
            method = inspect.getMethod('getValue', unohelper.METHOD_CONCEPT_ALL)
            the_value = ()
            the_value, dummy = method.invoke(invoc,(name,))

        return the_value

#    ###########################

    def _isValideXRay(self, name):
        """ Is a recursive XRay Valid ?"""
        is_valid = False
        ctx = self.ctx
        introspection = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.beans.Introspection',
                                            ctx)
        inspect = introspection.inspect( self.cur_obj )

        if self.cur_display == 'method':
        # must return an interface and have no parameter
            my_method = inspect.getMethod(name, unohelper.METHOD_CONCEPT_ALL)

            if my_method.ReturnType.TypeClass == unoInterface:
                is_valid = True

            if len(my_method.ParameterTypes) > 0:
                is_valid = False


        if self.cur_display == 'property':
        # must return an interface
            if self._getReturnedType(name) == unoInterface:
                is_valid = True

        return is_valid

#    ###########################

    def _getReturnedType(self, analize):
        """ Return the UNO type of the argument.
         It is a com.sun.star.uno.TypeClass"""

        obj=self.cur_obj
        ctx = self.ctx

        introspection = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.beans.Introspection',
                                            ctx)
        inspect = introspection.inspect(obj)

        if self.cur_display == 'method':
            the_method = inspect.getMethod(analize, unohelper.METHOD_CONCEPT_ALL)
            returned_type = the_method.ReturnType.TypeClass

        if self.cur_display == 'property':
            the_prop = inspect.getProperty(analize, unohelper.PROPERTY_CONCEPT_ALL)
            returned_type = the_prop.Type.typeClass

        return returned_type

#    ###########################

    def _getParsedValue(self, the_name, the_value):
        """ Build output of result, can be called recursively"""
        returned_value = ''
        uno_type = uno.getTypeByName(the_name) # skip the []
        uno_class = uno_type.typeClass

        if uno_class == unoSequence:
            # a sequence
            for i in range(len(the_value)):
                result = self._getParsedValue(the_name[2:],the_value[i])
                returned_value = returned_value + '\n-----  ' + str(i)
                returned_value = returned_value + '  -----\n' + result

        elif uno_class == unoStruct:
            # a structure
            # after many failing tries using CoreReflexion service
            # use of string manipulation tools
            a_string = str(the_value)
            # eg: (com.sun.star.beans.PropertyValue)
            #{ Name = (string)"FilterName", Handle = (long)0x0,
            # Value = (any){ (string)"StarOffice XML (Writer)" },
            # State = (com.sun.star.beans.PropertyState)DIRECT_VALUE }
            a = a_string.find('{')
            cleaner = a_string[a+1:len(a_string)-1]
            #eg : Name = (string)"FilterName", Handle = (long)0x0,
            # Value = (any){ (string)"StarOffice XML (Writer)" },
            # State = (com.sun.star.beans.PropertyState)DIRECT_VALUE
            decoupe=cleaner.split(',')
            result = ''
            for line in decoupe:
                # Hexa conversion
                a = line.find('0x')
                my_str = ''
                if a != -1:
                    b = line.find(' ',a)
                    if b == -1:
                        b = len(line)
                    hexa = line[a:b]
                    if hexa.find('-') != -1: # handles negative character !!!
                        my_long = hexa[2:]
                    else:
                        my_long = long(hexa,0)
                    my_str = ' = ' + str(my_long)
                # Concatenate
                result = result +'   '+ line + my_str + '\n'
            returned_value = result

        elif uno_class == unoInterface:
            returned_value = self.gui_rsc['need_XRay']

        elif uno_class == unoBoolean:
            if the_value == 0:
                returned_value = "False"
            else:
                returned_value = "True"

        elif uno_class == unoVoid:
            returned_value = ''

        else:
            # other type --> use a string
            returned_value = str(the_value)

        return returned_value


    #####################################################
    #              SDK Querying                         #
    #####################################################
    def _displaySDK(self, name):
        """Retreive or Build the HTML page for the SDK Querying"""

        #first letter to find index file
        lcase_name = name.lower()
        alpha = ord(lcase_name[0]) - ord('a') + 1
        if alpha == -1:
            alpha = 27 # name begins with _

        # read index file
        if (alpha >= 1) & (alpha <= 27):
            doc_filename = 'index-files' + sep + 'index-' + str(alpha) + '.html'
            doc_addr = SDK_ADDRESS  + doc_filename
            # Open index file
            if SDK_ADDRESS[:7] == 'http://':
                # SDK over http://
                file_service = self.smgr.createInstanceWithContext(
                                            'com.sun.star.ucb.SimpleFileAccess',
                                            self.ctx)
                #temp index filename
                ss = self.smgr.createInstanceWithContext(
                                        'com.sun.star.util.PathSubstitution',
                                        self.ctx)
                work_filename = "$(temp)" + sep + doc_filename
                work_filename = ss.substituteVariables(work_filename, False)
                # test if file already retreived
                if not path.isfile(work_filename[7:]):
                    if not path.isdir(path.dirname(work_filename[7:])):
                        #creates temp indexes directory
                        mkdir(path.dirname(work_filename[7:]))
                    # retreive file
                    file_service.copy(doc_addr,work_filename)

                # open file
                file_index = open(work_filename[7:], 'r') #[7:] remove file://
            else:
                # SDK local files
                file_index = open(doc_addr,'r')

            #read lines
            lines = file_index.readlines()
            file_index.close()

        is_temp_file = False
        if (self.cur_display == 'method') | ((self.cur_display == 'property')):

            resultList = self._listPossibleSDKPages(lines, name)

            if len(resultList) == 1:
                is_temp_file = False
                # Normal case - a file has been found
                mark1 = '<dt><a href="../'
                mark2 = '">'
                a_string = resultList[0]
                x1 = a_string.find(mark1)
                if x1 > -1:
                    x1 = x1 + len(mark1)
                    x2 = a_string.find(mark2, x1)
                    if x2 > -1:
                        page_address = a_string[x1:x2]
            else:
                is_temp_file = True
                if len(resultList) == 0:
                    #No result
                    contenu = "Aucun Resultat"
                else:
                    #more than one result
                    contenu = ''
                    for ii in resultList:
                        contenu = contenu + ii

                # Build temp HTML file
                cheminBase = unohelper.systemPathToFileUrl(SDK_ADDRESS)
                cheminBase = cheminBase[7:len(cheminBase)] #vire file://
                a_string =  '<html> <head> <title>pyXray Results</title>'
                a_string = a_string +' <base href="'
                a_string = a_string + cheminBase +'index-files/'
                a_string = a_string + '"> </head> <body> <h3> ' + name
                a_string = a_string + '</h3> <dl> '
                a_string=a_string + contenu + '</dl> </body> </html>'
                # save temp file
                ss = self.smgr.createInstanceWithContext(
                                        'com.sun.star.util.PathSubstitution',
                                        self.ctx)
                work_filename = "$(temp)" + sep + "XrayResults.html"
                work_filename = ss.substituteVariables(work_filename, False)
                temp_file = open(work_filename[7:],'w') #remove file://
                temp_file.write(a_string)
                temp_file.close()
                page_address=work_filename[7:] #remove file://

        elif (self.cur_display == 'interface') \
                    or (self.cur_display == 'service') \
                    or (self.cur_display == 'listener'):
            page_address=name.replace( '.', '/')+".html"

        if not is_temp_file:
            page_address = SDK_ADDRESS + page_address

        if sep == '\\':
            page_address = unohelper.fileUrlToSystemPath(page_address)

        # launch browser
        my_browser.open_new(page_address)

        # methode OOo -> marche pas sur fichier local (ni en macro) - ok pour lien web
        #leBrowser = 
self.smgr.createInstanceWithContext("com.sun.star.system.SystemShellExecute",self.ctx)
        #leBrowser.execute(page_address,"",NO_Error_Web)

#    ###########################

    def _listPossibleSDKPages(self, lines, search):
        """ In alphabetical index,
        search for property/method on the good interface"""

        a_list = []
        validation_list = []

        if self.cur_display == 'method':
            interfaces = self.cur_obj.getTypes() #interfaces
            for ii in interfaces:
                validation_list.append(ii.typeName)
            search_HTML = '<b>' + search + '()</b></a> - function'

        elif self.cur_display == 'property':
            services = self.cur_obj.getSupportedServiceNames() #services
            for ii in services:
                validation_list.append(ii)
            search_HTML = '<b>' + search + '</b></a> - property'

        # search for a supported interface
        for line in lines:
            if line.find(search_HTML) != -1:
                if self._isValidSDKContext(line, validation_list):
                    a_list.append(line)

        # Nothing found, list all uinterfaces for search
        if len(a_list) == 0:
            for line in lines:
                if line.find(search_HTML) != -1:
                    a_list.append(line)

        return a_list

#    ###########################

    def _isValidSDKContext(self, line, supported_list):
        """ returns True if the service or interface
        of the SDK entry is supported"""
        valid_context = True
        x1 = line.find('com/sun/star/')
        if x1 > -1:
            x2 = line.find('.html', x1 + 13)
            if x2 > -1:
                intf_serv = line[x1:x2]
                intf_serv = intf_serv.replace( '/', '.')
                supported_list=str(supported_list) # HACK : TODO !!!!
                if supported_list.find(intf_serv) == -1:
                    valid_context = False
        return valid_context


#####################################################
#                     Listeners                     #
#####################################################

class ButtonXrayListener(unohelper.Base, XActionListener):
    """Recursive call on selected element in ListInspect"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def actionPerformed(self, actionEvent):
        ctrl_lst_inspect=self.caller.dialog.getControl('ListInspect')
        selection = ctrl_lst_inspect.getSelectedItem()
        cleaner = selection.strip()
        if self.caller._isValideXRay(cleaner):
            obj = self.caller._getXRayObject(self.caller.cur_obj,
                                                  cleaner)
            ctrl_lst_obj = self.caller.dialog.getControl('ListObj')
            pos = ctrl_lst_obj.SelectedItemPos
            self.caller._initializeObject(obj, cleaner, pos)
            ctrl_txt_detail = self.caller.dialog.getControl('TxtObjInfosDetail')
            ctrl_txt_detail.setText('')

############################

class ButtonSDKListener(unohelper.Base, XActionListener):
    """call SDK"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def actionPerformed(self, actionEvent):
        ctrl_list = self.caller.dialog.getControl('ListInspect')
        selection = ctrl_list.getSelectedItem()
        cleaner = selection.strip()
        self.caller._displaySDK(cleaner)

############################

class OptMethodListener(unohelper.Base, XActionListener):
    """Analyze methods"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def actionPerformed(self, actionEvent):
        obj = self.caller.cur_obj
        ctx = self.caller.ctx
        introspection = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.beans.Introspection',
                                            ctx)
        inspect = introspection.inspect(obj)
        methods = inspect.getMethods(unohelper.METHOD_CONCEPT_ALL)
        a_string = []
        for ii in methods:
            a_string.append('   ' + ii.Name)
        self.caller._displayObjects(a_string)
        self.caller.cur_display = 'method'
        ctrl_list = self.caller.dialog.getControl('ListInspect')
        ctrl_list.selectItemPos(0,True)

############################

class OptPropertyListener(unohelper.Base, XActionListener):
    """Analyze properties"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def actionPerformed(self, actionEvent):
        obj=self.caller.cur_obj
        ctx = self.caller.ctx
        introspection = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.beans.Introspection',
                                            ctx)
        inspect = introspection.inspect(obj)
        props = inspect.getProperties(unohelper.PROPERTY_CONCEPT_ALL)
        a_string=[]
        for ii in props:
            a_string.append('   ' + ii.Name)
        self.caller._displayObjects(a_string)
        self.caller.cur_display='property'
        ctrl_list = self.caller.dialog.getControl('ListInspect')
        ctrl_list.selectItemPos(0,True)

############################

class OptInterfaceListener(unohelper.Base, XActionListener):
    """Analyze interfaces"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def actionPerformed(self, actionEvent):
        obj = self.caller.cur_obj
        interfaces = obj.getTypes()
        a_string = []
        for ii in interfaces:
            a_string.append('   '+ ii.typeName )
        self.caller._displayObjects(a_string)
        self.caller.cur_display = 'interface'
        ctrl_list = self.caller.dialog.getControl('ListInspect')
        ctrl_list.selectItemPos(0,True)

############################

class OptServiceListener(unohelper.Base, XActionListener):
    """Analyze services"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def actionPerformed(self, actionEvent):
        obj=self.caller.cur_obj
        a_string=[]
        # supported services
        try:
            names = obj.getSupportedServiceNames()
            for ii in names:
                a_string.append('   ' +  ii)
        except:
            pass
        #available services
        try:
            names = obj.getAvailableServiceNames()
            a_string = []
            for ii in names:
                a_string.append('   ' +  ii)
        except:
            pass

        if len(a_string) == 0:
            a_string.append(' ')
        self.caller._displayObjects(a_string)
        self.caller.cur_display = 'service'
        ctrl_list = self.caller.dialog.getControl('ListInspect')
        ctrl_list.selectItemPos(0,True)

############################

class OptListenListener(unohelper.Base, XActionListener):
    """Analyze listeners"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def actionPerformed(self, actionEvent):
        obj = self.caller.cur_obj
        ctx = self.caller.ctx
        introspection = ctx.ServiceManager.createInstanceWithContext(
                                            'com.sun.star.beans.Introspection',
                                            ctx)
        inspect = introspection.inspect(obj)
        props = inspect.getSupportedListeners()
        #can be empty
        a_string = []
        if len(props) > 0:
            for ii in props:
                a_string.append('   ' + ii.typeName)
        self.caller._displayObjects(a_string)
        self.caller.cur_display = 'listener'
        if len(props) > 0:
            ctrl_list = caller.dialog.getControl('ListInspect')
            ctrl_list.selectItemPos(0,True)
        else:
            # clean previous detail text
            ctrl_txt_detail = self.caller.dialog.getControl('TxtObjInfosDetail')
            ctrl_txt_detail.setText('')

############################

class ListInspectListener(unohelper.Base, XItemListener):
    """Selection in list"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def itemStateChanged(self, itemEvent):
        ctrl_list = self.caller.dialog.getControl('ListInspect')
        selection = ctrl_list.getSelectedItem()
        cleaner = selection.strip()
        # enable Xray button for recursive calls
        ctrl_button=self.caller.dialog.getControl('DeeperBtn')
        ctrl_button.Enable = self.caller._isValideXRay(cleaner)
        # fills text informations
        self.caller._displayInfos(cleaner)

############################

class ListHistoListener(unohelper.Base, XItemListener):
    """Navigate in historical list"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def itemStateChanged(self, itemEvent):
        num_select = int(itemEvent.Selected)
        self.caller.cur_obj = self.caller.lst_histo_obj[num_select]
        # update properties list
        ctrl_radio = self.caller.dialog.getControl('BtnProperties')
        ctrl_radio.State = True
        self.caller.lst_listeners['BtnProperties'].actionPerformed(None)

    ############################

class MouseAuthorListener(unohelper.Base, XMouseListener):
    """link to author label"""
    def __init__(self, caller):
        self.caller = caller

    def mousePressed(self, eventObject):
        adress = 'http://www.indesko.org'
        my_browser.open_new(adress)

    def mouseReleased(self, eventObject):
        pass

    def mouseEntered(self, eventObject):
        ctrl_label = self.caller.dialog.getControl('LabelAuteur')
        ctrl_label.Model.TextColor = 0xff0000
        # changement de POinteur --> ne marche pas TODO
        #objPointeur = self.caller.ctx.ServiceManager.queryInterface( "com.sun.star.awt.XPointer", 
self.caller.ctx )
        #print objPointeur #--> retourne None
        #objPointeur.setType(28)
        #self.caller.dialog.Peer.setPointer(objPointeur)

    def mouseExited(self, eventObject):
        ctrl_label = self.caller.dialog.getControl('LabelAuteur')
        ctrl_label.Model.TextColor = 0x000000
        # changement de Pointeur --> ne marche pas TODO
        #objPointeur = self.caller.ctx.ServiceManager.createInstanceWithContext( 
"com.sun.star.awt.XPointer", self.caller.ctx )
        #objPointeur.setType(0)
        #self.caller.dialog.Peer.setPointer(objPointeur)

Context


Privacy Policy | Impressum (Legal Info) | Copyright information: Unless otherwise specified, all text and images on this website are licensed under the Creative Commons Attribution-Share Alike 3.0 License. This does not include the source code of LibreOffice, which is licensed under the Mozilla Public License (MPLv2). "LibreOffice" and "The Document Foundation" are registered trademarks of their corresponding registered owners or are in actual use as trademarks in one or more countries. Their respective logos and icons are also subject to international copyright laws. Use thereof is explained in our trademark policy.