def actionPerformed (self, actionEvent): try: if self.xRB_m.getState(): self.sSelectedDic = 'moderne' elif self.xRB_c.getState(): self.sSelectedDic = 'classique' elif self.xRB_r.getState(): self.sSelectedDic = 'reforme1990' elif self.xRB_t.getState(): self.sSelectedDic = 'toutesvariantes' else: # no dictionary selected pass if self.sSelectedDic and self.sSelectedDic != self.sCurrentDic : # Modify the registry xSettings = helpers.getConfigSetting("/org.openoffice.Office.Linguistic/ServiceManager/Dictionaries/HunSpellDic_fr", True) xLocations = xSettings.getByName("Locations") v1 = xLocations[0].replace(self.sCurrentDic, self.sSelectedDic) v2 = xLocations[1].replace(self.sCurrentDic, self.sSelectedDic) #xSettings.replaceByName("Locations", xLocations) # doesn't work, see line below uno.invoke(xSettings, "replaceByName", ("Locations", uno.Any("[]string", (v1, v2)))) xSettings.commitChanges() self.xContainer.endExecute() except: traceback.print_exc()
def updateData(self): useUno = False try: try: data = getattr(self._dataObject, self._field) except Exception: useUno = True data = uno.invoke(self._dataObject, "get" + self._field, ()) ui = self.getFromUI() if data is not ui: if isinstance(ui,Date): d = datetime(ui.Year, ui.Month, ui.Day) ui = d.strftime('%d/%m/%y') elif isinstance(ui,Time): t = datetime(1, 1, 1, ui.Hours, ui.Minutes) ui = t.strftime('%H:%M') if useUno: uno.invoke(self._dataObject, "set" + self._field, (ui,)) else: if isinstance(ui,tuple): #Listbox Element ui = ui[0] setattr(self._dataObject, self._field, ui) except Exception: traceback.print_exc()
def generateTestPropertyValues(self, count): sm = self.context.ServiceManager values = sm.createInstanceWithContext("com.sun.star.document.IndexedPropertyValues", self.context) for i in range(count): properties = (PropertyValue(Name='n'+str(i), Value='v'+str(i)),) uno.invoke(values, "insertByIndex", (i, uno.Any("[]com.sun.star.beans.PropertyValue", properties))) return values
def removeMenuItem( self, documenttype, command, submenu = False ): aUIMgr = self.ctx.ServiceManager.createInstanceWithContext( 'com.sun.star.ui.ModuleUIConfigurationManagerSupplier', self.ctx ) xUIMgr = aUIMgr.getUIConfigurationManager( documenttype ) settings = xUIMgr.getSettings( 'private:resource/menubar/menubar', True ) def findCommand( items, command ): for i in range( items.getCount() ): menu = unprops( items.getByIndex( i ) ) if 'CommandURL' in menu and menu.CommandURL == command: return items, i + 1 if 'ItemDescriptorContainer' in menu and menu.ItemDescriptorContainer: container, index = findCommand( menu.ItemDescriptorContainer, command ) if container is not None: return container, index return None, None if submenu or ':' in command: url = command else: url = self.commandURL( command ) container, index = findCommand( settings, url ) while container is not None: uno.invoke( container, 'removeByIndex', (index-1,) ) container, index = findCommand( settings, url ) xUIMgr.replaceSettings( 'private:resource/menubar/menubar', settings) xUIMgr.store()
def tstDoc(self): try: props = [("ReadOnly", True)] loadProps = tuple([self.mkPropertyValue(name, value) for (name, value) in props]) m_xMSF = self.xContext.ServiceManager desktop = m_xMSF.createInstanceWithContext('com.sun.star.frame.Desktop', self.xContext) filepath = os.path.abspath("FIXME") if os.name == "nt": sourceFile = "file:///" + filepath + "/" + quote(self.fileName) else: sourceFile = "file://" + quote(filepath) + "/" + quote(self.fileName) self.xDoc = desktop.loadComponentFromURL(sourceFile ,"_blank", 0 , loadProps) assert(self.xDoc) if os.name == "nt": targetFile = "file:///" + self.m_TargetDir + quote(self.m_SourceDir) + "/" + quote(self.fileName) else: targetFile = "file://" + quote(self.m_TargetDir) + quote(self.m_SourceDir) + "/" + quote(self.fileName) p1 = PropertyValue() PropValue = uno.Any("[]com.sun.star.beans.PropertyValue", (p1,)) uno.invoke(self.xDoc, "storeToURL", (targetFile, PropValue)) except Exception: raise
def testInvoke( self ): self.failUnless( 5 == uno.invoke( self.tobj , "transportAny" , (uno.Any("byte", 5),) ) ) self.failUnless( 5 == uno.invoke( PythonTransporter(), "transportAny" , (uno.Any( "byte", 5 ),) ) ) t = uno.getTypeByName( "long" ) mystruct = uno.createUnoStruct( "com.sun.star.beans.PropertyValue", "foo",0,uno.Any(t,2),0 ) mystruct.Value = uno.Any(t, 1)
def breakLinkOfTextSection(self, oTextSection): try: oSectionLink = \ uno.createUnoStruct('com.sun.star.text.SectionFileLink') oSectionLink.FileURL = "" uno.invoke(oTextSection, "setPropertyValues", (("FileLink", "LinkRegion"), (oSectionLink, ""))) except Exception: traceback.print_exc()
def insertControlModel(self, serviceName, componentName, sPropNames, oPropValues): try: xControlModel = self.xDialogModel.createInstance(serviceName) uno.invoke(xControlModel, "setPropertyValues", (sPropNames, oPropValues)) self.xDialogModel.insertByName(componentName, xControlModel) xControlModel.Name = componentName except Exception: traceback.print_exc() aObj = self.xUnoDialog.getControl(componentName) return aObj
def addControl(self, sAwtName, sControlName, dProps): oControlModel = self.DialogModel.createInstance("com.sun.star.awt.UnoControl" + sAwtName + "Model") while dProps: prp = dProps.popitem() uno.invoke(oControlModel, "setPropertyValue", (prp[0], prp[1])) oControlModel.Name = sControlName self.DialogModel.insertByName(sControlName, oControlModel) if sAwtName == "Button": self.DialogContainer.getControl(sControlName).addActionListener(self) self.DialogContainer.getControl(sControlName).setActionCommand(sControlName + '_OnClick') return oControlModel
def __init__(self, ctx, res={}, title=None, ids=(), titles={}, help_url=None): self.ctx = ctx self.res = res self.title = title self.titles = titles wizard = self.create_service("com.sun.star.ui.dialogs.Wizard") uno.invoke(wizard, "initialize", ((uno.Any("[]short", ids), self),)) self.wizard = wizard if self.title: wizard.setTitle(self._(title)) if help_url: wizard.HelpURL = help_url
def printDoc(xContext, xDoc, url): props = [ mkPropertyValue("FileName", url) ] # xDoc.print(props) uno.invoke(xDoc, "print", (tuple(props),)) # damn, that's a keyword! busy = True while busy: print("printing...") time.sleep(1) prt = xDoc.getPrinter() for value in prt: if value.Name == "IsBusy": busy = value.Value print("...done printing")
def setDialogProperties(self, closeable, height, moveable, position_x, position_Y, step, tabIndex, title, width): uno.invoke(self.xDialogModel, "setPropertyValues", ((PropertyNames.PROPERTY_CLOSEABLE, PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_MOVEABLE, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_TITLE, PropertyNames.PROPERTY_WIDTH), (closeable, height, moveable, position_x, position_Y, step, tabIndex, title, width)))
def trigger (self, args): try: dialog = FrenchDictionarySwitcher(self.ctx) dialog.run() if dialog.sSelectedDic and dialog.sSelectedDic != dialog.sCurrentDic : # Modify the registry xSettings = getConfigSetting("/org.openoffice.Office.Linguistic/ServiceManager/Dictionaries/HunSpellDic_fr", True) xLocations = xSettings.getByName("Locations") v1 = xLocations[0].replace(dialog.sCurrentDic, dialog.sSelectedDic) v2 = xLocations[1].replace(dialog.sCurrentDic, dialog.sSelectedDic) #xSettings.replaceByName("Locations", xLocations) # doesn't work, see line below uno.invoke(xSettings, "replaceByName", ("Locations", uno.Any("[]string", (v1, v2)))) xSettings.commitChanges() except: traceback.print_exc()
def create_index(self, anchor=None, index_type='toc', index_name=None, index_title=''): """ com.sun.star.text.DocumentIndex alphabetical index com.sun.star.text.ContentIndex table of contents com.sun.star.text.UserIndex user defined index com.sun.star.text.IllustrationIndex illustrations index com.sun.star.text.ObjectIndex objects index com.sun.star.text.TableIndex (text) tables index com.sun.star.text.Bibliography bibliographical index level_format = ( ( PropertyValue('TokenType', 0, 'TokenEntryText', DIRECT_VALUE), PropertyValue('CharacterStyleName', 0, '', DIRECT_VALUE), ), ( PropertyValue('TokenType', 0, 'TokenTabStop', DIRECT_VALUE), PropertyValue('TabStopRightAligned', 0, True, DIRECT_VALUE), PropertyValue('TabStopFillCharacter', 0, ' ', DIRECT_VALUE), PropertyValue('CharacterStyleName', 0, '', DIRECT_VALUE), PropertyValue('WithTab', 0, True, DIRECT_VALUE), ), ( PropertyValue('TokenType', 0, 'TokenPageNumber', DIRECT_VALUE), PropertyValue('CharacterStyleName', 0, '', DIRECT_VALUE) ), ) # these two lines are a work around for bug #12504. See python-uno FAQ. # since index.LevelFormat.replaceByIndex(2,level_format) does not work level_format = uno.Any('[][]com.sun.star.beans.PropertyValue', level_format) uno.invoke(index.LevelFormat, 'replaceByIndex', (2, level_format)) """ index_types = { 'alpha': 'com.sun.star.text.DocumentIndex', 'toc': 'com.sun.star.text.ContentIndex', 'user': '******', } index = self.document.createInstance(index_types[index_type]) index.Name = index_name or index_type index.Title = index_title if anchor is None: anchor = self.cursor anchor.Text.insertTextContent(anchor, index, False) return index
def linkSectiontoTemplate( self, TemplateName, SectionName, oTextSection=None): try: if not oTextSection: oTextSection = self.xTextDocument.TextSections.getByName( SectionName) oSectionLink = \ uno.createUnoStruct('com.sun.star.text.SectionFileLink') oSectionLink.FileURL = TemplateName uno.invoke(oTextSection, "setPropertyValues", (("FileLink", "LinkRegion"), (oSectionLink, SectionName))) NewSectionName = oTextSection.Name if NewSectionName is not SectionName: oTextSection.Name = SectionName except Exception: traceback.print_exc()
def setToUI(self, value): if (isinstance(value, list)): value = tuple(value) elif self.isShort: value = uno.Any("[]short", (value,)) if value: if(hasattr(self.unoModel, self.unoPropName)): if self.unoPropName == "Date": d = datetime.strptime(value, '%d/%m/%y') value = Date(d.day, d.month, d.year) elif self.unoPropName == "Time": t = datetime.strptime(value, '%H:%M') value = Time(0, 0, t.minute, t.hour, False) setattr(self.unoModel, self.unoPropName, value) else: uno.invoke(self.unoModel, "set" + self.unoPropName, (value,))
def attachEventCall(self, xComponent, EventName, EventType, EventURL): try: oEventProperties = list(range(2)) oEventProperties[0] = uno.createUnoStruct( 'com.sun.star.beans.PropertyValue') oEventProperties[0].Name = "EventType" oEventProperties[0].Value = EventType # "Service", "StarBasic" oEventProperties[1] = uno.createUnoStruct( 'com.sun.star.beans.PropertyValue') oEventProperties[1].Name = "Script" #"URL"; oEventProperties[1].Value = EventURL uno.invoke(xComponent.Events, "replaceByName", (EventName, uno.Any("[]com.sun.star.beans.PropertyValue", tuple(oEventProperties)))) except Exception: traceback.print_exc()
def addMenuItem( self, documenttype, menu, title, command, submenu = False, inside = True ): aUIMgr = self.ctx.ServiceManager.createInstanceWithContext( 'com.sun.star.ui.ModuleUIConfigurationManagerSupplier', self.ctx ) xUIMgr = aUIMgr.getUIConfigurationManager( documenttype ) settings = xUIMgr.getSettings( 'private:resource/menubar/menubar', True ) def findCommand( items, command ): for i in range( items.getCount() ): menu = unprops( items.getByIndex( i ) ) if 'CommandURL' in menu and menu.CommandURL == command: if inside and 'ItemDescriptorContainer' in menu and menu.ItemDescriptorContainer: return menu.ItemDescriptorContainer, 0 else: return items, i + 1 if 'ItemDescriptorContainer' in menu and menu.ItemDescriptorContainer: container, index = findCommand( menu.ItemDescriptorContainer, command ) if container is not None: return container, index return None, None newmenu = EasyDict() if submenu: newmenu.CommandURL = command newmenu.ItemDescriptorContainer = xUIMgr.createSettings() elif ':' not in command: newmenu.CommandURL = self.commandURL( command ) else: newmenu.CommandURL = command newmenu.Label = title newmenu.Type = 0 container, index = findCommand( settings, newmenu.CommandURL ) if index == 0: # assume this submenu was created by us and ignore it return while container is not None: uno.invoke( container, 'removeByIndex', (index-1,) ) container, index = findCommand( settings, newmenu.CommandURL ) container, index = findCommand( settings, menu ) assert container is not None, '%s not found in %s'%(menu, documenttype) # we need uno.invoke() to pass PropertyValue array as Any uno.invoke( container, 'insertByIndex', (index, anyprops( newmenu )) ) xUIMgr.replaceSettings( 'private:resource/menubar/menubar', settings) xUIMgr.store()
def __init__(self, xmsf, p): super(FTPDialog, self).__init__(xmsf) self.publish = p templateDir = p.root.soTemplateDir self.imagesDirectory = FileAccess.connectURLs(templateDir, "../wizard/bitmap/") self.dataAware = [] self.host = "" self.username = "" self.password = "" # Load Resources self.resources = FTPDialogResources(xmsf) self.ucb = UCB(xmsf) # set dialog properties... uno.invoke(self.xDialogModel, "setPropertyValues", (("Closeable", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, "Moveable", PropertyNames.PROPERTY_NAME, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, "Title", PropertyNames.PROPERTY_WIDTH), (True, 160, HelpIds.getHelpIdString(HID_FTP), True, "FTPDialog", 167, 82, self.resources.resFTPDialog_title, 222))) # add controls to dialog self.build() #make the hostname, username and password textfield data-aware. self.configure() #make sure we display a disconnected status. self.disconnect()
def __init__(self, xmsf, width, taskName, displayCount, resources, hid): super(StatusDialog, self).__init__(xmsf) self.res = resources if not (len(self.res) == 6): # display a close button? raise IllegalArgumentException("The resources argument should contain 6 Strings, see doc on constructor.") b = not (self.enableBreak or self.closeOnFinish) uno.invoke(self.xDialogModel, "setPropertyValues", ( ("Closeable", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, "Moveable", PropertyNames.PROPERTY_NAME, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, "Title", PropertyNames.PROPERTY_WIDTH), (False, 6 + 25 + (27 if b else 7), hid, True, "StatusDialog", 102, 52, 0, self.res[0], width))) tabstop = 1 self.lblTaskName = self.insertLabel("lblTask", (PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH), (8, taskName, 6, 6, tabstop, int(width * 2 / 3))) tabstop += 1 self.lblCounter = self.insertLabel("lblCounter", (PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH), (8, "", int(width * 2 / 3), 6, tabstop, int(width / 3) - 4)) tabstop += 1 self.progressBar = self.insertProgressBar("progress", (PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH), (10, 6, 16, tabstop, width - 12)) tabstop += 1 if b: self.btnCancel = self.insertButton("btnCancel", "performCancel", self, (PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH), (14, self.res[1], width / 2 - 20, 6 + 25 + 7, tabstop, 40)) tabstop += 1
def updateUI(self): try: data = getattr(self._dataObject, self._field) except Exception: data = uno.invoke(self._dataObject, "get" + self._field, ()) ui = self.getFromUI() if data is not ui: try: self.setToUI(data) except Exception: traceback.print_exc()
def moveSelection(self, image): self.grbxSelectedImage.Visible = False row = int(image / self.cols) if self.rowSelect: col = 0 else: col = image - (row * self.cols) self.MOVE_SELECTION_VALS[0] = \ int(self.getImagePosX(col) - self.selectionGap.Width) self.MOVE_SELECTION_VALS[1] = \ int(self.getImagePosY(row) - self.selectionGap.Height) uno.invoke(self.grbxSelectedImage.Model, "setPropertyValues", ((ImageList.MOVE_SELECTION), (tuple(self.MOVE_SELECTION_VALS)))) if (self.dialogModel.Step == self.step): self.grbxSelectedImage.Visible = True #now focus... for index,item in enumerate(self.m_aImages): if index != image: self.defocus(index) else: self.m_aImages[image].Model.Tabstop = True
def __initVariantDropdown(self, windowContainer): variantDropdown = windowContainer.getControl("variant") variantProps = variantDropdown.getModel() # populate dropdown list with available variants self.__initAvailableVariants() uno.invoke(variantProps, "setPropertyValue", ("StringItemList", uno.Any("[]string", tuple(self.__dictionaryVariantList)))) # read selected dictionary variant from registry registryVariantValue = "standard" try: registryVariantValue = PropertyManager.getInstance().readFromRegistry("/org.puimula.ooovoikko.Config/dictionary", "variant") except UnknownPropertyException as e: logging.exception(e) return registryVariantValue = registryVariantValue + ": " selectedValues = [0] for i, dVariant in enumerate(self.__dictionaryVariantList): if dVariant.startswith(registryVariantValue): selectedValues[0] = i; break; # set the selected item in the dropdown list uno.invoke(variantProps, "setPropertyValue", ("SelectedItems", uno.Any("[]short", tuple(selectedValues))))
def generateTestContentIndex(self, doc): index = getContentIndexInstance(doc) for i in range(10): styles = ('n'+str(i),) uno.invoke(index.LevelParagraphStyles, "replaceByIndex", (i, uno.Any("[]string", styles))) return index
def build(self): #set dialog properties... ilWidth = (self.il.imageSize.Width + self.il.gap.Width) \ * self.il.cols + self.il.gap.Width ilHeight = (self.il.imageSize.Height + self.il.gap.Height) \ * self.il.rows + self.il.gap.Height dialogWidth = 6 + ilWidth + 6 + 50 + 6 dialogHeight = 3 + 16 + 3 + (ilHeight + 8 + 14) + 6 uno.invoke(self.xDialogModel, "setPropertyValues",( ("Closeable", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, "Moveable", PropertyNames.PROPERTY_NAME, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, "Title", PropertyNames.PROPERTY_WIDTH), (True, dialogHeight, HelpIds.getHelpIdString(self.hid), True, "imgDialog", 59, 24, 1, self.resources[ImageListDialog.RES_TITLE],dialogWidth))) #Set member- FontDescriptors... self.fontDescriptor1.Weight = 150 PROPNAMES = ("DefaultButton", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_HELPURL, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_NAME, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, "PushButtonType", PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH) iButtonsX = 6 + ilWidth + 6 self.btnOK = self.insertButton( "btnOK", None, PROPNAMES, (True, 14, HelpIds.getHelpIdString(self.hid + 3), self.resources[ImageListDialog.RES_OK], "btnOK", iButtonsX, 22, uno.Any("short", OK), 7, 50), self) self.btnCancel = self.insertButton( "btnCancel", None, PROPNAMES, (False, 14, HelpIds.getHelpIdString(self.hid + 4), self.resources[ImageListDialog.RES_CANCEL], "btnCancel", iButtonsX, 41, uno.Any("short", CANCEL), 8, 50), self) self.btnHelp = self.insertButton( "btnHelp", None, PROPNAMES, (False, 14, "", self.resources[ImageListDialog.RES_HELP], "CommandButton3", iButtonsX, 71, uno.Any("short", HELP), 9, 50), self) if self.showOtherButton: aux = 0 if self.showDeselectButton: aux = 19 otherY = 22 + ilHeight - 14 - aux self.btnOther = self.insertButton( "btnOther", "other", PROPNAMES, (False, 14, HelpIds.getHelpIdString(self.hid + 1), self.resources[ImageListDialog.RES_OTHER], "btnOther", iButtonsX, otherY, uno.Any("short", STANDARD), 5, 50), self) if self.showDeselectButton: deselectY = 22 + ilHeight - 14 self.btnDeselect = self.insertButton( "btnNoImage", "deselect", PROPNAMES, (False, 14, HelpIds.getHelpIdString(self.hid + 2), self.resources[ImageListDialog.RES_DESELECT], "btnNoImage", iButtonsX, deselectY, uno.Any("short", STANDARD), 4, 50), self) self.il.step = 1 self.il.pos = Size(6, 22) self.il.helpURL = self.hid + 5 self.il.tabIndex = 1 self.il.create(self) self.lblTitle = self.insertLabel("lblTitle", ("FontDescriptor", PropertyNames.PROPERTY_HEIGHT, PropertyNames.PROPERTY_LABEL, PropertyNames.PROPERTY_NAME, PropertyNames.PROPERTY_POSITION_X, PropertyNames.PROPERTY_POSITION_Y, PropertyNames.PROPERTY_STEP, PropertyNames.PROPERTY_TABINDEX, PropertyNames.PROPERTY_WIDTH), (self.fontDescriptor1, 8, self.resources[ImageListDialog.RES_LABEL], "lblTitle", 6, 6, 1, 4, 216))
def invoke_method(self, method, args, name=None, pseud=False): try: if not name: if args: name = "%s(%s)" % (method.getName(), ", ".join([str(a) for a in args])) else: name = "%s()" % method.getName() out_params = self.get_out_param_index(method) if self.mode: _args, _any = self.extract_args(args) value, d = method.invoke(self.current.target, _args) else: _args, _any = self.extract_args(args) if _any: value, d = uno.invoke(method, "invoke", (self.current.target, _args)) else: value, d = method.invoke(self.current.target, _args) ret_type = method.getReturnType() entry = self.engine.create(self, name, value) if ret_type.getTypeClass() == TypeClass.ANY: # check the method from container if self.engine.check_method_from_container(method): _type = self.current.target.getElementType() ret_type = self.engine.for_name(_type.typeName) # added to solve problem on new configuration if ret_type.getTypeClass() == TypeClass.VOID: ret_type = self.engine.get_type(entry) entry.type = ret_type value_type = ExtAnyType2(entry, self.engine, ret_type.getName(), ret_type.getTypeClass()) entry.type = value_type if pseud: code_type = CGType.PSEUD_PROP else: code_type = CGType.METHOD entry.code_entry = self.code( type=code_type, key=method.getName(), value_type=value_type, args=args, idl=method) if out_params: param_infos = method.getParameterInfos() _d = [] for i, v in zip(out_params, d): _key = "%s_%s" % (name, i) _entry = self.engine.create(self, _key, v) _entry.type = param_infos[i] type = _entry.type.aType _entry.type = ExtType2(_entry, self.engine, type.getName(), type.getTypeClass()) _d.append(_entry) _entry.code_entry = args[i].code_entry ret = self.action_by_type(entry) return (ret,) + tuple(_d) else: return self.action_by_type(entry) except InvocationTargetException as e: te = e.TargetException self.error("Method: %s invocation exception.\nError Message: \n%s" % ( method.getName(), te.Message)) traceback.print_exc() except Exception as e: self.error("Method: %s unknown exception.\nError Message: \n%s" % ( name, str(e))) traceback.print_exc()
def test_checkIndexedPropertyValues(self): xServiceManager = self.xContext.ServiceManager xCont = xServiceManager.createInstanceWithContext( 'com.sun.star.document.IndexedPropertyValues', self.xContext) p1 = PropertyValue(Name="Jupp", Value="GoodGuy") prop1 = uno.Any("[]com.sun.star.beans.PropertyValue", (p1, )) p2 = PropertyValue(Name="Horst", Value="BadGuy") prop2 = uno.Any("[]com.sun.star.beans.PropertyValue", (p2, )) p3 = PropertyValue(Name="Peter", Value="FamilyGuy") prop3 = uno.Any("[]com.sun.star.beans.PropertyValue", (p3, )) t = xCont.getElementType() self.assertEqual(0, len(xCont), "Initial container is not empty") uno.invoke(xCont, "insertByIndex", (0, prop1)) ret = xCont[0] self.assertEqual(p1.Name, ret[0].Name) self.assertEqual(p1.Value, ret[0].Value) uno.invoke(xCont, "replaceByIndex", (0, prop2)) ret = xCont[0] self.assertEqual(p2.Name, ret[0].Name) self.assertEqual(p2.Value, ret[0].Value) xCont.removeByIndex(0) self.assertTrue(not (xCont.hasElements()) and len(xCont) == 0, "Could not remove PropertyValue") uno.invoke(xCont, "insertByIndex", (0, prop1)) uno.invoke(xCont, "insertByIndex", (1, prop2)) self.assertTrue(xCont.hasElements() and len(xCont) == 2, "Did not insert PropertyValue") uno.invoke(xCont, "insertByIndex", (1, prop2)) uno.invoke(xCont, "insertByIndex", (1, prop3)) ret = xCont[1] self.assertEqual(p3.Name, ret[0].Name) self.assertEqual(p3.Value, ret[0].Value) with self.assertRaises(IndexOutOfBoundsException): uno.invoke(xCont, "insertByIndex", (25, prop2)) with self.assertRaises(IndexOutOfBoundsException): xCont.removeByIndex(25) with self.assertRaises(IllegalArgumentException): uno.invoke(xCont, "insertByIndex", (3, "Example String"))
def test_checkIndexedPropertyValues(self): xServiceManager = self.xContext.ServiceManager xCont = xServiceManager.createInstanceWithContext('com.sun.star.document.IndexedPropertyValues', self.xContext) p1 = PropertyValue(Name="Jupp", Value="GoodGuy") prop1 = uno.Any("[]com.sun.star.beans.PropertyValue", (p1,)) p2 = PropertyValue(Name="Horst", Value="BadGuy") prop2 = uno.Any("[]com.sun.star.beans.PropertyValue", (p2,)) p3 = PropertyValue(Name="Peter", Value="FamilyGuy") prop3 = uno.Any("[]com.sun.star.beans.PropertyValue", (p3,)) t = xCont.getElementType() self.assertEqual(0, xCont.getCount(), "Initial container is not empty") uno.invoke(xCont, "insertByIndex", (0, prop1)) ret = xCont.getByIndex(0) self.assertEqual(p1.Name, ret[0].Name) self.assertEqual(p1.Value, ret[0].Value) uno.invoke(xCont, "replaceByIndex", (0, prop2)) ret = xCont.getByIndex(0) self.assertEqual(p2.Name, ret[0].Name) self.assertEqual(p2.Value, ret[0].Value) xCont.removeByIndex(0) self.assertTrue(not(xCont.hasElements()) and xCont.getCount()==0, "Could not remove PropertyValue") uno.invoke(xCont, "insertByIndex", (0, prop1)) uno.invoke(xCont, "insertByIndex", (1, prop2)) self.assertTrue(xCont.hasElements() and xCont.getCount()==2, "Did not insert PropertyValue") uno.invoke(xCont, "insertByIndex", (1, prop2)) uno.invoke(xCont, "insertByIndex", (1, prop3)) ret = xCont.getByIndex(1) self.assertEqual(p3.Name, ret[0].Name) self.assertEqual(p3.Value, ret[0].Value) with self.assertRaises(IndexOutOfBoundsException): uno.invoke(xCont, "insertByIndex", (25, prop2)) with self.assertRaises(IndexOutOfBoundsException): xCont.removeByIndex(25) with self.assertRaises(IllegalArgumentException): uno.invoke(xCont, "insertByIndex", (3, "Example String"))
def run(self): try: # read first self.readHeader() # initialize self.host = self.header.get("host",self.args.oo_host) self.port = self.header.get("port",self.args.oo_port) self.timeout = self.header.get("timeout",self.args.timeout) # open openoffice self.ooLocalCtx = uno.getComponentContext() self.ooLocalResolver = self.ooLocalCtx.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", self.ooLocalCtx) self.ooRemoteCtx = self.ooLocalResolver.resolve("uno:socket,host=%s,port=%s;urp;StarOffice.ComponentContext" % (self.host, self.port)) self.ooRemoteServiceManager = self.ooRemoteCtx.ServiceManager self.ooRemoteDesktop = self.ooRemoteServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", self.ooRemoteCtx) # send ok self.writeln("{}") # loop while run=true run = True while run: # read self.readHeader() fnct = self.header["fnct"] if fnct == "close": run = False self.writeln('{}') elif fnct == "closeDocument": self.closeDocument() self.writeln('{}') elif fnct == "putDocument": # cleanup self.closeDocument() # read data with Timer() as t: data = self.readData() _logger.debug("read data takes %s" % t.elapsed) # load document with Timer() as t: inputStream = self.ooRemoteServiceManager.createInstanceWithContext("com.sun.star.io.SequenceInputStream", self.ooRemoteCtx) try: inputStream.initialize((uno.ByteSequence(data),)) self.document = self.ooRemoteDesktop.loadComponentFromURL('private:stream', "_blank", 0, toProperties(InputStream = inputStream)) finally: inputStream.closeInput() _logger.debug("load document takes %s" % t.elapsed) self.writeln('{}') elif fnct == "printDocument": printer = self.header.get("printer") if printer: uno.invoke(self.document,"setPrinter", toProperties(Name = printer) ) uno.invoke(self.document, "print", toProperties(Wait = True) ) self.writeln('{}') elif fnct == "refreshDocument": self.refreshDocument() self.writeln('{}') elif fnct == "getDocument": filter_name = self.header.get("filter") self.refreshDocument() out = OutputStreamWrapper() try: self.document.storeToURL("private:stream", toProperties(OutputStream = out, FilterName = filter_name)) data_len = len(out.data.getvalue()) self.writeln('{"length" : %s }' % data_len ) _logger.info("Send document with length=%s" % data_len) self.fd.write(out.data.getvalue()) except IOException: self.writeln('{ "error" : "io-error", "message" : "Exception during conversion" }') finally: out.closeOutput() elif fnct == "streamDocument": run = False with Timer() as t: filter_name = self.header.get("filter") self.refreshDocument() out = OutputStreamWrapper(self.fd) try: self.document.storeToURL("private:stream", toProperties(OutputStream = out, FilterName = filter_name)) _logger.debug("streamDocument takes %s" % t.elapsed) finally: out.closeOutput() elif fnct == "insertDocument": data = self.readData() name = self.header["name"] placeholder_text = "<insert_doc('%s')>" % name filterName = "writer8" if name.lower().endswith(".html"): filterName = "HTML" # prepare stream inputStream = self.ooRemoteServiceManager.createInstanceWithContext("com.sun.star.io.SequenceInputStream", self.ooRemoteCtx) try: inputStream.initialize((uno.ByteSequence(data),)) # search search = self.document.createSearchDescriptor() search.SearchString = placeholder_text found = self.document.findFirst(search) # insert error = None while found: try: found.insertDocumentFromURL('private:stream', toProperties(InputStream = inputStream, FilterName = filterName)) found = self.document.findNext(found.End, search) except Exception as e: error = e.message or "Error" break if error: self.writeln('{ "error" : "io-error", "message" : "Unable to insert document %s, because %s" }' % (self.header["name"]),error) else: self.writeln("{}") finally: inputStream.closeInput() elif fnct == "addDocument": data = self.readData() inputStream = self.ooRemoteServiceManager.createInstanceWithContext("com.sun.star.io.SequenceInputStream", self.ooRemoteCtx) try: inputStream.initialize((uno.ByteSequence(data),)) self.document.Text.getEnd().insertDocumentFromURL('private:stream', toProperties(InputStream = inputStream, FilterName = "writer8")) self.writeln("{}") except Exception: inputStream.closeInput() self.writeln('{ "error" : "io-error", "message" : "Unable to insert document" }') else: raise UnsupportedException(fnct) # FLUSH after finished loop self.fd.flush() except IllegalArgumentException: _logger.error("Invalid URL!") self.writeln('{ "error": "invalid-url", "message" : "The url is invalid }"') except NoConnectException: _logger.error("Not connected!") self.writeln('{ "error": "no-connection", "message" : "Failed to connect to OpenOffice.org on host %s, port %s" }' % (self.host, self.port)) except NotConnectedException: _logger.error("Failed accessing stream!") self.writeln('{ "error": "not-connected", "message" : "Connection to OpenOffice.org on host %s, port %s are lost" }' % (self.host, self.port)) except ConnectionSetupException: self.writeln('{ "error": "no-access", "message" : "Not possible to accept on a local resource" }') except TimeoutException: info("Socket Timeout %s" % self.peer_name) except NoDataExeption: info("Stream closed %s" % self.peer_name) except UnsupportedException as e: msg = "Unsupported function %s" % e.message _logger.fatal(msg) self.writeln('{ "error": "unsupported", "message" : "%s" }' % msg) except Exception as e: _logger.exception(e) self.writeln('{ "error": "unexpected", "message" : "Unexpected error" }') finally: try: self.fd.close() except Exception as e: _logger.exception(e) try: self.sock.close() except Exception as e: _logger.exception(e) try: self.cleanup() except Exception as e: _logger.exception(e) info("Client %s disconnected" % self.peer_name)
def getFromUI(self): return uno.invoke(self.control, "get" + self.controlField, ())
def test_checkNamedPropertyValues(self): xServiceManager = self.xContext.ServiceManager xCont = xServiceManager.createInstanceWithContext('com.sun.star.document.NamedPropertyValues', self.xContext) p1 = PropertyValue(Name="Jupp", Value="GoodGuy") prop1 = uno.Any("[]com.sun.star.beans.PropertyValue", (p1,)) p2 = PropertyValue(Name="Horst", Value="BadGuy") prop2 = uno.Any("[]com.sun.star.beans.PropertyValue", (p2,)) t = xCont.getElementType() self.assertFalse(xCont.hasElements(), "Initial container is not empty") uno.invoke(xCont, "insertByName", ("prop1", prop1)) ret = xCont["prop1"] self.assertEqual(p1.Name, ret[0].Name) self.assertEqual(p1.Value, ret[0].Value) uno.invoke(xCont, "replaceByName", ("prop1", prop2)) ret = xCont["prop1"] self.assertEqual(p2.Name, ret[0].Name) self.assertEqual(p2.Value, ret[0].Value) xCont.removeByName("prop1") self.assertFalse(xCont.hasElements(), "Could not remove PropertyValue.") uno.invoke(xCont, "insertByName", ("prop1", prop1)) uno.invoke(xCont, "insertByName", ("prop2", prop2)) self.assertTrue(xCont.hasElements(), "Did not insert PropertyValue") names = xCont.getElementNames() self.assertEqual(2, len(names), "Not all element names were returned") for i in range(len(names)): self.assertIn(names[i], ["prop1", "prop2"], "Got a wrong element name") with self.assertRaises(ElementExistException): uno.invoke(xCont, "insertByName", ("prop2", prop1)) with self.assertRaises(IllegalArgumentException): uno.invoke(xCont, "insertByName", ("prop3", "Example String")) with self.assertRaises(NoSuchElementException): xCont.removeByName("prop3")
def setBorder(self, control, border): uno.invoke(control.Model, "setPropertyValues",(("Border"), (enable)))
def test_checkNamedPropertyValues(self): xServiceManager = self.xContext.ServiceManager xCont = xServiceManager.createInstanceWithContext( 'com.sun.star.document.NamedPropertyValues', self.xContext) p1 = PropertyValue(Name="Jupp", Value="GoodGuy") prop1 = uno.Any("[]com.sun.star.beans.PropertyValue", (p1, )) p2 = PropertyValue(Name="Horst", Value="BadGuy") prop2 = uno.Any("[]com.sun.star.beans.PropertyValue", (p2, )) t = xCont.getElementType() self.assertFalse(xCont.hasElements(), "Initial container is not empty") uno.invoke(xCont, "insertByName", ("prop1", prop1)) ret = xCont["prop1"] self.assertEqual(p1.Name, ret[0].Name) self.assertEqual(p1.Value, ret[0].Value) uno.invoke(xCont, "replaceByName", ("prop1", prop2)) ret = xCont["prop1"] self.assertEqual(p2.Name, ret[0].Name) self.assertEqual(p2.Value, ret[0].Value) xCont.removeByName("prop1") self.assertFalse(xCont.hasElements(), "Could not remove PropertyValue.") uno.invoke(xCont, "insertByName", ("prop1", prop1)) uno.invoke(xCont, "insertByName", ("prop2", prop2)) self.assertTrue(xCont.hasElements(), "Did not insert PropertyValue") names = xCont.getElementNames() self.assertEqual(2, len(names), "Not all element names were returned") for i in range(len(names)): self.assertIn(names[i], ["prop1", "prop2"], "Got a wrong element name") with self.assertRaises(ElementExistException): uno.invoke(xCont, "insertByName", ("prop2", prop1)) with self.assertRaises(IllegalArgumentException): uno.invoke(xCont, "insertByName", ("prop3", "Example String")) with self.assertRaises(NoSuchElementException): xCont.removeByName("prop3")
def setToUI(self, value): uno.invoke(self.control, "set" + self.controlField, (value,))