Пример #1
0
    def insertVisibleNotice(self, xSpreadsheet=None):
        """Create and insert an auto-text containing the license(
        if spreadsheet is given,to it)

        Arguments:
        - `xSpreadsheet`:xSpreadsheet- Spread sheet to insert the text
        """
        try:
            if xSpreadsheet is None:
                xDocModel = self.component
                xController = xDocModel.getCurrentController()
                xSpreadsheet = xController.getActiveSheet()

            docLicense = super(Calc, self).getDocumentLicense()

            #xDrawPageSupplier=xSpreadsheet
            xPage = xSpreadsheet.getDrawPage()

            #xShapes=xPage

            aLineSpacing = LineSpacing()
            aLineSpacing.Mode = PROP

            #first shape
            acrSc = self.__getActiveCellsRange(self.component).StartColumn
            acrSr = self.__getActiveCellsRange(self.component).StartRow + 3

            absCellPos = self.__getAbsoluteCellPosition(xSpreadsheet,
                                                        acrSc, acrSr)

            xRectangle = createShape(
                self.component, absCellPos, Size(15000, 1500),
                                   "com.sun.star.drawing.RectangleShape")
            xPage.add(xRectangle)

            xShapePropSet = xRectangle

            xRectangle.setPropertyValue("TextAutoGrowHeight", True)
            xShapePropSet.setPropertyValue("TextAutoGrowWidth", True)
            noneLineStyle = uno.getConstantByName(
                "com.sun.star.drawing.LineStyle.NONE")
            xShapePropSet.setPropertyValue("LineStyle", noneLineStyle)
            noneFillStyle = uno.getConstantByName(
                "com.sun.star.drawing.FillStyle.NONE")
            xShapePropSet.setPropertyValue("FillStyle", noneFillStyle)
            xShapePropSet.setPropertyValue("Name", "ccoo:licenseText")

            #first paragraph
            xTextPropSet = addPortion(xRectangle, docLicense.name, False)
            #TODO-has this been done correctly??
            xTextPropSet.setPropertyValue("CharColor", int(0x000000))

            #insert the graphic
            self.__embedGraphic(docLicense.imageUrl, xSpreadsheet)
        except Exception, e:
            traceback.print_exc()
Пример #2
0
 def _setDocumentUserProperty(self, property, value):
     properties = self.document.DocumentProperties.UserDefinedProperties
     if properties.PropertySetInfo.hasPropertyByName(property):
         properties.setPropertyValue(property, value)
     else:
         properties.addProperty(property,
         uno.getConstantByName("com.sun.star.beans.PropertyAttribute.MAYBEVOID") + 
         uno.getConstantByName("com.sun.star.beans.PropertyAttribute.BOUND") + 
         uno.getConstantByName("com.sun.star.beans.PropertyAttribute.REMOVABLE") + 
         uno.getConstantByName("com.sun.star.beans.PropertyAttribute.MAYBEDEFAULT"),
         value)
  def PrintDoc(self,fpath):
    #Presentar como documento el archivo cuyo path esta en fpath
    #Antes de abrir otro cerramos el anterior (si hay)
    if self.doc!=None:
      try:
	self.doc.close(True)
      except:
	pass
    url=self.ConvertToUrl(fpath)
    flags=uno.getConstantByName("com.sun.star.frame.FrameSearchFlag.CREATE")+uno.getConstantByName("com.sun.star.frame.FrameSearchFlag.ALL")
    self.doc=self.desktop.loadComponentFromURL(url,"Salt",flags,())
Пример #4
0
 def _setDocumentRecord(self, index):
     dispatch = None
     frame = self.document.CurrentController.Frame
     if self.document.supportsService("com.sun.star.text.TextDocument"):
         url = self._getUrl(".uno:DataSourceBrowser/InsertContent")
         dispatch = frame.queryDispatch(url, "_self", uno.getConstantByName("com.sun.star.frame.FrameSearchFlag.SELF"))
     elif self.document.supportsService("com.sun.star.sheet.SpreadsheetDocument"):
         url = self._getUrl(".uno:DataSourceBrowser/InsertColumns")
         dispatch = frame.queryDispatch(url, "_self", uno.getConstantByName("com.sun.star.frame.FrameSearchFlag.SELF"))
     if dispatch is not None:
         dispatch.dispatch(url, self._getDataDescriptor(index + 1))
     self.index = index
 def NewPage(self):
   #Sub InsertPageBreak( oCursor ) 
      #oText = oCursor.getText() 
      #oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False ) 
      #oCursor.BreakType = com.sun.star.style.BreakType.PAGE_BEFORE 
   #End Sub
   if not self.pagini:
     self.PrintLine("")
     text=self.cursor.getText()
     text.insertControlCharacter(self.cursor,uno.getConstantByName("com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK"),0)
     self.cursor.BreakType=uno.getConstantByName("com.sun.star.style.BreakType.PAGE_BEFORE")
   self.pagini=False
Пример #6
0
 def trigger(self, args):
     provider = self.ctx.ServiceManager.createInstanceWithContext("com.sun.star.awt.DialogProvider", self.ctx)
     self.dialog = provider.createDialogWithHandler("vnd.sun.star.script:gContactOOo.Dialog?location=application", self)
     configuration = self._getConfiguration(self.configuration)
     datasources = self._getDataSources()
     if not self._checkDocumentService():
         self._logMessage("TextMerge", "79.Dialog.TextMerge.Text", ("",))
         self._openDialog(5)
     elif not configuration.getByName("OffLineUse") and not self._checkMailService():
         self._openDialog(5)
     elif not len(datasources):
         self._logMessage("TextMsg", "12.Dialog.TextMsg.Text")
         self._openDialog(1)
     else:
         self.dialog.getControl("AddressBook").addActionListener(self)
         self.dialog.getControl("Address").addItemListener(self)
         self.dialog.getControl("Recipient").addItemListener(self)
         self.dialog.getControl("Attachments").addItemListener(self)
         self.address = self.ctx.ServiceManager.createInstance("com.sun.star.sdb.RowSet")
         self.address.CommandType = uno.getConstantByName("com.sun.star.sdb.CommandType.TABLE")
         self.address.addRowSetListener(self)
         self.recipient = self.ctx.ServiceManager.createInstance("com.sun.star.sdb.RowSet")
         self.recipient.CommandType = uno.getConstantByName("com.sun.star.sdb.CommandType.QUERY")
         self.recipient.addRowSetListener(self)
         control = self.dialog.getControl("DataSource")
         control.addActionListener(self)
         control.Model.StringItemList = datasources
         datasource = self._getDocumentDataSource()
         if datasource in datasources:
             control.selectItem(datasource, True)
         else:
             control.selectItemPos(0, True)
         self._setStep()
         self.dialog.getControl("Subject").Text = self.document.DocumentProperties.Subject
         description = self.dialog.getControl("Description")
         state = self._getDocumentUserProperty("SendAsHtml", configuration.getByName("SendAsHtml"))
         description.Text = self.document.DocumentProperties.Description
         description.Model.Enabled = not state
         self.dialog.getControl("SendAsHtml").Model.State = state
         self.dialog.getControl("SendAsPdf").Model.State = self._getDocumentUserProperty("SendAsPdf", configuration.getByName("SendAsPdf"))
         self.dialog.getControl("Attachments").Model.StringItemList = self._getAttachmentsPath("")
         self.dialog.execute()
         self._saveDialog()
         self.recipient.dispose()
         self.address.dispose()
         self.dialog.getControl("Attachments").dispose()
         self.dialog.getControl("Recipient").dispose()
         self.dialog.getControl("Address").dispose()
         self.dialog.getControl("AddressBook").dispose()
         self.dialog.getControl("DataSource").dispose()
         self.dialog.dispose()
         self.dialog = None
Пример #7
0
def showFilePicker(filePath="", title="Выбор файла с данными о схеме", **fileFilters):
    """Показать диалоговое окно выбора файла.

    Аргументы:

    filePath -- имя файла по умолчанию;
    fileFilters -- перечень фильтров для выбора файлов в формате:
        {"Текстовые файлы": "*.txt", "Документы": "*.odt;*.ods"}

    Возвращаемое значение -- полное имя файла или None, если файл не выбран.

    """
    context = XSCRIPTCONTEXT.getComponentContext()
    if os.path.isfile(filePath):
        directory, file = os.path.split(filePath)
    else:
        docUrl = XSCRIPTCONTEXT.getDocument().URL
        if docUrl:
            directory = os.path.dirname(uno.fileUrlToSystemPath(docUrl))
        else:
            directory = os.path.expanduser('~')
        file = ""
    filePicker = context.ServiceManager.createInstanceWithContext(
        "com.sun.star.ui.dialogs.OfficeFilePicker",
        context
    )
    filePicker.setTitle(title)
    pickerType = uno.getConstantByName(
        "com.sun.star.ui.dialogs.TemplateDescription.FILEOPEN_SIMPLE"
    )
    filePicker.initialize((pickerType,))
    filePicker.setDisplayDirectory(
        uno.systemPathToFileUrl(directory)
    )
    filePicker.setDefaultName(file)
    for filterTitle, filterValue in fileFilters.items():
        filePicker.appendFilter(filterTitle, filterValue)
        if not filePicker.getCurrentFilter():
            # Установить первый фильтр в качестве фильтра по умолчанию.
            filePicker.setCurrentFilter(filterTitle)
    result = filePicker.execute()
    OK = uno.getConstantByName(
        "com.sun.star.ui.dialogs.ExecutableDialogResults.OK"
    )
    if result == OK:
        sourcePath = uno.fileUrlToSystemPath(filePicker.Files[0])
        return sourcePath
    return None
Пример #8
0
 def exportRules(self):
     if not self.dRules:
         return
     sText = json.dumps(self.dRules, ensure_ascii=False)
     try:
         xFilePicker = self.xSvMgr.createInstanceWithContext(
             'com.sun.star.ui.dialogs.FilePicker', self.ctx
         )  # other possibility: com.sun.star.ui.dialogs.SystemFilePicker
         xFilePicker.initialize([
             uno.getConstantByName(
                 "com.sun.star.ui.dialogs.TemplateDescription.FILESAVE_SIMPLE"
             )
         ])  # seems useless
         xFilePicker.appendFilter("Supported files", "*.json")
         xFilePicker.setDefaultName(
             "grammalecte_tf_trans_rules.json")  # doesn’t work on Windows
         xFilePicker.setDisplayDirectory("")
         xFilePicker.setMultiSelectionMode(False)
         nResult = xFilePicker.execute()
         if nResult == 1:
             # lFile = xFilePicker.getSelectedFiles()
             lFile = xFilePicker.getFiles()
             spfExported = lFile[0][5:].lstrip("/")  # remove file://
             if platform.system() != "Windows":
                 spfExported = "/" + spfExported
             #spfExported = os.path.join(os.path.expanduser("~"), "fr.personal.json")
             with open(spfExported, "w", encoding="utf-8") as hDst:
                 hDst.write(sText)
     except:
         sMessage = traceback.format_exc()
         MessageBox(self.xDocument, sMessage, ui.get('error'), ERRORBOX)
Пример #9
0
 def _getPropertySetInfo(self):
     properties = {}
     readonly = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.READONLY')
     transient = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.TRANSIENT')
     properties['Provider'] = getProperty('Provider',
                                          'com.sun.star.uno.XInterface',
                                          readonly)
     properties['Id'] = getProperty('Id', 'string', transient)
     properties['Value'] = getProperty('Value', 'string', readonly)
     properties['Values'] = getProperty('Values', '[]string', transient)
     properties['Authorized'] = getProperty('Authorized', 'boolean',
                                            readonly)
     properties['State'] = getProperty('State', 'short', transient)
     return properties
Пример #10
0
    def link_db(self, document, db_name, table_name):
        # Update db fields url
        fields_enum = document.getTextFields().createEnumeration()

        while fields_enum.hasMoreElements():
            field = fields_enum.nextElement()
            master_field = field.getTextFieldMaster()

            # Conditional field
            try:
                cond = field.getPropertyValue("Condition")
                cond = cond.split('.')
                if len(cond) == 3:  # db.table.field
                    cond[0] = db_name
                    field.setPropertyValue("Condition", '.'.join(cond))
            except UnknownPropertyException:
                pass

            # Merge mail field
            try:
                master_field.setPropertyValue("DataBaseName", db_name)
                master_field.setPropertyValue("DataTableName", table_name)
            except UnknownPropertyException:
                pass

        # Attach the db to the document
        stg = document.createInstance("com.sun.star.text.DocumentSettings")
        stg.setPropertyValue("CurrentDatabaseDataSource", db_name)
        stg.setPropertyValue("CurrentDatabaseCommand", table_name)
        stg.setPropertyValue(
            "CurrentDatabaseCommandType",
            uno.getConstantByName("com.sun.star.sdb.CommandType.TABLE"))

        document.store()
def conditional_format():
    ctx = XSCRIPTCONTEXT.getComponentContext()
    serviceManager = ctx.ServiceManager
    desktop = XSCRIPTCONTEXT.getDesktop()
    doc = desktop.getCurrentComponent()
    sheets = doc.getSheets() #XSpreadSheets
    sheet = sheets.getByIndex(0)

    ### Aquí empieza el ejercicio de traducción del ejemplo de formateado condicional

    xCellRange = sheet.getCellRangeByName("A1:B10");
    xEntries = xCellRange.getPropertyValue("ConditionalFormat");

    cond1 = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
    cond2 = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
    cond3 = uno.createUnoStruct("com.sun.star.beans.PropertyValue")

    cond1.Name = "Operator";
    cond1.Value = uno.getConstantByName("com.sun.star.sheet.ConditionOperator.GREATER")
    cond2.Name = "Formula"
    cond2.Value = "1"
    cond3.Name = "StyleName"
    cond3.Value = "Heading"
    xEntries.addNew((cond1, cond2, cond3))
    xCellRange.setPropertyValue("ConditionalFormat", xEntries); 
Пример #12
0
 def createWaitingMessageBox(self):
     #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" )
     ctx = uno.getComponentContext()
     smgr = ctx.ServiceManager
     desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",
                                              ctx)
     doc = desktop.getCurrentComponent()  #get the current active document
     if not hasattr(doc, "Text"):
         doc = desktop.loadComponentFromURL("private:factory/swriter",
                                            "_blank", 0, ())
     parentwin = doc.CurrentController.Frame.ContainerWindow
     vclAttribute = uno.getConstantByName(
         "com.sun.star.awt.VclWindowPeerAttribute.OK")
     windowClass = uno.Enum("com.sun.star.awt.WindowClass", "MODALTOP")
     rectangle = self.createRectangle(50, 100, 300,
                                      200)  #create dialog rectangle
     windowService = "messbox"  #type of the dialog
     msgbox = self.createMessageBox(ctx, smgr, windowClass, parentwin,
                                    rectangle, windowService, vclAttribute)
     #create dialog according to the attributes given
     msgbox.setMessageText("Fetching Data from Wolfram Alpha Math Engine")
     msgbox.setCaptionText("In Progress")  #set title and message
     return msgbox
Пример #13
0
    def run(self):
        address = self.controller.Configuration.Url.Scope.Provider.RedirectAddress
        port = self.controller.Configuration.Url.Scope.Provider.RedirectPort
        result = uno.getConstantByName(
            'com.sun.star.ui.dialogs.ExecutableDialogResults.CANCEL')
        connection = self.acceptor.accept(
            'socket,host=%s,port=%s,tcpNoDelay=1' % (address, port))
        if connection:
            with self.lock:
                result = self._getResult(connection)
                basename = getResourceLocation(self.ctx, g_identifier,
                                               'OAuth2OOo')
                basename += '/OAuth2Success_%s.html' if result else '/OAuth2Error_%s.html'
                locale = getCurrentLocale(self.ctx)
                length, body = getFileSequence(self.ctx,
                                               basename % locale.Language,
                                               basename % 'en')
                header = uno.ByteSequence(b'''\
HTTP/1.1 200 OK
Content-Length: %d
Content-Type: text/html; charset=utf-8
Connection: Closed

''' % length)
                connection.write(header + body)
                connection.close()
                self.acceptor.stopAccepting()
                self.controller.Handler.Wizard.DialogWindow.endDialog(result)
                self.lock.notifyAll()
Пример #14
0
def _getLogIndex(ctx, logger='org.openoffice.logging.DefaultLogger'):
    index = 7
    level = _getLoggerConfiguration(ctx, logger).LogLevel
    enabled = level != uno.getConstantByName('com.sun.star.logging.LogLevel.OFF')
    if enabled:
        index = _getLogLevels().index(level)
    return enabled, index
Пример #15
0
 def activatePage(self):
     level = uno.getConstantByName('com.sun.star.logging.LogLevel.INFO')
     self.Logger.logp(level, 'WizardPage', 'activatePage()',
                      'PageId: %s...' % self.PageId)
     if self.PageId == 1:
         username = self.Configuration.Url.Scope.Provider.User.Id
         self.Window.getControl('TextField1').setText(username)
         urls = self.Configuration.UrlList
         control = self.Window.getControl('ComboBox1')
         control.Model.StringItemList = urls
         providers = self.Configuration.Url.ProviderList
         self.Window.getControl(
             'ComboBox2').Model.StringItemList = providers
         url = self.Configuration.Url.Id
         if url:
             control.setText(url)
     elif self.PageId == 2:
         url = getAuthorizationStr(self.ctx, self.Configuration, self.Uuid)
         self.Window.getControl('TextField1').setText(url)
         address = self.Configuration.Url.Scope.Provider.RedirectAddress
         self.Window.getControl('TextField2').setText(address)
         port = self.Configuration.Url.Scope.Provider.RedirectPort
         self.Window.getControl('NumericField1').setValue(port)
         option = 'OptionButton%s' % getActivePath(self.Configuration)
         self.Window.getControl(option).setState(True)
     elif self.PageId == 3:
         openUrl(self.ctx, self.Configuration, self.Uuid)
     elif self.PageId == 4:
         openUrl(self.ctx, self.Configuration, self.Uuid)
     self.Window.setVisible(True)
     self.Logger.logp(level, 'WizardPage', 'activatePage()',
                      'PageId: %s... Done' % self.PageId)
Пример #16
0
def _setLogIndex(ctx, enabled, index, logger='org.openoffice.logging.DefaultLogger'):
    level = uno.getConstantByName('com.sun.star.logging.LogLevel.OFF')
    if enabled:
        level = _getLogLevels()[index]
    configuration = _getLoggerConfiguration(ctx, logger)
    configuration.LogLevel = level
    configuration.commitChanges()
Пример #17
0
def removePageRevTable():
    """Удалить таблицу изменений на текущем листе."""
    doc = XSCRIPTCONTEXT.getDocument()
    frame = doc.CurrentController.Frame
    pageNum = doc.CurrentController.ViewCursor.Page
    if ("Изм_стр_%d" % pageNum) not in doc.TextFrames:
        return
    global SKIP_MODIFY_EVENTS
    SKIP_MODIFY_EVENTS = True
    isEmpty = True
    for j in range(2):
        for i in range(5):
            cell = doc.TextTables["Изм_таб_%d" % pageNum].getCellByPosition(
                i, j)
            if cell.String != "":
                isEmpty = False
                viewCursor = doc.CurrentController.ViewCursor
                viewCursor.gotoRange(cell.Start, False)
                doc.refresh()
                break
    doRemove = True
    if not isEmpty:
        msgbox = frame.ContainerWindow.Toolkit.createMessageBox(
            frame.ContainerWindow,
            uno.Enum("com.sun.star.awt.MessageBoxType", "MESSAGEBOX"),
            uno.getConstantByName(
                "com.sun.star.awt.MessageBoxButtons.BUTTONS_YES_NO"),
            "Внимание!", "Таблица с изменениями не пуста.\n"
            "Удалить?")
        yes = uno.getConstantByName("com.sun.star.awt.MessageBoxResults.YES")
        result = msgbox.execute()
        if result != yes:
            doRemove = False
    if doRemove:
        if not isEmpty:
            viewCursor = doc.CurrentController.ViewCursor
            viewCursor.jumpToEndOfPage()
            doc.refresh()
        doc.lockControllers()
        doc.UndoManager.lock()
        doc.TextTables["Изм_таб_%d" % pageNum].dispose()
        doc.TextFrames["Изм_стр_%d" % pageNum].dispose()
        doc.UndoManager.unlock()
        doc.UndoManager.clear()
        doc.unlockControllers()
    SKIP_MODIFY_EVENTS = False
    return
Пример #18
0
 def _getTokens(self, code, codeverifier):
     url = self.Setting.Url.Scope.Provider.TokenUrl
     data = getTokenParameters(self.Setting, code, codeverifier)
     message = "Make Http Request: %s?%s" % (url, data)
     level = uno.getConstantByName('com.sun.star.logging.LogLevel.INFO')
     self.Setting.Logger.logp(level, "OAuth2Service", "_getTokens", message)
     response = self._getResponseFromRequest(url, data)
     return self._getTokenFromResponse(response)
Пример #19
0
 def _getPropertySetInfo(self):
     properties = {}
     readonly = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.READONLY')
     properties['RowCount'] = getProperty('RowCount', 'long', readonly)
     properties['IsRowCountFinal'] = getProperty('IsRowCountFinal',
                                                 'boolean', readonly)
     return properties
Пример #20
0
 def insertImage(self,image_name,width=None,height=None,vposition=None):
     """ Add image to a document
     Image is added to the active cursor position
     @param image_name Image filename
     """
     oShape = self.doc.createInstance("com.sun.star.text.TextGraphicObject") 
     oShape.GraphicURL = image_name
     oShape.AnchorType = AS_CHARACTER
     if width is not None:
         oShape.Width=width
     if height is not None:
         oShape.Height=height
     if vposition is not None:
         oShape.VertOrient=uno.getConstantByName( "com.sun.star.text.VertOrientation.CHAR_CENTER")
         oShape.VertOrientRelation=uno.getConstantByName( "com.sun.star.text.RelOrientation.TEXT_LINE" )
         oShape.VertOrientPosition=vposition
     self.cursor.Text.insertTextContent(self.cursor,oShape,uno.Bool(0))
Пример #21
0
 def _getPropertySetInfo(self):
     properties = {}
     readonly = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.READONLY')
     properties['Wizard'] = getProperty('Wizard',
                                        'com.sun.star.ui.dialogs.XWizard',
                                        readonly)
     return properties
Пример #22
0
def copyUsingPropertySetInfo(srcObj, dstObj):
    """
    Cope the whole PropertySet of an UNO object to an other instance.
    """
    ctx = uno.getComponentContext()
    smgr = ctx.ServiceManager
    sPInfo = srcObj.getPropertySetInfo()
    dPInfo = dstObj.getPropertySetInfo()
    oProps = sPInfo.getProperties()

    for i in xrange(len(oProps)):
        oProp = oProps[i]
        try:
            if dPInfo.hasPropertyByName(oProp.Name):

                xray(smgr, ctx, oProp.Type)
                if oProp.Type.getName() == dPInfo.getPropertyByName(
                        oProp.Name).Type.getName():

                    oSValue = srcObj.getPropertyValue(oProp.Name)
                    if canCopyTypeWithAssignment(oSValue):
                        if (uno.getConstantByName(
                                "com.sun.star.beans.PropertyAttribute.READONLY"
                        ) and oProp.Attributes) == False:
                            if oProp.Name != "GridLines":
                                dstObj.setPropertyValue(oProp.Name, oSValue)
                    elif uno.IsArray(oSValue):
                        pass
                    else:
                        oDValue = dstObj.getPropertyValue(oProp.Name)
                        if oDValue == None or uno.IsEmpty(oDValue):
                            if (uno.getConstantByName(
                                    "com.sun.star.beans.PropertyAttribute.READONLY"
                            ) and oProp.Attributes) == False:
                                dstObj.setPropertyValue(oProp.Name, oSValue)
                            elif uno.HasUnoInterfaces(
                                    oSValue,
                                    "com.sun.star.beans.XPropertySet"):
                                if oSValue.SupportsService(
                                        "com.sun.star.text.Text"):
                                    pass
                                else:
                                    copyUsingPropertySetInfo(oSValue, oDValue)
        except Exception, e:
            xray(smgr, ctx, e.message)
            return
Пример #23
0
 def _getPropertySetInfo(self):
     properties = {}
     readonly = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.READONLY')
     transient = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.TRANSIENT')
     properties['Id'] = getProperty('Id', 'string', transient)
     properties['AccessToken'] = getProperty('AccessToken', 'string',
                                             readonly)
     properties['HasExpired'] = getProperty('HasExpired', 'boolean',
                                            readonly)
     properties['IsValid'] = getProperty('IsValid', 'boolean', readonly)
     properties['Scopes'] = getProperty('Scopes', '[]string', readonly)
     properties['MetaData'] = getProperty('MetaData',
                                          'com.sun.star.auth.XRestKeyMap',
                                          transient)
     return properties
Пример #24
0
def _getLogLevels():
    levels = (uno.getConstantByName('com.sun.star.logging.LogLevel.SEVERE'),
              uno.getConstantByName('com.sun.star.logging.LogLevel.WARNING'),
              uno.getConstantByName('com.sun.star.logging.LogLevel.INFO'),
              uno.getConstantByName('com.sun.star.logging.LogLevel.CONFIG'),
              uno.getConstantByName('com.sun.star.logging.LogLevel.FINE'),
              uno.getConstantByName('com.sun.star.logging.LogLevel.FINER'),
              uno.getConstantByName('com.sun.star.logging.LogLevel.FINEST'),
              uno.getConstantByName('com.sun.star.logging.LogLevel.ALL'))
    return levels
Пример #25
0
 def importRules(self):
     spfImported = ""
     try:
         xFilePicker = self.xSvMgr.createInstanceWithContext(
             'com.sun.star.ui.dialogs.FilePicker', self.ctx
         )  # other possibility: com.sun.star.ui.dialogs.SystemFilePicker
         xFilePicker.initialize([
             uno.getConstantByName(
                 "com.sun.star.ui.dialogs.TemplateDescription.FILEOPEN_SIMPLE"
             )
         ])  # seems useless
         xFilePicker.appendFilter("Supported files", "*.json")
         xFilePicker.setDefaultName(
             "grammalecte_tf_trans_rules.json")  # useless, doesn’t work
         xFilePicker.setDisplayDirectory("")
         xFilePicker.setMultiSelectionMode(False)
         nResult = xFilePicker.execute()
         if nResult == 1:
             # lFile = xFilePicker.getSelectedFiles()
             lFile = xFilePicker.getFiles()
             #print(lFile)
             spfImported = lFile[0][5:].lstrip("/")  # remove file://
             if platform.system() != "Windows":
                 spfImported = "/" + spfImported
     except:
         sMessage = traceback.format_exc()
         MessageBox(self.xDocument, sMessage, ui.get('error'), ERRORBOX)
         return
     if not spfImported or not os.path.isfile(spfImported):
         sMessage = ui.get('file_not_found') + "<" + spfImported + ">"
         MessageBox(self.xDocument, sMessage, ui.get('error'), ERRORBOX)
         return
     try:
         with open(spfImported, "r", encoding="utf-8") as hFile:
             dImportedRules = json.load(hFile)
     except:
         sMessage = traceback.format_exc()
         MessageBox(self.xDocument, sMessage, ui.get('error'), ERRORBOX)
     else:
         nButton = MessageBox(self.xDocument, ui.get('import_question'),
                              ui.get('import_title'), QUERYBOX,
                              BUTTONS_YES_NO_CANCEL)
         if nButton == 0:  # cancel
             return
         xGridDataModel = self.xGridModel.GridDataModel
         if nButton == 2:  # yes
             self.dRules.update(dImportedRules)
             self.xGridModel.GridDataModel.removeAllRows()
             for sRuleName in self.dRules:
                 xGridDataModel.addRow(xGridDataModel.RowCount + 1,
                                       self._getValuesForRow(sRuleName))
         else:  # 3 = no
             for sRuleName, dValues in dImportedRules.items():
                 if not sRuleName in self.dRules:
                     self.dRules[sRuleName] = dValues
                     xGridDataModel.addRow(xGridDataModel.RowCount + 1,
                                           self._getValuesForRow(sRuleName))
         xGridDataModel.sortByColumn(0, True)
Пример #26
0
def _setTitle(source, context, title):
    identifier = source.Identifier
    parent = identifier.getParent()
    count = parent.countChildTitle(title)
    if u'~' in title:
        msg = "Can't set property: Title value: %s contains invalid character: '~'." % title
        level = uno.getConstantByName('com.sun.star.logging.LogLevel.SEVERE')
        data = getPropertyValueSet({
            'Uri': identifier.getContentIdentifier(),
            'ResourceName': title
        })
        error = getInteractiveAugmentedIOException(msg, context, 'ERROR',
                                                   'INVALID_CHARACTER', data)
        result = uno.Any('com.sun.star.ucb.InteractiveAugmentedIOException',
                         error)
    elif (identifier.IsNew and count == 1) or (not identifier.IsNew
                                               and count != 0):
        msg = "Can't set property: %s value: %s - Name Clash Error" % ('Title',
                                                                       title)
        level = uno.getConstantByName('com.sun.star.logging.LogLevel.SEVERE')
        data = getPropertyValueSet({
            'TargetFolderURL':
            parent.getContentIdentifier(),
            'ClashingName':
            title,
            'ProposedNewName':
            '%s(1)' % title
        })
        #data = getPropertyValueSet({'Uri': identifier.getContentIdentifier(),'ResourceName': title})
        error = getInteractiveAugmentedIOException(msg, context, 'ERROR',
                                                   'ALREADY_EXISTING', data)
        result = uno.Any('com.sun.star.ucb.InteractiveAugmentedIOException',
                         error)
    else:
        if identifier.IsNew:
            source.MetaData.insertValue(
                'Title', identifier.setTitle(title, source.IsFolder))
        else:
            default = source.MetaData.getValue('Title')
            source.MetaData.insertValue('Title',
                                        identifier.updateTitle(title, default))
        msg = "Set property: %s value: %s" % ('Title', title)
        level = uno.getConstantByName('com.sun.star.logging.LogLevel.INFO')
        result = None
    return result, level, msg
Пример #27
0
 def getToken(self, format=''):
     level = uno.getConstantByName('com.sun.star.logging.LogLevel.INFO')
     msg = "Request Token ... "
     if not self._isAuthorized():
         level = uno.getConstantByName(
             'com.sun.star.logging.LogLevel.SEVERE')
         msg += "ERROR: Cannot InitializeSession()..."
         token = ''
     elif self.Setting.Url.Scope.Provider.User.HasExpired:
         token = self._refreshToken()
         msg += "Refresh needed ... Done"
     else:
         token = self.Setting.Url.Scope.Provider.User.AccessToken
         msg += "Get from configuration ... Done"
     self.Setting.Logger.logp(level, "OAuth2Service", "getToken()", msg)
     if format:
         token = format % token
     return token
Пример #28
0
 def _getPropertySetInfo(self):
     properties = {}
     readonly = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.READONLY')
     transient = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.TRANSIENT')
     properties['Url'] = getProperty('Url', 'com.sun.star.uno.XInterface',
                                     readonly)
     properties['HandlerTimeout'] = getProperty('HandlerTimeout', 'short',
                                                transient)
     properties['ConnectTimeout'] = getProperty('ConnectTimeout', 'short',
                                                transient)
     properties['ReadTimeout'] = getProperty('ReadTimeout', 'short',
                                             transient)
     properties['Timeout'] = getProperty('Timeout', 'any', readonly)
     properties['Initialized'] = getProperty('Initialized', 'boolean',
                                             readonly)
     return properties
Пример #29
0
 def _getResult(self, connection):
     parameters = self._getParameters(connection)
     response = self._getResponse(parameters)
     level = uno.getConstantByName('com.sun.star.logging.LogLevel.SEVERE')
     result = uno.getConstantByName(
         'com.sun.star.ui.dialogs.ExecutableDialogResults.CANCEL')
     if 'code' in response and 'state' in response:
         if response['state'] == self.controller.Uuid:
             self.controller.AuthorizationCode.Value = response['code']
             self.controller.AuthorizationCode.IsPresent = True
             level = uno.getConstantByName(
                 'com.sun.star.logging.LogLevel.INFO')
             result = uno.getConstantByName(
                 'com.sun.star.ui.dialogs.ExecutableDialogResults.OK')
     self.controller.Configuration.Logger.logp(level, 'HttpServer',
                                               '_getResult',
                                               '%s' % response)
     return result
Пример #30
0
def _setProperty(source, context, name, value):
    if name == 'Title':
        result, level, msg = _setTitle(source, context, value)
    else:
        source.MetaData.insertValue(name, value)
        msg = "Set property: %s value: %s" % (name, value)
        level = uno.getConstantByName('com.sun.star.logging.LogLevel.INFO')
        result = None
    return result, level, msg
Пример #31
0
 def insertImage(self, image_name, width=None, height=None, vposition=None):
     """ Add image to a document
     Image is added to the active cursor position
     @param image_name Image filename
     """
     oShape = self.doc.createInstance("com.sun.star.text.TextGraphicObject")
     oShape.GraphicURL = image_name
     oShape.AnchorType = AS_CHARACTER
     if width is not None:
         oShape.Width = width
     if height is not None:
         oShape.Height = height
     if vposition is not None:
         oShape.VertOrient = uno.getConstantByName(
             "com.sun.star.text.VertOrientation.CHAR_CENTER")
         oShape.VertOrientRelation = uno.getConstantByName(
             "com.sun.star.text.RelOrientation.TEXT_LINE")
         oShape.VertOrientPosition = vposition
     self.cursor.Text.insertTextContent(self.cursor, oShape, uno.Bool(0))
Пример #32
0
 def _getPropertySetInfo(self):
     properties = {}
     maybevoid = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.MAYBEVOID')
     readonly = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.READONLY')
     transient = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.TRANSIENT')
     properties['Url'] = getProperty('Url', 'com.sun.star.uno.XInterface',
                                     readonly)
     properties['UrlList'] = getProperty('UrlList', '[]string', readonly)
     properties['RequestTimeout'] = getProperty('RequestTimeout', 'short',
                                                transient)
     properties['HandlerTimeout'] = getProperty('HandlerTimeout', 'short',
                                                transient)
     properties['Logger'] = getProperty('Logger',
                                        'com.sun.star.logging.XLogger',
                                        readonly)
     return properties
Пример #33
0
 def _getPropertySetInfo(self):
     properties = {}
     bound = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.BOUND')
     readonly = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.READONLY')
     maybevoid = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.MAYBEVOID')
     properties['Configuration'] = getProperty(
         'Configuration', 'com.sun.star.uno.XInterface', readonly)
     properties['PageId'] = getProperty('PageId', 'short', readonly)
     properties['Window'] = getProperty('Window',
                                        'com.sun.star.awt.XWindow',
                                        readonly)
     properties['Uuid'] = getProperty('Uuid', 'string', readonly)
     properties['AuthorizationCode'] = getProperty(
         'AuthorizationCode', 'com.sun.star.beans.Optional<string>',
         transient)
     return properties
Пример #34
0
def createListBox(ctx,width,height,x,y):
    smgr = ctx.ServiceManager
    Rectangle=uno.createUnoStruct("com.sun.star.awt.Rectangle")
    Rectangle.Width =width
    Rectangle.Height=height
    Rectangle.X=x
    Rectangle.Y=y
    WindowDescriptor = uno.createUnoStruct("com.sun.star.awt.WindowDescriptor") 
    WindowClass = uno.Enum("com.sun.star.awt.WindowClass","MODALTOP") 
    VclWindowPeerAttribute = uno.getConstantByName("com.sun.star.awt.VclWindowPeerAttribute.OK")
Пример #35
0
 def _getPropertySetInfo(self):
     properties = {}
     readonly = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.READONLY')
     properties['User'] = getProperty('User', 'com.sun.star.uno.XInterface',
                                      readonly)
     properties['MetaData'] = getProperty('MetaData',
                                          'com.sun.star.auth.XRestKeyMap',
                                          readonly)
     return properties
Пример #36
0
 def _getPropertySetInfo(self):
     properties = {}
     bound = uno.getConstantByName('com.sun.star.beans.PropertyAttribute.BOUND')
     readonly = uno.getConstantByName('com.sun.star.beans.PropertyAttribute.READONLY')
     transient = uno.getConstantByName('com.sun.star.beans.PropertyAttribute.TRANSIENT')
     maybevoid = uno.getConstantByName('com.sun.star.beans.PropertyAttribute.MAYBEVOID')
     properties['ResourceUrl'] = getProperty('ResourceUrl', 'string', transient)
     properties['UserName'] = getProperty('UserName', 'string', transient)
     properties['ActivePath'] = getProperty('ActivePath', 'short', readonly)
     properties['AuthorizationCode'] = getProperty('AuthorizationCode', 'com.sun.star.beans.Optional<string>', bound)
     properties['AuthorizationStr'] = getProperty('AuthorizationStr', 'string', readonly)
     properties['CheckUrl'] = getProperty('CheckUrl', 'boolean', readonly)
     properties['Uuid'] = getProperty('Uuid', 'string', readonly)
     properties['CodeVerifier'] = getProperty('CodeVerifier', 'string', readonly)
     properties['Configuration'] = getProperty('Configuration', 'com.sun.star.uno.XInterface', readonly)
     properties['Server'] = getProperty('Server', 'com.sun.star.uno.XInterface', bound | readonly)
     properties['Paths'] = getProperty('Paths', '[][]short', readonly)
     properties['Handler'] = getProperty('Handler', 'com.sun.star.uno.XInterface', readonly)
     return properties
Пример #37
0
def _setPropertyValue(source, context, property):
    name, value = property.Name, property.Value
    if source._propertySetInfo.get(name).Attributes & READONLY:
        msg = "ERROR: Requested property: %s is READONLY" % name
        level = uno.getConstantByName('com.sun.star.logging.LogLevel.SEVERE')
        error = IllegalAccessException(msg, source)
        result = uno.Any('com.sun.star.lang.IllegalAccessException', error)
    else:
        result, level, msg = _setProperty(source, context, name, value)
    return result, level, msg
Пример #38
0
	def box( self, message, kind = 'infobox', buttons = 'OK', title = None ):
		if kind == 'infobox' and buttons != 'OK':
			kind = 'querybox'	# infobox only supports OK
		if title is None: title = self.localize( 'title' )
		toolkit = self.ctx.ServiceManager.createInstance( 'com.sun.star.awt.Toolkit' )
		rectangle = uno.createUnoStruct( 'com.sun.star.awt.Rectangle' )
		msgbox = toolkit.createMessageBox( self.getdesktop().getCurrentFrame().getContainerWindow(), rectangle,
			kind, uno.getConstantByName( 'com.sun.star.awt.MessageBoxButtons.BUTTONS_'+buttons ),
			title, message )
		return msgbox.execute()
Пример #39
0
 def wrapper (*args, **kwargs):
     # self is the first parameter if the decorator is applied on a object
     self = args[0]
     # before
     xPointer = self.xSvMgr.createInstanceWithContext("com.sun.star.awt.Pointer", self.ctx)
     xPointer.setType(uno.getConstantByName("com.sun.star.awt.SystemPointer.WAIT"))
     xWindowPeer = self.xContainer.getPeer()
     xWindowPeer.setPointer(xPointer)
     for x in xWindowPeer.Windows:
         x.setPointer(xPointer)
     # processing
     result = funcDecorated(*args, **kwargs)
     # after
     xPointer.setType(uno.getConstantByName("com.sun.star.awt.SystemPointer.ARROW"))
     xWindowPeer.setPointer(xPointer)
     for x in xWindowPeer.Windows:
         x.setPointer(xPointer)
     self.xContainer.setVisible(True) # seems necessary to refresh the dialog box and text widgets (why?)
     # return
     return result
Пример #40
0
 def _getDataDescriptor(self, row):
     args = []
     value = uno.Enum("com.sun.star.beans.PropertyState", "DIRECT_VALUE")
     args.append(PropertyValue("DataSourceName", -1, self.recipient.ActiveConnection.Parent.Name, value))
     args.append(PropertyValue("ActiveConnection", -1, self.recipient.ActiveConnection, value))
     args.append(PropertyValue("Command", -1, self.query.Name, value))
     args.append(PropertyValue("CommandType", -1, uno.getConstantByName("com.sun.star.sdb.CommandType.QUERY"), value))
     args.append(PropertyValue("Cursor", -1, self.recipient, value))
     args.append(PropertyValue("Selection", -1, [row], value))
     args.append(PropertyValue("BookmarkSelection", -1, False, value))
     return args
Пример #41
0
 def _getPropertySetInfo(self):
     properties = {}
     interface = 'com.sun.star.uno.XInterface'
     optional = 'com.sun.star.beans.Optional<string>'
     readonly = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.READONLY')
     transient = uno.getConstantByName(
         'com.sun.star.beans.PropertyAttribute.TRANSIENT')
     properties['Configuration'] = getProperty('Configuration', interface,
                                               readonly)
     properties['PageId'] = getProperty('PageId', 'short', readonly)
     properties['Window'] = getProperty('Window',
                                        'com.sun.star.awt.XWindow',
                                        readonly)
     properties['Uuid'] = getProperty('Uuid', 'string', readonly)
     properties['AuthorizationCode'] = getProperty('AuthorizationCode',
                                                   optional, transient)
     properties['FirstLoad'] = getProperty('FirstLoad', 'boolean',
                                           transient)
     return properties
Пример #42
0
    def date(self, date):
        """Sets the date of all cells affected by this selector. Expects a datetime.datetime object."""
        delta = date - self.basedate
        self.value = delta.days

        date_format = uno.getConstantByName( "com.sun.star.util.NumberFormat.DATE" )
        formats = self.model.getNumberFormats()
        cells = self.sheet.getCellRangeByName(self.selector)
        #if formats.getByKey(cells).Type != date_format:
        for cell in self._cells:
            if formats.getByKey(cell.NumberFormat).Type != date_format:
                locale = uno.createUnoStruct( "com.sun.star.lang.Locale" )
                cell.NumberFormat = formats.getStandardFormat( date_format, locale )
    def insertBlankPages(self, inputFile, outputFile, pageCount):
        inputUrl = self._fileUrl(inputFile)
        outputUrl = self._fileUrl(outputFile)

        document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, _unoProps(Hidden=True, ReadOnly=True))
        try:
          document.refresh()
        except AttributeError:
          pass

	text = document.getText()
	cursor = text.createTextCursor()

	breakPageAfter = uno.getConstantByName("com.sun.star.style.BreakType.PAGE_AFTER")
	paragraphBreak = uno.getConstantByName("com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK")

	for i in range(pageCount):
		cursor.setPropertyValue("BreakType", breakPageAfter)
		cursor.setPropertyValue("NumberingStyleName", "None")
		text.insertControlCharacter(cursor, paragraphBreak, False)
	
        document.storeToURL(outputUrl, _unoProps())
        document.close(True)
Пример #44
0
    def run (self, sLang):
        try:
            dUI = ca_strings.getUI(sLang)

            # dialog
            self.xDialog = self.xSvMgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialogModel', self.ctx)
            self.xDialog.Width = 160
            self.xDialog.Height = 85
            self.xDialog.Title = dUI.get('title', "#err")

            # fonts
            xFDBut = uno.createUnoStruct("com.sun.star.awt.FontDescriptor")
            xFDBut.Height = 10
            xFDBut.Weight = uno.getConstantByName("com.sun.star.awt.FontWeight.BOLD")
            xFDBut.Name = "Verdana"

            # document
            xDesktop = self.ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", self.ctx)
            self.xDoc = xDesktop.getCurrentComponent()
            sAuthor = self.xDoc.DocumentProperties.Author  if self.xDoc.DocumentProperties.Author  else  dUI.get('empty', "#err")

            # widgets
            nTextWidth = self.xDialog.Width - 20
            state = self._addWidget('state', 'FixedText', 10, 10, nTextWidth, 10, Label = dUI.get('state', "#err"))
            value = self._addWidget('value', 'FixedText', 10, 20, nTextWidth, 10, Label = sAuthor, FontSlant = 2, TextColor = 0x000044)
            
            inputlbl = self._addWidget('inputlbl', 'FixedText', 10, 34, nTextWidth, 10, Label = dUI.get('newvalue', "#err"))
            self.inputtxt = self._addWidget('input', 'Edit', 10, 45, nTextWidth-20, 12, Text=self.xDoc.DocumentProperties.Author, MaxTextLen=150)
            but0 = self._addWidget('reset', 'Button', self.xDialog.Width-25, 45, 15, 12, Label = u"×", FontDescriptor = xFDBut, TextColor = 0x440000)

            but1 = self._addWidget('modify', 'Button', self.xDialog.Width-115, self.xDialog.Height-20, 50, 14, \
                                   Label = dUI.get('modify', "#err"), FontDescriptor = xFDBut, TextColor = 0x004400)
            but2 = self._addWidget('cancel', 'Button', self.xDialog.Width-60, self.xDialog.Height-20, 50, 14, \
                                   Label = dUI.get('cancel', "#err"), FontDescriptor = xFDBut, TextColor = 0x440000)

            # container
            self.xContainer = self.xSvMgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialog', self.ctx)
            self.xContainer.setModel(self.xDialog)
            self.xContainer.getControl('reset').addActionListener(self)
            self.xContainer.getControl('reset').setActionCommand('Reset')
            self.xContainer.getControl('modify').addActionListener(self)
            self.xContainer.getControl('modify').setActionCommand('Modify')
            self.xContainer.getControl('cancel').addActionListener(self)
            self.xContainer.getControl('cancel').setActionCommand('Cancel')
            self.xContainer.setVisible(False)
            xToolkit = self.xSvMgr.createInstanceWithContext('com.sun.star.awt.ExtToolkit', self.ctx)
            self.xContainer.createPeer(xToolkit, None)
            self.xContainer.execute()
        except:
            traceback.print_exc()
Пример #45
0
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
Пример #46
0
 def createSelectTextMessageBox(self):                       #create the select text message box
     #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" )
     ctx=uno.getComponentContext()
     smgr = ctx.ServiceManager
     desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
     doc = desktop.getCurrentComponent()                     #get the current active component
     if not hasattr(doc, "Text"):
         doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
     parentwin = doc.CurrentController.Frame.ContainerWindow
     vclAttribute = uno.getConstantByName("com.sun.star.awt.VclWindowPeerAttribute.OK") 
     windowClass = uno.Enum("com.sun.star.awt.WindowClass","MODALTOP") 
     rectangle = self.createRectangle(50, 100, 300, 200)
     windowService ="messbox"
     msgbox = self.createMessageBox(ctx, smgr,windowClass, parentwin, rectangle, windowService, vclAttribute)
     msgbox.setMessageText(" Select A Text and Press Button")
     msgbox.setCaptionText("No Text")
     return msgbox
Пример #47
0
 def createWaitingMessageBox(self):
     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
     desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
     doc = desktop.getCurrentComponent()
     if not hasattr(doc, "Text"):
         doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
     parentwin = doc.CurrentController.Frame.ContainerWindow
     #vclAttribute=uno.getConstantByName("com.sun.star.awt.WindowAttribute.CLO") 
     vclAttribute = uno.getConstantByName("com.sun.star.awt.VclWindowPeerAttribute.OK") 
     windowClass = uno.Enum("com.sun.star.awt.WindowClass","MODALTOP") 
     rectangle = self.createRectangle(50, 100, 300, 200)
     windowService ="messbox"
     msgbox = self.createMessageBox(ctx, smgr,windowClass, parentwin, rectangle, windowService, vclAttribute)
     msgbox.setMessageText("Fetching Data from Wolfram Alpha Math Engine")
     msgbox.setCaptionText("In Progress")
     return msgbox
Пример #48
0
def messagebox(ctx, parent, message, title, message_type, buttons):
    """ Show message in message box. """
    toolkit = parent.getToolkit()
    older_imple = check_method_parameter(
        ctx, "com.sun.star.awt.XMessageBoxFactory", "createMessageBox", 
        1, "com.sun.star.awt.Rectangle")
    if older_imple:
        msgbox = toolkit.createMessageBox(
            parent, Rectangle(), message_type, buttons, title, message)
    else:
        message_type = uno.getConstantByName("com.sun.star.awt.MessageBoxType." + {
            "messbox": "MESSAGEBOX", "infobox": "INFOBOX", 
            "warningbox": "WARNINGBOX", "errorbox": "ERRORBOX", 
            "querybox": "QUERYBOX"}[message_type])
        msgbox = toolkit.createMessageBox(
            parent, message_type, buttons, title, message)
    n = msgbox.execute()
    msgbox.dispose()
    return n
Пример #49
0
    def notifyContextMenuExecute (self, xEvent):
        sWord = self._getWord()
        try:
            aItem, aVerb = oLexicographe.analyzeWord(sWord)
            if not aItem:
                #return uno.Enum("com.sun.star.ui.ContextMenuInterceptorAction", "IGNORED") # don’t work on AOO, have to import the value
                return IGNORED

            xContextMenu = xEvent.ActionTriggerContainer
            if xContextMenu:
                # entries index
                i = xContextMenu.Count

                nUnoConstantLine = uno.getConstantByName("com.sun.star.ui.ActionTriggerSeparatorType.LINE")
                i = self._addItemToContextMenu(xContextMenu, i, "ActionTriggerSeparator", SeparatorType=nUnoConstantLine)
                for item in aItem:
                    if isinstance(item, str):
                        i = self._addItemToContextMenu(xContextMenu, i, "ActionTrigger", Text=item)
                    elif isinstance(item, tuple):
                        sRoot, lMorph = item
                        # submenu
                        xSubMenuContainer = xContextMenu.createInstance("com.sun.star.ui.ActionTriggerContainer")
                        for j, s in enumerate(lMorph):
                            self._addItemToContextMenu(xSubMenuContainer, j, "ActionTrigger", Text=s)
                        # create root menu entry
                        i = self._addItemToContextMenu(xContextMenu, i, "ActionTrigger", Text=sRoot, SubContainer=xSubMenuContainer)
                    else:
                        i = self._addItemToContextMenu(xContextMenu, i, "ActionTrigger", Text="# erreur : {}".format(item))
                
                # Links to Conjugueur
                if aVerb:
                    i = self._addItemToContextMenu(xContextMenu, i, "ActionTriggerSeparator", SeparatorType=nUnoConstantLine)
                    for sVerb in aVerb:
                        i = self._addItemToContextMenu(xContextMenu, i, "ActionTrigger", Text="Conjuguer “{}”…".format(sVerb),
                                                       CommandURL="service:net.grammalecte.AppLauncher?CJ/"+sVerb)

                # The controller should execute the modified context menu and stop notifying other interceptors.
                #return uno.Enum("com.sun.star.ui.ContextMenuInterceptorAction", "EXECUTE_MODIFIED") # don’t work on AOO, have to import the value
                return EXECUTE_MODIFIED
        except:
            traceback.print_exc()
        #return uno.Enum("com.sun.star.ui.ContextMenuInterceptorAction", "IGNORED") # don’t work on AOO, have to import the value
        return IGNORED
Пример #50
0
 def MsgBox(self, message, title="", message_type="infobox", buttons=1):
     """ Show message in message box. """
     parent = self.StarDesktop.getCurrentFrame().getContainerWindow()
     toolkit = parent.getToolkit()
     older_imple = self._check_method_parameter(
             "com.sun.star.awt.XMessageBoxFactory", "createMessageBox",
             1, "com.sun.star.awt.Rectangle")
     if older_imple:
         from com.sun.star.awt import Rectangle
         msgbox = toolkit.createMessageBox(
             parent, Rectangle(), message_type, buttons, title, message)
     else:
         message_type = uno.getConstantByName("com.sun.star.awt.MessageBoxType." + {
             "messbox": "MESSAGEBOX", "infobox": "INFOBOX",
             "warningbox": "WARNINGBOX", "errorbox": "ERRORBOX",
             "querybox": "QUERYBOX"}[message_type])
         msgbox = toolkit.createMessageBox(
             parent, message_type, buttons, title, message)
     n = msgbox.execute()
     msgbox.dispose()
     return n
Пример #51
0
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
Пример #52
0
def show_message(ctx, frame, message, title="", type="messbox", buttons=1, labels=None):
    """ Show text in message box. """
    try:
        peer = frame.getContainerWindow()
    except:
        peer = frame
    
    older_imple = check_method_parameter(
        ctx, "com.sun.star.awt.XMessageBoxFactory", 
        "createMessageBox", 1, "com.sun.star.awt.Rectangle")
    
    if older_imple:
        box = peer.getToolkit().createMessageBox(
            peer, Rectangle(), type, buttons, title, message)
    else:
        if type == "messbox":
            name = "MESSAGEBOX"
        elif type == "infobox":
            name = "INFOBOX"
        elif type == "warningbox":
            name = "WARNINGBOX"
        elif type == "errorbox":
            name = "ERRORBOX"
        elif type == "querybox":
            name = "QUERYBOX"
        type = uno.getConstantByName("com.sun.star.awt.MessageBoxType." + name)
        box = peer.getToolkit().createMessageBox(
            peer, type, buttons, title, message)
    
    ws = box.getWindows()
    if labels and len(ws) == len(labels):
        for label, w in zip(labels, ws):
            w.Label = label
    
    n = box.execute()
    box.dispose()
    return n
Пример #53
0
#  cx_freeze -- not too sure if I care about this or not...

# Exceptions
UnoException = uno.getClass('com.sun.star.uno.Exception')
NoConnectException = uno.getClass('com.sun.star.connection.NoConnectException')
RuntimeException = uno.getClass('com.sun.star.uno.RuntimeException')
IllegalArgumentException = uno.getClass(
                    'com.sun.star.lang.IllegalArgumentException')
DisposedException = uno.getClass('com.sun.star.lang.DisposedException')
IOException = uno.getClass('com.sun.star.io.IOException')
NoSuchElementException = uno.getClass(
                    'com.sun.star.container.NoSuchElementException')


# Control Characters
PARAGRAPH_BREAK = uno.getConstantByName(
                    'com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK')
LINE_BREAK = uno.getConstantByName(
                    'com.sun.star.text.ControlCharacter.LINE_BREAK')
HARD_HYPHEN = uno.getConstantByName(
                    'com.sun.star.text.ControlCharacter.HARD_HYPHEN')
SOFT_HYPHEN = uno.getConstantByName(
                    'com.sun.star.text.ControlCharacter.SOFT_HYPHEN')
HARD_SPACE = uno.getConstantByName(
                    'com.sun.star.text.ControlCharacter.HARD_SPACE')
APPEND_PARAGRAPH = uno.getConstantByName(
                    'com.sun.star.text.ControlCharacter.APPEND_PARAGRAPH')


# Styles
SLANT_ITALIC = uno.getConstantByName('com.sun.star.awt.FontSlant.ITALIC')
SLANT_NONE = uno.getConstantByName('com.sun.star.awt.FontSlant.NONE')
Пример #54
0
 def setHoriJustify(self,j):
     debug("setHoriJustify %s" % (j))
     self.cell.HoriJustify = uno.getConstantByName("com.sun.star.awt.TextAlign." + j)
Пример #55
0
 def setCharWeight(self, w):
     debug("setFontWeight %s" % (w))
     self.cell.CharWeight = uno.getConstantByName("com.sun.star.awt.FontWeight." + w )
Пример #56
0
    def run (self, sUI):
        try:
            dUI = op_strings.getUI(sUI)
            dUI2 = gce.gc_options.getUI(sUI)

            # fonts
            xFDTitle = uno.createUnoStruct("com.sun.star.awt.FontDescriptor")
            xFDTitle.Height = 9
            xFDTitle.Weight = uno.getConstantByName("com.sun.star.awt.FontWeight.BOLD")
            xFDTitle.Name = "Verdana"

            xFDBut = uno.createUnoStruct("com.sun.star.awt.FontDescriptor")
            xFDBut.Height = 10
            xFDBut.Weight = uno.getConstantByName("com.sun.star.awt.FontWeight.BOLD")
            xFDBut.Name = "Verdana"

            # dialog
            self.xDialog = self.xSvMgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialogModel', self.ctx)
            self.xDialog.Width = 300
            self.xDialog.Height = 400
            self.xDialog.Title = dUI.get('title', "#err")
            
            # build
            y = 0
            nWidth = self.xDialog.Width - 20
            nHeight = 10
            
            self.lxOptions = []

            for t in gce.gc_options.lStructOpt:
                x = 10
                y += 10
                self._addWidget(t[0], 'FixedLine', x, y, nWidth, nHeight, Label = dUI2.get(t[0], "#err")[0], FontDescriptor= xFDTitle)
                y += 3
                for lOptLine in t[1]:
                    x = 15
                    y += 10
                    n = len(lOptLine)
                    for sOpt in lOptLine:
                        w = self._addWidget(sOpt, 'CheckBox', x, y, nWidth/n, nHeight, State = options.get(sOpt, False), \
                                            Label = dUI2.get(sOpt, "#err")[0], HelpText = dUI2.get(sOpt, "#err")[1])
                        self.lxOptions.append(w)
                        x += nWidth / n
            
            self.xDialog.Height = y + 40

            but0 = self._addWidget('default', 'Button', 10, self.xDialog.Height-20, 50, 14, \
                                   Label = dUI.get('default', "#err"), FontDescriptor = xFDBut, TextColor = 0x000044)
            but1 = self._addWidget('apply', 'Button', self.xDialog.Width-115, self.xDialog.Height-20, 50, 14, \
                                   Label = dUI.get('apply', "#err"), FontDescriptor = xFDBut, TextColor = 0x004400)
            but2 = self._addWidget('cancel', 'Button', self.xDialog.Width-60, self.xDialog.Height-20, 50, 14,
                                   Label = dUI.get('cancel', "#err"), FontDescriptor = xFDBut, TextColor = 0x440000)

            # container
            self.xContainer = self.xSvMgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialog', self.ctx)
            self.xContainer.setModel(self.xDialog)
            self.xContainer.getControl('default').addActionListener(self)
            self.xContainer.getControl('default').setActionCommand('Default')
            self.xContainer.getControl('apply').addActionListener(self)
            self.xContainer.getControl('apply').setActionCommand('Apply')
            self.xContainer.getControl('cancel').addActionListener(self)
            self.xContainer.getControl('cancel').setActionCommand('Cancel')
            self.xContainer.setVisible(False)
            xToolkit = self.xSvMgr.createInstanceWithContext('com.sun.star.awt.ExtToolkit', self.ctx)
            self.xContainer.createPeer(xToolkit, None)
            self.xContainer.execute()
        except:
            traceback.print_exc()
Пример #57
0
    def run (self, sArgs=""):
        ## dialog
        self.xDialog = self.xSvMgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialogModel', self.ctx)
        self.xDialog.Width = 250
        self.xDialog.Title = u"Grammalecte · Conjugueur"

        xFDinput = uno.createUnoStruct("com.sun.star.awt.FontDescriptor")
        xFDinput.Height = 11
        xFDinput.Weight = uno.getConstantByName("com.sun.star.awt.FontWeight.BOLD")
        xFDinput.Name = "Verdana"

        xFDmode = uno.createUnoStruct("com.sun.star.awt.FontDescriptor")
        xFDmode.Height = 13
        xFDmode.Name = "Constantia"

        xFDtemps = uno.createUnoStruct("com.sun.star.awt.FontDescriptor")
        xFDtemps.Height = 10
        xFDtemps.Weight = uno.getConstantByName("com.sun.star.awt.FontWeight.BOLD")
        xFDtemps.Name = "Constantia"

        xFDbold = uno.createUnoStruct("com.sun.star.awt.FontDescriptor")
        xFDbold.Height = 10
        xFDbold.Weight = uno.getConstantByName("com.sun.star.awt.FontWeight.BOLD")
        xFDbold.Name = "Verdana"

        xFDinfo = uno.createUnoStruct("com.sun.star.awt.FontDescriptor")
        xFDinfo.Height = 7
        xFDinfo.Name = "Verdana"

        xFDsmall = uno.createUnoStruct("com.sun.star.awt.FontDescriptor")
        xFDsmall.Height = 6
        xFDsmall.Name = "Verdana"

        ## widgets
        nGroupBoxWith = (self.xDialog.Width - 16) // 2
        nWidth = nGroupBoxWith-10
        nHeight = 10
        nHeightCj = 8
        nColorHead = 0xAA2200
        nColorHead2 = 0x0022AA

        # grid
        nX1 = 10; nX2 = nX1+123;
        nY0 = 2; nY1 = nY0+28; nY2 = nY1-4; nY3 = nY1+15; nY4 = nY3+49; nY5 = nY4+53; nY6 = nY5+53; nY7 = nY6+53; nY6b = nY6+20; nY7b = nY6b+53

        # group box // indicatif
        gb_infi = self._addWidget('groupbox_infi', 'GroupBox', nX1-5, nY0, nGroupBoxWith, 25, Label = "Infinitif", \
                                  FontDescriptor = xFDmode, FontRelief = 1, TextColor = nColorHead)
        self.infi = self._addWidget('infi', 'FixedText', nX1, nY0+12, nWidth, nHeight, Label = "", FontDescriptor = xFDbold)

        # input field + button
        self.input = self._addWidget('input', 'ComboBox', nX2-5, nY0+5, 68, 14, \
                                     FontDescriptor = xFDinput, TextColor = 0x666666, Dropdown = True, LineCount = 20)
        for n, s in enumerate(self.lDropDown):
            self.input.insertItemText(n, s)
        self.cbutton = self._addWidget('cbutton', 'Button', nX2+66, nY0+5, 46, 14, Label = "Conjuguer", FontDescriptor = xFDinput)

        # informations
        self.info = self._addWidget('info', 'FixedText', nX1, nY1, nWidth, nHeight, FontDescriptor = xFDinfo)

        # options
        self.oneg = self._addWidget('oneg', 'CheckBox', nX2-5, nY2, 35, nHeight, Label = u"négation")
        self.opro = self._addWidget('opro', 'CheckBox', nX2+30, nY2, 50, nHeight, Label = u"pronominal")
        self.ofem = self._addWidget('ofem', 'CheckBox', nX2+80, nY2, 45, nHeight, Label = u"féminin")
        self.oint = self._addWidget('oint', 'CheckBox', nX2-5, nY2+9, 55, nHeight, Label = u"interrogatif")
        self.otco = self._addWidget('otco', 'CheckBox', nX2+55, nY2+9, 60, nHeight, Label = u"temps composés")

        # group box // participe passé
        gb_ppas = self._addWidget('groupbox_ppas', 'GroupBox', nX1-5, nY3-7, nGroupBoxWith, 55, Label = u"Participes présent et passés", \
                                  FontDescriptor = xFDmode, FontRelief = 1, TextColor = nColorHead)
        self.ppre = self._addWidget('ppre', 'FixedText', nX1, nY3+5, nWidth, nHeightCj, Label = "")
        self.ppas1 = self._addWidget('ppas1', 'FixedText', nX1, nY3+14, nWidth, nHeightCj, Label = "")
        self.ppas2 = self._addWidget('ppas2', 'FixedText', nX1, nY3+21, nWidth, nHeightCj, Label = "")
        self.ppas3 = self._addWidget('ppas3', 'FixedText', nX1, nY3+28, nWidth, nHeightCj, Label = "")
        self.ppas4 = self._addWidget('ppas4', 'FixedText', nX1, nY3+35, nWidth, nHeightCj, Label = "")

        # group box // impératif
        gb_impe = self._addWidget('groupbox_impe', 'GroupBox', nX2-5, nY3, nGroupBoxWith, 48, Label = u"Impératif", \
                                  FontDescriptor = xFDmode, FontRelief = 1, TextColor = nColorHead)
        self.impe = self._addWidget('impe', 'FixedText', nX2, nY3+12, nWidth, nHeight, Label = u"Présent", \
                                    FontDescriptor = xFDtemps, FontRelief = 1, TextColor = nColorHead2)
        self.impe1 = self._addWidget('impe1', 'FixedText', nX2, nY3+21, nWidth, nHeightCj, Label = "")
        self.impe2 = self._addWidget('impe2', 'FixedText', nX2, nY3+28, nWidth, nHeightCj, Label = "")
        self.impe3 = self._addWidget('impe3', 'FixedText', nX2, nY3+35, nWidth, nHeightCj, Label = "")

        # group box // indicatif
        gb_ind = self._addWidget('groupbox_ind', 'GroupBox', nX1-5, nY4, nGroupBoxWith, 228, Label = u"Indicatif", \
                                 FontDescriptor = xFDmode, FontRelief = 1, TextColor = nColorHead)
        self.ipre = self._addWidget('ipre', 'FixedText', nX1, nY4+12, nWidth, nHeight, Label = u"Présent", \
                                    FontDescriptor = xFDtemps, FontRelief = 1, TextColor = nColorHead2)
        self.ipre1 = self._addWidget('ipre1', 'FixedText', nX1, nY4+21, nWidth, nHeightCj, Label = "")
        self.ipre2 = self._addWidget('ipre2', 'FixedText', nX1, nY4+28, nWidth, nHeightCj, Label = "")
        self.ipre3 = self._addWidget('ipre3', 'FixedText', nX1, nY4+35, nWidth, nHeightCj, Label = "")
        self.ipre4 = self._addWidget('ipre4', 'FixedText', nX1, nY4+42, nWidth, nHeightCj, Label = "")
        self.ipre5 = self._addWidget('ipre5', 'FixedText', nX1, nY4+49, nWidth, nHeightCj, Label = "")
        self.ipre6 = self._addWidget('ipre6', 'FixedText', nX1, nY4+56, nWidth, nHeightCj, Label = "")

        self.iimp = self._addWidget('iimp', 'FixedText', nX1, nY5+12, nWidth, nHeight, Label = u"Imparfait", \
                                    FontDescriptor = xFDtemps, FontRelief = 1, TextColor = nColorHead2)
        self.iimp1 = self._addWidget('iimp1', 'FixedText', nX1, nY5+21, nWidth, nHeightCj, Label = "")
        self.iimp2 = self._addWidget('iimp2', 'FixedText', nX1, nY5+28, nWidth, nHeightCj, Label = "")
        self.iimp3 = self._addWidget('iimp3', 'FixedText', nX1, nY5+35, nWidth, nHeightCj, Label = "")
        self.iimp4 = self._addWidget('iimp4', 'FixedText', nX1, nY5+42, nWidth, nHeightCj, Label = "")
        self.iimp5 = self._addWidget('iimp5', 'FixedText', nX1, nY5+49, nWidth, nHeightCj, Label = "")
        self.iimp6 = self._addWidget('iimp6', 'FixedText', nX1, nY5+56, nWidth, nHeightCj, Label = "")

        self.ipsi = self._addWidget('ipsi', 'FixedText', nX1, nY6+12, nWidth, nHeight, Label = u"Passé Simple", \
                                    FontDescriptor = xFDtemps, FontRelief = 1, TextColor = nColorHead2)
        self.ipsi1 = self._addWidget('ipsi1', 'FixedText', nX1, nY6+21, nWidth, nHeightCj, Label = "")
        self.ipsi2 = self._addWidget('ipsi2', 'FixedText', nX1, nY6+28, nWidth, nHeightCj, Label = "")
        self.ipsi3 = self._addWidget('ipsi3', 'FixedText', nX1, nY6+35, nWidth, nHeightCj, Label = "")
        self.ipsi4 = self._addWidget('ipsi4', 'FixedText', nX1, nY6+42, nWidth, nHeightCj, Label = "")
        self.ipsi5 = self._addWidget('ipsi5', 'FixedText', nX1, nY6+49, nWidth, nHeightCj, Label = "")
        self.ipsi6 = self._addWidget('ipsi6', 'FixedText', nX1, nY6+56, nWidth, nHeightCj, Label = "")

        self.ifut = self._addWidget('ifut', 'FixedText', nX1, nY7+12, nWidth, nHeight, Label = u"Futur", \
                                    FontDescriptor = xFDtemps, FontRelief = 1, TextColor = nColorHead2)
        self.ifut1 = self._addWidget('ifut1', 'FixedText', nX1, nY7+21, nWidth, nHeightCj, Label = "")
        self.ifut2 = self._addWidget('ifut2', 'FixedText', nX1, nY7+28, nWidth, nHeightCj, Label = "")
        self.ifut3 = self._addWidget('ifut3', 'FixedText', nX1, nY7+35, nWidth, nHeightCj, Label = "")
        self.ifut4 = self._addWidget('ifut4', 'FixedText', nX1, nY7+42, nWidth, nHeightCj, Label = "")
        self.ifut5 = self._addWidget('ifut5', 'FixedText', nX1, nY7+49, nWidth, nHeightCj, Label = "")
        self.ifut6 = self._addWidget('ifut6', 'FixedText', nX1, nY7+56, nWidth, nHeightCj, Label = "")

        self.infomsg = self._addWidget('infomsg', 'FixedText', nX1-5, nY7+74, 120, 20, FontDescriptor = xFDsmall, MultiLine = True, TextColor = 0x333333, \
                                       Label = u"De nombreux verbes n’ont pas encore été étiquetés et contrôlés. " \
                                               u"Pour ceux-ci, les options “pronominal” et “temps composés” sont désactivées.")

        # group box // subjonctif
        gb_sub = self._addWidget('groupbox_sub', 'GroupBox', nX2-5, nY4, nGroupBoxWith, 123, Label = u"Subjonctif", \
                                 FontDescriptor = xFDmode, FontRelief = 1, TextColor = nColorHead)
        self.spre = self._addWidget('spre', 'FixedText', nX2, nY4+12, nWidth, nHeight, Label = u"Présent", \
                                    FontDescriptor = xFDtemps, FontRelief = 1, TextColor = nColorHead2)
        self.spre1 = self._addWidget('spre1', 'FixedText', nX2, nY4+21, nWidth, nHeightCj, Label = "")
        self.spre2 = self._addWidget('spre2', 'FixedText', nX2, nY4+28, nWidth, nHeightCj, Label = "")
        self.spre3 = self._addWidget('spre3', 'FixedText', nX2, nY4+35, nWidth, nHeightCj, Label = "")
        self.spre4 = self._addWidget('spre4', 'FixedText', nX2, nY4+42, nWidth, nHeightCj, Label = "")
        self.spre5 = self._addWidget('spre5', 'FixedText', nX2, nY4+49, nWidth, nHeightCj, Label = "")
        self.spre6 = self._addWidget('spre6', 'FixedText', nX2, nY4+56, nWidth, nHeightCj, Label = "")

        self.simp = self._addWidget('simp', 'FixedText', nX2, nY5+12, nWidth, nHeight, Label = u"Imparfait", \
                                    FontDescriptor = xFDtemps, FontRelief = 1, TextColor = nColorHead2)
        self.simp1 = self._addWidget('simp1', 'FixedText', nX2, nY5+21, nWidth, nHeightCj, Label = "")
        self.simp2 = self._addWidget('simp2', 'FixedText', nX2, nY5+28, nWidth, nHeightCj, Label = "")
        self.simp3 = self._addWidget('simp3', 'FixedText', nX2, nY5+35, nWidth, nHeightCj, Label = "")
        self.simp4 = self._addWidget('simp4', 'FixedText', nX2, nY5+42, nWidth, nHeightCj, Label = "")
        self.simp5 = self._addWidget('simp5', 'FixedText', nX2, nY5+49, nWidth, nHeightCj, Label = "")
        self.simp6 = self._addWidget('simp6', 'FixedText', nX2, nY5+56, nWidth, nHeightCj, Label = "")

        # group box // conditionnel
        gb_cond = self._addWidget('groupbox_cond', 'GroupBox', nX2-5, nY6b, nGroupBoxWith, 123, Label = u"Conditionnel", \
                                  FontDescriptor = xFDmode, FontRelief = 1, TextColor = nColorHead)
        self.conda = self._addWidget('conda', 'FixedText', nX2, nY6b+12, nWidth, nHeight, Label = u"Présent", \
                                     FontDescriptor = xFDtemps, FontRelief = 1, TextColor = nColorHead2)
        self.conda1 = self._addWidget('conda1', 'FixedText', nX2, nY6b+21, nWidth, nHeightCj, Label = "")
        self.conda2 = self._addWidget('conda2', 'FixedText', nX2, nY6b+28, nWidth, nHeightCj, Label = "")
        self.conda3 = self._addWidget('conda3', 'FixedText', nX2, nY6b+35, nWidth, nHeightCj, Label = "")
        self.conda4 = self._addWidget('conda4', 'FixedText', nX2, nY6b+42, nWidth, nHeightCj, Label = "")
        self.conda5 = self._addWidget('conda5', 'FixedText', nX2, nY6b+49, nWidth, nHeightCj, Label = "")
        self.conda6 = self._addWidget('conda6', 'FixedText', nX2, nY6b+56, nWidth, nHeightCj, Label = "")

        self.condb = self._addWidget('condb', 'FixedText', nX2, nY7b+12, nWidth, nHeight, Label = "", \
                                     FontDescriptor = xFDtemps, FontRelief = 1, TextColor = nColorHead2)
        self.condb1 = self._addWidget('condb1', 'FixedText', nX2, nY7b+21, nWidth, nHeightCj, Label = "")
        self.condb2 = self._addWidget('condb2', 'FixedText', nX2, nY7b+28, nWidth, nHeightCj, Label = "")
        self.condb3 = self._addWidget('condb3', 'FixedText', nX2, nY7b+35, nWidth, nHeightCj, Label = "")
        self.condb4 = self._addWidget('condb4', 'FixedText', nX2, nY7b+42, nWidth, nHeightCj, Label = "")
        self.condb5 = self._addWidget('condb5', 'FixedText', nX2, nY7b+49, nWidth, nHeightCj, Label = "")
        self.condb6 = self._addWidget('condb6', 'FixedText', nX2, nY7b+56, nWidth, nHeightCj, Label = "")

        # dialog height
        self.xDialog.Height = 350

        ## container
        self.xContainer = self.xSvMgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialog', self.ctx)
        self.xContainer.setModel(self.xDialog)
        self.xContainer.setVisible(False)

        #self.xContainer.getControl('input').addEventListener(self)
        #self.xContainer.getControl('input').addEventCommand('New')
        self.xContainer.getControl('cbutton').addActionListener(self)
        self.xContainer.getControl('cbutton').setActionCommand('New')
        self.xContainer.getControl('oneg').addActionListener(self)
        self.xContainer.getControl('oneg').setActionCommand('Change')
        self.xContainer.getControl('opro').addActionListener(self)
        self.xContainer.getControl('opro').setActionCommand('Change')
        self.xContainer.getControl('oint').addActionListener(self)
        self.xContainer.getControl('oint').setActionCommand('Change')
        self.xContainer.getControl('otco').addActionListener(self)
        self.xContainer.getControl('otco').setActionCommand('Change')
        self.xContainer.getControl('ofem').addActionListener(self)
        self.xContainer.getControl('ofem').setActionCommand('Change')

        ## set verb
        self.input.Text = sArgs  if sArgs  else u"être"
        self._newVerb()

        ## mysterious action
        xToolkit = self.xSvMgr.createInstanceWithContext('com.sun.star.awt.ExtToolkit', self.ctx)
        self.xContainer.createPeer(xToolkit, None)
        self.xContainer.execute()
Пример #58
0
def TestMessageBox():
    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
    Rectangle =uno.createUnoStruct("com.sun.star.awt.Rectangle")
    Rectangle.Width =100
    Rectangle.Height=100
    Rectangle.X=0
    Rectangle.Y=300
    WindowDescriptor = uno.createUnoStruct("com.sun.star.awt.WindowDescriptor") 
    WindowClass = uno.Enum("com.sun.star.awt.WindowClass","MODALTOP")      
    print(WindowClass)
    VclWindowPeerAttribute = uno.getConstantByName("com.sun.star.awt.VclWindowPeerAttribute.OK")
    print(VclWindowPeerAttribute)
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
    doc = desktop.getCurrentComponent()
    if not hasattr(doc, "Text"):
        doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )    
    parentwin = doc.CurrentController.Frame.ContainerWindow
 
    s = "This is a test"
    t = "Test"
    # res = MessageBox(parentwin, s, t, "querybox", VclWindowPeerAttribute.YES_NO_CANCEL + VclWindowPeerAttribute.DEF_NO)
 
    #s = res
    MsgType = "messbox".lower()
 
    #available msg types
    MsgTypes = ("messbox", "infobox", "errorbox", "warningbox", "querybox")
 
    if not ( MsgType in MsgTypes ):
        MsgType = "messbox"
    print(WindowClass)
    #describe window properties.
    aDescriptor = WindowDescriptor
    aDescriptor.Type = WindowClass
    aDescriptor.WindowServiceName = "listbox"
    aDescriptor.ParentIndex = -1
    aDescriptor.Parent = parentwin
    aDescriptor.Bounds = Rectangle
    aDescriptor.WindowAttributes=uno.getConstantByName("com.sun.star.awt.VclWindowPeerAttribute.YES_NO_CANCEL")
#     aDescriptor.WindowAttributes= 1
    tk = aDescriptor.Parent.getToolkit()
    #msgbox.execute()
    lstbox = tk.createWindow(aDescriptor)
    lstbox.addItem("added",0)
    lstbox.addItem("added",1)
    lstbox.makeVisible(1)
    print(lstbox)
    lstbox.Visible=True
    lstbox.setProperty('Dropdown',True)
    lstbox.setProperty('Focus',True)
    lstbox.setProperty('Enabled',True)
    #lstbox.invalidate(16384)
    a=lstbox.getProperties()
    for b in a:
        print(b)
    listbox = smgr.createInstanceWithContext("com.sun.star.awt.UnoControlListBoxModel",ctx)
    #lsPropSet = listbox.createInstance("com.sun.star.beans.XMultiPropertySet")
    #listbox.Enable=True;
    print(lstbox.hasFocus())
    print(lstbox.getOutputSize())
    itemList = uno.createUnoStruct("com.sun.star.awt.XItemList")
    print(itemList)
    #listbox.insertItem=(1,'red','')
    items=[]
    items.append("item1")
    items.append("item2")
    print(listbox.StringItemList)
    listbox.StringItemList = uno.ByteSequence("item1item2")
    print(listbox.StringItemList)
Пример #59
0
 def testConstant( self ):
     self.failUnless( uno.getConstantByName( "com.sun.star.beans.PropertyConcept.ATTRIBUTES" ) == 4,\
                                      "constant retrieval test" )
Пример #60
0
#   except in compliance with the License. You may obtain a copy of
#   the License at http://www.apache.org/licenses/LICENSE-2.0 .
#
import uno
import traceback
from unohelper import systemPathToFileUrl, absolutize
from ..common.Desktop import Desktop

from com.sun.star.awt import WindowDescriptor
from com.sun.star.awt import Rectangle
from com.sun.star.awt.WindowClass import TOP
from com.sun.star.task import ErrorCodeIOException

#Window Constants
com_sun_star_awt_WindowAttribute_BORDER \
    = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.BORDER" )
com_sun_star_awt_WindowAttribute_SIZEABLE \
    = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.SIZEABLE" )
com_sun_star_awt_WindowAttribute_MOVEABLE \
    = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.MOVEABLE" )
com_sun_star_awt_VclWindowPeerAttribute_CLIPCHILDREN \
    = uno.getConstantByName(
        "com.sun.star.awt.VclWindowPeerAttribute.CLIPCHILDREN" )

class OfficeDocument(object):
    '''Creates a new instance of OfficeDocument '''

    def __init__(self, _xMSF):
        self.xMSF = _xMSF

    @classmethod