コード例 #1
0
ファイル: pyuno3ext.py プロジェクト: hanya/pyuno3ext
def Create_Python_sh(*args, **kwargs):
    """ Creates shell script which execute python3 with environmental variables 
    to connect the office instance from the extension package. """
    version = kwargs.get("version", 3)
    ext_id = "mytools.loader.Python" + ("" if version < 3 else str(version))
    import sys
    import stat
    import uno
    ctx = XSCRIPTCONTEXT.getComponentContext()
    def create(name):
        return ctx.getServiceManager().createInstanceWithContext(name, ctx)
    
    dest = _get_path(ctx, save=True, default_name="python", 
            filter_names=(("All Files (*.*)", "*.*"),), default_filter=0)
    if not dest:
        return
    sd_prog = uno.fileUrlToSystemPath(create("com.sun.star.util.PathSubstitution").substituteVariables("$(prog)", True))
    
    prov = ctx.getValueByName("/singletons/com.sun.star.deployment.PackageInformationProvider")
    ext_dir = uno.fileUrlToSystemPath(prov.getPackageLocation(ext_id))
    
    values = (("%%OFFICE_PROGRAM%%", sd_prog), ("%%EXTENSION_DIR%%", ext_dir), 
              ("%%PYVERSION%%", "{}.{}".format(sys.version_info.major, sys.version_info.minor)), 
              ("%%VERSION_SUFFIX%%", str(version)))
    s = PYTHON_SH_BASE
    for name, value in values:
        s = s.replace(name, value)
    
    with open(dest, "w") as f:#, encoding="utf-8") as f:
        f.write(s)
    if os.path.exists(dest):
        st = os.stat(dest)
        os.chmod(dest, st.st_mode | stat.S_IEXEC)
コード例 #2
0
ファイル: bundle.py プロジェクト: mattwilsoncp/MRI
 def copy_from_archive(self, macros_url, dest_base, file_name):
     import uno
     macros_path = uno.fileUrlToSystemPath(macros_url)
     file_path = uno.fileUrlToSystemPath(dest_base + "/" + file_name)
     if file_name.endswith(self.ZIP_EXTENSION):
         a = self.ZipArchive(file_path, "r")
     else:
         if file_name.endswith(self.GZ_EXTENSION):
             mode = "r:gz"
         elif file_name.endswith(self.BZ2_EXTENSION):
             mode = "r:bz2"
         else:
             raise TypeError("Illegal file name: %s" % file_name)
         a = self.TarArchive(file_path, mode)
     names = a.get_names()
     status = a.get_status(macros_path, names)
     message = "Following files will be imported from %s:\n%s" % \
         (file_name, "\n".join(status))
     self.message(message)
     try:
         if a.has_file(self.README):
             message = a.extract_file(self.README)
             if not self.show_readme(file_name, message):
                 raise Exception()
             a.extract(self.README, macros_path,
                       "%s-%s" % (self.README, a.name))
         names.remove(self.README)
         for name in names:
             a.extract(name, macros_path)
     except Exception as e:
         print(e)
     a.close()
コード例 #3
0
ファイル: bundle.py プロジェクト: billyoc/MRI
 def copy_from_archive(self, macros_url, dest_base, file_name):
     import uno
     macros_path = uno.fileUrlToSystemPath(macros_url)
     file_path = uno.fileUrlToSystemPath(dest_base + "/" + file_name)
     if file_name.endswith(self.ZIP_EXTENSION):
         a = self.ZipArchive(file_path, "r")
     else:
         if file_name.endswith(self.GZ_EXTENSION):
             mode = "r:gz"
         elif file_name.endswith(self.BZ2_EXTENSION):
             mode = "r:bz2"
         else: raise TypeError("Illegal file name: %s" % file_name)
         a = self.TarArchive(file_path, mode)
     names = a.get_names()
     status = a.get_status(macros_path, names)
     message = "Following files will be imported from %s:\n%s" % \
         (file_name, "\n".join(status))
     self.message(message)
     try:
         if a.has_file(self.README):
             message = a.extract_file(self.README)
             if not self.show_readme(file_name, message):
                 raise Exception()
             a.extract(self.README, macros_path, "%s-%s" % (self.README, a.name))
         names.remove(self.README)
         for name in names:
             a.extract(name, macros_path)
     except Exception as e:
         print(e)
     a.close()
コード例 #4
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
コード例 #5
0
ファイル: ootools.py プロジェクト: Tbutje/klaasculator_3
    def __init__(self):
        """Lees bestaande."""
        ctx = OOContext()
        inst = ctx.get().ServiceManager.createInstance('com.sun.star.comp.framework.PathSubstitution')

        userdir = inst.getSubstituteVariableValue('$(user)')
        lang = inst.getSubstituteVariableValue('$(vlang)')

        sdirs = ('config', 'soffice.cfg', 'modules', 'scalc', 'accelerator', lang)

        d = uno.fileUrlToSystemPath(userdir)
        for sd in sdirs:
            d = os.path.join(d, sd)
            if not os.path.exists(d):
                print 'mkdir', d
                os.mkdir(d)

        self.fname = os.path.join(d, 'current.xml')

        self.head = ['<?xml version="1.0" encoding="UTF-8"?>\n', '<accel:acceleratorlist xmlns:accel="http://openoffice.org/2001/accel" xmlns:xlink="http://www.w3.org/1999/xlink">\n']
        self.tail = ['</accel:acceleratorlist>\n']
        self.lines = []

        try:
            f = open(self.fname, 'r')
            for line in f.readlines():
                if line.strip().startswith('<accel:item') and not 'klaasculator' in line:
                    self.lines.append(line + '')
            f.close()
        except Exception, e:
            print e
            print 'geen bestaande regels gelezen.'
コード例 #6
0
ファイル: pythonscript.py プロジェクト: hanya/pyuno3ext
    def getModuleByUrl(self, url):
        entry = self.modules.get(url)
        load = True
        lastRead = self.sfa.getDateTimeModified(url)
        if entry:
            if hasChanged(entry.lastRead, lastRead):
                log.debug("file {} has changed, reloading", url)
            else:
                load = False

        if load:
            log.debug("opening >{}<", url)

            src = readTextFromStream(self.sfa.openFileRead(url))
            checkForPythonPathBesideScript(url[0 : url.rfind("/")])

            # execute the module
            entry = ModuleEntry(lastRead, type(sys)("ooo_script_framework"))
            entry.module.__dict__[GLOBAL_SCRIPTCONTEXT_NAME] = self.scriptContext

            code = compile(src, encfile(uno.fileUrlToSystemPath(url)) if url.startswith("file:") else url, "exec")
            exec(code, entry.module.__dict__)
            entry.module.__file__ = url
            self.modules[url] = entry
            log.debug("mapped {} to {}", url, entry.module)
        return entry.module
コード例 #7
0
 def to_system_path(self, url):
     """ Convert if the url specify on the local file system. """
     try:
         if url.startswith("file:"):
             return uno.fileUrlToSystemPath(url)
     except:
         return url
コード例 #8
0
ファイル: pythonscript.py プロジェクト: AriesYB/kkfile
    def getModuleByUrl(self, url):
        entry = self.modules.get(url)
        load = True
        lastRead = self.sfa.getDateTimeModified(url)
        if entry:
            if hasChanged(entry.lastRead, lastRead):
                log.debug("file " + url + " has changed, reloading")
            else:
                load = False

        if load:
            log.debug("opening >" + url + "<")

            src = readTextFromStream(self.sfa.openFileRead(url))
            checkForPythonPathBesideScript(url[0:url.rfind('/')])
            src = ensureSourceState(src)

            # execute the module
            entry = ModuleEntry(lastRead,
                                imp.new_module("ooo_script_framework"))
            entry.module.__dict__[
                GLOBAL_SCRIPTCONTEXT_NAME] = self.scriptContext

            code = None
            if url.startswith("file:"):
                code = compile(src, encfile(uno.fileUrlToSystemPath(url)),
                               "exec")
            else:
                code = compile(src, url, "exec")
            exec(code, entry.module.__dict__)
            entry.module.__file__ = url
            self.modules[url] = entry
            log.debug("mapped " + url + " to " + str(entry.module))
        return entry.module
コード例 #9
0
ファイル: pythonscript.py プロジェクト: beppec56/openoffice
    def getModuleByUrl( self, url ):
        entry =  self.modules.get(url)
        load = True
        lastRead = self.sfa.getDateTimeModified( url )
        if entry:
            if hasChanged( entry.lastRead, lastRead ):
                log.debug( "file " + url + " has changed, reloading" )
            else:
                load = False

        if load:
            log.debug( "opening >" + url + "<" )

            src = readTextFromStream( self.sfa.openFileRead( url ) )
            checkForPythonPathBesideScript( url[0:url.rfind('/')] )
            src = ensureSourceState( src )

            # execute the module
            entry = ModuleEntry( lastRead, imp.new_module("ooo_script_framework") )
            entry.module.__dict__[GLOBAL_SCRIPTCONTEXT_NAME] = self.scriptContext

            code = None
            if url.startswith( "file:" ):
                code = compile( src, encfile(uno.fileUrlToSystemPath( url ) ), "exec" )
            else:
                code = compile( src, url, "exec" )
            exec(code, entry.module.__dict__)
            entry.module.__file__ = url
            self.modules[ url ] = entry
            log.debug( "mapped " + url + " to " + str( entry.module ) )
        return  entry.module
コード例 #10
0
    def convertCurrentDocument(self):
        docPath = Path(uno.fileUrlToSystemPath(self._document.getLocation()))
        conversionSettings = ConversionSettings(docPath)
        textModel = self._document.getText()

        self._convertXTextObject(textModel, conversionSettings)

        dbg.printCentered('done')
        print('result:\n', self.getResult())

        targetFile = docPath.with_suffix(self.getFileExtension())
        if targetFile.exists():
            from writer2wiki.w2w_office.lo_enums import MbType, MbButtons, MbResult
            answer = self._ui.messageBox(
                ui_text.conversionDoneAndTargetFileExists(
                    targetFile, conversionSettings),
                boxType=MbType.QUERYBOX,
                buttons=MbButtons.BUTTONS_OK_CANCEL)
            if answer == MbResult.CANCEL:
                return
        else:
            self._ui.messageBox(
                ui_text.conversionDoneAndTargetFileDoesNotExist(
                    targetFile, conversionSettings))

        with openW2wFile(targetFile, 'w') as f:
            f.write(self.getResult())

        if not conversionSettings.saveStyles():
            self._ui.messageBox(
                ui_text.failedToSaveMappingsFile(
                    conversionSettings.getFilePath()))
コード例 #11
0
    def __conn_z_open(self, modpath):
        if self.__conn is not None:
            return

        if modpath.startswith('file:'):
            modpath = uno.fileUrlToSystemPath(modpath)
        self.__conn = zipfile.ZipFile(modpath + '/' + CONTENTZIP)
コード例 #12
0
def save_active_doc_with_timestamp(args):
    """Save the Active Document with new current timeStamp."""
    print("-" * 42)
    print("save_active_doc_with_timestamp:")

    doc = get_current_document()
    filename_full_path = uno.fileUrlToSystemPath(doc.URL)
    print("filename_full_path:")
    print(filename_full_path)
    print("", filename_full_path)

    # so extract the FileName from the path_full
    path_full = os.path.dirname(filename_full_path)
    filename = os.path.basename(filename_full_path)
    file_basename = os.path.splitext(filename)[0]
    file_ext = os.path.splitext(filename)[1]
    # print("doc_name: " + doc_name)

    file_basename_new = update_timestamp(file_basename)
    if file_basename_new:
        # put together new filename_full_path_new
        filename_full_path_new = path_full + "/" + file_basename_new + file_ext
        print("filename_full_path_new:")
        print(filename_full_path_new)
        # https://wiki.openoffice.org/wiki/Documentation/DevGuide/OfficeDev/Storing_Documents
        doc.storeAsURL(uno.systemPathToFileUrl(filename_full_path_new), ())
    else:
        info = "no timestamp found in filename - so i can't update it."
        print(info)
        msgbox(info)

    print("-" * 42)
コード例 #13
0
ファイル: options.py プロジェクト: Koala/BookmarksMenu
 def to_system_path(self, url):
     """ Convert if the url specify on the local file system. """
     try:
         if url.startswith("file:"):
             return uno.fileUrlToSystemPath(url)
     except:
         return url
コード例 #14
0
ファイル: macros.py プロジェクト: mattwilsoncp/MRI
 def __init__(self, main):
     self.main = main
     self.loaded = False
     if Macros.EXT_MACROS_DIR is None:
         Macros.EXT_MACROS_DIR = uno.fileUrlToSystemPath(
             mytools_Mri.values.MRI_DIR + "/" + self.MACROS)
     if Macros.USER_MACROS_DIR is None:
         self.set_user_dir(main.config.macros)
コード例 #15
0
 def addCurrentDoc(self):
     logger.debug(util.funcName())
     url = self.app.unoObjs.document.getURL()
     if not url:
         self.app.msgbox.display("Please save the current document first.")
         return
     syspath = uno.fileUrlToSystemPath(url)
     self.filesList.addFile(syspath)
コード例 #16
0
ファイル: macros.py プロジェクト: mattwilsoncp/MRI
 def set_user_dir(self, url):
     """ Change user's directory. """
     if url.startswith("$"):
         ctx = self.main.ctx
         url = ctx.getServiceManager().createInstanceWithContext(
             "com.sun.star.util.PathSubstitution", ctx).\
                 substituteVariables(url, True)
     Macros.USER_MACROS_DIR = uno.fileUrlToSystemPath(url)
コード例 #17
0
def setGettextDomain(ctx):
    info = ctx.getByName(
        "/singletons/com.sun.star.deployment.PackageInformationProvider")

    extension_uri = info.getPackageLocation("org.parlatype.loextension")
    extension_path = uno.fileUrlToSystemPath(extension_uri)
    locale_path = os.path.join(extension_path, 'locale')

    gettext.bindtextdomain('parlatype_lo', locale_path)
    gettext.textdomain('parlatype_lo')
コード例 #18
0
def uno_url_to_path(url: str) -> Optional[Path]:
    """
    Wrapper
    @param url: the url
    @return: the path or None if the url is empty
    """
    if url.strip():
        return Path(uno.fileUrlToSystemPath(url))
    else:
        return None
コード例 #19
0
def fill(*args):
    """Заполнить основную надпись.

    Считать данные из файла списка цепей и заполнить графы основной надписи.
    Имеющиеся данные не удаляются из основной надписи.
    Новое значение вносится только в том случае, если оно не пустое.

    """
    if common.isThreadWorking():
        return
    schematic = common.getSchematicData()
    if schematic is None:
        return
    doc = XSCRIPTCONTEXT.getDocument()
    doc.lockControllers()
    # Наименование документа
    docTitle = schematic.title.replace('\\n', '\n')
    if config.getboolean("stamp", "convert doc title"):
        tailPos = docTitle.find("Схема электрическая")
        if tailPos > 0:
            docTitle = docTitle[:tailPos]
        docTitle = docTitle.strip()
        if docTitle:
            docTitle += '\n'
        docName = "Ведомость покупных изделий"
        if config.getboolean("stamp", "doc type is file name"):
            docName = path.splitext(
                path.basename(uno.fileUrlToSystemPath(doc.URL)))[0]
        docTitle += docName
    setFirstPageFrameValue("1 Наименование документа", docTitle)
    # Наименование организации
    companyName = schematic.company.replace('\\n', '\n')
    setFirstPageFrameValue("9 Наименование организации", companyName)
    # Обозначение документа
    docId = schematic.number
    idParts = re.match(r"([А-ЯA-Z0-9]+(?:[\.\-]\d+)+\s?)(Э\d)", docId)
    if config.getboolean("stamp", "convert doc id") \
        and idParts is not None:
        docId = idParts.group(1) + "ВП"
    setFirstPageFrameValue("2 Обозначение документа", docId)
    # Первое применение
    if config.getboolean("stamp", "fill first usage") \
        and idParts is not None:
        setFirstPageFrameValue("25 Перв. примен.", idParts.group(1).strip())
    # Разработал
    setFirstPageFrameValue("11 Разраб.", schematic.developer)
    # Проверил
    setFirstPageFrameValue("11 Пров.", schematic.verifier)
    # Нормативный контроль
    setFirstPageFrameValue("11 Н. контр.", schematic.inspector)
    # Утвердил
    setFirstPageFrameValue("11 Утв.", schematic.approver)

    common.syncCommonFields()
    doc.unlockControllers()
コード例 #20
0
 def useCurrent(self):
     logger.debug(util.funcName('begin'))
     url = self.unoObjs.document.getURL()
     if not url:
         self.msgbox.display("Please save the current document first.")
         return
     syspath = uno.fileUrlToSystemPath(url)
     self.dlgCtrls.fileControl.setText(syspath)
     dummy, title = DocReader.SUPPORTED_FORMATS[0]
     self.dlgCtrls.listboxFileType.selectItem(title, False)
     self.dlgCtrls.listboxFileType.selectItem(title, True)
コード例 #21
0
ファイル: pythonscript.py プロジェクト: johnsonc/swarm
def getLogTarget():
    ret = sys.stdout
    if not LOG_STDOUT:
        try:
            pathSubst = uno.getComponentContext().ServiceManager.createInstance("com.sun.star.util.PathSubstitution")
            userInstallation = pathSubst.getSubstituteVariableValue("user")
            if len(userInstallation) > 0:
                systemPath = uno.fileUrlToSystemPath(userInstallation + "/Scripts/python/log.txt")
                ret = file(systemPath, "a")
        except Exception, e:
            print "Exception during creation of pythonscript logfile: " + lastException2String() + "\n, delagating log to stdout\n"
コード例 #22
0
    def createComparisonDoc(self):
        """
        Create an empty writer doc.
        If the main file has a saved path, then only one comparison doc
        should be created.
        Returns True if a new document was created.
        """
        if not self.makeDoc:
            return
        if self.writerDoc is not None:
            if self.writerDoc.document is not None:
                ## Document is already open
                return

        varname = "ComparisonDocForFile"
        currentFilepath = None  # file path of main document
        url = self.mainDoc.document.getURL()
        if url:
            currentFilepath = uno.fileUrlToSystemPath(url)
            doclist = self.mainDoc.getOpenDocs(util.UnoObjs.DOCTYPE_WRITER)
            for docUnoObjs in doclist:
                logger.debug("Checking writer document for settings.")
                userVars = UserVars(self.VAR_PREFIX, docUnoObjs.document,
                                    logger)
                if not userVars.isEmpty(varname):
                    varFilepath = userVars.get(varname)
                    if varFilepath == currentFilepath:
                        logger.debug("found comparison doc")
                        self.writerDoc = docUnoObjs
                        return False
                    else:
                        logger.debug("%s != %s", varFilepath, currentFilepath)

        logger.debug("opening new document for comparison")
        newDoc = self.mainDoc.desktop.loadComponentFromURL(
            "private:factory/swriter", "_blank", 0, ())
        self.writerDoc = self.mainDoc.getDocObjs(newDoc)
        self.writerDoc.text.insertString(
            self.writerDoc.viewcursor,
            "Here are the changes that have been made.  " +
            "You may want to look through these changes, and make any " +
            "corrections in the main document.  " +
            "When finished checking, just close this window without saving.",
            0)
        self.writerDoc.text.insertControlCharacter(self.writerDoc.viewcursor,
                                                   PARAGRAPH_BREAK, 0)
        self.writerDoc.text.insertControlCharacter(self.writerDoc.viewcursor,
                                                   PARAGRAPH_BREAK, 0)
        if currentFilepath:
            userVars = UserVars(self.VAR_PREFIX, self.writerDoc.document,
                                logger)
            userVars.store(varname, currentFilepath)
        self.emptyDoc = True
        logger.debug(util.funcName('end'))
コード例 #23
0
ファイル: pythonscript.py プロジェクト: truonggiang/SMSView
def getLogTarget():
    ret = sys.stdout
    if not LOG_STDOUT:
        try:
            pathSubst = uno.getComponentContext().ServiceManager.createInstance(
                "com.sun.star.util.PathSubstitution" )
            userInstallation =  pathSubst.getSubstituteVariableValue( "user" )
            if len( userInstallation ) > 0:
                systemPath = uno.fileUrlToSystemPath( userInstallation + "/Scripts/python/log.txt" )
                ret = file( systemPath , "a" )
        except Exception,e:
            print "Exception during creation of pythonscript logfile: "+ lastException2String() + "\n, delagating log to stdout\n"
コード例 #24
0
ファイル: listener.py プロジェクト: eldarkg/eskd-templates
def cleanup(*args):
    """Удалить объекты встроенных модулей из системы импорта Python."""

    for moduleName in EMBEDDED_MODULES:
        moduleName += XSCRIPTCONTEXT.getDocument().RuntimeUID
        if moduleName in sys.modules:
            del sys.modules[moduleName]
    fileUrl = XSCRIPTCONTEXT.getDocument().URL
    if fileUrl:
        docPath = uno.fileUrlToSystemPath(fileUrl)
        if docPath in zipimport._zip_directory_cache:
            del zipimport._zip_directory_cache[docPath]
コード例 #25
0
ファイル: Dialog.py プロジェクト: prrvchr/GContactOOo
 def _sendMessage(self, service, arguments, attachments=[]):
     self.transferable = ["body"]
     mail = self.ctx.ServiceManager.createInstanceWithArgumentsAndContext("com.sun.star.mail.MailMessage", arguments, self.ctx)
     if self._getDocumentUserProperty("SendAsPdf"):
         url = self._saveDocumentAs("pdf")
         self.transferable.append(url)
         mail.addAttachment(MailAttachment(self, uno.fileUrlToSystemPath(self._getUrl(url).Name)))
     for url in attachments:
         self.transferable.append(url)
         mail.addAttachment(MailAttachment(self, uno.fileUrlToSystemPath(self._getUrl(url).Name)))
     try:
         service.sendMailMessage(mail)
     except Exception as e:
         recipients = self._getRecipientFilters(range(self.recipient.Row))
         self._rowRecipientExecute(recipients)
         self._logMessage("TextMerge", "78.Dialog.TextMerge.Text", (arguments[0], e))
         self._setDialogError()
     else:
         self._logMessage("TextMerge", "77.Dialog.TextMerge.Text", (arguments[0],))
         return True
     return False
コード例 #26
0
 def printTraceback(self):
     if sys.platform.startswith("win"):
         xPathSubstitution = self.context.ServiceManager.createInstance("com.sun.star.util.PathSubstitution")
         user = xPathSubstitution.getSubstituteVariableValue("user")
         path = uno.fileUrlToSystemPath(user + "/Scripts/python/log.txt")
         dir = os.path.dirname(path)
         if not os.path.exists(dir):
             os.makedirs(dir)
         sock = open(path, "a")
         traceback.print_exc(file=sock)
         sock.close()
     else:
         traceback.print_exc(file=sys.stderr)
コード例 #27
0
ファイル: output.py プロジェクト: mattwilsoncp/MRI
    def _get_temp_dir(self):
        temp = self.main.ctx.getServiceManager().createInstanceWithContext(
            'com.sun.star.io.TempFile', self.main.ctx)
        uri = temp.Uri
        sys_path = uno.fileUrlToSystemPath(uri)
        i = 0
        while True:
            if not os.path.exists(sys_path + ("-%s" % i)):
                break
        name = sys_path + ("-%s" % i)
        os.mkdir(name)

        return name
コード例 #28
0
ファイル: output.py プロジェクト: billyoc/MRI
 def _get_temp_dir(self):
     temp = self.main.ctx.getServiceManager().createInstanceWithContext(
         'com.sun.star.io.TempFile', self.main.ctx)
     uri = temp.Uri
     sys_path = uno.fileUrlToSystemPath(uri)
     i = 0
     while True:
         if not os.path.exists(sys_path + ("-%s" % i)):
             break
     name = sys_path + ("-%s" % i)
     os.mkdir(name)
     
     return name
コード例 #29
0
ファイル: base.py プロジェクト: vmiklos/ged2dot
 def print_traceback(self) -> None:
     """Prints the backtrace on error."""
     if sys.platform.startswith("win"):
         path_substitution = self.context.ServiceManager.createInstance("com.sun.star.util.PathSubstitution")
         user = path_substitution.getSubstituteVariableValue("user")
         path = uno.fileUrlToSystemPath(user + "/Scripts/python/log.txt")
         directory = os.path.dirname(path)
         if not os.path.exists(directory):
             os.makedirs(directory)
         with open(path, "a", encoding="utf-8") as stream:
             traceback.print_exc(file=stream)
     else:
         traceback.print_exc(file=sys.stderr)
コード例 #30
0
ファイル: Dialog.py プロジェクト: prrvchr/GContactOOo
 def _checkAttachment(self, service, url):
     self._logMessage("TextMerge", "72.Dialog.TextMerge.Text", (uno.fileUrlToSystemPath(url),))
     if service.exists(url):
         size = service.getSize(url)
         maxsize = self.maxsize if self.maxsize != 0 else size
         if size != 0 and size <= maxsize:
             self._logMessage("TextMerge", "73.Dialog.TextMerge.Text")
             return True
         else:
             self._logMessage("TextMerge", "74.Dialog.TextMerge.Text")
     else:
         self._logMessage("TextMerge", "75.Dialog.TextMerge.Text")
     return False
コード例 #31
0
ファイル: base.py プロジェクト: vmiklos/ged2dot
 def printTraceback(self) -> None:
     if sys.platform.startswith("win"):
         xPathSubstitution = self.context.ServiceManager.createInstance("com.sun.star.util.PathSubstitution")
         user = xPathSubstitution.getSubstituteVariableValue("user")
         path = uno.fileUrlToSystemPath(user + "/Scripts/python/log.txt")
         dir = os.path.dirname(path)
         if not os.path.exists(dir):
             os.makedirs(dir)
         sock = open(path, "a")
         traceback.print_exc(file=sock)
         sock.close()
     else:
         traceback.print_exc(file=sys.stderr)
コード例 #32
0
def filename_handle():

    filename_lst.clear()
    path = uno.fileUrlToSystemPath(dirname)

    files = os.listdir(path)
    for file in files:
        if '.csv' in str(file) and 'lock' not in str(file):
            filename_lst.append(file)

    filename_lst.insert(len(filename_lst) - 1, filename_lst.pop(0))

    for i in range(len(filename_lst)):
        filename_lst[i] = os.path.join(path, filename_lst[i])
コード例 #33
0
ファイル: menu_start.py プロジェクト: XRoemer/Organon
    def wurde_als_template_geoeffnet(self):
        if debug: log(inspect.stack)
        try:
            enum = self.desktop.Components.createEnumeration()
            comps = []

            while enum.hasMoreElements():
                comps.append(enum.nextElement())
                
            # Wenn ein neues Dokument geoeffnet wird, gibt es bei der Initialisierung
            # noch kein Fenster, aber die Komponente wird schon aufgefuehrt.
            doc = comps[0]
            
            # Pruefen, ob doc von Organon erzeugt wurde
            ok = False
            for a in doc.Args:
                if a.Name == 'DocumentTitle':
                    if a.Value.split(';')[0] == 'opened by Organon':
                        ok = True
                        projekt_pfad = a.Value.split(';')[1]
                        break
            
            if not ok:
                return False        
            
            self.cont.dispose()
            self.erzeuge_Menu()
            
            prop2 = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
            prop2.Name = 'Overwrite'
            prop2.Value = True
            
            doc.storeAsURL(projekt_pfad,(prop2,)) 
            
            sys_pfad = uno.fileUrlToSystemPath(projekt_pfad)
            orga_name = os.path.basename(sys_pfad).split('.')[0] + '.organon'
            sys_pfad1 = sys_pfad.split(orga_name)[0]
            pfad = os.path.join(sys_pfad1,orga_name,orga_name)
            
            self.Menu_Bar.class_Projekt.lade_Projekt(False,pfad)
          
        except:
            log(inspect.stack,tb())
コード例 #34
0
    def wurde_als_template_geoeffnet(self):
        if debug: log(inspect.stack)
        try:
            enum = self.desktop.Components.createEnumeration()
            comps = []

            while enum.hasMoreElements():
                comps.append(enum.nextElement())

            # Wenn ein neues Dokument geoeffnet wird, gibt es bei der Initialisierung
            # noch kein Fenster, aber die Komponente wird schon aufgefuehrt.
            doc = comps[0]

            # Pruefen, ob doc von Organon erzeugt wurde
            ok = False
            for a in doc.Args:
                if a.Name == 'DocumentTitle':
                    if a.Value.split(';')[0] == 'opened by Organon':
                        ok = True
                        projekt_pfad = a.Value.split(';')[1]
                        break

            if not ok:
                return False

            self.cont.dispose()
            self.erzeuge_Menu()

            prop2 = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
            prop2.Name = 'Overwrite'
            prop2.Value = True

            doc.storeAsURL(projekt_pfad, (prop2, ))

            sys_pfad = uno.fileUrlToSystemPath(projekt_pfad)
            orga_name = os.path.basename(sys_pfad).split('.')[0] + '.organon'
            sys_pfad1 = sys_pfad.split(orga_name)[0]
            pfad = os.path.join(sys_pfad1, orga_name, orga_name)

            self.Menu_Bar.class_Projekt.lade_Projekt(False, pfad)

        except:
            log(inspect.stack, tb())
コード例 #35
0
def startConsole():
    "open console from APSO extension"
    try:
        xContext = uno.getComponentContext()
        xContext.ServiceManager.createInstance(
            "apso.python.script.organizer.impl")
        # now we can import apso_utils library
        from apso_utils import console
        console()
    except:
        try:
            xContext = uno.getComponentContext()
            xPathSettings = xContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.util.PathSettings", xContext)
            spPyInstallion = uno.fileUrlToSystemPath(xPathSettings.Module)
            subprocess.Popen(spPyInstallion + os.sep +
                             "python")  # Start Python interactive Shell
        except:
            traceback.print_exc()
コード例 #36
0
ファイル: DocTempl.py プロジェクト: NDCODF/NDCHelp
def formatDoc(modpath, templ, idx, title, keyword):
    global imgs, forZip

    forZip = modpath is not None

    # 透過 createUnoService(...) 呼叫過來時,若要 import 其他模駔
    # 則需由 caller 傳路徑以供定位
    if forZip:
        import sys
        op = 'z'
        modpath = uno.fileUrlToSystemPath(modpath)
        sys.path.insert(0, modpath + '/Python')
    else:
        op = 'h'
        modpath = ''
    from RestData import HelpObj

    imgs = list()
    content = list()
    data = HelpObj(op).getContent(idx, keyword, modpath)
    ridx = HelpObj(op).getImgIndex(idx, title, modpath)
    for buf in data.split('\n'):  # 處理每一行
        result = re.match('^(#{1,6})(.*)$', buf)  # 找 # ## ### ####
        chp1 = re.match(r'^\+\s(.*)$', buf)
        chp2 = re.match(r'^\s\s\-\s(.*)$', buf)

        if result:  # 解析 # ## ### #### 成 H1 Hn
            hnumber = len(result.groups()[0])
            subject = result.groups()[1]
            buf = header_t % (hnumber, hnumber, html.escape(subject))
        elif chp1:  # 項目第一層
            buf = chp1_t % (html.escape(chp1.groups()[0]))
        elif chp2:  # 項目第二層
            buf = chp2_t % (html.escape(chp2.groups()[0]))
        else:  # 解析圖片網址
            buf = regCheckImg(modpath, buf, ridx)

        content.append(buf)

    content = '\n'.join(content)
    content = content.replace('\n', lineBreak)
    return [templ.replace("{%content}", content), imgs]
コード例 #37
0
def showFolderPicker(genericUnoObjs, defaultFoldername=None):
    logger.debug(util.funcName('begin'))
    dlg = genericUnoObjs.smgr.createInstanceWithContext(
        "com.sun.star.ui.dialogs.FolderPicker", genericUnoObjs.ctx)
    if defaultFoldername:
        logger.debug("Default foldername %s", defaultFoldername)
        dlg.setDisplayDirectory(defaultFoldername)
    result = dlg.execute()

    # Get results.
    folderpath = ""
    if result == _RESULT_OK:
        folderpath = dlg.getDirectory()
        folderpath = uno.fileUrlToSystemPath(folderpath)
        if os.path.exists(folderpath):
            if os.path.isfile(folderpath) or os.path.islink(folderpath):
                logger.warning("'%s' is not a folder", folderpath)
                folderpath = ""
    logger.debug(util.funcName('end', args=folderpath))
    return folderpath
コード例 #38
0
 def showDetailDialog(self, theme_name):
     try:
         # path substitution instance
         ps = self.ctx.getServiceManager().createInstanceWithContext(
             'com.sun.star.util.PathSubstitution', self.ctx)
         # get user profile dir ($HOME/.config/libreoffice/4/user/)
         userdir = uno.fileUrlToSystemPath(
             ps.getSubstituteVariableValue("$(user)"))
         for theme in self.installed_themes:
             if theme["name"] == theme_name:
                 theme_dir = userdir + "/lotc-themes/" + theme["location"]
                 break
         theme_data = Helper.parse_manifest(theme_dir)
         if theme_data == None:
             theme_data = {
                 "author":
                 "LibreOffice",
                 "description":
                 "LibreOffice default theme",
                 "name":
                 theme_name,
                 "screenshots":
                 ["file://{}/program/intro.png".format(theme_dir)]
             }
         theme_data["theme_location"] = theme_dir
         theme_data["current_active"] = self.active_theme
         detailDialog = DetailsDialog(ctx=self.ctx, theme_data=theme_data)
     except Exception as e:
         print(e)
         traceback.print_exc()
         exit(255)
     new_active_theme = detailDialog.showDialog()
     if self.active_theme != new_active_theme:
         self.active_theme = new_active_theme
     self.installed_themes = self.refresh_installed_themes(userdir)
     self.alter_installed_themes(userdir)
     # clear first
     self.clear_theme_list()
     # then generate
     for theme in self.installed_themes:
         self.create_new_component(theme, self.active_theme)
コード例 #39
0
ファイル: DocTempl.py プロジェクト: NDCODF/NDCHelp
def formatDocQA(modpath, templ, id, breadcrumb):
    # 透過 createUnoService(...) 呼叫過來時,若要 import 其他模駔
    # 則需由 caller 傳路徑以供定位
    import sys
    modpath = uno.fileUrlToSystemPath(modpath)
    sys.path.insert(0, modpath + '/Python')
    from RestData import QAObj

    content = ''
    for idx, buf in enumerate(QAObj().getSearchTopic(id)):  # 處理每一筆
        buf = buf.replace('\n', lineBreak)

        # 每筆以表格框起來
        pos = idx + 2  # A2
        if pos > 3:  # or A3
            pos = 2
        content += table_t % (pos, buf)

    templ = templ.replace("{%content}", content)
    templ = templ.replace("{%breadcrumb}", breadcrumb)  # ... >> ...
    return templ
コード例 #40
0
ファイル: common.py プロジェクト: eldarkg/eskd-templates
def getSourceFileName():
    """Получить имя файла с данными о схеме.

    Попытаться найти файл с данными о схеме в текущем каталоге.
    В случае неудачи, показать диалоговое окно выбора файла.

    Для KiCad источником данных о схеме является список цепей.

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

    """
    sourcePath = config.get("doc", "source")
    if os.path.exists(sourcePath):
        return sourcePath
    sourceDir = ""
    sourceName = ""
    docUrl = XSCRIPTCONTEXT.getDocument().URL
    if docUrl:
        docPath = uno.fileUrlToSystemPath(docUrl)
        sourceDir = os.path.dirname(docPath)
        for fileName in os.listdir(sourceDir):
            if fileName.endswith(".pro"):
                sourceName = fileName.replace(".pro", ".net")
        if sourceName:
            sourcePath = os.path.join(sourceDir, sourceName)
            if os.path.exists(sourcePath):
                config.set("doc", "source", sourcePath)
                config.save()
                return sourcePath
    sourcePath = showFilePicker(
        os.path.join(sourceDir, sourceName), **{
            "Список цепей KiCad": "*.net;*.xml",
            "Все файлы": "*.*"
        })
    if sourcePath is not None:
        config.set("doc", "source", sourcePath)
        config.save()
        return sourcePath
    return None
コード例 #41
0
    def _search_in_index(self, prefix, word, declared_class):
        import json
        index_file = "{}_{}.js".format(prefix,
                                       hex(ord(word[0].lower()))[2:].lower())
        if not index_file in self.index:
            index_path = "{BASE}docs/idl/ref/search/{}".format(
                index_file, BASE=self.sdk_path)
            if index_path.startswith("file://"):
                with open(uno.fileUrlToSystemPath(index_path),
                          "r",
                          encoding="utf-8") as f:
                    s = f.read()
            elif index_path.startswith("http://"):
                import urllib.request
                f = urllib.request.urlopen(index_path)
                s = f.read().decode("utf-8")

            s = s[16:-2].replace("'", '"')
            j = json.loads(s, "utf-8")
            self.index[index_file] = j

        j = self.index[index_file]
        _word = word.lower()
        found = None
        for item in j:
            if item[0] == _word:
                entries = item[1]
                if entries[0] == word:
                    if len(entries) == 2:
                        if entries[1][2] == declared_class:
                            found = entries[1][0]
                            break
                    else:
                        _name = "{}::{}()".format(declared_class, word)
                        for entry in entries[1:]:
                            if entry[2] == _name:
                                found = entry[0]
                                break

        return found.lstrip("../")
コード例 #42
0
ファイル: einstellungen.py プロジェクト: kublaj/Organon
    def actionPerformed(self,ev):
        if self.mb.debug: log(inspect.stack)

        try:
            if ev.ActionCommand == 'Konsole':
                
                self.control_log.Enable = (ev.Source.State == 1)
                self.control_arg.Enable = (ev.Source.State == 1)
                self.mb.class_Log.output_console = ev.Source.State
                self.mb.settings_orga['log_config']['output_console'] = ev.Source.State
                self.mb.class_Funktionen.schreibe_settings_orga()
                self.mb.debug = ev.Source.State
                
            elif ev.ActionCommand == 'Logdatei':
                self.mb.class_Log.write_debug_file = ev.Source.State
                self.mb.settings_orga['log_config']['write_debug_file'] = ev.Source.State
                self.mb.class_Funktionen.schreibe_settings_orga()
                
            elif ev.ActionCommand == 'Argumente':
                self.mb.class_Log.log_args = ev.Source.State
                self.mb.settings_orga['log_config']['log_args'] = ev.Source.State
                self.mb.class_Funktionen.schreibe_settings_orga()
                
            elif ev.ActionCommand == 'File':
                Folderpicker = self.mb.createUnoService("com.sun.star.ui.dialogs.FolderPicker")
                Folderpicker.execute()
                
                if Folderpicker.Directory == '':
                    return
                filepath = fileUrlToSystemPath(Folderpicker.getDirectory())
                
                self.mb.class_Log.location_debug_file = filepath
                self.control_filepath.Model.Label = filepath
                
                self.mb.settings_orga['log_config']['location_debug_file'] = filepath
                self.mb.class_Funktionen.schreibe_settings_orga()
   
        except:
            log(inspect.stack,tb())
コード例 #43
0
 def _search_in_index(self, prefix, word, declared_class):
     import json
     index_file = "{}_{}.js".format(prefix, hex(ord(word[0].lower()))[2:].lower())
     if not index_file in self.index:
         index_path = "{BASE}docs/idl/ref/search/{}".format(index_file, BASE=self.sdk_path)
         if index_path.startswith("file://"):
             with open(uno.fileUrlToSystemPath(index_path), "r", encoding="utf-8") as f:
                 s = f.read()
         elif index_path.startswith("http://"):
             import urllib.request
             f = urllib.request.urlopen(index_path)
             s = f.read().decode("utf-8")
         
         s = s[16:-2].replace("'", '"')
         j = json.loads(s, "utf-8")
         self.index[index_file] = j
     
     j = self.index[index_file]
     _word = word.lower()
     found = None
     for item in j:
         if item[0] == _word:
             entries = item[1]
             if entries[0] == word:
                 if len(entries) == 2:
                     if entries[1][2] == declared_class:
                         found = entries[1][0]
                         break
                 else:
                     _name = "{}::{}()".format(declared_class, word)
                     for entry in entries[1:]:
                         if entry[2] == _name:
                             found = entry[0]
                             break
     
     return found.lstrip("../")
コード例 #44
0
ファイル: test.py プロジェクト: hanya/pyuno3
 def test_fileUrlToSystemPath(self):
     sys_path = "/home/foo/bar/hoge/123.ods"
     url = "file:///home/foo/bar/hoge/123.ods"
     
     result = uno.fileUrlToSystemPath(url)
     self.assertEqual(result, sys_path)
コード例 #45
0
ファイル: manager.py プロジェクト: Koala/BookmarksMenu
 def has_location(self):
     """ Check the file exists. """
     return os.path.exists(uno.fileUrlToSystemPath(self.file_url))
コード例 #46
0
def framework_handler(arg):
	doc = XSCRIPTCONTEXT.getDocument()
	scripts_path = os.path.dirname(uno.fileUrlToSystemPath(doc.URL)) + '/framework/handler.py'
	framework = imp.load_source('module.name', scripts_path)
	framework.launch(arg, doc);
コード例 #47
0
ファイル: Dialog.py プロジェクト: prrvchr/GContactOOo
 def callHandlerMethod(self, dialog, event, method):
     if self.dialog == dialog:
         if method == "DialogBack":
             self._setStep(event.Source.Model.Tag)
             return True
         elif method == "DialogNext":
             self._setStep(event.Source.Model.Tag)
             return True
         elif method == "AddressBook":
             self._executeShell("thunderbird", "-addressbook")
             return True
         elif method == "RecipientAdd":
             recipients = self._getRecipientFilters()
             filters = self._getAddressFilters(self.dialog.getControl("Address").Model.SelectedItems, recipients)
             self._rowRecipientExecute(recipients + filters)
             return True
         elif method == "RecipientAddAll":
             recipients = self._getRecipientFilters()
             filters = self._getAddressFilters(range(self.address.RowCount), recipients)
             self._rowRecipientExecute(recipients + filters)
             return True
         elif method == "RecipientRemove":
             recipients = self._getRecipientFilters(self.dialog.getControl("Recipient").Model.SelectedItems)
             self._rowRecipientExecute(recipients)
             return True
         elif method == "RecipientRemoveAll":
             self._rowRecipientExecute([])
             return True
         elif method == "SendAsHtml":
             state = (event.Source.Model.State == 1)
             self._setDocumentUserProperty("SendAsHtml", state)
             self.dialog.getControl("Description").Model.Enabled = not state
             return True
         elif method == "ViewHtml":
             url = self._saveDocumentAs("html")
             self._executeShell(url)
             return True
         elif method == "SendAsPdf":
             state = (event.Source.Model.State == 1)
             self._setDocumentUserProperty("SendAsPdf", state)
             return True
         elif method == "ViewPdf":
             url = self._saveDocumentAs("pdf")
             self._executeShell(url)
             return True
         elif method == "AttachmentAdd":
             control = self.dialog.getControl("Attachments")
             for url in self._getSelectedFiles():
                 path = uno.fileUrlToSystemPath(url)
                 if path not in control.Model.StringItemList:
                     control.addItem(path, control.ItemCount)
             self._setAttachments(control.SelectedItemPos)
             return True
         elif method == "AttachmentRemove":
             control = self.dialog.getControl("Attachments")
             for i in reversed(control.Model.SelectedItems):
                 control.removeItems(i, 1)
             self._setAttachments(control.SelectedItemPos)
             return True
         elif method == "AttachmentView":
             url = uno.systemPathToFileUrl(self.dialog.getControl("Attachments").SelectedItem)
             self._executeShell(url)
             return True
     return False
コード例 #48
0
ファイル: Test_embed.py プロジェクト: kelsa-pi/unodit
    def __init__(self):
        self.LocalContext = uno.getComponentContext()
        self.ServiceManager = self.LocalContext.ServiceManager
        self.Toolkit = self.ServiceManager.createInstanceWithContext("com.sun.star.awt.ExtToolkit", self.LocalContext)

        # -----------------------------------------------------------
        #               Create dialog and insert controls
        # -----------------------------------------------------------

        # --------------create dialog container and set model and properties
        self.DialogContainer = self.ServiceManager.createInstanceWithContext("com.sun.star.awt.UnoControlDialog", self.LocalContext)
        self.DialogModel = self.ServiceManager.createInstance("com.sun.star.awt.UnoControlDialogModel")
        self.DialogContainer.setModel(self.DialogModel)
        self.DialogModel.Moveable = True
        self.DialogModel.Closeable = True
        self.DialogModel.Name = "Default"
        self.DialogModel.Width = 300
        self.DialogModel.PositionX = "60"
        self.DialogModel.Height = 220
        self.DialogModel.PositionY = "60"


        # --------- create an instance of ComboBox control, set properties ---
        self.ComboBox1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlComboBoxModel")

        self.ComboBox1.TabIndex = 10
        self.ComboBox1.Dropdown = True
        self.ComboBox1.StringItemList = ('one', 'two')
        self.ComboBox1.Name = "ComboBox1"
        self.ComboBox1.Width = 60
        self.ComboBox1.PositionX = "83"
        self.ComboBox1.Height = 20
        self.ComboBox1.PositionY = "143"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("ComboBox1", self.ComboBox1)

        # --------- create an instance of GroupBox control, set properties ---
        self.FrameControl1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlGroupBoxModel")

        self.FrameControl1.TabIndex = 36
        self.FrameControl1.Label = "FrameControl1"
        self.FrameControl1.Name = "FrameControl1"
        self.FrameControl1.Width = 60
        self.FrameControl1.PositionX = "9"
        self.FrameControl1.Height = 65
        self.FrameControl1.PositionY = "147"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("FrameControl1", self.FrameControl1)

        # --------- create an instance of Button control, set properties ---
        self.CommandButton1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlButtonModel")

        self.CommandButton1.Align = 0
        self.CommandButton1.TabIndex = 0
        self.CommandButton1.Label = "CommandButton1"
        self.CommandButton1.Toggle = 1
        self.CommandButton1.Name = "CommandButton1"
        self.CommandButton1.Width = 60
        self.CommandButton1.PositionX = "9"
        self.CommandButton1.Height = 20
        self.CommandButton1.PositionY = "8"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("CommandButton1", self.CommandButton1)

        # add the action listener
        self.DialogContainer.getControl('CommandButton1').addActionListener(self)
        self.DialogContainer.getControl('CommandButton1').setActionCommand('CommandButton1_OnClick')

        # --------- create an instance of FixedText control, set properties ---
        self.Label8 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label8.TabIndex = 29
        self.Label8.Label = "ProgressBar"
        self.Label8.Name = "Label8"
        self.Label8.Width = 60
        self.Label8.PositionX = "83"
        self.Label8.Height = 10
        self.Label8.PositionY = "170"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label8", self.Label8)

        # --------- create an instance of FixedText control, set properties ---
        self.Label4 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label4.TabIndex = 25
        self.Label4.Label = "NumericField"
        self.Label4.Name = "Label4"
        self.Label4.Width = 60
        self.Label4.PositionX = "158"
        self.Label4.Height = 10
        self.Label4.PositionY = "76"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label4", self.Label4)

        # --------- create an instance of FileControl control, set properties ---
        self.FileControl1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFileControlModel")

        self.FileControl1.TabIndex = 18
        self.FileControl1.Name = "FileControl1"
        self.FileControl1.Text = "/home/sasa"
        self.FileControl1.Width = 60
        self.FileControl1.PositionX = "235"
        self.FileControl1.Height = 20
        self.FileControl1.PositionY = "17"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("FileControl1", self.FileControl1)

        # --------- create an instance of FixedText control, set properties ---
        self.Label7 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label7.TabIndex = 28
        self.Label7.Label = "PatternField"
        self.Label7.Name = "Label7"
        self.Label7.Width = 60
        self.Label7.PositionX = "158"
        self.Label7.Height = 10
        self.Label7.PositionY = "185"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label7", self.Label7)

        # --------- create an instance of FixedText control, set properties ---
        self.Label5 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label5.TabIndex = 26
        self.Label5.Label = "CurrencyField"
        self.Label5.Name = "Label5"
        self.Label5.Width = 60
        self.Label5.PositionX = "158"
        self.Label5.Height = 10
        self.Label5.PositionY = "114"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label5", self.Label5)

        # --------- create an instance of Button control, set properties ---
        self.CommandButton2 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlButtonModel")

        self.CommandButton2.TabIndex = 1
        self.CommandButton2.Label = "CommandButton2"
        self.CommandButton2.Enabled = True
        self.CommandButton2.Name = "CommandButton2"
        self.CommandButton2.Width = 29
        self.CommandButton2.PositionY = "33"
        self.CommandButton2.Height = 20
        self.CommandButton2.PositionX = "9"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("CommandButton2", self.CommandButton2)

        # add the action listener
        self.DialogContainer.getControl('CommandButton2').addActionListener(self)
        self.DialogContainer.getControl('CommandButton2').setActionCommand('CommandButton2_OnClick')

        # --------- create an instance of SpinButton control, set properties ---
        self.SpinButton1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlSpinButtonModel")

        self.SpinButton1.TabIndex = 22
        self.SpinButton1.Name = "SpinButton1"
        self.SpinButton1.Width = 60
        self.SpinButton1.PositionX = "235"
        self.SpinButton1.Height = 20
        self.SpinButton1.PositionY = "167"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("SpinButton1", self.SpinButton1)

        # --------- create an instance of FixedText control, set properties ---
        self.Label13 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label13.TabIndex = 34
        self.Label13.Label = "SpinButton"
        self.Label13.Name = "Label13"
        self.Label13.Width = 60
        self.Label13.PositionX = "235"
        self.Label13.Height = 10
        self.Label13.PositionY = "156"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label13", self.Label13)

        # --------- create an instance of NumericField control, set properties ---
        self.NumericField1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlNumericFieldModel")

        self.NumericField1.TabIndex = 14
        self.NumericField1.Value = 55555
        self.NumericField1.Name = "NumericField1"
        self.NumericField1.Width = 60
        self.NumericField1.PositionX = "158"
        self.NumericField1.Height = 20
        self.NumericField1.PositionY = "87"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("NumericField1", self.NumericField1)

        # --------- create an instance of TimeField control, set properties ---
        self.TimeField1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlTimeFieldModel")

        self.TimeField1.TabIndex = 13
        self.TimeField1.TimeMin = uno.createUnoStruct("com.sun.star.util.Time", Hours = 10, Minutes = 0, Seconds = 0, NanoSeconds = 0, IsUTC = True)
        self.TimeField1.Name = "TimeField1"
        self.TimeField1.Width = 60
        self.TimeField1.PositionX = "160"
        self.TimeField1.Text = "Set Time"
        self.TimeField1.Time = uno.createUnoStruct("com.sun.star.util.Time", Hours = 14, Minutes = 5, Seconds = 3, NanoSeconds = 0, IsUTC = True)
        self.TimeField1.PositionY = "52"
        self.TimeField1.Height = 20
        self.TimeField1.TimeMax = uno.createUnoStruct("com.sun.star.util.Time", Hours = 22, Minutes = 59, Seconds = 0, NanoSeconds = 0, IsUTC = True)

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("TimeField1", self.TimeField1)

        # --------- create an instance of FixedText control, set properties ---
        self.Label1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label1.TabIndex = 7
        self.Label1.Label = "New"
        self.Label1.Name = "Label1"
        self.Label1.Width = 20
        self.Label1.PositionX = "83"
        self.Label1.Height = 20
        self.Label1.PositionY = "8"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label1", self.Label1)

        # --------- create an instance of FixedText control, set properties ---
        self.Label12 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label12.TabIndex = 33
        self.Label12.Label = "TreeControl"
        self.Label12.Name = "Label12"
        self.Label12.Width = 60
        self.Label12.PositionX = "235"
        self.Label12.Height = 10
        self.Label12.PositionY = "41"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label12", self.Label12)

        # --------- create an instance of FixedText control, set properties ---
        self.Label3 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label3.TabIndex = 24
        self.Label3.Label = "TimeField"
        self.Label3.Name = "Label3"
        self.Label3.Width = 60
        self.Label3.PositionX = "158"
        self.Label3.Height = 10
        self.Label3.PositionY = "42"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label3", self.Label3)

        # --------- create an instance of .tree.TreeControl control, set properties ---
        self.TreeControl1 = self.DialogModel.createInstance("com.sun.star.awt.tree.TreeControlModel")

        self.TreeControl1.TabIndex = 35
        self.TreeControl1.Name = "TreeControl1"
        self.TreeControl1.Width = 59
        self.TreeControl1.PositionX = "235"
        self.TreeControl1.Height = 100
        self.TreeControl1.PositionY = "53"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("TreeControl1", self.TreeControl1)

        # --------- create an instance of ImageControl control, set properties ---
        self.ImageControl1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlImageControlModel")

        self.ImageControl1.TabIndex = 3
        self.ImageControl1.ImageURL = uno.fileUrlToSystemPath("file:///home/sasa/Pictures/coquette-icons-set/png/32x32/add_home.png")
        self.ImageControl1.Name = "ImageControl1"
        self.ImageControl1.Width = 60
        self.ImageControl1.PositionX = "9"
        self.ImageControl1.Height = 60
        self.ImageControl1.PositionY = "56"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("ImageControl1", self.ImageControl1)

        # --------- create an instance of FixedText control, set properties ---
        self.Label6 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label6.TabIndex = 27
        self.Label6.Label = "FormattedField"
        self.Label6.Name = "Label6"
        self.Label6.Width = 60
        self.Label6.PositionX = "158"
        self.Label6.Height = 10
        self.Label6.PositionY = "150"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label6", self.Label6)

        # --------- create an instance of DateField control, set properties ---
        self.DateField1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlDateFieldModel")

        self.DateField1.TabIndex = 12
        self.DateField1.RepeatDelay = 50
        self.DateField1.Date = uno.createUnoStruct("com.sun.star.util.Date", Year = 2015, Month = 3, Day = 26)
        self.DateField1.Name = "DateField1"
        self.DateField1.Width = 60
        self.DateField1.PositionX = "158"
        self.DateField1.DateFormat = 9
        self.DateField1.Dropdown = True
        self.DateField1.DateMax = uno.createUnoStruct("com.sun.star.util.Date", Year = 2020, Month = 1, Day = 1)
        self.DateField1.Text = "Set Date"
        self.DateField1.DateMin = uno.createUnoStruct("com.sun.star.util.Date", Year = 1820, Month = 1, Day = 1)
        self.DateField1.PositionY = "17"
        self.DateField1.Height = 20

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("DateField1", self.DateField1)

        # --------- create an instance of Button control, set properties ---
        self.CommandButton3 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlButtonModel")

        self.CommandButton3.TabIndex = 2
        self.CommandButton3.Label = "CommandButton3"
        self.CommandButton3.Name = "CommandButton3"
        self.CommandButton3.EnableVisible = False
        self.CommandButton3.Width = 26
        self.CommandButton3.PositionX = "43"
        self.CommandButton3.Height = 20
        self.CommandButton3.PositionY = "33"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("CommandButton3", self.CommandButton3)

        # add the action listener
        self.DialogContainer.getControl('CommandButton3').addActionListener(self)
        self.DialogContainer.getControl('CommandButton3').setActionCommand('CommandButton3_OnClick')

        # --------- create an instance of RadioButton control, set properties ---
        self.OptionButton2 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlRadioButtonModel")

        self.OptionButton2.TabIndex = 6
        self.OptionButton2.Label = "OptionButton2"
        self.OptionButton2.Name = "OptionButton2"
        self.OptionButton2.Width = 50
        self.OptionButton2.PositionX = "14"
        self.OptionButton2.Height = 20
        self.OptionButton2.PositionY = "187"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("OptionButton2", self.OptionButton2)

        # --------- create an instance of FixedLine control, set properties ---
        self.FixedLine1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedLineModel")

        self.FixedLine1.TabIndex = 19
        self.FixedLine1.Orientation = 1
        self.FixedLine1.Name = "FixedLine1"
        self.FixedLine1.Width = 4
        self.FixedLine1.PositionX = "75"
        self.FixedLine1.Height = 210
        self.FixedLine1.PositionY = "5"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("FixedLine1", self.FixedLine1)

        # --------- create an instance of CheckBox control, set properties ---
        self.CheckBox1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlCheckBoxModel")

        self.CheckBox1.TabIndex = 4
        self.CheckBox1.Label = "CheckBox1"
        self.CheckBox1.PositionY = "121"
        self.CheckBox1.Name = "CheckBox1"
        self.CheckBox1.Width = 60
        self.CheckBox1.State = True
        self.CheckBox1.PositionX = "9"
        self.CheckBox1.Height = 20
        self.CheckBox1.TriState = True

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("CheckBox1", self.CheckBox1)

        # --------- create an instance of ListBox control, set properties ---
        self.ListBox1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlListBoxModel")

        self.ListBox1.MultiSelection = True
        self.ListBox1.TabIndex = 9
        self.ListBox1.Align = 1
        self.ListBox1.StringItemList = ('one', 'two')
        self.ListBox1.Name = "ListBox1"
        self.ListBox1.Width = 60
        self.ListBox1.PositionX = "83"
        self.ListBox1.Height = 82
        self.ListBox1.PositionY = "45"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("ListBox1", self.ListBox1)

        # --------- create an instance of FixedLine control, set properties ---
        self.FixedLine3 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedLineModel")

        self.FixedLine3.TabIndex = 21
        self.FixedLine3.Orientation = 1
        self.FixedLine3.Name = "FixedLine3"
        self.FixedLine3.Width = 4
        self.FixedLine3.PositionX = "225"
        self.FixedLine3.Height = 210
        self.FixedLine3.PositionY = "5"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("FixedLine3", self.FixedLine3)

        # --------- create an instance of CurrencyField control, set properties ---
        self.CurrencyField1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlCurrencyFieldModel")

        self.CurrencyField1.TabIndex = 15
        self.CurrencyField1.Value = 5555
        self.CurrencyField1.PositionY = "124"
        self.CurrencyField1.Name = "CurrencyField1"
        self.CurrencyField1.Width = 60
        self.CurrencyField1.PositionX = "158"
        self.CurrencyField1.Height = 20
        self.CurrencyField1.ShowThousandsSeparator = True

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("CurrencyField1", self.CurrencyField1)

        # --------- create an instance of ProgressBar control, set properties ---
        self.ProgressBar1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlProgressBarModel")

        self.ProgressBar1.ProgressValue = 50
        self.ProgressBar1.TabIndex = 11
        self.ProgressBar1.Name = "ProgressBar1"
        self.ProgressBar1.Width = 60
        self.ProgressBar1.PositionX = "85"
        self.ProgressBar1.Height = 20
        self.ProgressBar1.PositionY = "184"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("ProgressBar1", self.ProgressBar1)

        # --------- create an instance of RadioButton control, set properties ---
        self.OptionButton1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlRadioButtonModel")

        self.OptionButton1.TabIndex = 5
        self.OptionButton1.Label = "OptionButton1"
        self.OptionButton1.Name = "OptionButton1"
        self.OptionButton1.Width = 50
        self.OptionButton1.State = True
        self.OptionButton1.PositionX = "14"
        self.OptionButton1.Height = 20
        self.OptionButton1.PositionY = "162"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("OptionButton1", self.OptionButton1)

        # --------- create an instance of FormattedField control, set properties ---
        self.FormattedField1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFormattedFieldModel")

        self.FormattedField1.EffectiveMax = 5000
        self.FormattedField1.TabIndex = 16
        self.FormattedField1.EffectiveMin = 1000
        self.FormattedField1.Name = "FormattedField1"
        self.FormattedField1.Width = 60
        self.FormattedField1.PositionX = "158"
        self.FormattedField1.EffectiveValue = 2000
        self.FormattedField1.Text = "2,000"
        self.FormattedField1.PositionY = "160"
        self.FormattedField1.Height = 20

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("FormattedField1", self.FormattedField1)

        # --------- create an instance of FixedLine control, set properties ---
        self.FixedLine2 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedLineModel")

        self.FixedLine2.TabIndex = 20
        self.FixedLine2.Orientation = 1
        self.FixedLine2.Name = "FixedLine2"
        self.FixedLine2.Width = 4
        self.FixedLine2.PositionX = "150"
        self.FixedLine2.Height = 210
        self.FixedLine2.PositionY = "5"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("FixedLine2", self.FixedLine2)

        # --------- create an instance of FixedText control, set properties ---
        self.Label2 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label2.TabIndex = 23
        self.Label2.Label = "DateField"
        self.Label2.Name = "Label2"
        self.Label2.Width = 60
        self.Label2.PositionX = "158"
        self.Label2.Height = 10
        self.Label2.PositionY = "6"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label2", self.Label2)

        # --------- create an instance of FixedText control, set properties ---
        self.Label9 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label9.TabIndex = 30
        self.Label9.Label = "ListBox"
        self.Label9.Name = "Label9"
        self.Label9.Width = 60
        self.Label9.PositionX = "85"
        self.Label9.Height = 10
        self.Label9.PositionY = "35"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label9", self.Label9)

        # --------- create an instance of FixedText control, set properties ---
        self.Label10 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label10.TabIndex = 31
        self.Label10.Label = "ComboBox"
        self.Label10.Name = "Label10"
        self.Label10.Width = 60
        self.Label10.PositionX = "83"
        self.Label10.Height = 10
        self.Label10.PositionY = "133"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label10", self.Label10)

        # --------- create an instance of Edit control, set properties ---
        self.TextField1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlEditModel")

        self.TextField1.TabIndex = 8
        self.TextField1.Name = "TextField1"
        self.TextField1.Text = "New Text"
        self.TextField1.Width = 40
        self.TextField1.PositionX = "103"
        self.TextField1.Height = 20
        self.TextField1.PositionY = "8"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("TextField1", self.TextField1)

        # --------- create an instance of PatternField control, set properties ---
        self.PatternField1 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlPatternFieldModel")

        self.PatternField1.TabIndex = 17
        self.PatternField1.EditMask = "NNLNNLLLLL"
        self.PatternField1.Name = "PatternField1"
        self.PatternField1.Width = 60
        self.PatternField1.LiteralMask = "__.__.2015"
        self.PatternField1.PositionX = "158"
        self.PatternField1.StrictFormat = True
        self.PatternField1.Text = "Pattern Field Text"
        self.PatternField1.PositionY = "194"
        self.PatternField1.Height = 20

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("PatternField1", self.PatternField1)

        # --------- create an instance of FixedText control, set properties ---
        self.Label11 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")

        self.Label11.TabIndex = 32
        self.Label11.Label = "FileControl"
        self.Label11.Name = "Label11"
        self.Label11.Width = 60
        self.Label11.PositionX = "235"
        self.Label11.Height = 10
        self.Label11.PositionY = "6"

        # inserts the control model into the dialog model
        self.DialogModel.insertByName("Label11", self.Label11)
コード例 #49
0
ファイル: command.py プロジェクト: Koala/BookmarksMenu
 def extract_as_row(self, res, item, graphics, show_value=True, show_description=True, show_tags=True):
     """ Command to strings for grid view. """
     def _(name):
         return res.get(name, name)
     
     def get_qs(name):
         try:
             return qs[name]
         except:
             return ""
     command = item.get_command()
     value = ""
     args = ""
     icon = None
     
     main, protocol, path, query = self.bk_command_parse(command)
     qs = self.bk_parse_qs(query)
     protocol = protocol + ":"
     
     if protocol == self.PROTOCOL_COMMAND:
         if qs and main.startswith(self.COMMAND_OPEN_FROM) and \
             self.QUERY_NAME_URL in qs:
             value = get_qs(self.QUERY_NAME_URL)
             icon = graphics["document"]
             try:
                 if value.startswith(self.PROTOCOL_FILE):
                     value = uno.fileUrlToSystemPath(value)
             except:
                 pass
         else:
             value = command
             icon = graphics["command"]
     
     elif protocol == self.PROTOCOL_SCRIPT:
         language = get_qs("language")
         value = "%s: %s" % (language, main[20:])
         icon = graphics["macro"]
     
     elif protocol == self.PROTOCOL_MACRO:
         value = "Basic: %s" % main[6:]
     
     elif protocol == self.PROTOCOL_BOOKMARKS:
         item_type = path.lower()
         if item_type == "program":
             arguments = get_qs(self.QUERY_NAME_ARGUMENTS)
             if arguments:
                 value = "%s: %s, \n%s: %s" % (
                     _("Program"), get_qs(self.QUERY_NAME_PATH), 
                     _("Arguments"), arguments)
             else:
                 value = "%s: %s" % (_("Program"), 
                     get_qs(self.QUERY_NAME_PATH))
         elif item_type == "file":
             # icon indicates its type, isnt enough?
             #value = "%s: %s" % (_("File"), get_qs(self.QUERY_NAME_PATH))
             value = get_qs(self.QUERY_NAME_PATH)
         elif item_type == "folder":
             #value = "%s: %s" % (_("Folder"), get_qs(self.QUERY_NAME_PATH))
             value = get_qs(self.QUERY_NAME_PATH)
         elif item_type == "web":
             #value = "%s: %s" % (_("Web"), get_qs(self.QUERY_NAME_PATH))
             value = get_qs(self.QUERY_NAME_PATH)
         elif item_type == "edit" or item_type == "addthis":
             value = ""
         
         else:
             value = command
         
         icon = graphics[path.lower()]
     
     elif main == self.TAG_POPUP_URI:
         if qs:
             value = get_qs(self.QUERY_NAME_TAG)
         else:
             value = command
         icon = graphics["tag"]
     
     elif main == self.DIRECTORY_POPUP_URI:
         if qs:
             value = get_qs(self.QUERY_NAME_URL)
             try:
                 value = uno.fileUrlToSystemPath(value)
             except:
                 pass
         else:
             value = command
         icon = graphics["directory_popup"]
     
     else:
         value = command
         icon = graphics["command"]
         
     data = [icon, item.get_name()]
     if show_tags:
         data.append(",".join(item.get_tags()))
     if show_value:
         data.append(value)
     if show_description:
         data.append(item.get_description())
     return tuple(data)
コード例 #50
0
ファイル: Dialog.py プロジェクト: prrvchr/GContactOOo
 def _getAttachmentsPath(self, default=None):
     paths = []
     for url in self._getAttachments(default):
         paths.append(uno.fileUrlToSystemPath(url))
     return paths
コード例 #51
0
 def _switch_path(self, path):
     if path.startswith("file://"):
         return uno.fileUrlToSystemPath(path)
     else:
         return uno.systemPathToFileUrl(path)
コード例 #52
0
ファイル: Dialog.py プロジェクト: prrvchr/GContactOOo
 def _getAttachment(self, url):
     attachment = MailAttachment()
     attachment.Data = self
     attachment.ReadableName = uno.fileUrlToSystemPath(self._getUrl(url).Name)
     return attachment
コード例 #53
0
ファイル: keys.py プロジェクト: billyoc/MRI
 def get_key_config_path(self):
     ps = self._create_service("com.sun.star.util.PathSubstitution")
     url = ps.substituteVariables(self.CONFIG, True)
     return uno.fileUrlToSystemPath(url)
コード例 #54
0
ファイル: command.py プロジェクト: Koala/BookmarksMenu
 def generate_command(self, d):
     """ Generate commmnd from new value. """
     qs = {}
     type = d["type"]
     if type == "document":
         path = d["path"]
         try:
             if not path.startswith(self.PROTOCOL_FILE):
                 path = uno.systemPathToFileUrl(path)
         except:
             pass
         qs[self.QUERY_NAME_FRAME_NAME] ="_default"
         filter = d.get("filter", None)
         main = self.COMMAND_OPEN_DOCUMENT
         qs[self.QUERY_NAME_URL] = path
         if filter:
             qs[self.QUERY_NAME_FILTER_NAME] = filter
     
     elif type == "macro":
         command = d["command"]
     
     elif type == "command":
         if d["arguments"]:
             command = "%s?%s" % (d["command"], d["arguments"])
             #main = d["command"]
         else:
             command = d["command"]
     
     elif type == "program":
         path = d["path"]
         if path.startswith(self.PROTOCOL_FILE):
             try:
                 path = uno.fileUrlToSystemPath(path)
             except:
                 pass
         main = self.COMMAND_PROGRAM
         qs[self.QUERY_NAME_PATH] = path
         qs[self.QUERY_NAME_ARGUMENTS] = d["arguments"]
     
     elif type == "something":
         main = self.COMMAND_SOMETHING % d["flag"].capitalize()
         qs[self.QUERY_NAME_PATH] = d["path"]
     
     elif type == "special":
         flag = d["flag"]
         path = d["path"]
         try:
             path = uno.systemPathToFileUrl(path)
         except:
             pass
         if flag == "open_from_folder":
             main = self.COMMAND_OPEN_FROM
             qs[self.QUERY_NAME_FOLDER_NAME] = path
         
         elif flag == "saveas_into_folder":
             main = self.COMMAND_SAVE_AS_INTO
             qs[self.QUERY_NAME_FOLDER_NAME] = path
         
         elif flag == "directory_popup":
             main = self.DIRECTORY_POPUP_URI
             if "create" in d:
                 qs[self.QUERY_NAME_URL] = d["path"]
                 if "filter" in d:
                     qs[self.QUERY_NAME_FILTER] = d["filter"]
             else:
                 command = d["path"]
     
     elif type == "tag":
         main = self.TAG_POPUP_URI
         qs[self.QUERY_NAME_TAG] = d["tag_name"]
     
     else:
         command = "ERRROR"
     
     if qs:
         command = main + "?" + self.bk_urlencode(qs)
     
     return command
コード例 #55
0
ファイル: web.py プロジェクト: billyoc/MRI
 def set_browser(self, browser):
     """set browser path."""
     Web.set_browser(self, uno.fileUrlToSystemPath(browser).replace("\\", '/'))
コード例 #56
0
def alterar_diretorio(document):
    url = document.URL
    syspath = uno.fileUrlToSystemPath(url)
    directory = os.path.dirname(syspath)
    os.chdir(directory)
コード例 #57
0
ファイル: package.py プロジェクト: Koala/BookmarksMenu
 def generate(self, name, _titles, 
     merge_point, merge_command, merge_context, description, data=None, another=False, ext_id=None):
     """ Generate extension package. """
     self.delete_package()
     self.package_url = self.get_package_url()
     file_path = uno.fileUrlToSystemPath(self.package_url)
     
     merge_fallback = "AddPath"
     
     if ext_id:
         id = ext_id[len(EXT_ID)+1:]
     if another:
         url = PROTOCOL_BOOKMARKS + id
         #node_name = url
         node_name = url + "_" + get_id()
         # different ext_id (and node name) with the same url
         id = get_id()
         ext_id = EXT_ID + "." + id
     else:
         if not ext_id:
             id = get_id()
             ext_id = EXT_ID + "." + id
         url = PROTOCOL_BOOKMARKS + id
         node_name = url
     
     arc_data = BookmarksManager.FILE_NAME % id
     
     titles = []
     for locale, title in _titles:
         titles.append(TITLE_VALUE % (
             locale, title))
     
     # url is used as node name
     addons = ADDONS % (
         EXT_ID, 
         node_name, 
         merge_point, 
         merge_command, 
         merge_fallback, 
         merge_context, 
         "child", 
         "\n".join(titles), 
         url, 
         merge_context
     )
     
     manifests = []
     manifests.append(CONFIG_DATA % ARC_ADDONS)
     if not another:
         manifests.append(CONFIG_DATA % ARC_CONTROLLER)
         manifests.append(CONFIG_DATA % ARC_SETTINGS)
     manifest = MANIFEST % ("\n".join(manifests))
     
     descriptions = DESCRIPTIONS % (
         ext_id, 
         "Bookmarks Menu %s" % escape(name)
     )
     
     desc = description #"%s" % name
     
     if not another:
         controller = CONTROLLER % (
             node_name, 
             url, 
             IMPLE_NAME
         )
         settings = SETTINGS % (
             node_name, 
             escape(name)
         )
     
     encoding = self.Encoding
     z = zipfile.ZipFile(file_path, "w")
     z.writestr(ARC_MANIFEST, manifest.encode(encoding))
     z.writestr(ARC_DESCRIPTION, descriptions.encode(encoding))
     z.writestr(ARC_DESCRIPTIONS, desc.encode(encoding))
     z.writestr(ARC_ADDONS, addons.encode(encoding))
     if not another:
         z.writestr(ARC_CONTROLLER, controller.encode(encoding))
         z.writestr(ARC_SETTINGS, settings.encode(encoding))
     if data:
         z.writestr(arc_data, data.encode(encoding))
     z.close()