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

Danny's Python Modules
Goto page 1, 2  Next
 
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: Sat Nov 20, 2004 11:26 am    Post subject: Danny's Python Modules Reply with quote

In this thread I am going to post some various Python modules from my growing library.

Table Of Contents

The following links take you directly to the message where a particular class is posted.

Danny.OOo.OOoLib.py
This module makes programming OOo in Python much more like programming OOo in Basic. It also contains some frequently used functions that I typically write in Basic, such as makePropertyValue().

Danny.OOo.DrawLib.py
This module has routines to make programming OOo Drawing documents easier. Much of this code was derrived from Basic code, that also appears in Danny's Draw Power Tools found at OOoMacros.org.

Danny.HSBConversions.py
HSB to RGB color space conversion routines. This module is a prerequisite for the module Danny.OOo.DrawLib.py.

Danny.OOo.PrintToWriter.py
This makes it easy and convenient to print a bunch of text into a Writer document. See the example routine in the module that shows how easy this module is to use, and how useful it can be.

Danny.OOo.ConfigLib.py
Routines for working with the Configuration Manager.

Danny.OOo.DialogLib.py
A class to build a dialog box from the com.sun.star.awt.* services. This doesn't do anything you couldn't already do using OOo's UNO API, this just makes it much easier.

Danny.OOo.WindowLib.py
A class to build a modeless window from the com.sun.star.awt.* services. This doesn't do anything you couldn't already do using OOo's UNO API, this just makes it much easier.

Danny.OOo.Listeners.ListenerProcAdapters.py
This module has various helpers that make it extremely easy to create listeners on the fly, and make them call an arbitrary python procedure. See quick example that appears with the code.

Danny.OOo.Listeners.TopWindowListener.py
When you need to add a window listener to a top window, this class makes is easy to create such a listener. You can use this class, or your own subclass of it. If you create a subclass, you don't need to bother to implement every one of the methods, because you can inherit the empty implementations of methods from this class for the methods you are not interested in.

Danny.HeapSort
A simple implementation of HeapSort. Yet, it allows a customizable notion of "comparison" and "swapping" by passing in your own compareGreaterProc, and swapProc.
This is NOT an OOo specific module. It can be used for any type of Python code.



See also....
String Utility functions for Python
That thread has my module, which I now call... Danny.StringOps.


import Danny.StringOps
import Danny.HSBConversions
import Danny.OOo.OOoLib
import Danny.OOo.DrawLib
import Danny.OOo.PrintToWriter
import Danny.OOo.ConfigLib
import Danny.OOo.DialogLib
import Danny.OOo.WindowLib

I plan to make reference to the modules in this thread as I write more and more Python examples.

Some of the following modules were previously published in a more primitive form, combined as a single module, here.
http://www.oooforum.org/forum/viewtopic.php?p=12909#12909

Here are some pointers to setting up Python IDLE (the GUI development environment) on Windows XP to work with OOo's Python. And here is an even better article on setting up Python on Windows to use IDLE.

Update: here are updated instructions to use OOo 2.0 beta's private python with IDLE.


Here are other python related links and articles.....

Python
======
Danny's Python Modules
http://www.oooforum.org/forum/viewtopic.phtml?t=14409

A lot of introductory information / answers about OOo UNO and Python
http://www.oooforum.org/forum/viewtopic.phtml?p=75468#75468

Modeless window with controls in Python
http://www.oooforum.org/forum/viewtopic.phtml?t=14411

FYI...How to use OOo with Python on Windows
Setting up the IDLE development system for use with OOo's Python.
http://www.oooforum.org/forum/viewtopic.php?t=4818

MakePropertyValue in python
http://www.oooforum.org/forum/viewtopic.php?p=26198#26198

Calc Examples in Python
http://www.oooforum.org/forum/viewtopic.phtml?p=56037#56037
self contained example that runs between two different computers
http://www.oooforum.org/forum/viewtopic.phtml?p=75067#75067

String Utility functions for Python
http://www.oooforum.org/forum/viewtopic.php?t=10974

HasUnoInterfaces in python
http://www.oooforum.org/forum/viewtopic.php?t=6766

Document conversion example
Danny's Python Library OOoLib 2003-08-29-01
How to use Python in Windows
http://www.oooforum.org/forum/viewtopic.php?t=3451

python script NOT using API to extract text from Writer
Also a shell command to extract text from writer
http://www.oooforum.org/forum/viewtopic.php?t=1500

Start python script from OOo via. shell command
http://www.oooforum.org/forum/viewtopic.php?t=5748

It is possible? to access Windows Registry from Python...
http://www.oooforum.org/forum/viewtopic.php?t=6221

Python in scripting framework
http://udk.openoffice.org/python/scriptingframework/index.html
Python UNO bridge
http://udk.openoffice.org/python/python-bridge.html

Example of a service in python
http://www.oooforum.org/forum/viewtopic.php?t=2047

Registering a component in Python
http://www.oooforum.org/forum/viewtopic.php?t=6355

Python component providing XML parser
http://www.oooforum.org/forum/viewtopic.php?p=38234#38234

Python container components
http://www.oooforum.org/forum/viewtopic.php?t=9115

Development of Calc Function add ons in Python
http://www.oooforum.org/forum/viewtopic.php?t=8456

Example of storing and retrieving a custom attribute on a spreadsheet cell
http://www.oooforum.org/forum/viewtopic.phtml?p=76972#76972

oood.py - A simple daemon for OpenOffice.org
http://udk.openoffice.org/python/oood


OO beta and Python??
http://www.oooforum.org/forum/viewtopic.phtml?t=18227

pyuno:: interactive python.bat -> cannot 'import re'
http://www.oooforum.org/forum/viewtopic.php?t=4054


explanation of sequence in python is a tuple
http://www.oooforum.org/forum/viewtopic.php?p=13501#13501

How can i get python-bridge on debian to work
http://www.oooforum.org/forum/viewtopic.php?t=4368

Python and OOo: do you have some links?
http://www.oooforum.org/forum/viewtopic.php?t=4772

Java vs. Python for OOo
http://www.oooforum.org/forum/viewtopic.php?p=29457#29457
http://www.oooforum.org/forum/viewtopic.php?t=3735




See Also...

Danny's Java classes
http://www.oooforum.org/forum/viewtopic.phtml?t=12954

Danny's Basic Library
http://www.oooforum.org/forum/viewtopic.phtml?t=18762
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Sat May 21, 2005 11:26 am; edited 25 times in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Nov 20, 2004 11:32 am    Post subject: Reply with quote

Danny.OOo.OOoLib.py

This module makes programming OOo in Python much more like programming OOo in Basic. It also contains some frequently used functions that I typically write in Basic, such as makePropertyValue().

When I write Components in Python, the first function in this module, the getServiceManager() function is replaced by a completely different implementation. Otherwise, even in a component, the features of this module are available.

A Component is something that is installed into the office. Here is an example of a compoennt that I wrote in Python. That example does NOT use this module. The example does include Basic code to show how to use it. Here is another example of a Calc AddIn component. This component DOES use code drawn from this module, with the alternate getServiceManager() function. In the Developer's Guide, you can find a section on how to develop Calc Add-Ons.

Anyway, here is the source of my most basic OOo module.

Code:
#**********************************************************************
#
#   Danny.OOo.OOoLib.py
#
#   A module to easily work with OpenOffice.org.
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2004-06-07-01
#
#**********************************************************************

import string

# OOo's libraries
import uno


#------------------------------------------------------------
#   Uno ServiceManager access
#   A different version of this routine and global variable
#    is needed for code running inside a component.
#------------------------------------------------------------


# The ServiceManager of the running OOo.
# It is cached in a global variable.
goServiceManager = False
def getServiceManager( cHost="localhost", cPort="8100" ):
    """Get the ServiceManager from the running OpenOffice.org.
        Then retain it in the global variable goServiceManager for future use.
        This is similar to the GetProcessServiceManager() in OOo Basic.
    """
    global goServiceManager
    if not goServiceManager:
        # Get the uno component context from the PyUNO runtime
        oLocalContext = uno.getComponentContext()
        # Create the UnoUrlResolver on the Python side.
        oLocalResolver = oLocalContext.ServiceManager.createInstanceWithContext(
                                    "com.sun.star.bridge.UnoUrlResolver", oLocalContext )
        # Connect to the running OpenOffice.org and get its context.
        oContext = oLocalResolver.resolve( "uno:socket,host=" + cHost + ",port=" + cPort + ";urp;StarOffice.ComponentContext" )
        # Get the ServiceManager object
        goServiceManager = oContext.ServiceManager
    return goServiceManager


#------------------------------------------------------------
#   Uno convenience functions
#   The stuff in this section is just to make
#    python progrmaming of OOo more like using OOo Basic.
#------------------------------------------------------------


# This is the same as ServiceManager.createInstance( ... )
def createUnoService( cClass ):
    """A handy way to create a global objects within the running OOo.
    Similar to the function of the same name in OOo Basic.
    """
    oServiceManager = getServiceManager()
    oObj = oServiceManager.createInstance( cClass )
    return oObj


# The StarDesktop object.  (global like in OOo Basic)
# It is cached in a global variable.
StarDesktop = None
def getDesktop():
    """An easy way to obtain the Desktop object from a running OOo.
    """
    global StarDesktop
    if StarDesktop == None:
        StarDesktop = createUnoService( "com.sun.star.frame.Desktop" )
    return StarDesktop
# preload the StarDesktop variable.
getDesktop()


# The CoreReflection object.
# It is cached in a global variable.
goCoreReflection = False
def getCoreReflection():
    global goCoreReflection
    if not goCoreReflection:
        goCoreReflection = createUnoService( "com.sun.star.reflection.CoreReflection" )
    return goCoreReflection


def createUnoStruct( cTypeName ):
    """Create a UNO struct and return it.
    Similar to the function of the same name in OOo Basic.
    """
    oCoreReflection = getCoreReflection()
    # Get the IDL class for the type name
    oXIdlClass = oCoreReflection.forName( cTypeName )
    # Create the struct.
    oReturnValue, oStruct = oXIdlClass.createObject( None )
    return oStruct



#def newConnectionToOOo( cHost="localhost", cPort="8100" ):
#    """Call this to establish, or re-establish a connection to OOo."""
#    global goServiceManager
#    global StarDesktop
#    global goCoreReflection
#    goServiceManager = False
#    StarDesktop = None
#    goCoreReflection = False
#    getServiceManager( cHost, cPort )
#    getDesktop()



#------------------------------------------------------------
#   API helpers
#------------------------------------------------------------

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

def hasUnoInterfaces( oObject, *cInterfaces ):
    """Similar to the function of the same name in OOo Basic."""
    for cInterface in cInterfaces:
        if not hasUnoInterface( oObject, cInterface ):
            return False
    return True



#------------------------------------------------------------
#   High level general purpose functions
#------------------------------------------------------------


def makePropertyValue( cName=None, uValue=None, nHandle=None, nState=None ):
    """Create a com.sun.star.beans.PropertyValue struct and return it.
    """
    oPropertyValue = createUnoStruct( "com.sun.star.beans.PropertyValue" )

    if cName != None:
        oPropertyValue.Name = cName
    if uValue != None:
        oPropertyValue.Value = uValue
    if nHandle != None:
        oPropertyValue.Handle = nHandle
    if nState != None:
        oPropertyValue.State = nState

    return oPropertyValue


def makePoint( nX, nY ):
    """Create a com.sun.star.awt.Point struct."""
    oPoint = createUnoStruct( "com.sun.star.awt.Point" )
    oPoint.X = nX
    oPoint.Y = nY
    return oPoint


def makeSize( nWidth, nHeight ):
    """Create a com.sun.star.awt.Size struct."""
    oSize = createUnoStruct( "com.sun.star.awt.Size" )
    oSize.Width = nWidth
    oSize.Height = nHeight
    return oSize


def makeRectangle( nX, nY, nWidth, nHeight ):
    """Create a com.sun.star.awt.Rectangle struct."""
    oRect = createUnoStruct( "com.sun.star.awt.Rectangle" )
    oRect.X = nX
    oRect.Y = nY
    oRect.Width = nWidth
    oRect.Height = nHeight
    return oRect


def Array( *args ):
    """This is just sugar coating so that code from OOoBasic which
    contains the Array() function can work perfectly in python."""
    tArray = ()
    for arg in args:
        tArray += (arg,)
    return tArray


def loadComponentFromURL( cUrl, tProperties=() ):
    """Open or Create a document from it's URL.
    New documents are created from URL's such as:
        private:factory/sdraw
        private:factory/swriter
        private:factory/scalc
        private:factory/simpress
    """
    StarDesktop = getDesktop()
    oDocument = StarDesktop.loadComponentFromURL( cUrl, "_blank", 0, tProperties )
    return oDocument



#def makeWriterDocument():
#    """Create a new OOo Writer document."""
#    return loadComponentFromURL( "private:factory/swriter" )
#
#
#def makeCalcDocument():
#    """Create a new OOo Calc document."""
#    return loadComponentFromURL( "private:factory/scalc" )




#------------------------------------------------------------
#   Styles
#------------------------------------------------------------


def defineStyle( oDrawDoc, cStyleFamily, cStyleName, cParentStyleName=None ):
    """Add a new style to the style catalog if it is not already present.
    This returns the style object so that you can alter its properties.
    """

    oStyleFamily = oDrawDoc.getStyleFamilies().getByName( cStyleFamily )

    # Does the style already exist?
    if oStyleFamily.hasByName( cStyleName ):
        # then get it so we can return it.
        oStyle = oStyleFamily.getByName( cStyleName )
    else:
        # Create new style object.
        oStyle = oDrawDoc.createInstance( "com.sun.star.style.Style" )

        # Set its parent style
        if cParentStyleName != None:
            oStyle.setParentStyle( cParentStyleName )

        # Add the new style to the style family.
        oStyleFamily.insertByName( cStyleName, oStyle )

    return oStyle


def getStyle( oDrawDoc, cStyleFamily, cStyleName ):
    """Lookup and return a style from the document.
    """
    return oDrawDoc.getStyleFamilies().getByName( cStyleFamily ).getByName( cStyleName )





#------------------------------------------------------------
#   General Utility functions
#------------------------------------------------------------


def convertToURL( cPathname ):
    """Convert a Windows or Linux pathname into an OOo URL."""
    if len( cPathname ) > 1:
        if cPathname[1:2] == ":":
            cPathname = "/" + cPathname[0] + "|" + cPathname[2:]
    cPathname = string.replace( cPathname, "\\", "/" )
    cPathname = "file://" + cPathname
    return cPathname

_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Sat Nov 20, 2004 2:34 pm; edited 5 times in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Nov 20, 2004 11:59 am    Post subject: Reply with quote

Danny.HSBConversions.py

HSB to RGB color space conversion routines.

This module is a prerequisite for the module
Danny.OOo.DrawLib.py

For more understanding of the theory of this module see my other thread...

Color conversions: HSB to RGB and back again
http://www.oooforum.org/forum/viewtopic.php?t=4945

That thread has HSB <<--->> RGB conversion code in Basic.

The OOoMacros.org site has Danny's Draw Power Tools which has a document Understanding HSB Color which explains the theory in much detail with pictures.

The following code was originally published in a more primitive form over here.


Code:
#**********************************************************************
#
#   Danny.HSBConversions.py
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2003-08-21-01
#
#**********************************************************************


#   HSB to RGB color space conversion routines.



def RGBtoHSB( nRed, nGreen, nBlue ):
    """RGB to HSB color space conversion routine.
    nRed, nGreen and nBlue are all numbers from 0 to 255.
    This routine returns three floating point numbers, nHue, nSaturation, nBrightness.
    nHue, nSaturation and nBrightness are all from 0.0 to 1.0.
    """
    nMin = min( nRed, nGreen, nBlue )
    nMax = max( nRed, nGreen, nBlue )

    if nMin == nMax:
        # Grayscale
        nHue = 0.0
        nSaturation = 0.0
        nBrightness = nMax
    else:
        if nRed == nMin:
            d = nGreen = nBlue
            h = 3.0
        elif nGreen == nMin:
            d = nBlue - nRed
            h = 5.0
        else:
            d = nRed - nGreen
            h = 1.0

        nHue = ( h - ( float( d ) / (nMax - nMin) ) ) / 6.0
        nSaturation = (nMax - nMin) / float( nMax )
        nBrightness = nMax / 255.0

    return nHue, nSaturation, nBrightness



def HSBtoRGB( nHue, nSaturation, nBrightness ):
    """HSB to RGB color space conversion routine.
    nHue, nSaturation and nBrightness are all from 0.0 to 1.0.
    This routine returns three integer numbers, nRed, nGreen, nBlue.
    nRed, nGreen and nBlue are all numbers from 0 to 255.
    """
    # Scale the brightness from a range of 0.0 thru 1.0
    #  to a range of 0.0 thru 255.0
    # Then truncate to an integer.
    nBrightness = int( min( nBrightness * 256.0, 255.0 ) )

    if nSaturation == 0.0:
        # Grayscale because there is no saturation
        nRed = nBrightness
        nGreen = nBrightness
        nBlue = nBrightness
    else:
        # Make hue angle be within a single rotation.
        # If the hue is > 1.0 or < 0.0, then it has
        #  "gone around the color wheel" too many times.
        #  For example, a value of 1.2 means that it has
        #  gone around the wheel 1.2 times, which is really
        #  the same ending angle as 0.2 trips around the wheel.
        # Scale it back to the 0.0 to 1.0 range.
        if nHue > 1.0:
            nHue = nHue - int( nHue )
        elif nHue < 0.0:
            nHue = abs( nHue )
            if nHue > 1.0:
                nHue = nHue - int( nHue )
            nHue = 1.0 - nHue
        # Rescale hue to a range of 0.0 thru 6.0
        nHue = nHue * 6.0
        # Separate hue into int and fractional parts
        iHue = int( nHue )
        fHue = nHue - iHue
        # Is hue even?
        if iHue % 2 == 0:
            fHue = 1.0 - fHue
        #
        m = nBrightness * (1.0 - nSaturation)
        n = nBrightness * (1.0 - (nSaturation * fHue))

        if iHue == 1:
            nRed = n
            nGreen = nBrightness
            nBlue = m
        elif iHue == 2:
            nRed = m
            nGreen = nBrightness
            nBlue = n
        elif iHue == 3:
            nRed = m
            nGreen = n
            nBlue = nBrightness
        elif iHue == 4:
            nRed = n
            nGreen = m
            nBlue = nBrightness
        elif iHue == 5:
            nRed = nBrightness
            nGreen = m
            nBlue = n
        else:
            nRed = nBrightness
            nGreen = n
            nBlue = m
   
    return nRed, nGreen, nBlue

_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Sat Nov 20, 2004 1:54 pm; edited 3 times in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Nov 20, 2004 12:06 pm    Post subject: Reply with quote

Danny.OOo.DrawLib.py

This module has routines to make programming OOo Drawing documents easier. Much of this code was derrived from Basic code, that also appears in Danny's Draw Power Tools found at OOoMacros.org.

This module depends upon the modules...
Danny.OOo.OOoLib.py
Danny.HSBConversions.py
presented elsewhere in this thread.

The following code was originally published in more primitive form over here.

Code:
#**********************************************************************
#
#   Danny.OOo.DrawLib.py
#
#   A module to easily work with OOo Drawings.
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2004-05-24-01
#
#**********************************************************************



# Python libraries
import math
import string

# Danny's libraries
from Danny import HSBConversions
from Danny.OOo.OOoLib import *

# OOo's libraries
import uno



#------------------------------------------------------------
#   Functions for working with Draw documents.
#------------------------------------------------------------



def makeDrawDocument():
    """Create a new OOo Draw document."""
    return loadComponentFromURL( "private:factory/sdraw" )

def makeImpressDocument():
    """Create a new OOo Impress document."""
    return loadComponentFromURL( "private:factory/simpress" )


# Notes about some properties and constants for shape objects...

    # LineStyle can be one of...
    #   com.sun.star.drawing.LineStyle.NONE
    #   com.sun.star.drawing.LineStyle.SOLID
    #   com.sun.star.drawing.LineStyle.DASH

    # CircleKind can be one of...
    #   com.sun.star.drawing.CircleKind.FULL
    #   com.sun.star.drawing.CircleKind.SECTION   ' a circle with a cut connected by two lines
    #   com.sun.star.drawing.CircleKind.CUT ' a circle with a cut connected by a line
    #   com.sun.star.drawing.CircleKind.ARC ' a circle with an open cut
   
    # FillStyle can be one of...
    #   com.sun.star.drawing.FillStyle.NONE
    #   com.sun.star.drawing.FillStyle.SOLID
    #   com.sun.star.drawing.FillStyle.GRADIENT
    #   com.sun.star.drawing.FillStyle.HATCH
    #   com.sun.star.drawing.FillStyle.BITMAP
   
    # TextHorizontalAdjust can be one of...
    #   com.sun.star.drawing.TextHorizontalAdjust.LEFT
    #   com.sun.star.drawing.TextHorizontalAdjust.CENTER
    #   com.sun.star.drawing.TextHorizontalAdjust.RIGHT
    #   com.sun.star.drawing.TextHorizontalAdjust.BLOCK
   
    # TextVerticalAdjust can be one of...
    #   com.sun.star.drawing.TextVerticalAdjust.TOP
    #   com.sun.star.drawing.TextVerticalAdjust.CENTER
    #   com.sun.star.drawing.TextVerticalAdjust.BOTTOM
    #   com.sun.star.drawing.TextVerticalAdjust.BLOCK
   
    # TextFitToSize can be one of...
    #    com.sun.star.drawing.TextFitToSizeType.NONE
    #    com.sun.star.drawing.TextFitToSizeType.PROPORTIONAL
    #    com.sun.star.drawing.TextFitToSizeType.ALLLINES
    #    com.sun.star.drawing.TextFitToSizeType.RESIZEATTR

# Useful code snippets...

    # Accessing pages of a drawing document.
    #   oDrawPage = oDrawDoc.getDrawPages().getByIndex( 0 )
    #   oDrawPage = oDrawDoc.getDrawPages().getCount()
    #   oDrawPage = oDrawDoc.getDrawPages().insertByIndex( 1 )



#------------------------------------------------------------
#   Document functions
#------------------------------------------------------------


def setDrawPageOrientationLandscape( oDrawPage ):
    """Pass in any GenericDrawPage object, and this changes it to landscape orientation,
     in addition to swapping the height/width as you would expect.
    """
    # Save some settings
    nOldWidth = oDrawPage.Width
    nOldHeight = oDrawPage.Height
    nOldBorderTop = oDrawPage.BorderTop
    nOldBorderLeft = oDrawPage.BorderLeft
    nOldBorderRight = oDrawPage.BorderRight
    nOldBorderBottom = oDrawPage.BorderBottom
   
    # Change so that it will PRINT in landscape
    oDrawPage.Orientation = uno.getConstantByName( "com.sun.star.view.PaperOrientation.LANDSCAPE" )

    # Now change some paper dimensions to match
    oDrawPage.Width = nOldHeight
    oDrawPage.Height = nOldWidth
    oDrawPage.BorderTop = nOldBorderRight
    oDrawPage.BorderLeft = nOldBorderTop
    oDrawPage.BorderRight = nOldBorderBottom
    oDrawPage.BorderBottom = nOldBorderLeft



#------------------------------------------------------------
#   Shape functions
#------------------------------------------------------------



def makeRectangleShape( oDrawDoc, oPosition=None, oSize=None ):
    """Create a new RectangleShape with an optional position and size."""
    oShape = makeShape( oDrawDoc, "com.sun.star.drawing.RectangleShape", oPosition, oSize )
    return oShape


def makeEllipseShape( oDrawDoc, oPosition=None, oSize=None ):
    """Create a new EllipseShape with an optional position and size."""
    oShape = makeShape( oDrawDoc, "com.sun.star.drawing.EllipseShape", oPosition, oSize )
    return oShape


def makeLineShape( oDrawDoc, oPosition=None, oSize=None ):
    """Create a new LineShape with an optional position and size."""
    oShape = makeShape( oDrawDoc, "com.sun.star.drawing.LineShape", oPosition, oSize )
    return oShape


def makeTextShape( oDrawDoc, oPosition=None, oSize=None ):
    """Create a new TextShape with an optional position and size."""
    oShape = makeShape( oDrawDoc, "com.sun.star.drawing.TextShape", oPosition, oSize )
    return oShape


def findShapeByName( oShapes, cShapeName ):
    """Find a named shape within an XShapes interface.
    oShapes can be a drawing page, which supports the XShapes interface.
    Thus, you can find a named shape within a draw page, or within a grouped shape,
     or within a selection of sseveral shapes.
    """
    nNumShapes = oShapes.getCount()
    for i in range( nNumShapes ):
        oShape = oShapes.getByIndex( i )
        cTheShapeName = oShape.getName()
        if cTheShapeName == cShapeName:
            return oShape
    return None


def makeShape( oDrawDoc, cShapeClassName, oPosition=None, oSize=None ):
    """Create a new shape of the specified class.
    Position and size arguments are optional.
    """
    oShape = oDrawDoc.createInstance( cShapeClassName )

    if oPosition != None:
        oShape.Position = oPosition
    if oSize != None:
        oShape.Size = oSize

    return oShape



#------------------------------------------------------------
#   Color manipulation
#------------------------------------------------------------


def rgbColor( nRed, nGreen, nBlue ):
    """Return an integer which repsents a color.
    The color is specified in RGB notation.
    Each of nRed, nGreen and nBlue must be a number from 0 to 255.
    """
    return (int( nRed ) & 255) << 16 | (int( nGreen ) & 255) << 8 | (int( nBlue ) & 255)


def hsbColor( nHue, nSaturation, nBrightness ):
    """Return an integer which repsents a color.
    The color is specified in HSB notation.
    Each of nHue, nSaturation and nBrightness must be a number from 0.0 to 1.0.
    """
    nRed, nGreen, nBlue = HSBConversions.HSBtoRGB( nHue, nSaturation, nBrightness )
    return rgbColor( nRed, nGreen, nBlue )


def redColor( nColor ):
    """Return the Red component of a color as an integer from 0 to 255.
    nColor is an integer representing a color.
    This function is complimentary to the rgbColor function.
    """
    return (int( nColor ) >> 16) & 255


def greenColor( nColor ):
    """Return the Green component of a color as an integer from 0 to 255.
    nColor is an integer representing a color.
    This function is complimentary to the rgbColor function.
    """
    return (int( nColor ) >> 8) & 255


def blueColor( nColor ):
    """Return the Blue component of a color as an integer from 0 to 255.
    nColor is an integer representing a color.
    This function is complimentary to the rgbColor function.
    """
    return int( nColor ) & 255





#------------------------------------------------------------
#   Drawing routines
#------------------------------------------------------------


# Multiply this number by an OOo angle in 100'ths of a degree
#  to convert to radians.
nRadiansPerHundredthDegree = math.pi / 18000


def drawLine( oDrawDoc, oDrawPage, x1,y1, x2,y2, nLineColor=None ):
    """Draw a line from x1,y1 to x2,y2.  Optionally specify line color.
    This adds the LineShape to the page.
    The LineShape is returned.
    """
    # make sure size is non-zero
    #if x1 = x2: x2 = x1 + 1
    #if y1 = y2: y2 = y1 + 1

    oPosition = makePoint( x1, y1 )
    oSize = makeSize( x2-x1, y2-y1 )

    oShape = makeLineShape( oDrawDoc, oPosition, oSize )

    if nLineColor != None:
        oShape.LineColor = nLineColor
    #oShape.LineWidth = 0

    oDrawPage.add( oShape )
    return oShape


def drawLineVector( oDrawDoc, oDrawPage, x1,y1, nAngle,nDistance, nLineColor=None ):
    """Draw a line from x1,y1 in the direction of nAngle, for a distance of nDistance.
    nAngle is measured in radians, clockwise from the 3 O'Clock (east) direction.
    nDistance is in 1000ths of a centimeter.
    This adds the LineShape to the page.
    The LineShape is returned.
    """
    nDX = math.cos( nAngle ) * nDistance
    nDY = math.sin( nAngle ) * nDistance

    return drawLine( oDrawDoc, oDrawPage, x1,y1, x1+nDX,y1+nDY, nLineColor )


def drawAutoSizingText( oDrawDoc, oDrawPage,
                        cText, nHeight, nExtraWidthPercent=40 ):
    """Create a TextShape that will automatically resize its characters
     to its shape bounding rectangle.
    The TextShape is created with a specified height.
    The width is determined based on the natural character width of the
     text.
    The initial position of the text is -10000,-10000, so that the text is not visible.
    This returns the TextShape, which has already been added to the drawing page,
     at coordinates which make it invisible.
    You must set the object's Position property to make the text visible.
    (Hint: You may look at the Size property to help you determine where
     you want to place the text, for instance if you are trying to center
     it, or place it relative to some other shape object.)
    If you don't supply nExtraWidthPercent, then a default fudge factor is used.
    This is the percentage of the average character width, which is added to the shape's
     total width.
    """
    # Create TextShape
    oShape = makeTextShape( oDrawDoc, makePoint( -10000, -10000 ), makeSize( 1, 1 ) )

    # Add it to the page.
    oDrawPage.add( oShape )

    # Make text stick to upper left corner of the shape rather than centered within the shape.
    oShape.TextHorizontalAdjust = uno.getConstantByName( "com.sun.star.drawing.TextHorizontalAdjust.LEFT" )
    oShape.TextVerticalAdjust = uno.getConstantByName( "com.sun.star.drawing.TextVerticalAdjust.TOP" )

    # Make the shape auto-grow in size, based on the text.
    # Once we set the text, in the next step, the shape will grow to some
    #  unknown size, based on the current font in use.
    #oShape.TextAutoGrowHeight = True
    oShape.TextAutoGrowWidth = True

    # Set the text of the TextShape.
    # Because of the TextAutoGrowWidth, the shape now occupies some unknown size.
    oShape.setString( cText )

    # Get the shape's current size.
    nSaveHeight = oShape.Size.Height
    nSaveWidth = oShape.Size.Width

    # Make the shape NOT auto-grow in size, based on the text.
    #oShape.TextAutoGrowHeight = False
    oShape.TextAutoGrowWidth = False

    # This next setting causes the TextShape to automatically resize its characters
    #  to fit the size of the text shape.
    oShape.TextFitToSize = uno.getConstantByName( "com.sun.star.drawing.TextFitToSizeType.PROPORTIONAL" )

    # Calculate the new width, based on the desired height,
    #  and saved width/height ratio for the current font in use.
    nWidth = nSaveWidth * (float(nHeight) / nSaveHeight)

    nAverageCharacterWidth = nWidth / len( cText )

    nExtraWidth = nAverageCharacterWidth * (nExtraWidthPercent / 100.0)

    oShape.TextLeftDistance = nExtraWidth
    oShape.TextRightDistance = nExtraWidth
    nWidth = nWidth + 2 * nExtraWidth

    # Now resize the TextShape.
    oShape.Size.Width = nWidth
    oShape.Size.Height = nHeight

    return oShape


def drawArcPath( oDrawDoc, oDrawPage,
                 nStartX, nStartY, nStartAngle,
                 nArcAngle, nArcRadius, bTurnLeft ):
    """Draw an arc of a circle from a starting position and direction.
    The arc has a certian radius and arc angle,
     and turns either to the left or to the right.
    Parameters:
    nStartX and nStartY are the starting position of the "turtle".
    nStartAngle is the angle direction that the turtle is pointing,
     in 100'ths of a degree.
    An arc is drawn by moving the turtle forward and turning either left or right as it moves.
    nArcAngle is the angle of the arc describing the turtle's path,
     in 100'ths of a degree.
    nArcRadius is the radius of the arc describing the turtle's path.
    bTurnLeft is True if the turtle turns to the left, or False to turn to the right.
    Four values are returned.
    (1) the circle shape, (2) the new X position, (3) new Y position, and (4) new angle.
    Use the last three return values as initial values to draw another arc
     which is connected to the ending position of the arc just drawn.
    """

    # Figure out how big of a circle that the arc is a part of.
    nCircleDiameter = nArcRadius + nArcRadius
    oCircleSize = makeSize( nCircleDiameter, nCircleDiameter )

    # Figure out the position of the circle (ellipse) shape object.
    #
    # Determine the angle of the center point from the starting position.
    if bTurnLeft:
        nCenterPointAngle = nStartAngle + 9000
    else:
        nCenterPointAngle = nStartAngle - 9000
    # Convert to radians.
    nCenterPointAngle = nCenterPointAngle * nRadiansPerHundredthDegree
    # Determine where the center of the circle shape should be.
    nCenterX = nStartX + (nArcRadius * math.cos( nCenterPointAngle ))
    nCenterY = nStartY - (nArcRadius * math.sin( nCenterPointAngle ))
    oCirclePosition = makePoint( nCenterX - nArcRadius, nCenterY - nArcRadius )

    # Figure out what arc portion of the circle needs to be drawn.
    # Angles measures in 100'ths of a degree.
    if bTurnLeft:
        nCircleStartAngle = nStartAngle - 9000
        nCircleEndAngle = nCircleStartAngle + nArcAngle
    else:
        nCircleEndAngle = nStartAngle + 9000
        nCircleStartAngle = nCircleEndAngle - nArcAngle
 
    # Make the circle shape.
    oCircle = makeEllipseShape( oDrawDoc, oCirclePosition, oCircleSize )
    # Fill in its properties
    oCircle.FillStyle = uno.getConstantByName( "com.sun.star.drawing.FillStyle.NONE" )
    oCircle.CircleKind = uno.getConstantByName( "com.sun.star.drawing.CircleKind.ARC" )
    oCircle.CircleStartAngle = nCircleStartAngle
    oCircle.CircleEndAngle = nCircleEndAngle
    # Put it on the drawing
    oDrawPage.add( oCircle )

    # Figure out the ending turtle location and direction.
    if bTurnLeft:
        nEndAngle = nStartAngle - 9000 + nArcAngle
    else:
        nEndAngle = nStartAngle + 9000 - nArcAngle
    # Convert to radians
    nEndAngleRad = nEndAngle * nRadiansPerHundredthDegree
    # Ending Position
    nEndX = nCenterX + (nArcRadius * math.cos( nEndAngleRad ))
    nEndY = nCenterY - (nArcRadius * math.sin( nEndAngleRad ))
    # Ending angle
    if bTurnLeft:
        nEndAngle = normalizeOOoAngle( nEndAngle + 9000 )
    else:
        nEndAngle = normalizeOOoAngle( nEndAngle - 9000 )

    return oCircle, nEndX, nEndY, nEndAngle


def drawSpiralOfArcs( oDrawDoc, oDrawPage,
                      nStartX, nStartY, nStartAngle,
                      nArcAngle, nArcRadius, bTurnLeft,
                      nNumArcs,
                      nRadiusGrowthMultiplier=1.0, nRadiusGrowthAddIn=0 ):
    """Draw a spiral starting from a certian position and direction.
    The spiral turns either towards the left or towards the right.
    Parameters:
    nStartX and nStartY are the starting position of the "turtle".
    nStartAngle is the angle direction that the turtle is pointing,
     in 100'ths of a degree.
    A spiral is drawn by moving the turtle forward and turning either left or right as it moves.
    nArcAngle is the angle of the first arc of the spiral,
     in 100'ths of a degree.
    nArcRadius is the radius of the first arc of the spiral.
    bTurnLeft is True if the turtle turns to the left, or False to turn to the right.
    nNumArcs is the number of arcs which are drawn.
    nRadiusGrowthMultiplier - the radius of the arc is multiplied by this after each arc is drawn.
     Use a number such as 1.1 to cause the radius to grow geometrically as the spiral turns.
    nRadiusGrowthAddIn - this is added to the radius after each arc.
     Use a number, such as the original nArcRadius / number of arcs in a complete circle to cause the radius to grow arithmeteically as the spiral turns.
    Four values are returned.
    (1) the spiral shape, (2) the new X position, (3) new Y position, and (4) new angle.
    Use the last three return values as initial values to draw another arc
     which is connected to the ending position of the arc just drawn.
    """
    nX = nStartX
    nY = nStartY
    nAngle = nStartAngle

    oShapesToGroup = createUnoService( "com.sun.star.drawing.ShapeCollection" )
    for i in range( nNumArcs - 1 ):
        oArcShape, nX, nY, nAngle = drawArcPath( oDrawDoc, oDrawPage, nX, nY, nAngle, nArcAngle, nArcRadius, bTurnLeft )
        nArcRadius = nArcRadius * nRadiusGrowthMultiplier + nRadiusGrowthAddIn

        oShapesToGroup.add( oArcShape )
    oSpiralShape = oDrawPage.group( oShapesToGroup )
    return oSpiralShape, nX, nY, nAngle



#------------------------------------------------------------
#   Styles
#------------------------------------------------------------


def defineGraphicsStyle( oDrawDoc, cStyleName, cParentStyleName=None ):
    """Add a new style to the style catalog if it is not already present.
    This returns the style object so that you can alter its properties.
    """
    return defineStyle( oDrawDoc, "graphics", cStyleName, cParentStyleName )


def getGraphicsStyle( oDrawDoc, cStyleName ):
    """Lookup and return a graphics style from the document.
    """
    return getStyle( oDrawDoc, "graphics", cStyleName )





#------------------------------------------------------------
#   General Utility functions
#------------------------------------------------------------

def normalizeOOoAngle( nAngleOOo ):
    """Given an angle in 100'ths of a degree,
    adjust it to be from 0 to 360 degrees."""
    if nAngleOOo < 0:
        nSign = -1
    else:
        nSign = 1
    nAngleOOo = nAngleOOo - (int( abs( nAngleOOo ) / 36000.0 ) * 36000 * nSign)
    if nAngleOOo < 0:
        nAngleOOo += 36000
    return nAngleOOo

_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Nov 20, 2004 12:27 pm    Post subject: Reply with quote

Danny.OOo.PrintToWriter.py

This makes it easy and convenient to print a bunch of text into a Writer document.

See the example routine in the module that shows how easy this module is to use, and how useful it can be.


Code:
#**********************************************************************
#
#   Danny.OOo.PrintToWriter.py
#
#   This makes it easy and convenient to print a bunch of text into
#    a Writer document.
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2004-06-05-01
#
#**********************************************************************




# OOo's libraries
import uno

# Danny's libraries
from Danny.OOo.OOoLib import StarDesktop


com_sun_star_text_ControlCharacter_PARAGRAPH_BREAK  = uno.getConstantByName( "com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK" )
com_sun_star_text_ControlCharacter_LINE_BREAK       = uno.getConstantByName( "com.sun.star.text.ControlCharacter.LINE_BREAK" )
com_sun_star_text_ControlCharacter_HARD_HYPHEN      = uno.getConstantByName( "com.sun.star.text.ControlCharacter.HARD_HYPHEN" )
com_sun_star_text_ControlCharacter_SOFT_HYPHEN      = uno.getConstantByName( "com.sun.star.text.ControlCharacter.SOFT_HYPHEN" )
com_sun_star_text_ControlCharacter_HARD_SPACE       = uno.getConstantByName( "com.sun.star.text.ControlCharacter.HARD_SPACE" )
com_sun_star_text_ControlCharacter_APPEND_PARAGRAPH = uno.getConstantByName( "com.sun.star.text.ControlCharacter.APPEND_PARAGRAPH" )



class PrintToWriter:
    """A class which allows conveniently printing stuff into a Writer document.
    Very useful for debugging, general output purposes, or even for creating reports."""
    def __init__( self ):
        self.oWriterDoc = StarDesktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, () )
        self.oWriterText = self.oWriterDoc.getText()
        self.oWriterCursor = self.oWriterText.createTextCursor()

    def writeLn( self, *args ):
        if len( args ) > 0:
            apply( self.write, args )
        self.writeParagraphBreak()

    def write( self, arg1, *argsRest ):
        self.writeOne( arg1 )
        for arg in argsRest:
            self.writeTab()
            self.writeOne( arg )

    def writeOne( self, arg, bAbsorb=False ):
        self.writeString( str( arg ), bAbsorb )

    def writeTab( self, bAbsorb=False ):
        self.writeString( "\t", bAbsorb )

    def writeParagraphBreak( self, bAbsorb=False ):
        self.writeControlCharacter( com_sun_star_text_ControlCharacter_PARAGRAPH_BREAK, bAbsorb )

    def writeString( self, cString, bAbsorb=False ):
        self.oWriterText.insertString( self.oWriterCursor, cString, bAbsorb )

    def writeControlCharacter( self, nCtrlChar, bAbsorb=False ):
        self.oWriterText.insertControlCharacter( self.oWriterCursor, nCtrlChar, bAbsorb )




def example_PrintToWriter():
    """An example of how to use the PrintToWriter class to trivially create
    a new Writer document, and write out text into it."""
    oOutput = PrintToWriter()
    oOutput.writeLn( "Hello World" )
    oOutput.write( "String", 123, 456.23, True )
    oOutput.writeLn()
    oOutput.writeLn()

    oOutput.writeLn( "Tab delimited values..." )
   
    oOutput.write( 123 )
    oOutput.writeTab()
    oOutput.write( 456 )
    oOutput.writeTab()
    oOutput.write( 789 )
    oOutput.writeLn()
   
    oOutput.write( 465 )
    oOutput.writeTab()
    oOutput.write( 522 )
    oOutput.writeTab()
    oOutput.write( 835 )
    oOutput.writeLn()
   
    oOutput.write( 886 )
    oOutput.writeTab()
    oOutput.write( 164 )
    oOutput.writeTab()
    oOutput.write( 741 )
    oOutput.writeLn()

_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Nov 20, 2004 12:35 pm    Post subject: Reply with quote

Danny.OOo.ConfigLib.py

Routines for working with the Configuration Manager.

Here are examples of how I use my getConfigAccess() function in Basic.

create top level menus
http://www.oooforum.org/forum/viewtopic.php?p=23391&highlight=getconfigaccess#23391
how many times can you undo?
http://www.oooforum.org/forum/viewtopic.php?p=45487&highlight=getconfigaccess#45487
disable automatic spellchecking
http://www.oooforum.org/forum/viewtopic.php?p=40339&highlight=getconfigaccess#40339
install custom toolbar items
http://www.oooforum.org/forum/viewtopic.php?p=29341&highlight=getconfigaccess#29341
and many other uses. Basically, useful anytime you need to access or modify configuration nodes.



Code:
#**********************************************************************
#
#   Danny.OOo.ConfigLib.py
#
#   A module to easily work with OpenOffice.org.
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2004-06-20-01
#
#**********************************************************************



# OOo's libraries
import uno
import unohelper

# Danny's libraries
from Danny.OOo.OOoLib import createUnoService, createUnoStruct
from Danny.OOo.OOoLib import makePropertyValue
from Danny.OOo.OOoLib import getServiceManager



def getConfigAccess( cNodePath, bWriteAccess=False, bEnableSync=True, bLazyWrite=False ):
    """An easy way to obtain a configuration node from the configuration manager."""
    oConfigProvider = getServiceManager().createInstanceWithArguments(
   "com.sun.star.configuration.ConfigurationProvider",
   ( makePropertyValue( "enablesync", bEnableSync ), ) )
   
    if bWriteAccess:
        cServiceName = "com.sun.star.configuration.ConfigurationUpdateAccess"
    else:
        cServiceName = "com.sun.star.configuration.ConfigurationAccess"

    oConfigAccess = oConfigProvider.createInstanceWithArguments( cServiceName,
        ( makePropertyValue( "nodepath", cNodePath ),
          makePropertyValue( "lazywrite", bLazyWrite ), ) )

    return oConfigAccess


# oConfigAccess = getConfigAccess( "/org.openoffice.Office.Addons/AddonUI" )
# oElement = oConfigAccess.getByName( "AddonMenu" )
# tNames = oElement.getElementNames()

_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Nov 20, 2004 12:51 pm    Post subject: Reply with quote

Danny.OOo.DialogLib.py

A class to build a dialog box from the com.sun.star.awt.* services. This doesn't do anything you couldn't already do using OOo's UNO API, this just makes it much easier.

You can change the dialog box size, position, title, etc. You can add controls, and listeners for those controls to the dialog box. This class can be used by subclassing it, or without subclassing it.

This module depends upon Danny.OOo.Listeners.ListenerProcAdapters.py found elsewhere in this thread.

Previously, I have shown an example in Basic of how to create dialog boxes on the fly without using the Basic IDE.
http://www.oooforum.org/forum/viewtopic.php?p=11765#11765


NOTE: this class is not yet complete, but I have not worked on it for a long time, and decided to publish it here.

Code:
#**********************************************************************
#
#   Danny.OOo.DialogLib.py
#
#   A module to easily work with OpenOffice.org.
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2004-06-05-01
#
#**********************************************************************



# OOo's libraries
import uno
import unohelper

# Danny's libraries
from Danny.OOo.OOoLib import createUnoService, createUnoStruct
from Danny.OOo.Listeners.ListenerProcAdapters import *
#from Danny.OOo.Listeners.TopWindowListener import TopWindowListener



# The global Awt Toolkit.
# This is initialized the first time it is needed.
#goAwtToolkit = createUnoService( "com.sun.star.awt.Toolkit" )
goAwtToolkit = None
#
def getAwtToolkit():
    global goAwtToolkit
    if goAwtToolkit == None:
        goAwtToolkit = createUnoService( "com.sun.star.awt.Toolkit" )
    return goAwtToolkit



# This class builds dialog boxes.
# This can be used in two different ways...
# 1. by subclassing it (elegant)
# 2. without subclassing it (less elegant)
class DBModalDialog:
    """Class to build a dialog box from the com.sun.star.awt.* services.
    This doesn't do anything you couldn't already do using OOo's UNO API,
     this just makes it much easier.
    You can change the dialog box size, position, title, etc.
    You can add controls, and listeners for those controls to the dialog box.
    This class can be used by subclassing it, or without subclassing it.
    """
    def __init__( self, nPositionX=None, nPositionY=None, nWidth=None, nHeight=None, cTitle=None ):
        self.oDialogModel = createUnoService( "com.sun.star.awt.UnoControlDialogModel" )
        if nPositionX != None:  self.oDialogModel.PositionX = nPositionX
        if nPositionY != None:  self.oDialogModel.PositionY = nPositionY
        if nWidth     != None:  self.oDialogModel.Width     = nWidth
        if nHeight    != None:  self.oDialogModel.Height    = nHeight
        if cTitle     != None:  self.oDialogModel.Title     = cTitle
        self.oDialogControl = createUnoService( "com.sun.star.awt.UnoControlDialog" )
        self.oDialogControl.setModel( self.oDialogModel )

    def release( self ):
        """Release resources.
        After calling this, you can no longer use this object.
        """
        self.oDialogControl.dispose()

    #--------------------------------------------------
    #   Dialog box adjustments
    #--------------------------------------------------
   
    def setDialogPosition( self, nX, nY ):
        self.oDialogModel.PositionX = nX
        self.oDialogModel.PositionY = nY

    def setDialogSize( self, nWidth, nHeight ):
        self.oDialogModel.Width = nWidth
        self.oDialogModel.Height = nHeight

    def setDialogTitle( self, cCaption ):
        self.oDialogModel.Title = cCaption

    def setVisible( self, bVisible ):
        self.oDialogControl.setVisible( bVisible )


    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlButton
    #--------------------------------------------------

    # After you add a Button control, you can call self.setControlModelProperty()
    #  passing any of the properties for a...
    #       com.sun.star.awt.UnoControlButtonModel
    #       com.sun.star.awt.UnoControlDialogElement
    #       com.sun.star.awt.UnoControlModel
    def addButton( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                       cLabel=None,
                       actionListenerProc=None,
                       nTabIndex=None ):
        self.addControl( "com.sun.star.awt.UnoControlButtonModel",
                         cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                         cLabel=cLabel,
                         nTabIndex=nTabIndex )
        if actionListenerProc != None:
            self.addActionListenerProc( cCtrlName, actionListenerProc )

    def setButtonLabel( self, cCtrlName, cLabel ):
        """Set the label of the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setLabel( cLabel )
   
    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlCheckBox
    #--------------------------------------------------

    # After you add a CheckBox control, you can call self.setControlModelProperty()
    #  passing any of the properties for a...
    #       com.sun.star.awt.UnoControlCheckBoxModel
    #       com.sun.star.awt.UnoControlDialogElement
    #       com.sun.star.awt.UnoControlModel
    def addCheckBox( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                       cLabel=None,
                       itemListenerProc=None,
                       nTabIndex=None ):
        self.addControl( "com.sun.star.awt.UnoControlCheckBoxModel",
                         cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                         cLabel=cLabel,
                         nTabIndex=nTabIndex )
        if itemListenerProc != None:
            self.addItemListenerProc( cCtrlName, itemListenerProc )

    def setCheckBoxLabel( self, cCtrlName, cLabel ):
        """Set the label of the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setLabel( cLabel )

    def getCheckBoxState( self, cCtrlName ):
        """Get the state of the control."""
        oControl = self.getControl( cCtrlName )
        return oControl.getState();

    def setCheckBoxState( self, cCtrlName, nState ):
        """Set the state of the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setState( nState )

    def enableCheckBoxTriState( self, cCtrlName, bTriStateEnable ):
        """Enable or disable the tri state mode of the control."""
        oControl = self.getControl( cCtrlName )
        oControl.enableTriState( bTriStateEnable )

   
    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlFixedText
    #--------------------------------------------------

    def addFixedText( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                        cLabel=None ):
        self.addControl( "com.sun.star.awt.UnoControlFixedTextModel",
                         cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                         cLabel=cLabel )
           
    #--------------------------------------------------
    #   Add Controls to dialog
    #--------------------------------------------------

    def addControl( self, cCtrlServiceName,
                        cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                        cLabel=None,
                        nTabIndex=None ):
        oControlModel = self.oDialogModel.createInstance( cCtrlServiceName )
        self.oDialogModel.insertByName( cCtrlName, oControlModel )

        # if negative coordinates are given for X or Y position,
        #  then make that coordinate be relative to the right/bottom
        #  edge of the dialog box instead of to the left/top.
        if nPositionX < 0: nPositionX = self.oDialogModel.Width  + nPositionX - nWidth
        if nPositionY < 0: nPositionY = self.oDialogModel.Height + nPositionY - nHeight
        oControlModel.PositionX = nPositionX
        oControlModel.PositionY = nPositionY
        oControlModel.Width = nWidth
        oControlModel.Height = nHeight
        oControlModel.Name = cCtrlName
       
        if cLabel != None:
            oControlModel.Label = cLabel

        if nTabIndex != None:
            oControlModel.TabIndex = nTabIndex

    #--------------------------------------------------
    #   Access controls and control models
    #--------------------------------------------------

    def getControl( self, cCtrlName ):
        """Get the control (not its model) for a particular control name.
        The control returned includes the service com.sun.star.awt.UnoControl,
         and another control-specific service which inherits from it.
        """
        oControl = self.oDialogControl.getControl( cCtrlName )
        return oControl

    def getControlModel( self, cCtrlName ):
        """Get the control model (not the control) for a particular control name.
        The model returned includes the service UnoControlModel,
         and another control-specific service which inherits from it.
        """
        oControl = self.getControl( cCtrlName )
        oControlModel = oControl.getModel()
        return oControlModel


    #--------------------------------------------------
    #   Adjust properties of control models
    #--------------------------------------------------

    def setControlModelProperty( self, cCtrlName, cPropertyName, uValue ):
        """Set the value of a property of a control's model.
        This affects the control model, not the control.
        """
        oControlModel = self.getControlModel( cCtrlName )
        oControlModel.setPropertyValue( cPropertyName, uValue )

    def getControlModelProperty( self, cCtrlName, cPropertyName ):
        """Get the value of a property of a control's model.
        This affects the control model, not the control.
        """
        oControlModel = self.getControlModel( cCtrlName )
        return oControlModel.getPropertyValue( cPropertyName )


    #--------------------------------------------------
    #   Sugar coated property adjustments to control models.
    #--------------------------------------------------

    def setEnabled( self, cCtrlName, bEnabled=True ):
        """Supported controls...
            UnoControlButtonModel
            UnoControlCheckBoxModel
        """
        self.setControlModelProperty( cCtrlName, "Enabled", bEnabled )

    def getEnabled( self, cCtrlName ):
        """Supported controls...
            UnoControlButtonModel
            UnoControlCheckBoxModel
        """
        return self.getControlModelProperty( cCtrlName, "Enabled" )

    def setState( self, cCtrlName, nState ):
        """Supported controls...
            UnoControlButtonModel
            UnoControlCheckBoxModel
        """
        self.setControlModelProperty( cCtrlName, "State", nState )

    def getState( self, cCtrlName ):
        """Supported controls...
            UnoControlButtonModel
            UnoControlCheckBoxModel
        """
        return self.getControlModelProperty( cCtrlName, "State" )

    def setLabel( self, cCtrlName, cLabel ):
        """Supported controls...
            UnoControlButtonModel
            UnoControlCheckBoxModel
        """
        self.setControlModelProperty( cCtrlName, "Label", cLabel )

    def getLabel( self, cCtrlName ):
        """Supported controls...
            UnoControlButtonModel
            UnoControlCheckBoxModel
        """
        return self.getControlModelProperty( cCtrlName, "Label" )

    def setHelpText( self, cCtrlName, cHelpText ):
        """Supported controls...
            UnoControlButtonModel
            UnoControlCheckBoxModel
        """
        self.setControlModelProperty( cCtrlName, "HelpText", cHelpText )

    def getHelpText( self, cCtrlName ):
        """Supported controls...
            UnoControlButtonModel
            UnoControlCheckBoxModel
        """
        return self.getControlModelProperty( cCtrlName, "HelpText" )


    #--------------------------------------------------
    #   Adjust controls (not models)
    #--------------------------------------------------

    # The following apply to all controls which are a
    #   com.sun.star.awt.UnoControl

    def setDesignMode( self, cCtrlName, bDesignMode=True ):
        oControl = self.getControl( cCtrlName )
        oControl.setDesignMode( bDesignMode )

    def isDesignMode( self, cCtrlName, bDesignMode=True ):
        oControl = self.getControl( cCtrlName )
        return oControl.isDesignMode()
 
    def isTransparent( self, cCtrlName, bDesignMode=True ):
        oControl = self.getControl( cCtrlName )
        return oControl.isTransparent()
     

    # The following apply to all controls which are a
    #   com.sun.star.awt.UnoControlDialogElement

    def setPosition( self, cCtrlName, nPositionX, nPositionY ):
        self.setControlModelProperty( cCtrlName, "PositionX", nPositionX )
        self.setControlModelProperty( cCtrlName, "PositionY", nPositionY )
    def setPositionX( self, cCtrlName, nPositionX ):
        self.setControlModelProperty( cCtrlName, "PositionX", nPositionX )
    def setPositionY( self, cCtrlName, nPositionY ):
        self.setControlModelProperty( cCtrlName, "PositionY", nPositionY )
    def getPositionX( self, cCtrlName ):
        return self.getControlModelProperty( cCtrlName, "PositionX" )
    def getPositionY( self, cCtrlName ):
        return self.getControlModelProperty( cCtrlName, "PositionY" )

    def setSize( self, cCtrlName, nWidth, nHeight ):
        self.setControlModelProperty( cCtrlName, "Width", nWidth )
        self.setControlModelProperty( cCtrlName, "Height", nHeight )
    def setWidth( self, cCtrlName, nWidth ):
        self.setControlModelProperty( cCtrlName, "Width", nWidth )
    def setHeight( self, cCtrlName, nHeight ):
        self.setControlModelProperty( cCtrlName, "Height", nHeight )
    def getWidth( self, cCtrlName ):
        return self.getControlModelProperty( cCtrlName, "Width" )
    def getHeight( self, cCtrlName ):
        return self.getControlModelProperty( cCtrlName, "Height" )

    def setTabIndex( self, cCtrlName, nWidth, nTabIndex ):
        self.setControlModelProperty( cCtrlName, "TabIndex", nTabIndex )
    def getTabIndex( self, cCtrlName ):
        return self.getControlModelProperty( cCtrlName, "TabIndex" )

    def setStep( self, cCtrlName, nWidth, nStep ):
        self.setControlModelProperty( cCtrlName, "Step", nStep )
    def getStep( self, cCtrlName ):
        return self.getControlModelProperty( cCtrlName, "Step" )

    def setTag( self, cCtrlName, nWidth, cTag ):
        self.setControlModelProperty( cCtrlName, "Tag", cTag )
    def getTag( self, cCtrlName ):
        return self.getControlModelProperty( cCtrlName, "Tag" )


    #--------------------------------------------------
    #   Add listeners to controls.
    #--------------------------------------------------

    # This applies to...
    #   UnoControlButton
    def addActionListenerProc( self, cCtrlName, actionListenerProc ):
        """Create an com.sun.star.awt.XActionListener object and add it to a control.
        A listener object is created which will call the python procedure actionListenerProc.
        The actionListenerProc can be either a method or a global procedure.
        The following controls support XActionListener:
            UnoControlButton
        """
        oControl = self.getControl( cCtrlName )
        oActionListener = ActionListenerProcAdapter( actionListenerProc )
        oControl.addActionListener( oActionListener )

    # This applies to...
    #   UnoControlCheckBox
    def addItemListenerProc( self, cCtrlName, itemListenerProc ):
        """Create an com.sun.star.awt.XItemListener object and add it to a control.
        A listener object is created which will call the python procedure itemListenerProc.
        The itemListenerProc can be either a method or a global procedure.
        The following controls support XActionListener:
            UnoControlCheckBox
        """
        oControl = self.getControl( cCtrlName )
        oActionListener = ItemListenerProcAdapter( itemListenerProc )
        oControl.addItemListener( oActionListener )

    #--------------------------------------------------
    #   Display the modal dialog.
    #--------------------------------------------------

    def doModalDialog( self ):
        """Display the dialog as a modal dialog."""
        self.oDialogControl.setVisible( True )
        self.oDialogControl.execute()

    def endExecute( self ):
        """Call this from within one of the listeners to end the modal dialog.
        For instance, the listener on your OK or Cancel button would call this to end the dialog.
        """
        self.oDialogControl.endExecute()






#--------------------------------------------------
# Example of Dialog box built by subclassing the DBModalDialog class.

class Test1Dialog( DBModalDialog ):
    def __init__( self ):
        DBModalDialog.__init__( self )
        self.setDialogPosition( 60, 50 )
        self.setDialogSize( 150, 80 )
        self.setDialogTitle( "My Test1 Dialog" )
        self.addButton( "btnOK", -10, -10, 30, 14, "OK",
                        actionListenerProc = self.btnOK_clicked )
        self.addButton( "btnCancel", -50, -10, 30, 14, "Cancel",
                        actionListenerProc = self.btnCancel_clicked )
        self.nOkClicks = 0
        self.nCancelClicks = 0

    # Called when the OK button is clicked.
    def btnOK_clicked( self, oActionEvent ):
        self.nOkClicks += 1

    # Called when the Cancel button is clicked.
    def btnCancel_clicked( self, oActionEvent ):
        self.nCancelClicks += 1

def Test1():
    oTestDialog =  Test1Dialog()

    # Display dialog box.
    # This does not return until the dialog box is dismissed.
    oTestDialog.doModalDialog()
   
    # Print out the global button click counters.
    print oTestDialog.nCancelClicks, oTestDialog.nOkClicks



#--------------------------------------------------
# Example of modal creating a dialog box without subclassing DBModalDialog.

# Global vars to keep track of button clicks.
nOkClicks = 0
nCancelClicks = 0
# Global procs, called as event listeners on button clicks.
def OKClicked( oActionEvent ):
    global nOkClicks
    nOkClicks += 1
def CancelClicked( oActionEvent ):
    global nCancelClicks
    nCancelClicks += 1

# Create a modal dialog box without subclassing DBModalDialog.
def Test2():
    oTestDialog = DBModalDialog( 60, 50, 150, 80, "My Test2 Dialog" )
    oTestDialog.addButton( "btnOK", -10, -10, 30, 14, "OK" )
    oTestDialog.addButton( "btnCancel", -50, -10, 30, 14, "Cancel" )
    oTestDialog.addFixedText( "lbl01", 10, 10, 30, 14, "Test1" )

    # Install global event listener procs.
    # Use the addActionListenerProc() routine instead of supplying the event
    #  listener to the addButton() as in first example.
    oTestDialog.addActionListenerProc( "btnOK", OKClicked )
    oTestDialog.addActionListenerProc( "btnCancel", CancelClicked )

    # Display dialog box.
    # This does not return until the dialog box is dismissed.
    oTestDialog.doModalDialog()

    # Print out the global button click counters.
    print nCancelClicks, nOkClicks




#--------------------------------------------------
# Example of Dialog box built by subclassing the DBModalDialog class.

class ModalDoggieKittyMonkeyDialog( DBModalDialog ):
    def __init__( self ):       
        self.nNumDoggies = 0
        self.nNumKitties = 0
        self.nNumMonkeys = 0
        self.bTails = False
        self.bOkay = False

        DBModalDialog.__init__( self, 60, 50, 200, 90, "Doggie/Kitty/Monkey Dialog" )

        # Add an OK and a Cancel button.
        # Both buttons share an action listener named "self.btnOkOrCancel_clicked".
        self.addButton( "btnOK", -10, -10, 50, 14, "OK",
                        actionListenerProc = self.btnOkOrCancel_clicked )
        self.addButton( "btnCancel", -10 - 50 - 10, -10, 50, 14, "Cancel",
                        actionListenerProc = self.btnOkOrCancel_clicked )

        # Add three buttons.
        self.addButton( "btnDoggie", 5, 10, 50, 14, "Add Doggie",
                        actionListenerProc = self.btnDoggie_Clicked )
        self.addButton( "btnKitty", 5, 30, 50, 14, "Add Kitty",
                        actionListenerProc = self.btnKitty_Clicked )
        self.addButton( "btnMonkey", 5, 50, 50, 14, "Add Monkey",
                        actionListenerProc = self.btnMonkey_Clicked )

        # Add a label to the dialog.
        self.addFixedText( "lbl1", 60, 10, 100, 14, "Add some doggies, kitties, and monkeys." )

        # Add a checkbox to the dialog.
        self.addCheckBox( "chkTails", 60, 30, 50, 14, "With tails",
                          itemListenerProc = self.chkTails_changed )

    def btnOkOrCancel_clicked( self, oActionEvent ):
        """Called when the OK or Cancel button is clicked."""
        if oActionEvent.Source.getModel().Name == "btnOK":
            self.bOkay = True
        self.endExecute()

    def btnDoggie_Clicked( self, oActionEvent ):
        """Called with the Doggie button is clicked."""
        self.nNumDoggies += 1

    def btnKitty_Clicked( self, oActionEvent ):
        """Called with the Kitty button is clicked."""
        self.nNumKitties += 1

    def btnMonkey_Clicked( self, oActionEvent ):
        """Called with the Monkey button is clicked."""
        self.nNumMonkeys += 1

    def chkTails_changed( self, oItemEvent ):
        """Called when the Tails checkbox is clicked."""
        self.bTails = self.getState( "chkTails" )


def Test3():
    oTestDialog = ModalDoggieKittyMonkeyDialog()
    oTestDialog.doModalDialog()
   
    # Print out the global button click counters.
    print oTestDialog.nNumDoggies, oTestDialog.nNumKitties, oTestDialog.nNumMonkeys
    print "okay:",oTestDialog.bOkay," tails:",oTestDialog.bTails, oTestDialog.getState( "chkTails" )





#>>> import Danny.OOo.DialogLib
#>>> reload( Danny.OOo.DialogLib ); from Danny.OOo.DialogLib import *



Just adding a cross reference....
http://www.oooforum.org/forum/viewtopic.phtml?p=96917#96917
Please note that accabrown's ComboBox support needs to also add appropriate comments to any other methods (in above code) which now also work with a ComboBox. Thanks accabrown for this bit of code. I had planned to come back to the dialog box and add support for a bunch of other control types, but then I got distracted by working on the modeless window class, and then by other non-OOo things.
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Wed Oct 12, 2005 12:12 pm; edited 3 times in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Nov 20, 2004 1:00 pm    Post subject: Reply with quote

Danny.OOo.Listeners.ListenerProcAdapters.py

This module has various helpers that make it extremely easy to create listeners on the fly, and make them call an arbitrary python procedure.

A brief explanation....

For instance, when you want to attach a listener to a button, you would call the button's addActionListener(). But you need to pass an actual listener implementation to addActionListener(). With the classes in this module, you can trivially create a listener like this....

Code:
oActionListener = ActionListenerProcAdapter( YourPythonProcName )

def YourPythonProcName( oEvent ):
   # do whatever you want with the oEvent parameter.

oSomeButton.addActionListener( oActionListener )


In fact you can simply do this....
Code:
oSomeButton.addActionListener( ActionListenerProcAdapter( YourProc ) )


Hopefully, you will agree that this makes it easy to attach listeners to buttons, combo boxes, listboxes, etc.

But wait! There's more. You can add additional arbitrary parameters to your listener proc. That way you can use the same listener proc for multiple buttons.
Code:
def YourButtonListener( oEvent, cBtnName ):
   # do whatever you want with the oEvent parameter.
   # also you can look at the cBtnName parameter to tell what button is presed

oSomeButton1.addActionListener( ActionListenerProcAdapter( YourButtonListener, "Meow Mix" ) )
oSomeButton2.addActionListener( ActionListenerProcAdapter( YourButtonListener, "Cat Chew" ) )

Now when button 1 is clicked, the cBtnName parameter will receive the string "Meow Mix", and then button 2 clicked, it will get "Cat Chew".

Now how much would you pay!

This module is used by the DialogLib and WindowLib modules.


Code:
#**********************************************************************
#
#   Danny.OOo.Listeners.ListenerProcAdapters.py
#
#   A module to easily work with OpenOffice.org.
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2004-06-05-01
#
#**********************************************************************



# OOo's libraries
import uno
import unohelper




#--------------------------------------------------
# An ActionListener adapter.
# This object implements com.sun.star.awt.XActionListener.
# When actionPerformed is called, this will call an arbitrary
#  python procedure, passing it...
#   1. the oActionEvent
#   2. any other parameters you specified to this object's constructor (as a tuple).
from com.sun.star.awt import XActionListener
class ActionListenerProcAdapter( unohelper.Base, XActionListener ):
    def __init__( self, oProcToCall, tParams=() ):
        self.oProcToCall = oProcToCall # a python procedure
        self.tParams = tParams # a tuple

    # oActionEvent is a com.sun.star.awt.ActionEvent struct.
    def actionPerformed( self, oActionEvent ):
        if callable( self.oProcToCall ):
            apply( self.oProcToCall, (oActionEvent,) + self.tParams )


#--------------------------------------------------
# An ItemListener adapter.
# This object implements com.sun.star.awt.XItemListener.
# When itemStateChanged is called, this will call an arbitrary
#  python procedure, passing it...
#   1. the oItemEvent
#   2. any other parameters you specified to this object's constructor (as a tuple).
from com.sun.star.awt import XItemListener
class ItemListenerProcAdapter( unohelper.Base, XItemListener ):
    def __init__( self, oProcToCall, tParams=() ):
        self.oProcToCall = oProcToCall # a python procedure
        self.tParams = tParams # a tuple

    # oItemEvent is a com.sun.star.awt.ItemEvent struct.
    def itemStateChanged( self, oItemEvent ):
        if callable( self.oProcToCall ):
            apply( self.oProcToCall, (oItemEvent,) + self.tParams )


#--------------------------------------------------
# An TextListener adapter.
# This object implements com.sun.star.awt.XTextistener.
# When textChanged is called, this will call an arbitrary
#  python procedure, passing it...
#   1. the oTextEvent
#   2. any other parameters you specified to this object's constructor (as a tuple).
from com.sun.star.awt import XTextListener
class TextListenerProcAdapter( unohelper.Base, XTextListener ):
    def __init__( self, oProcToCall, tParams=() ):
        self.oProcToCall = oProcToCall # a python procedure
        self.tParams = tParams # a tuple

    # oTextEvent is a com.sun.star.awt.TextEvent struct.
    def textChanged( self, oTextEvent ):
        if callable( self.oProcToCall ):
            apply( self.oProcToCall, (oTextEvent,) + self.tParams )

_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Nov 20, 2004 1:12 pm    Post subject: Reply with quote

Danny.OOo.Listeners.TopWindowListener.py

This is similar in purpose to the Danny.OOo.Listeners.ListenerProcAdapters.py module.

This one is NOT an adapter however. It is a class that you subclass. Your subclass does not need to implement every possible listener method, because you inherit the empty implementations from this class. So when you need to add a window listener to a TopWindow, this class comes in very handy.



Code:
#**********************************************************************
#
#   Danny.OOo.Listeners.TopWindowListener.py
#
#   A module to easily work with OpenOffice.org.
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2004-06-05-01
#
#**********************************************************************



# OOo's libraries
import uno
import unohelper

from com.sun.star.awt import XTopWindowListener


class TopWindowListener( XTopWindowListener ):
    """An empty implementation of com.sun.star.awt.XTopWindowListener.
    It is useful for you to be able to subclass from this.
    """
    # NOTE:
    # If you subclass from this, you must either:
    #  1. also subclass from unohelper.Base.
    #  2. or otherwise implement com.sun.star.lang.XTypeProvider.


    #----------------------------------------
    #   Interface:  XTopWindowListener
    #
    #   This interface is implemented so that your subclass
    #    can conveniently override these methods!
    #
    #   Note that com.sun.star.lang.EventObject has the following members:
    #       Source  which is a  com.sun.star.uno.XInterface
    #           refers to the object that fired the event.
    #----------------------------------------

    # [oneway] void
    # windowOpened( [in] com.sun.star.lang.EventObject tEvent );
    def windowOpened( self, tEvent ):
        """is invoked when a window has been opened."""
        pass

    # [oneway] void
    # windowClosing( [in] com.sun.star.lang.EventObject tEvent );
    def windowClosing( self, tEvent ):
        """is invoked when a window is in the process of being closed.
        The close operation can be overridden at this point."""
        pass

    # [oneway] void
    # windowClosed( [in] com.sun.star.lang.EventObject tEvent );
    def windowClosed( self, tEvent ):
        """is invoked when a window has been closed."""
        pass

    # [oneway] void
    # windowMinimized( [in] com.sun.star.lang.EventObject tEvent );
    def windowMinimized( self, tEvent ):
        """is invoked when a window is iconified."""
        pass

    # [oneway] void
    # windowNormalized( [in] com.sun.star.lang.EventObject tEvent );
    def windowNormalized( self, tEvent ):
        """is invoked when a window is de-iconified."""
        pass

    # [oneway] void
    # windowActivated( [in] com.sun.star.lang.EventObject tEvent );
    def windowActivated( self, tEvent ):
        """is invoked when a window is activated."""
        pass

    # [oneway] void
    # windowDeactivated( [in] com.sun.star.lang.EventObject tEvent );
    def windowDeactivated( self, tEvent ):
        """is invoked when a window is de-activated."""
        pass

_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Nov 20, 2004 1:18 pm    Post subject: Reply with quote

Danny.OOo.WindowLib.py

A class to build a modeless window from the com.sun.star.awt.* services. This doesn't do anything you couldn't already do using OOo's UNO API, this just makes it much easier.

This class IS NOT the actual OOo window, but you can get the OOo window or frame by calling getWindow() or getFrame() on this class.

You can change the window size, position, title, etc. You can add controls, and listeners for those controls to the window. This class can be used by subclassing it, or without subclassing it.

For an example of how to use this module, see this thread.


Code:
#**********************************************************************
#
#   Danny.OOo.WindowLib.py
#
#   A module to easily work with OpenOffice.org.
#
#**********************************************************************
#   Copyright (c) 2003-2004 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2004-06-05-02
#
#**********************************************************************



# OOo's libraries
import uno
import unohelper

# Danny's libraries
from Danny.OOo.OOoLib import createUnoService, createUnoStruct
from Danny.OOo.OOoLib import makeRectangle, StarDesktop
#
from Danny.OOo.Listeners.ListenerProcAdapters import *


#----------
#   com.sun.star.awt.WindowAttribute
#
# specifies that the window is initially visible.
com_sun_star_awt_WindowAttribute_SHOW        = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.SHOW" )
# specifies that the window fills the complete desktop area.
com_sun_star_awt_WindowAttribute_FULLSIZE    = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.FULLSIZE" )
com_sun_star_awt_WindowAttribute_OPTIMUMSIZE = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.OPTIMUMSIZE" )
com_sun_star_awt_WindowAttribute_MINSIZE     = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.MINSIZE" )
# specifies that the window has visible borders.
com_sun_star_awt_WindowAttribute_BORDER      = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.BORDER" )
# specifies that the size of the window can be changed by the user.
com_sun_star_awt_WindowAttribute_SIZEABLE    = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.SIZEABLE" )
# specifies that the window can be moved by the user.
com_sun_star_awt_WindowAttribute_MOVEABLE    = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.MOVEABLE" )
# specifies that the window can be closed by the user.
com_sun_star_awt_WindowAttribute_CLOSEABLE   = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.CLOSEABLE" )
#[ DEPRECATED ] specifies that the window should support the XSystemDependentWindowPeer interface.
com_sun_star_awt_WindowAttribute_SYSTEMDEPENDENT = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.SYSTEMDEPENDENT" )


# Default window attributes.
# The DBWindow class (and subclasses) use this as the default window attributes
#  when you don't specify any window attributes on the constructor.
gnDefaultWindowAttributes = \
        com_sun_star_awt_WindowAttribute_SHOW + \
        com_sun_star_awt_WindowAttribute_BORDER + \
        com_sun_star_awt_WindowAttribute_MOVEABLE + \
        com_sun_star_awt_WindowAttribute_CLOSEABLE
        # we could have addedd...
        #com_sun_star_awt_WindowAttribute_SIZEABLE



# The global Awt Toolkit.
# This is initialized the first time it is needed.
#goAwtToolkit = createUnoService( "com.sun.star.awt.Toolkit" )
goAwtToolkit = None
#
def getAwtToolkit():
    global goAwtToolkit
    if goAwtToolkit == None:
        goAwtToolkit = createUnoService( "com.sun.star.awt.Toolkit" )
    return goAwtToolkit



# This class is a sugar coated abstraction for OOo's Awt Window.
# This can be used in two different ways...
# 1. by subclassing it (elegant)
# 2. without subclassing it (less elegant)
class DBWindow:
    """Class to build a modeless window from the com.sun.star.awt.* services.
    This doesn't do anything you couldn't already do using OOo's UNO API,
     this just makes it much easier.
    This class IS NOT the actual OOo window, but you can get the OOo window or frame by calling getWindow() or getFrame() on this class.
    You can change the window size, position, title, etc.
    You can add controls, and listeners for those controls to the window.
    This class can be used by subclassing it, or without subclassing it.
    """
    def __init__( self, cTitle=None, tBoundsRect=None, nWindowAttributes=None ):
        oAwtToolkit = getAwtToolkit()
        oWindowDesc = self.createMyWindowDescriptor( tBoundsRect, nWindowAttributes )
        self.oWindow = oAwtToolkit.createWindow( oWindowDesc )
       
        # At this point, if you stop the program, you will have a
        #  new OOo window on the screen, but you cannot do anything
        #  with it.  You cannot even close it!
        # In fact, you have to kill the OOo process, as even OOo
        #  cannot close this window since it has no Frame and
        #  therefore is not integrated into the desktop environment.
        # So we need to create a Frame for our window....

        # Create a new frame.
        self.oFrame = createUnoService( "com.sun.star.frame.Frame" )
        # Initialize this frame with our new window.
        self.oFrame.initialize( self.oWindow )
        # Tell the frame that its parent is the Desktop.
        self.oFrame.setCreator( StarDesktop )

        if cTitle != None:
            self.setWindowTitle( cTitle )

        # A collection of controls on this window.  (NOT control models, but controls.)
        self.controls = {}

    def createMyWindowDescriptor( self, tBoundsRect=None, nWindowAttributes=None ):
        """This returns the com.sun.star.awt.WindowDescriptor that will be used to create this window.
        Your subclass can override this method to provide a modified window descriptor."""
        if tBoundsRect == None:
            tBoundsRect = makeRectangle( 100, 200, 300, 400 )
        if nWindowAttributes == None:
            nWindowAttributes = gnDefaultWindowAttributes
        oAwtToolkit = getAwtToolkit()
       
        oWindowDesc = createUnoStruct( "com.sun.star.awt.WindowDescriptor" )
       
        # specifies a top level window on the desktop. It is also a container.
        oWindowDesc.Type = uno.getConstantByName( "com.sun.star.awt.WindowClass.TOP" )
       
        # specifies the name of the component service.
        # A zero length name means that the vcl creates a blank top,
        #  a container, or a simple window.
        oWindowDesc.WindowServiceName = ""
       
        # specifies the parent of the component.
        # If Parent == 0 && ParentIndex == -1 , then the window is on the desktop.
        oWindowDesc.Parent = oAwtToolkit.getDesktopWindow()
        # specifies the index of the parent window, if available.
        # If Parent == 0 and this struct is a member of an array,
        #  then this is the offset from the beginning of the array to the parent.
        #  A value of -1 means desktop.
        oWindowDesc.ParentIndex = -1
       
        # specifies the position and size of the window.
        # This member is ignored if the window attribute has
        #  WindowAttribute::FULLSIZE .
        oWindowDesc.Bounds = tBoundsRect
       
        # specifies the window attributes.
        oWindowDesc.WindowAttributes = nWindowAttributes

        return oWindowDesc

    #--------------------------------------------------
    #   The following two methods
    #   getWindow() and getFrame()
    #   return the two objects that this class manages.
    #--------------------------------------------------

    def getWindow( self ):
        """Return the OOo Awt Window that this object represents.
        The window object returned has the following interfaces...
            com.sun.star.awt.XTopWindow
            com.sun.star.awt.XWindow
            com.sun.star.awt.XWindowPeer
            com.sun.star.awt.XVclContainer      [deprecated]
            com.sun.star.awt.XVclContainerPeer  [deprecated]
            com.sun.star.awt.XVclWindowPeer     [deprecated]
            com.sun.star.awt.XLayoutConstraints
            com.sun.star.awt.XView
            com.sun.star.awt.XDevice
            com.sun.star.lang.XEventListener
            com.sun.star.lang.XComponent
            com.sun.star.lang.XTypeProvider
            com.sun.star.accessibility.XAccessible
        Properties...
            <object>    MenuBar
            <array>     Windows
            <array>     Group
            <object>    PosSize
            Boolean     Visible
            Boolean     Enable
            <object>    Toolkit
            <object>    Pointer
            Long        Background
            Boolean     DesignMode
            Long        Foreground
            <object>    ControlFont
            <object>    MinimumSize
            <object>    PreferredSize
            <object>    AccessibleContext
            <object>    Graphics
            <object>    Size
            <object>    Info
            <array>     FontDescriptors
        """
        return self.oWindow
   
    def getFrame( self ):
        """Return the Frame for the OOo Awt Window that this object represents."""
        return self.oFrame

    #--------------------------------------------------
    #   The following methods represent part of the sugar coating
    #    that this class provides to manage the window.
    #--------------------------------------------------

    def windowClose( self ):
        """Close the window frame."""
        self.getFrame().close( True )
        self.oFrame = None
        self.oWindow = None

    def windowToFront( self ):
        """places this window at the top of the stacking order and shows it in front of any other windows."""
        # By looking at the following line of code,
        #  and by looking at the list of interfaces from the comment in the getWindow() method,
        #  you should be able to figure out how to do lots of other things to this window.
        self.getWindow().toFront()

    def windowToBack( self ):
        """ places this window at the bottom of the stacking order and makes the corresponding adjustment to other visible windows."""
        self.getWindow().toBack()

    def setWindowTitle( self, cTitle ):
        """Set the title of the window that this object represents."""
        # By looking at the following line of code,
        #  and by looking at the com.sun.star.frame.Frame service,
        #  you should be able to figure out how to do lots of other things to this window.
        self.getFrame().Title = cTitle

    def getWindowTitle( self ):
        """Get the title of the window that this object represents"""
        return self.getFrame().Title

    def setWindowBackground( self, nColor ):
        """Set the background color of the window that this object represents."""
        self.getWindow().setBackground( nColor )

    def getWindowGraphics( self ):
        """Returns a com.sun.star.awt.XGraphics for the window that this object represents.
        You can then call methods on the XGraphics to draw things into this window."""
        return self.getWindow().getGraphics()

    def setWindowPosSize( self, nX, nY, nWidth, nHeight ):
        """Set the position and size of the window."""
        self.getWindow().setPosSize( nX, nY, nWidth, nHeight,
                                     uno.getConstantByName( "com.sun.star.awt.PosSize.POSSIZE" ) )
    def setWindowPosition( self, nX, nY ):
        """Set the position of the window."""
        self.getWindow().setPosSize( nX, nY, 0, 0,
                                     uno.getConstantByName( "com.sun.star.awt.PosSize.POS" ) )
    def setWindowSize( self, nWidth, nHeight ):
        """Set the position and size of the window."""
        self.getWindow().setPosSize( 0, 0, nWidth, nHeight,
                                     uno.getConstantByName( "com.sun.star.awt.PosSize.SIZE" ) )
    def getWindowPosSize( self ):
        """Returns a com.sun.star.awt.Rectangle that contains the position and size of this window."""
        return self.getWindow().getPosSize()

    def setWindowVisible( self, bVisible ):
        """Make this window (in)visible."""
        self.getWindow().setVisible( bVisible )
    def setWindowEnable( self, bEnable ):
        """Make this window (dis)enabled."""
        self.getWindow().setEnable( bEnable )

    def setWindowFocus( self ):
        """Set the focus to this window."""
        self.getWindow().setFocus()


    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlButton
    #--------------------------------------------------

    def addButton( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                        cLabel=None,
                        actionListenerProc=None ):
        """Add a Button control to the window."""
        oControlModel = createUnoService( "com.sun.star.awt.UnoControlButtonModel" )
        oControl      = createUnoService( oControlModel.DefaultControl ) # Create a control and its model.
        oControl.setModel( oControlModel )                              # Introduce the model to the control.
        oControl.createPeer( getAwtToolkit(), self.getWindow() )        # Make the control create its window peer.
        # Keep a dictionary of controls we are managing in the window.
        self.controls[ cCtrlName ] = oControl
        # Set position and size
        self.setPosSize( cCtrlName, nPositionX, nPositionY, nWidth, nHeight )

        if cLabel != None:
            oControlModel.Label = cLabel

        if actionListenerProc != None:
            self.addActionListenerProc( cCtrlName, actionListenerProc )

    def setButtonLabel( self, cCtrlName, cLabel ):
        """Set the label of the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setLabel( cLabel )

   
    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlCheckBox
    #--------------------------------------------------

    def addCheckBox( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                        cLabel=None,
                        itemListenerProc=None ):
        """Add a CheckBox control to the window."""
        oControlModel = createUnoService( "com.sun.star.awt.UnoControlCheckBoxModel" )
        oControl      = createUnoService( oControlModel.DefaultControl ) # Create a control and its model.
        oControl.setModel( oControlModel )                              # Introduce the model to the control.
        oControl.createPeer( getAwtToolkit(), self.getWindow() )        # Make the control create its window peer.
        # Keep a dictionary of controls we are managing in the window.
        self.controls[ cCtrlName ] = oControl
        # Set position and size
        self.setPosSize( cCtrlName, nPositionX, nPositionY, nWidth, nHeight )

        if cLabel != None:
            oControlModel.Label = cLabel

        if itemListenerProc != None:
            self.addItemListenerProc( cCtrlName, itemListenerProc )

    def setCheckBoxLabel( self, cCtrlName, cLabel ):
        """Set the label of the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setLabel( cLabel )

    def getCheckBoxState( self, cCtrlName ):
        """Get the state of the control."""
        oControl = self.getControl( cCtrlName )
        return oControl.getState();

    def setCheckBoxState( self, cCtrlName, nState ):
        """Set the state of the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setState( nState )

    def enableCheckBoxTriState( self, cCtrlName, bTriStateEnable ):
        """Enable or disable the tri state mode of the control."""
        oControl = self.getControl( cCtrlName )
        oControl.enableTriState( bTriStateEnable )

   
    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlComboBox
    #--------------------------------------------------

    def addComboBox( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                        bDropdown=True,
                        itemListenerProc=None,
                        actionListenerProc=None ):
        """Add a ComboBox control to the window."""
        oControlModel = createUnoService( "com.sun.star.awt.UnoControlComboBoxModel" )
        oControlModel.Dropdown = bDropdown
        oControl      = createUnoService( oControlModel.DefaultControl ) # Create a control and its model.
        oControl.setModel( oControlModel )                              # Introduce the model to the control.
        oControl.createPeer( getAwtToolkit(), self.getWindow() )        # Make the control create its window peer.
        # Keep a dictionary of controls we are managing in the window.
        self.controls[ cCtrlName ] = oControl
        # Set position and size
        self.setPosSize( cCtrlName, nPositionX, nPositionY, nWidth, nHeight )

        if itemListenerProc != None:
            self.addItemListenerProc( cCtrlName, itemListenerProc )
        if actionListenerProc != None:
            self.addActionListenerProc( cCtrlName, actionListenerProc )

    def addComboBoxItem( self, cCtrlName, cItemText, nPosition=-1 ):
        """Add an item to the ComboBox at specified position."""
        oControl = self.getControl( cCtrlName )
        if nPosition == -1: nPosition = self.getComboBoxItemCount( cCtrlName )
        oControl.addItem( cItemText, nPosition )

    def addComboBoxItems( self, cCtrlName, tcItemTexts, nPosition=0 ):
        """Add a tupple of items to the ComboBox at specified position."""
        oControl = self.getControl( cCtrlName )
        oControl.addItems( tcItemTexts, nPosition )

    def removeComboBoxItems( self, cCtrlName, nPosition, nCount=1 ):
        """Remove items from a ComboBox."""
        oControl = self.getControl( cCtrlName )
        oControl.removeItems( nPosition, nCount )

    def getComboBoxItemCount( self, cCtrlName ):
        """Get the number of items in a ComboBox."""
        oControl = self.getControl( cCtrlName )
        return oControl.getItemCount()

    def getComboBoxItem( self, cCtrlName, nPosition ):
        """Return the item at specified position within the ComboBox."""
        oControl = self.getControl( cCtrlName )
        return oControl.getItem( nPosition )

    def getComboBoxItems( self, cCtrlName ):
        """Return a tupple of all items in the ComboBox."""
        oControl = self.getControl( cCtrlName )
        return oControl.getItems()

    def getComboBoxDropDownLineCount( self, cCtrlName ):
        """Returns the number of visible lines in the drop down mode."""
        oControl = self.getControl( cCtrlName )
        return oControl.getDropDownLineCount()

    def setComboBoxDropDownLineCount( self, cCtrlName, nNumLines ):
        """Sets the number of visible lines in the drop down mode."""
        oControl = self.getControl( cCtrlName )
        oControl.setDropDownLineCount( nNumLines )

    def getComboBoxText( self, cCtrlName ):
        """Get the text of the ComboBox."""
        oControl = self.getControl( cCtrlName )
        return oControl.getText();

    def setComboBoxText( self, cCtrlName, cText ):
        """Set the text of the ComboBox."""
        oControl = self.getControl( cCtrlName )
        oControl.setText( cText )

    def insertComboBoxText( self, cCtrlName, cText, nMinSelection, nMaxSelection ):
        """Insert text at specified position in the ComboBox."""
        oControl = self.getControl( cCtrlName )
        tSelection = Selection()
        tSelection.Min = nMinSelection
        tSelection.Max = nMaxSelection
        oControl.insertText( tSelection, cText )

    def getComboBoxSelectedText( self, cCtrlName ):
        """Get the selected text of the ComboBox."""
        oControl = self.getControl( cCtrlName )
        return oControl.getSelectedText();

    def getComboBoxSelection( self, cCtrlName ):
        """Get the selection of the ComboBox.
        This is a com.sun.star.awt.Selection struct with members Min and Max."""
        oControl = self.getControl( cCtrlName )
        return oControl.getSelection()

    def isComboBoxEditable( self, cCtrlName ):
        """Indicate whether the text in the ComboBox is editable by the user."""
        oControl = self.getControl( cCtrlName )
        return oControl.isEditable()

    def setComboBoxEditable( self, cCtrlName, bEditable ):
        """Set whether the text in the ComboBox is editable by the user."""
        oControl = self.getControl( cCtrlName )
        oControl.setEditable( bEditable )

    def setComboBoxMaxTextLen( self, cCtrlName, nMaxLen ):
        """Set the maximum text length the ComboBox can have."""
        oControl = self.getControl( cCtrlName )
        oControl.setMaxTextLen( nMaxLen )

    def getComboBoxMaxTextLen( self, cCtrlName ):
        """Get the maximum text length the ComboBox can have."""
        oControl = self.getControl( cCtrlName )
        oControl.getMaxTextLen()

   
    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlEdit
    #--------------------------------------------------

    def addEdit( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                        cText=None,
                        textListenerProc=None ):
        """Add a Edit control to the window."""
        oControlModel = createUnoService( "com.sun.star.awt.UnoControlEditModel" )
        oControl      = createUnoService( oControlModel.DefaultControl ) # Create a control and its model.
        oControl.setModel( oControlModel )                              # Introduce the model to the control.
        oControl.createPeer( getAwtToolkit(), self.getWindow() )        # Make the control create its window peer.
        # Keep a dictionary of controls we are managing in the window.
        self.controls[ cCtrlName ] = oControl
        # Set position and size
        self.setPosSize( cCtrlName, nPositionX, nPositionY, nWidth, nHeight )

        if cText != None:
            self.setEditText( cCtrlName, cText )
        if textListenerProc != None:
            self.addTextListenerProc( cCtrlName, textListenerProc )

    def getEditText( self, cCtrlName ):
        """Get the text of the edit box."""
        oControl = self.getControl( cCtrlName )
        return oControl.getText();

    def setEditText( self, cCtrlName, cText ):
        """Set the text of the edit box."""
        oControl = self.getControl( cCtrlName )
        oControl.setText( cText )

    def insertEditText( self, cCtrlName, cText, nMinSelection, nMaxSelection ):
        """Insert text at specified position in the edit box."""
        oControl = self.getControl( cCtrlName )
        tSelection = Selection()
        tSelection.Min = nMinSelection
        tSelection.Max = nMaxSelection
        oControl.insertText( tSelection, cText )

    def getEditSelectedText( self, cCtrlName ):
        """Get the selected text of the edit box."""
        oControl = self.getControl( cCtrlName )
        return oControl.getSelectedText();

    def getEditSelection( self, cCtrlName ):
        """Get the selection of the edit box.
        This is a com.sun.star.awt.Selection struct with members Min and Max."""
        oControl = self.getControl( cCtrlName )
        return oControl.getSelection()

    def isEditEditable( self, cCtrlName ):
        """Indicate whether the text in the edit box is editable by the user."""
        oControl = self.getControl( cCtrlName )
        return oControl.isEditable()

    def setEditEditable( self, cCtrlName, bEditable ):
        """Set whether the text in the edit box is editable by the user."""
        oControl = self.getControl( cCtrlName )
        oControl.setEditable( bEditable )

    def setEditMaxTextLen( self, cCtrlName, nMaxLen ):
        """Set the maximum text length the edit box can have."""
        oControl = self.getControl( cCtrlName )
        oControl.setMaxTextLen( nMaxLen )

    def getEditMaxTextLen( self, cCtrlName ):
        """Get the maximum text length the edit box can have."""
        oControl = self.getControl( cCtrlName )
        oControl.getMaxTextLen()

       
    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlFixedText
    #--------------------------------------------------

    def addFixedText( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                        cLabel=None ):
        """Add a FixedText control to the window."""
        oControlModel = createUnoService( "com.sun.star.awt.UnoControlFixedTextModel" )
        oControl      = createUnoService( oControlModel.DefaultControl ) # Create a control and its model.
        oControl.setModel( oControlModel )                              # Introduce the model to the control.
        oControl.createPeer( getAwtToolkit(), self.getWindow() )        # Make the control create its window peer.
        # Keep a dictionary of controls we are managing in the window.
        self.controls[ cCtrlName ] = oControl
        # Set position and size
        self.setPosSize( cCtrlName, nPositionX, nPositionY, nWidth, nHeight )

        if cLabel != None:
            oControlModel.Label = cLabel

    def getFixedTextText( self, cCtrlName ):
        """Get the text of the control."""
        oControl = self.getControl( cCtrlName )
        return oControl.getText();

    def setFixedTextText( self, cCtrlName, cText ):
        """Set the text of the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setText( cText )

    def getFixedTextAlignment( self, cCtrlName ):
        """Get the alignment of the control.  0:left, 1:center, 2:right"""
        oControl = self.getControl( cCtrlName )
        return oControl.getAlignment();

    def setFixedTextAlignment( self, cCtrlName, nAlignment ):
        """Set the alignment of the control.  0:left, 1:center, 2:right"""
        oControl = self.getControl( cCtrlName )
        oControl.setAlignment( nAlignment )

       
    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlImageControl
    #--------------------------------------------------

    def addImageControl( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                         nBorder=1 ):
        """Add an ImageControl control to the window.
        nBorder = 0:none, 1:3D border, 2:simple border"""
        oControlModel = createUnoService( "com.sun.star.awt.UnoControlImageControlModel" )
        oControlModel.Border = nBorder
        oControl      = createUnoService( oControlModel.DefaultControl ) # Create a control and its model.
        oControl.setModel( oControlModel )                              # Introduce the model to the control.
        oControl.createPeer( getAwtToolkit(), self.getWindow() )        # Make the control create its window peer.
        # Keep a dictionary of controls we are managing in the window.
        self.controls[ cCtrlName ] = oControl
        # Set position and size
        self.setPosSize( cCtrlName, nPositionX, nPositionY, nWidth, nHeight )

    def getImageControlImageURL( self, cCtrlName ):
        """Get the ImageURL of the control."""
        self.getControlModelProperty( cCtrlName, "ImageURL" )

    def setImageControlImageURL( self, cCtrlName, cImageURL ):
        """Get the ImageURL of the control."""
        self.setControlModelProperty( cCtrlName, "ImageURL", cImageURL )


    #--------------------------------------------------
    #   com.sun.star.awt.UnoControlListBox
    #--------------------------------------------------

    def addListBox( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight,
                        bDropdown=False,
                        itemListenerProc=None,
                        actionListenerProc=None ):
        """Add a ComboBox control to the window."""
        oControlModel = createUnoService( "com.sun.star.awt.UnoControlListBoxModel" )
        oControlModel.Dropdown = bDropdown
        oControl      = createUnoService( oControlModel.DefaultControl ) # Create a control and its model.
        oControl.setModel( oControlModel )                              # Introduce the model to the control.
        oControl.createPeer( getAwtToolkit(), self.getWindow() )        # Make the control create its window peer.
        # Keep a dictionary of controls we are managing in the window.
        self.controls[ cCtrlName ] = oControl
        # Set position and size
        self.setPosSize( cCtrlName, nPositionX, nPositionY, nWidth, nHeight )

        if itemListenerProc != None:
            self.addItemListenerProc( cCtrlName, itemListenerProc )
        if actionListenerProc != None:
            self.addActionListenerProc( cCtrlName, actionListenerProc )

    def addListBoxItem( self, cCtrlName, cItemText, nPosition=-1 ):
        """Add an item to the ListBox at specified position."""
        oControl = self.getControl( cCtrlName )
        if nPosition == -1: nPosition = self.getComboBoxItemCount( cCtrlName )
        oControl.addItem( cItemText, nPosition )

    def addListBoxItems( self, cCtrlName, tcItemTexts, nPosition=0 ):
        """Add a tupple of items to the ListBox at specified position."""
        oControl = self.getControl( cCtrlName )
        oControl.addItems( tcItemTexts, nPosition )

    def removeListBoxItems( self, cCtrlName, nPosition, nCount=1 ):
        """Remove items from a ListBox."""
        oControl = self.getControl( cCtrlName )
        oControl.removeItems( nPosition, nCount )

    def getListBoxItemCount( self, cCtrlName ):
        """Get the number of items in a ListBox."""
        oControl = self.getControl( cCtrlName )
        return oControl.getItemCount()

    def getListBoxItem( self, cCtrlName, nPosition ):
        """Return the item at specified position within the ListBox."""
        oControl = self.getControl( cCtrlName )
        return oControl.getItem( nPosition )

    def getListBoxItems( self, cCtrlName ):
        """Return a tupple of all items in the ListBox."""
        oControl = self.getControl( cCtrlName )
        return oControl.getItems()

    def getListBoxSelectedItemPos( self, cCtrlName ):
        """Returns the position of the currently selected item."""
        oControl = self.getControl( cCtrlName )
        return oControl.getSelectedItemPos()

    def getListBoxSelectedItemsPos( self, cCtrlName ):
        """Returns the positions of all currently selected items."""
        oControl = self.getControl( cCtrlName )
        return oControl.getSelectedItemsPos()

    def getListBoxSelectedItem( self, cCtrlName ):
        """Returns the currently selected item."""
        oControl = self.getControl( cCtrlName )
        return oControl.getSelectedItem()

    def getListBoxSelectedItems( self, cCtrlName ):
        """Returns all currently selected items."""
        oControl = self.getControl( cCtrlName )
        return oControl.getSelectedItems()

    def selectListBoxItemPos( self, cCtrlName, nItemPos, bSelect=True ):
        """Select/Deselect the item at the specified position."""
        oControl = self.getControl( cCtrlName )
        return oControl.selectItemPos( nItemPos, bSelect )

    def selectListBoxItemsPos( self, cCtrlName, tnItemPos, bSelect=True ):
        """Selects/Deselects the items at the specified positions."""
        oControl = self.getControl( cCtrlName )
        return oControl.selectItemsPos( tnItemPos, bSelect )

    def selectListBoxItem( self, cCtrlName, cItemText, bSelect=True ):
        """Selects/Deselects the ispecified item."""
        oControl = self.getControl( cCtrlName )
        return oControl.selectItem( cItemText, bSelect )

    def isListBoxMultipleMode( self, cCtrlName ):
        """Selects/Deselects the ispecified item."""
        oControl = self.getControl( cCtrlName )
        return oControl.isMutipleMode()

    def setListBoxMultipleMode( self, cCtrlName, bMultipleMode ):
        """Selects/Deselects the ispecified item."""
        oControl = self.getControl( cCtrlName )
        return oControl.setMutipleMode( bMultipleMode )

    def getListBoxDropDownLineCount( self, cCtrlName ):
        """Returns the number of visible lines in the drop down mode."""
        oControl = self.getControl( cCtrlName )
        return oControl.getDropDownLineCount()

    def setListBoxDropDownLineCount( self, cCtrlName, nNumLines ):
        """Sets the number of visible lines in the drop down mode."""
        oControl = self.getControl( cCtrlName )
        oControl.setDropDownLineCount( nNumLines )

    def makeListBoxItemVisible( self, nItemPos ):
        """Makes the item at the specified position visible by scrolling the list box."""
        oControl = self.getControl( cCtrlName )
        oControl.makeVisible( nItemPos )

   
    #--------------------------------------------------
    #   Access controls and control models
    #--------------------------------------------------

    def getControl( self, cCtrlName ):
        """Get the control (not its model) for a particular control name.
        The control returned includes the service com.sun.star.awt.UnoControl,
         and another control-specific service which inherits from it.
        """
        oControl = self.controls[ cCtrlName ]
        return oControl


    def getControlModel( self, cCtrlName ):
        """Get the control model (not the control) for a particular control name.
        The model returned includes the service UnoControlModel,
         and another control-specific service which inherits from it.
        """
        oControl = self.getControl( cCtrlName )
        oControlModel = oControl.getModel()
        return oControlModel


    #--------------------------------------------------
    #   Adjust properties of control models
    #--------------------------------------------------

    def setControlModelProperty( self, cCtrlName, cPropertyName, uValue ):
        """Set the value of a property of a control's model.
        This affects the control model, not the control.
        """
        oControlModel = self.getControlModel( cCtrlName )
        oControlModel.setPropertyValue( cPropertyName, uValue )

    def getControlModelProperty( self, cCtrlName, cPropertyName ):
        """Get the value of a property of a control's model.
        This affects the control model, not the control.
        """
        oControlModel = self.getControlModel( cCtrlName )
        return oControlModel.getPropertyValue( cPropertyName )
     

    #--------------------------------------------------
    #   Adjust controls (not models)
    #--------------------------------------------------

    # The following apply to all controls which are a
    #   com.sun.star.awt.UnoControl
    # (which means all controls)

    def setDesignMode( self, cCtrlName, bDesignMode=True ):
        oControl = self.getControl( cCtrlName )
        oControl.setDesignMode( bDesignMode )

    def isDesignMode( self, cCtrlName, bDesignMode=True ):
        oControl = self.getControl( cCtrlName )
        return oControl.isDesignMode()
 
    def isTransparent( self, cCtrlName, bDesignMode=True ):
        oControl = self.getControl( cCtrlName )
        return oControl.isTransparent()

    def setPosSize( self, cCtrlName, nPositionX, nPositionY, nWidth, nHeight ):
        """Set the position and size of the window."""
        oControl = self.getControl( cCtrlName )
        # if negative coordinates are given for X or Y position,
        #  then make that coordinate be relative to the right/bottom
        #  edge of the window instead of to the left/top.
        if nPositionX < 0  or  nPositionY < 0:
            oWindowPosSizeRect = self.getWindowPosSize()
            if nPositionX < 0: nPositionX = oWindowPosSizeRect.Width  + nPositionX - nWidth
            if nPositionY < 0: nPositionY = oWindowPosSizeRect.Height + nPositionY - nHeight
        oControl.setPosSize( nPositionX, nPositionY, nWidth, nHeight,
                                     uno.getConstantByName( "com.sun.star.awt.PosSize.POSSIZE" ) )
    def setPosition( self, cCtrlName, nPositionX, nPositionY ):
        """Set the position of the window."""
        oControl = self.getControl( cCtrlName )
        # if negative coordinates are given for X or Y position,
        #  then make that coordinate be relative to the right/bottom
        #  edge of the window instead of to the left/top.
        if nPositionX < 0  or  nPositionY < 0:
            oCtrlPosSizeRect = oControl.getPosSize()
            oWindowPosSizeRect = self.getWindowPosSize()
            if nPositionX < 0: nPositionX = oWindowPosSizeRect.Width  + nPositionX - oCtrlPosSizeRect.Width
            if nPositionY < 0: nPositionY = oWindowPosSizeRect.Height + nPositionY - oCtrlPosSizeRect.Height
        oControl.setPosSize( nPositionX, nPositionY, 0, 0,
                                     uno.getConstantByName( "com.sun.star.awt.PosSize.POS" ) )
    def setSize( self, cCtrlName, nWidth, nHeight ):
        """Set the position and size of the window."""
        oControl = self.getControl( cCtrlName )
        oControl.setPosSize( 0, 0, nWidth, nHeight,
                                     uno.getConstantByName( "com.sun.star.awt.PosSize.SIZE" ) )
    def getPosSize( self, cCtrlName ):
        """Returns a com.sun.star.awt.Rectangle that contains the position and size of this window."""
        oControl = self.getControl( cCtrlName )
        return oControl.getPosSize()

    def setVisible( self, cCtrlName, bVisible ):
        """Show or hide the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setVisible( bVisible )

    def setEnable( self, cCtrlName, bEnable ):
        """Enable or disable the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setEnable( bEnable )

    def setFocus( self, cCtrlName ):
        """Set focus to the control."""
        oControl = self.getControl( cCtrlName )
        oControl.setFocus()
   

    #--------------------------------------------------
    #   Add listeners to controls.
    #--------------------------------------------------

    # This applies to...
    #   UnoControlButton
    #   UnoControlComboBox
    def addActionListenerProc( self, cCtrlName, actionListenerProc ):
        """Create an com.sun.star.awt.XActionListener object and add it to a control.
        A listener object is created which will call the python procedure actionListenerProc.
        The actionListenerProc can be either a method or a global procedure.
        The following controls support XActionListener:
            UnoControlButton
        """
        oControl = self.getControl( cCtrlName )
        oActionListener = ActionListenerProcAdapter( actionListenerProc )
        oControl.addActionListener( oActionListener )

    # This applies to...
    #   UnoControlCheckBox
    #   UnoControlComboBox
    def addItemListenerProc( self, cCtrlName, itemListenerProc ):
        """Create an com.sun.star.awt.XItemListener object and add it to a control.
        A listener object is created which will call the python procedure itemListenerProc.
        The itemListenerProc can be either a method or a global procedure.
        The following controls support XActionListener:
            UnoControlCheckBox
        """
        oControl = self.getControl( cCtrlName )
        oActionListener = ItemListenerProcAdapter( itemListenerProc )
        oControl.addItemListener( oActionListener )

    # This applies to...
    #   UnoControlEdit
    def addTextListenerProc( self, cCtrlName, textListenerProc ):
        """Create an com.sun.star.awt.XTextListener object and add it to a control.
        A listener object is created which will call the python procedure textListenerProc.
        The textListenerProc can be either a method or a global procedure.
        The following controls support XTextListener:
            UnoControlEdit
        """
        oControl = self.getControl( cCtrlName )
        oTextListener = TextListenerProcAdapter( textListenerProc )
        oControl.addTextListener( oTextListener )
   





from com.sun.star.awt import XTopWindowListener
from com.sun.star.awt import XWindowListener
from com.sun.star.awt import XFocusListener
from com.sun.star.awt import XKeyListener
from com.sun.star.awt import XMouseListener
from com.sun.star.awt import XPaintListener
from com.sun.star.lang import XEventListener
class DBListenerWindow( DBWindow, unohelper.Base,
                            XKeyListener, XMouseListener, XPaintListener,
                            XFocusListener, XWindowListener, XTopWindowListener,
                            XEventListener ):
    """This is like a DBWindow, but has useful listener methods implemented directly in this class.
    You can easily subclass this class, and override the various listener methods from the interfaces implemented by this class.
    """
    def __init__( self, cTitle=None, tBoundsRect=None, nWindowAttributes=None ):
        DBWindow.__init__( self,
                    cTitle=cTitle,
                    tBoundsRect=tBoundsRect,
                    nWindowAttributes=nWindowAttributes )

        # Since this class implements the XTopWindowListener interface,
        #  add ourself as a listener to our own window.
        self.oWindow.addTopWindowListener( self )

        # Since this class implements the XWindowListener interface,
        #  add ourself as a listener to our own window.
        self.oWindow.addWindowListener( self )

        # Since this class implements the XFocusListener interface,
        #  add ourself as a listener to our own window.
        self.oWindow.addFocusListener( self )

        # Since this class implements the XKeyListener interface,
        #  add ourself as a listener to our own window.
        self.oWindow.addKeyListener( self )

        # Since this class implements the XMouseListener interface,
        #  add ourself as a listener to our own window.
        self.oWindow.addMouseListener( self )

        # Since this class implements the XPaintListener interface,
        #  add ourself as a listener to our own window.
        self.oWindow.addPaintListener( self )

    #--------------------------------------------------
    #   Interface:  XTopWindowListener
    #
    #   This interface is implemented so that your subclass
    #    can conveniently override these methods!
    #
    #   Note that com.sun.star.lang.EventObject has the following members:
    #       Source  which is a  com.sun.star.uno.XInterface
    #           refers to the object that fired the event.
    #--------------------------------------------------

    # [oneway] void
    # windowOpened( [in] com.sun.star.lang.EventObject tEvent );
    def windowOpened( self, tEvent ):
        """is invoked when a window has been opened."""
        pass

    # [oneway] void
    # windowClosing( [in] com.sun.star.lang.EventObject tEvent );
    def windowClosing( self, tEvent ):
        """is invoked when a window is in the process of being closed.
        The close operation can be overridden at this point."""
        self.getWindow().dispose()

    # [oneway] void
    # windowClosed( [in] com.sun.star.lang.EventObject tEvent );
    def windowClosed( self, tEvent ):
        """is invoked when a window has been closed."""
        pass

    # [oneway] void
    # windowMinimized( [in] com.sun.star.lang.EventObject tEvent );
    def windowMinimized( self, tEvent ):
        """is invoked when a window is iconified."""
        pass

    # [oneway] void
    # windowNormalized( [in] com.sun.star.lang.EventObject tEvent );
    def windowNormalized( self, tEvent ):
        """is invoked when a window is de-iconified."""
        pass

    # [oneway] void
    # windowActivated( [in] com.sun.star.lang.EventObject tEvent );
    def windowActivated( self, tEvent ):
        """is invoked when a window is activated."""
        pass

    # [oneway] void
    # windowDeactivated( [in] com.sun.star.lang.EventObject tEvent );
    def windowDeactivated( self, tEvent ):
        """is invoked when a window is de-activated."""
        pass

    #--------------------------------------------------
    #   Interface:  XWindowListener
    #
    #   This interface is implemented so that your subclass
    #    can conveniently override these methods!
    #
    #   Note that com.sun.star.awt.WindowEvent has the following members:
    #       long X      long Y
    #       long Width  long Height
    #       long LeftInset  long TopInset   long RightInset     long BottomInset
    #--------------------------------------------------

    # void
    # windowResized( [in] WindowEvent tEvent );
    def windowResized( self, tEvent ):
        """is invoked when the window has been resized."""
        pass

    # void
    # windowMoved( [in] WindowEvent tEvent );
    def windowMoved( self, tEvent ):
        """is invoked when the window has been moved."""
        pass

    # void
    # windowShown( [in] EventObject tEvent );
    def windowShown( self, tEvent ):
        """is invoked when the window has been shown."""
        # please note the type of parameter is described
        #  above in the comment for XTopWindowListener.
        pass

    # void
    # windowHidden( [in] EventObject tEvent );
    def windowHidden( self, tEvent ):
        """is invoked when the window has been hidden."""
        # please note the type of parameter is described
        #  above in the comment for XTopWindowListener.
        pass

    #--------------------------------------------------
    #   Interface:  XFocusListener
    #
    #   This interface is implemented so that your subclass
    #    can conveniently override these methods!
    #
    #   Note that com.sun.star.awt.FocusEvent has the following members:
    #       short FocusFlags
    #       com.sun.star.uno.XInterface NextFocus
    #       boolean Temporary
    #--------------------------------------------------

    # [oneway] void
    # focusGained( [in] FocusEvent tEvent );
    def focusGained( self, tEvent ):
        """ is invoked when a window gains the keyboard focus."""
        pass

    # [oneway] void
    # focusLost( [in] FocusEvent tEvent );
    def focusLost( self, tEvent ):
        """ is invoked when a window loses the keyboard focus."""
        pass

    #--------------------------------------------------
    #   Interface:  XKeyListener
    #
    #   This interface is implemented so that your subclass
    #    can conveniently override these methods!
    #
    #   Note that com.sun.star.awt.KeyEvent has the following members:
    #       short KeyCode   (constant from com.sun.star.awt.Key)
    #       char  KeyChar
    #       short KeyFunc   (constant from com.sun.star.awt.KeyFunction)
    #--------------------------------------------------

    # [oneway] void
    # keyPressed( [in] com.sun.star.awt.KeyEvent tEvent );
    def keyPressed( self, tEvent ):
        """ is invoked when a key has been pressed."""
        pass

    # [oneway] void
    # keyReleased( [in] com.sun.star.awt.KeyEvent tEvent );
    def keyReleased( self, tEvent ):
        """ is invoked when a key has been released."""
        pass

    #--------------------------------------------------
    #   Interface:  XMouseListener
    #
    #   This interface is implemented so that your subclass
    #    can conveniently override these methods!
    #
    #   Note that com.sun.star.awt.MouseEvent has the following members:
    #       short Buttons       (constant from com.sun.star.awt.MouseButton)
    #       short X     short Y
    #       long ClickCount
    #       boolean PupupTrigger
    #--------------------------------------------------

    # [oneway] void
    # mousePressed( [in] com.sun.star.awt.MouseEvent tEvent );
    def mousePressed( self, tEvent ):
        """is invoked when a mouse button has been pressed on a window."""
        pass

    # [oneway] void
    # mouseReleased( [in] com.sun.star.awt.MouseEvent tEvent );
    def mouseReleased( self, tEvent ):
        """is invoked when a mouse button has been released on a window."""
        pass

    # [oneway] void
    # mouseEntered( [in] com.sun.star.awt.MouseEvent tEvent );
    def mouseEntered( self, tEvent ):
        """is invoked when the mouse enters a window."""
        pass

    # [oneway] void
    # mouseExited( [in] com.sun.star.awt.MouseEvent tEvent );
    def mouseExited( self, tEvent ):
        """is invoked when the mouse exits a window."""
        pass

    #--------------------------------------------------
    #   Interface:  XPaintListener
    #
    #   This interface is implemented so that your subclass
    #    can conveniently override these methods!
    #
    #   Note that com.sun.star.awt.PaintEvent has the following members:
    #       com.sun.star.awt.Rectangle UpdateRect
    #       short Count
    #--------------------------------------------------

    # [oneway] void
    # windowPaint( [in] PaintEvent tEvent );
    def windowPaint( self, tEvent ):
        """ is invoked when a region of the window became invalid, e.g. when another window has been moved away."""
        pass

    #--------------------------------------------------
    #   Interface:  XEventListener
    #
    #   This interface is implemented so that your subclass
    #    can conveniently override these methods!
    #
    #   Note that com.sun.star.lang.EventObject has the following members:
    #       Source  which is a  com.sun.star.uno.XInterface
    #           refers to the object that fired the event.
    #--------------------------------------------------

    # void
    # disposing( [in] com.sun.star.lang.EventObject tEvent );
    def disposing( self, tEvent ):
        """gets called when the broadcaster is about to be disposed."""
        pass





# import Danny.OOo.WindowLib
# reload( Danny.OOo.WindowLib ); from Danny.OOo.WindowLib import *

_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat Mar 19, 2005 10:18 am    Post subject: Reply with quote

I just updated the first message in this thread.
It now has many links to python related articles on OOoForum, as well as a pointer to my updated instructions on how to use IDLE with OOo 2 beta
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


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

PostPosted: Sat May 21, 2005 11:23 am    Post subject: Reply with quote

Here is my HeapSort module. This is NOT an OOo related module, but I am posting it because someone asked.....
http://www.oooforum.org/forum/viewtopic.phtml?p=79025#79025

Code:
#**********************************************************************
#
#   Danny.HeapSort.py
#
#**********************************************************************
#   Copyright (c) 2005 Danny Brewer
#   d29583@groovegarden.com
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   See:  http://www.gnu.org/licenses/lgpl.html
#
#**********************************************************************
#   If you make changes, please append to the change log below.
#
#   Change Log
#   Danny Brewer         Revised 2005-03-29
#
#**********************************************************************


def SwapItems( items, nIndex1, nIndex2 ):
    """Swap two items in the sequence.  Return a new sequence with the swap.
    nIndex1 and nIndex2 are zero based."""
    item1 = items[nIndex1]
    item2 = items[nIndex2]
    items[nIndex1] = item2
    items[nIndex2] = item1
    return items

def ItemsCompareGreater( items, nIndex1, nIndex2 ):
    """Return True if the item at nIndex1 is greater than the item at nIndex2.
    nIndex1 and nIndex2 are zero based."""
    return items[nIndex1] > items[nIndex2]



def HeapSort( items,
                      compareGreaterProc=ItemsCompareGreater,
                      swapProc=SwapItems ):
    MakeHeap( items, compareGreaterProc, swapProc )
    nNumItems = len( items )
    for i in range( nNumItems-1, -1, -1 ):
        swapProc( items, 0, i )
        SiftHeap( items, i, 0, compareGreaterProc, swapProc )
    return items


def MakeHeap( items,
                      compareGreaterProc=ItemsCompareGreater,
                      swapProc=SwapItems ):
    nNumItems = len( items )
    for i in range( nNumItems-1, -1, -1 ):
        SiftHeap( items, nNumItems, i, compareGreaterProc, swapProc )


def SiftHeap( items, nHeapSize, nTheNode,
                      compareGreaterProc=ItemsCompareGreater,
                      swapProc=SwapItems ):
    nLargestNode = nTheNode
    while True:
        bNeedSwap = False
        nParentNode = nLargestNode

        nChildNode = nParentNode+nParentNode+1 # left child
        if( nChildNode < nHeapSize and compareGreaterProc( items, nChildNode, nLargestNode ) ):
            nLargestNode = nChildNode
            bNeedSwap = True

        nChildNode = nChildNode + 1 # right child
        if( nChildNode < nHeapSize and compareGreaterProc( items, nChildNode, nLargestNode ) ):
            nLargestNode = nChildNode
            bNeedSwap = True

        if bNeedSwap:
            swapProc( items, nParentNode, nLargestNode )
        else:
            break




Here is example of how to use...
Code:
Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

    ****************************************************************
    Personal firewall software may warn about the connection IDLE
    makes to its subprocess using this computer's internal loopback
    interface.  This connection is not visible on any external
    interface and no data is sent to or received from the Internet.
    ****************************************************************
   
IDLE 1.0     
>>> import Danny.HeapSort
>>> from Danny.HeapSort import *
>>> HeapSort( ["won","too","free","fore","phive","sicks","sevin","ate","nihn","tin"] )
['ate', 'fore', 'free', 'nihn', 'phive', 'sevin', 'sicks', 'tin', 'too', 'won']
>>>

_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
rpinterg
Newbie
Newbie


Joined: 21 Jun 2006
Posts: 3

PostPosted: Thu Jul 27, 2006 12:38 am    Post subject: ListenerProcAdapters Reply with quote

I would like to catch a mouse click on a Ooo document. I think it could be made in a similar way yor ListenerProcAdapters do. I have added this to the module:

#--------------------------------------------------
# An MouseHandler adapter.
# This object implements com.sun.star.awt.XMouseClickHandler.
# When a mouse click is done, this will call an arbitrary
# python procedure, passing it...
# 1. the oTextEvent
# 2. any other parameters you specified to this object's constructor (as a tuple).
from com.sun.star.awt import XMouseClickHandler
class MouseListenerProcAdapter( unohelper.Base, XMouseClickHandler ):
def __init__( self, oProcToCall, tParams=() ):
self.oProcToCall = oProcToCall # a python procedure
self.tParams = tParams # a tuple

# oTextEvent is a com.sun.star.awt.TextEvent struct.
def mouseReleased( self, oTextEvent ):
if callable( self.oProcToCall ):
apply( self.oProcToCall, (oTextEvent,) + self.tParams )

I have this code to handle the mouse click:

def MouseIsPressed(oEvt,cNombre):
# do something
print “mouse click”

def ListenToClick(model):
#Escuchar clicks
dv=model.getCurrentController()
oMouseListener=sltlib.MouseListenerProcAdapter(MouseIsPressed)
dv.addMouseClickHandler(oMouseListener)

I call ListenToClick in order to create the handler, passing de model I have retrieved previously in this way:

desktop = self.ctx.ServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", self.ctx )

# get current document model
model = desktop.getCurrentComponent()

When I call ListenToClick no error occurs, but when I click on the document nothing happens.

I could do this in Ooo Basic copying this exemple:

Sub RegisterMouseClickHandler
On Error Resume Next
oDocView = ThisComponent.currentController
oMouseClickHandler = createUnoListener("Salt_", "com.sun.star.awt.XMouseClickHandler")

oDocView.addMouseClickHandler(oMouseClickHandler)

End Sub

Now when I click on the document my function Salt_mouseReleased(oEvt) is executed

Can you help me anyway.

Thanks,
Back to top
View user's profile Send private message
pedromorgan
Newbie
Newbie


Joined: 14 Sep 2010
Posts: 1

PostPosted: Tue Sep 14, 2010 3:29 pm    Post subject: website Reply with quote

Danny, your modules are wonderful.

Is there a website dedicated to them?

can I create one ?

pete
_________________
Pedro
Back to top
View user's profile Send private message
hol.sten
Super User
Super User


Joined: 14 Nov 2004
Posts: 3533
Location: Hamburg, Germany

PostPosted: Thu Sep 16, 2010 7:33 am    Post subject: Re: website Reply with quote

pedromorgan wrote:
Danny, your modules are wonderful.

Is there a website dedicated to them?

can I create one ?

pete

DannyB hasn't wrote a post for some years now, so don't expect answers to your questions from him.
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets All times are GMT - 8 Hours
Goto page 1, 2  Next
Page 1 of 2

 
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