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


Hi Michael,

MessageBoxButtons as well as XSCRIPTCONTEXT do not exist for me. Python
doesn´t find them and they are documented as “not published” [1]. I
think it would be nice to use createMessageBox() and to have a dynamic
size and a nice error icon. But with the use of Laurent´s implementation
I could solve the task. [2]

With the modified mailmerge.py I get the expected pythonerror in a
messagebox after closing the MsgBox. [3] In fact all pythonerrors are
reported like this on my computer. What does it look like on nonfree
platforms? In fact it is better to display only one error message.

Not all python errors are reported in a message by default. If there are
syntax errors at the beginning of the file, office remains silent. This
is problem. 

When there is a MsgBox that works for everybody I suggest to implement
it into pythonscript.py so that it is being used for all exceptions. 


regards,

Timo


[1]
http://api.openoffice.org/docs/common/ref/com/sun/star/awt/MessageBoxButtons.html#BUTTONS_OK

[2] see mailmerge.py and MsgBox.py from the attachments

[3] see screenshot Bildschirmfoto.png


Am Montag, den 11.04.2011, 17:01 +0100 schrieb Michael Meeks:
Hi Timo,

On Sat, 2011-04-09 at 02:22 +0200, Timo wrote:
Is there a way to test the pythonfile within office? At the moment each
time i kill soffice, restart writer and click

      So - after a bit more digging; I got to here:

class MessageBox:
    def __init__(self, XParentWindow):
        try:
            if XParentWindow is None:
                frame = XSCRIPTCONTEXT.getDesktop().getCurrentFrame()
                XParentWindow = frame.getContainerWindow()
            self.Parent = XParentWindow
            self.Toolkit = XParentWindow.getToolkit()
        except:
            raise AttributeError, 'Did not get a valid parent window'

    def msgbox(self, message='', flag=0, title=''):
        '''Wrapper for com.sun.star.awt.XMessageBoxFactory.'''
        rect = uno.createUnoStruct('com.sun.star.awt.Rectangle')
        dlg = self.Toolkit.createMessageBox(self.Parent, rect, "errorbox", 1, title, message)
        dlg.execute()


      Which at least works for me, though I couldn't see why the
com.sun.star.awt.MessageBoxButtons set of constants wouldn't work nicely
for me.

      When I whack that into my system's TableSample.py and add:

    box = MessageBox(None)
    box.msgbox ("What is this ?")

      to createTable() - I get a nice message-box first :-) I bound running
that macro to F4 to make it quicker to loop iterate / check the code
 
      The UNO API is pretty fearsome to use, it can help to read the
interface comments in offapi/ but it is not for the faint hearted,
clearly :-)

      I guess, seeing how broken the C++ side is - with helpful comments
like:

    if(!bIsLoggedIn)
    {
        OSL_FAIL("create error message");
        return;
    }

      that simply don't create an error message, or do anything useful -
perhaps a chunk of the work needed is on the C++ side anyway.

      HTH,

              Michael.


Attachment: Bildschirmfoto.png
Description: PNG image

# Caolan McNamara caolanm@redhat.com
# a simple email mailmerge component

# manual installation for hackers, not necessary for users
# cp mailmerge.py /usr/lib/openoffice.org2.0/program
# cd /usr/lib/openoffice.org2.0/program
# ./unopkg add --shared mailmerge.py
# edit ~/.openoffice.org2/user/registry/data/org/openoffice/Office/Writer.xcu
# and change EMailSupported to as follows...
#  <prop oor:name="EMailSupported" oor:type="xs:boolean">
#   <value>true</value>
#  </prop>

import unohelper
import uno
import re

#to implement com::sun::star::mail::XMailServiceProvider
#and
#to implement com.sun.star.mail.XMailMessage

#from com.sun.star.awt.MessageBoxButtons import *
from com.sun.star.mail import XMailServiceProvider
from com.sun.star.mail import XMailService
from com.sun.star.mail import XSmtpService
from com.sun.star.mail import XConnectionListener
from com.sun.star.mail import XAuthenticator
from com.sun.star.mail import XMailMessage
from com.sun.star.mail.MailServiceType import SMTP
from com.sun.star.mail.MailServiceType import POP3
from com.sun.star.mail.MailServiceType import IMAP
from com.sun.star.uno import XCurrentContext
from com.sun.star.lang import IllegalArgumentException
from com.sun.star.lang import EventObject
from com.sun.star.mail import SendMailMessageFailedException

from email.MIMEBase import MIMEBase
from email.Message import Message
from email import Encoders
from email.Header import Header
from email.MIMEMultipart import MIMEMultipart
from email.Utils import formatdate
from email.Utils import parseaddr

from com.sun.star.awt import WindowDescriptor
from com.sun.star.awt.WindowClass import MODALTOP
#import com.sun.star.awt.VclWindowPeerAttribute as Buttons
import MsgBox

import sys, smtplib, imaplib, poplib

dbg = False

def showError(ctx,text):
                #localContext = uno.getComponentContext()
                #resolver = localContext.ServiceManager.createInstanceWithContext(
                #    "com.sun.star.bridge.UnoUrlResolver", localContext )
                #ctx = resolver.resolve( 
"uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
                #smgr = ctx.ServiceManager
                #toolkit = smgr.createInstanceWithContext(
                #                'com.sun.star.awt.Toolkit',
                #                ctx)
                box = MsgBox.MsgBox(ctx)
                box.addButton("OK")
                box.renderFromBoxSize(400)
                box.numberOfLines = 10
                box.show(text,0,"Error")
                exit(1) 

class PyMailSMTPService(unohelper.Base, XSmtpService):
        def __init__( self, ctx ):
                self.ctx = ctx
                self.listeners = []
                self.supportedtypes = ('Insecure', 'Ssl')
                self.server = None
                self.connectioncontext = None
                self.notify = EventObject()
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService init"
        def addConnectionListener(self, xListener):
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService addConnectionListener"
                self.listeners.append(xListener)
        def removeConnectionListener(self, xListener):
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService removeConnectionListener"
                self.listeners.remove(xListener)
        def getSupportedConnectionTypes(self):
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService getSupportedConnectionTypes"
                return self.supportedtypes
        def connect(self, xConnectionContext, xAuthenticator):
                self.connectioncontext = xConnectionContext
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService connect"
                server = xConnectionContext.getValueByName("ServerName")
                if dbg:
                        print >> sys.stderr, server
                port = xConnectionContext.getValueByName("Port")
                if dbg:
                        print >> sys.stderr, port
                self.server = smtplib.SMTP(server, port)
                if dbg:
                        self.server.set_debuglevel(1)
                connectiontype = xConnectionContext.getValueByName("ConnectionType")
                if dbg:
                        print >> sys.stderr, connectiontype
                if connectiontype == 'Ssl':
                        self.server.ehlo()
                        self.server.starttls()
                        self.server.ehlo()

                user = xAuthenticator.getUserName().encode('ascii')
                password = xAuthenticator.getPassword().encode('ascii')
                if user != '':
                        if dbg:
                                print >> sys.stderr, 'Logging in, username of', user
                        self.server.login(user, password)

                for listener in self.listeners:
                        listener.connected(self.notify)
        def disconnect(self):
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService disconnect"
                if self.server:
                        self.server.quit()
                        self.server = None
                for listener in self.listeners:
                        listener.disconnected(self.notify)
        def isConnected(self):
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService isConnected"
                return self.server != None
        def getCurrentConnectionContext(self):
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService getCurrentConnectionContext"
                return self.connectioncontext
        def sendMailMessage(self, xMailMessage):
                COMMASPACE = ', '

                if dbg:
                        print >> sys.stderr, "PyMailSMPTService sendMailMessage"
                recipients = xMailMessage.getRecipients()
                sendermail = xMailMessage.SenderAddress
                sendername = xMailMessage.SenderName
                subject = xMailMessage.Subject
                ccrecipients = xMailMessage.getCcRecipients()
                bccrecipients = xMailMessage.getBccRecipients()
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService subject", subject
                        print >> sys.stderr, "PyMailSMPTService from", sendername.encode('utf-8')
                        print >> sys.stderr, "PyMailSMTPService from", sendermail
                        print >> sys.stderr, "PyMailSMPTService send to", recipients

                attachments = xMailMessage.getAttachments()

                textmsg = Message()

                content = xMailMessage.Body
                flavors = content.getTransferDataFlavors()
                if dbg:
                        print >> sys.stderr, "PyMailSMPTService flavors len", len(flavors)

                #Use first flavor that's sane for an email body
                for flavor in flavors:
                        if flavor.MimeType.find('text/html') != -1 or 
flavor.MimeType.find('text/plain') != -1:
                                if dbg:
                                        print >> sys.stderr, "PyMailSMPTService mimetype is", 
flavor.MimeType
                                textbody = content.getTransferData(flavor)
                                try:
                                        textbody = textbody.value
                                except:
                                        pass
                                textbody = textbody.encode('utf-8')

                                if len(textbody):
                                        mimeEncoding = re.sub("charset=.*", "charset=UTF-8", 
flavor.MimeType)
                                        if mimeEncoding.find('charset=UTF-8') == -1:
                                                mimeEncoding = mimeEncoding + "; charset=UTF-8"
                                        textmsg['Content-Type'] = mimeEncoding
                                        textmsg['MIME-Version'] = '1.0'
                                        textmsg.set_payload(textbody)

                                break

                if (len(attachments)):
                        msg = MIMEMultipart()
                        msg.epilogue = ''
                        msg.attach(textmsg)
                else:
                        msg = textmsg

                hdr = Header(sendername, 'utf-8')
                hdr.append('<'+sendermail+'>','us-ascii')
                msg['Subject'] = subject
                msg['From'] = hdr
                msg['To'] = COMMASPACE.join(recipients)
                if len(ccrecipients):
                        msg['Cc'] = COMMASPACE.join(ccrecipients)
                if xMailMessage.ReplyToAddress != '':
                        msg['Reply-To'] = xMailMessage.ReplyToAddress

                mailerstring = "OpenOffice.org 2.0 via Caolan's mailmerge component"
                try:
                        ctx = uno.getComponentContext() 
                        aConfigProvider = 
ctx.ServiceManager.createInstance("com.sun.star.configuration.ConfigurationProvider")
                        prop = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
                        prop.Name = "nodepath"
                        prop.Value = "/org.openoffice.Setup/Product"
                        aSettings = 
aConfigProvider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess",
                                (prop,))
                        mailerstring = aSettings.getByName("ooName") + " " + \
                                aSettings.getByName("ooSetupVersion") + " via Caolan's mailmerge 
component"
                except:
                        pass
                
                msg['X-Mailer'] = mailerstring
                msg['Date'] = formatdate(localtime=True)

                for attachment in attachments:
                        content = attachment.Data
                        flavors = content.getTransferDataFlavors()
                        flavor = flavors[0]
                        ctype = flavor.MimeType
                        maintype, subtype = ctype.split('/', 1)
                        msgattachment = MIMEBase(maintype, subtype)
                        data = content.getTransferData(flavor)
                        msgattachment.set_payload(data)
                        Encoders.encode_base64(msgattachment)
                        msgattachment.add_header('Content-Disposition', 'attachment', \
                                filename=attachment.ReadableName)
                        msg.attach(msgattachment)

                uniquer = {}
                for key in recipients:
                        uniquer[key] = True
                if len(ccrecipients):
                        for key in ccrecipients:
                                uniquer[key] = True
                if len(bccrecipients):
                        for key in bccrecipients:
                                uniquer[key] = True
                truerecipients = uniquer.keys()

                if dbg:
                        print >> sys.stderr, "PyMailSMPTService recipients are", truerecipients
                
                try:
                        self.server.sendmail(sendermail, truerecipients, msg.as_string())
                except smtplib.SMTPRecipientsRefused as inst:
                        msg = ""
                        for key,val in inst.recipients.iteritems():
                                msg+=val[1]+"\n"
                        showError(self.ctx,msg)
                except Exception as inst:
                        showError(self.ctx,str(inst))
                #except smtplib.SMTPException:

class PyMailIMAPService(unohelper.Base, XMailService):
        def __init__( self, ctx ):
                self.ctx = ctx
                self.listeners = []
                self.supportedtypes = ('Insecure', 'Ssl')
                self.server = None
                self.connectioncontext = None
                if dbg:
                        print >> sys.stderr, "PyMailIMAPService init"
        def addConnectionListener(self, xListener):
                if dbg:
                        print >> sys.stderr, "PyMailIMAPService addConnectionListener"
                self.listeners.append(xListener)
        def removeConnectionListener(self, xListener):
                if dbg:
                        print >> sys.stderr, "PyMailIMAPService removeConnectionListener"
                self.listeners.remove(xListener)
        def getSupportedConnectionTypes(self):
                if dbg:
                        print >> sys.stderr, "PyMailIMAPService getSupportedConnectionTypes"
                return self.supportedtypes
        def connect(self, xConnectionContext, xAuthenticator):
                if dbg:
                        print >> sys.stderr, "PyMailIMAPService connect"

                self.connectioncontext = xConnectionContext
                server = xConnectionContext.getValueByName("ServerName")
                if dbg:
                        print >> sys.stderr, server
                port = xConnectionContext.getValueByName("Port")
                if dbg:
                        print >> sys.stderr, port
                connectiontype = xConnectionContext.getValueByName("ConnectionType")
                if dbg:
                        print >> sys.stderr, connectiontype
                print >> sys.stderr, "BEFORE"
                if connectiontype == 'Ssl':
                        self.server = imaplib.IMAP4_SSL(server, port)
                else:
                        self.server = imaplib.IMAP4(server, port)
                print >> sys.stderr, "AFTER"
                        
                user = xAuthenticator.getUserName().encode('ascii')
                password = xAuthenticator.getPassword().encode('ascii')
                if user != '':
                        if dbg:
                                print >> sys.stderr, 'Logging in, username of', user
                        self.server.login(user, password)

                for listener in self.listeners:
                        listener.connected(self.notify)
        def disconnect(self):
                if dbg:
                        print >> sys.stderr, "PyMailIMAPService disconnect"
                if self.server:
                        self.server.logout()
                        self.server = None
                for listener in self.listeners:
                        listener.disconnected(self.notify)
        def isConnected(self):
                if dbg:
                        print >> sys.stderr, "PyMailIMAPService isConnected"
                return self.server != None
        def getCurrentConnectionContext(self):
                if dbg:
                        print >> sys.stderr, "PyMailIMAPService getCurrentConnectionContext"
                return self.connectioncontext

class PyMailPOP3Service(unohelper.Base, XMailService):
        def __init__( self, ctx ):
                self.ctx = ctx
                self.listeners = []
                self.supportedtypes = ('Insecure', 'Ssl')
                self.server = None
                self.connectioncontext = None
                if dbg:
                        print >> sys.stderr, "PyMailPOP3Service init"
        def addConnectionListener(self, xListener):
                if dbg:
                        print >> sys.stderr, "PyMailPOP3Service addConnectionListener"
                self.listeners.append(xListener)
        def removeConnectionListener(self, xListener):
                if dbg:
                        print >> sys.stderr, "PyMailPOP3Service removeConnectionListener"
                self.listeners.remove(xListener)
        def getSupportedConnectionTypes(self):
                if dbg:
                        print >> sys.stderr, "PyMailPOP3Service getSupportedConnectionTypes"
                return self.supportedtypes
        def connect(self, xConnectionContext, xAuthenticator):
                if dbg:
                        print >> sys.stderr, "PyMailPOP3Service connect"

                self.connectioncontext = xConnectionContext
                server = xConnectionContext.getValueByName("ServerName")
                if dbg:
                        print >> sys.stderr, server
                port = xConnectionContext.getValueByName("Port")
                if dbg:
                        print >> sys.stderr, port
                connectiontype = xConnectionContext.getValueByName("ConnectionType")
                if dbg:
                        print >> sys.stderr, connectiontype
                print >> sys.stderr, "BEFORE"
                if connectiontype == 'Ssl':
                        self.server = poplib.POP3_SSL(server, port)
                else:
                        self.server = poplib.POP3(server, port)
                print >> sys.stderr, "AFTER"
                        
                user = xAuthenticator.getUserName().encode('ascii')
                password = xAuthenticator.getPassword().encode('ascii')
                if dbg:
                        print >> sys.stderr, 'Logging in, username of', user
                self.server.user(user)
                self.server.pass_(user, password)

                for listener in self.listeners:
                        listener.connected(self.notify)
        def disconnect(self):
                if dbg:
                        print >> sys.stderr, "PyMailPOP3Service disconnect"
                if self.server:
                        self.server.quit()
                        self.server = None
                for listener in self.listeners:
                        listener.disconnected(self.notify)
        def isConnected(self):
                if dbg:
                        print >> sys.stderr, "PyMailPOP3Service isConnected"
                return self.server != None
        def getCurrentConnectionContext(self):
                if dbg:
                        print >> sys.stderr, "PyMailPOP3Service getCurrentConnectionContext"
                return self.connectioncontext

class PyMailServiceProvider(unohelper.Base, XMailServiceProvider):
        def __init__( self, ctx ):
                if dbg:
                        print >> sys.stderr, "PyMailServiceProvider init"
                self.ctx = ctx
        def create(self, aType):
                if dbg:
                        print >> sys.stderr, "PyMailServiceProvider create with", aType
                if aType == SMTP:
                        return PyMailSMTPService(self.ctx);
                elif aType == POP3:
                        return PyMailPOP3Service(self.ctx);
                elif aType == IMAP:
                        return PyMailIMAPService(self.ctx);
                else:
                        print >> sys.stderr, "PyMailServiceProvider, unknown TYPE", aType

class PyMailMessage(unohelper.Base, XMailMessage):
        def __init__( self, ctx, sTo='', sFrom='', Subject='', Body=None, aMailAttachment=None ):
                if dbg:
                        print >> sys.stderr, "PyMailMessage init"
                self.ctx = ctx

                self.recipients = sTo,
                self.ccrecipients = ()
                self.bccrecipients = ()
                self.aMailAttachments = ()
                if aMailAttachment != None:
                        self.aMailAttachments = aMailAttachment, 

                self.SenderName, self.SenderAddress = parseaddr(sFrom)
                self.ReplyToAddress = sFrom
                self.Subject = Subject
                self.Body = Body
                if dbg:
                        print >> sys.stderr, "post PyMailMessage init"
        def addRecipient( self, recipient ):
                if dbg:
                        print >> sys.stderr, "PyMailMessage.addRecipient", recipient
                self.recipients = self.recipients, recipient
        def addCcRecipient( self, ccrecipient ):
                if dbg:
                        print >> sys.stderr, "PyMailMessage.addCcRecipient", ccrecipient
                self.ccrecipients = self.ccrecipients, ccrecipient
        def addBccRecipient( self, bccrecipient ):
                if dbg:
                        print >> sys.stderr, "PyMailMessage.addBccRecipient", bccrecipient
                self.bccrecipients = self.bccrecipients, bccrecipient
        def getRecipients( self ):
                if dbg:
                        print >> sys.stderr, "PyMailMessage.getRecipients", self.recipients
                return self.recipients
        def getCcRecipients( self ):
                if dbg:
                        print >> sys.stderr, "PyMailMessage.getCcRecipients", self.ccrecipients
                return self.ccrecipients
        def getBccRecipients( self ):
                if dbg:
                        print >> sys.stderr, "PyMailMessage.getBccRecipients", self.bccrecipients
                return self.bccrecipients
        def addAttachment( self, aMailAttachment ):
                if dbg:
                        print >> sys.stderr, "PyMailMessage.addAttachment"
                self.aMailAttachments = self.aMailAttachments, aMailAttachment
        def getAttachments( self ):
                if dbg:
                        print >> sys.stderr, "PyMailMessage.getAttachments"
                return self.aMailAttachments

# pythonloader looks for a static g_ImplementationHelper variable
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation( \
        PyMailServiceProvider, "org.openoffice.pyuno.MailServiceProvider",
                ("com.sun.star.mail.MailServiceProvider",),)
g_ImplementationHelper.addImplementation( \
        PyMailMessage, "org.openoffice.pyuno.MailMessage",
                ("com.sun.star.mail.MailMessage",),)
# -*- encoding: iso-8859-15 -*-
#
#   The Contents of this file are made available subject to the terms of
#   the following license
#
#          - GNU Lesser General Public License Version 2.1
#
#   GNU Lesser General Public License Version 2.1
#   =============================================
#   Copyright 2005 by Sun Microsystems, Inc.
#   901 San Antonio Road, Palo Alto, CA 94303, USA
#
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License version 2.1, as published by the Free Software Foundation.
#
#   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
#
#
#   The Initial Developer of the Original Code is: Laurent Godard <lgodard@indesko.com>
#   All Rights Reserved.
#
#   Contributor(s): 
#   
#*************************************************************************

#prepare pythoin environnement - Add the path of this class
from os import path
from sys import modules
from sys import path as syspath
#print modules
#the_path = path.dirname (path.abspath (modules["__main__"].__file__))
#print the_path
#print syspath

#pyUNO program itself
import uno, unohelper

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

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

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

    def __init__(self, aContext):
        """acontext : a Valid UNO context
        """
        
        self.VERSION = '0.1'
        self.ctx = aContext
        self.smgr = aContext.ServiceManager
        # UI Dialog object
        self.dialog=None
        # List of openned Listeners
        self.lst_listeners={}
        #UI parameters
        self.ButtonSize = 50
        self.boxSize = 200
        self.lineHeight = 10
        self.fromBroxSize = False
        self.numberOfLines = -1

        self.Buttons = []
        self.Response = ''
                
        return
        
    #####################################################
    #                 GUI definition                    #
    #####################################################
    def _createBox(self):
        """Create the Box"""
        
    #computes parameters of the message dialog
        if self.numberOfLines == -1:
            #calculate
            numberOfLines = len(self.message.split(chr(10)))
        else:
            numberOfLines = self.numberOfLines    
            
        numberOfButtons = len(self.Buttons)#2 
        self.ButtonSpace = self.ButtonSize/2   
        if self.fromBroxSize:
            #button size is calculated from boxsize
            size = (2 * self.boxSize) / (3 * numberOfButtons + 1)
            self.ButtonSize = size
            self.ButtonSpace = self.ButtonSize/2   
        else:
            #boxsize i calculated form buttonsize
            self.boxSize = numberOfButtons * (self.ButtonSize + 
                                            self.ButtonSpace) + self.ButtonSpace
  
                                                  
    #create the dialog model and set the properties
        dialog_model = self.smgr.createInstanceWithContext(
                                    'com.sun.star.awt.UnoControlDialogModel',
                                    self.ctx)
        dialog_model.PositionX = 50
        dialog_model.Step = 1
        dialog_model.TabIndex = 7
        dialog_model.Width = self.boxSize#numberOfButtons * (self.ButtonSize + 
                             #               self.ButtonSpace) + 25
        dialog_model.Height = 10 + self.lineHeight * numberOfLines + 10 + 12  + 10
        dialog_model.PositionY = 63
        dialog_model.Sizeable = True
        dialog_model.Closeable = False

        dialog = self.smgr.createInstanceWithContext(
                                'com.sun.star.awt.UnoControlDialog',
                                self.ctx)

    # label Label0
        label = dialog_model.createInstance(
                                'com.sun.star.awt.UnoControlFixedTextModel')
        label.PositionX =  10
        label.TabIndex = 9
        label.Width = dialog_model.Width - label.PositionX 
        label.Height = self.lineHeight* numberOfLines
        label.PositionY = 10
        label.Align = left
        label.MultiLine = True
        label.Label = self.message
        dialog_model.insertByName('Label0', label)
        
        nb = 0
        for buttonName in self.Buttons:
            nb +=1
            button = dialog_model.createInstance(
                                    'com.sun.star.awt.UnoControlButtonModel')
            button.PositionX = nb * self.ButtonSpace + (nb-1)* self.ButtonSize
            button.TabIndex = 8
            button.Height = 12
            button.Width = self.ButtonSize
            button.PositionY = 10 + label.Height + 10
            button.PushButtonType =  standard
            if nb == 1:
                button.DefaultButton =  True
            else:
                button.DefaultButton =  False                
            button.Label = buttonName
            dialog_model.insertByName('Btn' + str(nb), button )

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

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

        return dialog

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

    def _addListeners(self):
        """Add listeners to dialog"""
        nb = 0
        for buttonName in self.Buttons:
            nb +=1
            a_control = self.dialog.getControl('Btn'+str(nb))
            the_listener = ButtonListener(self)
            a_control.addActionListener(the_listener)
            self.lst_listeners['Btn'+str(nb)] = the_listener

        return

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

    def _removeListeners(self):
        """ remove listeners on exiting"""
        nb = 0
        for buttonName in self.Buttons:
            nb +=1
            a_control = self.dialog.getControl('Btn'+str(nb))
            a_control.removeActionListener(self.lst_listeners['Btn'+str(nb)])

        return        

#    ###########################
                
    def show(self, message, decoration, title):
        self.message = message
        self.decoration = decoration
        self.title = title
        # Create GUI
        self.dialog = self._createBox()
        self._addListeners()
        #execute the dialog --> blocking call
        self.dialog.execute()
        #end --> release listeners and dispose dialog
        self._removeListeners()
        self.dialog.dispose()
        return self.Response        
       
    def addButton(self, caption):
        self.Buttons.append(caption)
        return
    
    def renderFromBoxSize(self, size = 150):
        self.boxSize = size
        self.fromBroxSize = True
        return
        
    def renderFromButtonSize(self, size = 50):
        self.ButtonSize = size
        self.fromBroxSize = False
        return        

        
class ButtonListener(unohelper.Base, XActionListener):
    """Stops the MessageBox, sets the button label as returned value"""
    def __init__(self, caller):
        self.caller = caller

    def disposing(self, eventObject):
        pass

    def actionPerformed(self, actionEvent):
        button = actionEvent.Source
        self.caller.Response = button.Model.Label
        self.caller.dialog.endExecute()
        return

### TEST
if __name__ == '__main__':       
    # get the uno component context from the PyUNO runtime
    localContext = uno.getComponentContext()
    
    # create the UnoUrlResolver
    resolver = localContext.ServiceManager.createInstanceWithContext(
                    "com.sun.star.bridge.UnoUrlResolver", localContext )
    
    # connect to the running office
    # OOo has to be launched in listen mode as 
    # ./soffice "-accept=socket,host=localhost,port=2002;urp;"
    
    ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
    
    myBox = MsgBox(ctx)  
    myBox.addButton("Oui")
    myBox.addButton("Non")
    myBox.addButton("Peut-Etre")
    myBox.renderFromBoxSize(150)
    myBox.numberOflines = 2
    
    print myBox.show("Un message sur une ligneUn message sur une ligneUn message sur une ligneUn 
message sur une ligneUn message sur une ligneUn message sur une ligneUn message sur une ligneUn 
message sur une ligne" + chr(10)+chr(10)+"�tes-vous d'accord ?",0,"Titre de la boite")        

    myBox = MsgBox(ctx)  
    myBox.addButton("oK")
    myBox.renderFromButtonSize()
    myBox.numberOflines = 2
    
    print myBox.show("Un message sur une ligne",0,"Titre de la boite")        
    



        
        

Context


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