예제 #1
0
    def scriptURI2StorageUri(self, scriptURI):
        try:
            # base path to the python script location
            sBaseUri = self.m_baseUri + "/"
            xBaseUri = self.m_uriRefFac.parse(sBaseUri)

            # path to the .py file + "$functionname, arguments, etc
            xStorageUri = self.m_uriRefFac.parse(scriptURI)
            # getName will apply url-decoding to the name, so encode back
            sStorageUri = xStorageUri.getName().replace("%", "%25")
            sStorageUri = sStorageUri.replace("|", "/")

            # path to the .py file, relative to the base
            funcNameStart = sStorageUri.find("$")
            if funcNameStart != -1:
                sFileUri = sStorageUri[0:funcNameStart]
                sFuncName = sStorageUri[funcNameStart + 1:]
            else:
                sFileUri = sStorageUri

            xFileUri = self.m_uriRefFac.parse(sFileUri)
            if not xFileUri:
                message = "pythonscript: invalid relative uri '" + sFileUri + "'"
                log.debug(message)
                raise RuntimeException(message, self.ctx)

            if not xFileUri.hasRelativePath():
                message = "pythonscript: an absolute uri is invalid '" + sFileUri + "'"
                log.debug(message)
                raise RuntimeException(message, self.ctx)

            # absolute path to the .py file
            xAbsScriptUri = self.m_uriRefFac.makeAbsolute(
                xBaseUri, xFileUri, True, RETAIN)
            sAbsScriptUri = xAbsScriptUri.getUriReference()

            # ensure py file is under the base path
            if not sAbsScriptUri.startswith(sBaseUri):
                message = "pythonscript: storage uri '" + sAbsScriptUri + "' not in base uri '" + self.m_baseUri + "'"
                log.debug(message)
                raise RuntimeException(message, self.ctx)

            ret = sAbsScriptUri
            if funcNameStart != -1:
                ret = ret + "$" + sFuncName
            log.debug("converting scriptURI=" + scriptURI + " to storageURI=" +
                      ret)
            return ret
        except UnoException as e:
            log.error("error during converting scriptURI=" + scriptURI + ": " +
                      e.Message)
            raise RuntimeException(
                "pythonscript:scriptURI2StorageUri: " + e.Message, self.ctx)
        except Exception as e:
            log.error("error during converting scriptURI=" + scriptURI + ": " +
                      str(e))
            raise RuntimeException(
                "pythonscript:scriptURI2StorageUri: " + str(e), self.ctx)
예제 #2
0
 def scriptURI2StorageUri( self, scriptURI ):
     try:
         myUri = self.m_uriRefFac.parse(scriptURI)
         ret = self.m_baseUri + "/" + myUri.getName().replace( "|", "/" )
         log.debug( "converting scriptURI="+scriptURI + " to storageURI=" + ret )
         return ret
     except UnoException as e:
         log.error( "error during converting scriptURI="+scriptURI + ": " + e.Message)
         raise RuntimeException( "pythonscript:scriptURI2StorageUri: " +e.getMessage(), None )
     except Exception as e:
         log.error( "error during converting scriptURI="+scriptURI + ": " + str(e))
         raise RuntimeException( "pythonscript:scriptURI2StorageUri: " + str(e), None )
예제 #3
0
    def getModuleFromUrl(self, url):
        if DEBUG:
            print("pythonloader: interpreting url " + url)
        protocol, dependent = splitUrl(url)
        if "vnd.sun.star.expand" == protocol:
            exp = self.ctx.getValueByName(
                "/singletons/com.sun.star.util.theMacroExpander")
            url = exp.expandMacros(dependent)
            protocol, dependent = splitUrl(url)

        if DEBUG:
            print("pythonloader: after expansion " + protocol + ":" +
                  dependent)

        try:
            if "file" == protocol:
                # remove \..\ sequence, which may be useful e.g. in the build env
                url = unohelper.absolutize(url, url)

                # did we load the module already ?
                mod = g_loadedComponents.get(url)
                if not mod:
                    mod = imp.new_module("uno_component")

                    # check for pythonpath.zip beside .py files
                    checkForPythonPathBesideComponent(url[0:url.rfind('/')])

                    # read the file
                    filename = unohelper.fileUrlToSystemPath(url)
                    fileHandle = file(filename)
                    src = fileHandle.read().replace("\r", "")
                    if not src.endswith("\n"):
                        src = src + "\n"

                    # compile and execute the module
                    codeobject = compile(src, encfile(filename), "exec")
                    exec(codeobject, mod.__dict__)
                    mod.__file__ = encfile(filename)
                    g_loadedComponents[url] = mod
                return mod
            elif "vnd.openoffice.pymodule" == protocol:
                return __import__(dependent)
            else:
                raise RuntimeException(
                    "PythonLoader: Unknown protocol " + protocol + " in url " +
                    url, self)
        except ImportError as e:
            raise RuntimeException(
                "Couldn't load " + url + " for reason " + str(e), None)
        return None
예제 #4
0
 def invoke(self, args, out, outindex):
     log.debug("PythonScript.invoke " + str(args))
     try:
         ret = self.func(*args)
     except UnoException as e:
         # UNO Exception continue to fly ...
         text = lastException2String()
         complete = "Error during invoking function " + \
             str(self.func.__name__) + " in module " + \
             self.mod.__file__ + " (" + text + ")"
         log.debug(complete)
         # some people may beat me up for modifying the exception text,
         # but otherwise office just shows
         # the type name and message text with no more information,
         # this is really bad for most users.
         e.Message = e.Message + " (" + complete + ")"
         raise
     except Exception as e:
         # General python exception are converted to uno RuntimeException
         text = lastException2String()
         complete = "Error during invoking function " + \
             str(self.func.__name__) + " in module " + \
             self.mod.__file__ + " (" + text + ")"
         log.debug(complete)
         raise RuntimeException(complete, self)
     log.debug("PythonScript.invoke ret = " + str(ret))
     return ret, (), ()
예제 #5
0
    def __init__( self, ctx, *args ):
        if log.isDebugLevel():
            mystr = ""
            for i in args:
                if len(mystr) > 0:
                    mystr = mystr +","
                mystr = mystr + str(i)
            log.debug( "Entering PythonScriptProvider.ctor" + mystr )

        doc = None
        inv = None
        storageType = ""

        if isinstance(args[0],unicode ):
            storageType = args[0]
            if storageType.startswith( "vnd.sun.star.tdoc" ):
                doc = getModelFromDocUrl(ctx, storageType)
        else:
            inv = args[0]
            try:
                doc = inv.ScriptContainer
                content = ctx.getServiceManager().createInstanceWithContext(
                    "com.sun.star.frame.TransientDocumentsDocumentContentFactory",
                    ctx).createDocumentContent(doc)
                storageType = content.getIdentifier().getContentIdentifier()
            except Exception as e:
                text = lastException2String()
                log.error( text )

        isPackage = storageType.endswith( ":uno_packages" )

        try:
#            urlHelper = ctx.ServiceManager.createInstanceWithArgumentsAndContext(
#                "com.sun.star.script.provider.ScriptURIHelper", (LANGUAGENAME, storageType), ctx)
            urlHelper = MyUriHelper( ctx, storageType )
            log.debug( "got urlHelper " + str( urlHelper ) )

            rootUrl = expandUri( urlHelper.getRootStorageURI() )
            log.debug( storageType + " transformed to " + rootUrl )

            ucbService = "com.sun.star.ucb.SimpleFileAccess"
            sfa = ctx.ServiceManager.createInstanceWithContext( ucbService, ctx )
            if not sfa:
                log.debug("PythonScriptProvider couldn't instantiate " +ucbService)
                raise RuntimeException(
                    "PythonScriptProvider couldn't instantiate " +ucbService, self)
            self.provCtx = ProviderContext(
                storageType, sfa, urlHelper, ScriptContext( uno.getComponentContext(), doc, inv ) )
            if isPackage:
                mapPackageName2Path = getPackageName2PathMap( sfa, storageType )
                self.provCtx.setPackageAttributes( mapPackageName2Path , rootUrl )
                self.dirBrowseNode = PackageBrowseNode( self.provCtx, LANGUAGENAME, rootUrl )
            else:
                self.dirBrowseNode = DirBrowseNode( self.provCtx, LANGUAGENAME, rootUrl )

        except Exception as e:
            text = lastException2String()
            log.debug( "PythonScriptProvider could not be instantiated because of : " + text )
            raise e
예제 #6
0
class MyUriHelper:
    def __init__(self, ctx, location):
        self.s_UriMap = \
        { "share" : "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" +  toIniName( "bootstrap") + "::BaseInstallation}/share/Scripts/python" , \
          "share:uno_packages" : "vnd.sun.star.expand:$UNO_SHARED_PACKAGES_CACHE/uno_packages", \
          "user" : "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" + toIniName( "bootstrap") + "::UserInstallation}/user/Scripts/python" , \
          "user:uno_packages" : "vnd.sun.star.expand:$UNO_USER_PACKAGES_CACHE/uno_packages" }
        self.m_uriRefFac = ctx.ServiceManager.createInstanceWithContext(
            "com.sun.star.uri.UriReferenceFactory", ctx)
        if location.startswith("vnd.sun.star.tdoc"):
            self.m_baseUri = location + "/Scripts/python"
            self.m_scriptUriLocation = "document"
        else:
            self.m_baseUri = expandUri(self.s_UriMap[location])
            self.m_scriptUriLocation = location
        log.isDebugLevel() and log.debug(
            "initialized urihelper with baseUri=" + self.m_baseUri +
            ",m_scriptUriLocation=" + self.m_scriptUriLocation)

    def getRootStorageURI(self):
        return self.m_baseUri

    def getStorageURI(self, scriptURI):
        return self.scriptURI2StorageUri(scriptURI)

    def getScriptURI(self, storageURI):
        return self.storageURI2ScriptUri(storageURI)

    def storageURI2ScriptUri(self, storageURI):
        if not storageURI.startswith(self.m_baseUri):
            message = "pythonscript: storage uri '" + storageURI + "' not in base uri '" + self.m_baseUri + "'"
            log.isDebugLevel() and log.debug(message)
            raise RuntimeException(message)

        ret = "vnd.sun.star.script:" + \
              storageURI[len(self.m_baseUri)+1:].replace("/","|") + \
              "?language=" + LANGUAGENAME + "&location=" + self.m_scriptUriLocation
        log.isDebugLevel() and log.debug("converting storageURI=" +
                                         storageURI + " to scriptURI=" + ret)
        return ret

    def scriptURI2StorageUri(self, scriptURI):
        try:
            myUri = self.m_uriRefFac.parse(scriptURI)
            ret = self.m_baseUri + "/" + myUri.getName().replace("|", "/")
            log.isDebugLevel() and log.debug("converting scriptURI=" +
                                             scriptURI + " to storageURI=" +
                                             ret)
            return ret
        except UnoException, e:
            log.error("error during converting scriptURI=" + scriptURI + ": " +
                      e.Message)
            raise RuntimeException(
                "pythonscript:scriptURI2StorageUri: " + e.getMessage(), None)
        except Exception, e:
            log.error("error during converting scriptURI=" + scriptURI + ": " +
                      str(e))
            raise RuntimeException(
                "pythonscript:scriptURI2StorageUri: " + str(e), None)
예제 #7
0
파일: Barcode.py 프로젝트: sterbur/barcode
    def insertBarcodeAPI(self, codetype, value, addChecksum, posX, posY):
        value = getattr(self, 'validate_%s' % codetype)(value, addChecksum)
        if value is None:
            raise RuntimeException('Error validating codetype ' + codetype,
                                   self.ctx)

        group = getattr(self, 'draw_%s' % codetype)(value, addChecksum)
        draw.setpos(group, posX, posY)
예제 #8
0
파일: test.py 프로젝트: slamj1/core-5
 def _handle_crash_reporter(self):
     xCrashReportDlg = self._xUITest.getTopFocusWindow()
     state = get_state_as_dict(xCrashReportDlg)
     print(state)
     if state['ID'] == "CrashReportDialog":
         print("found a crash reporter")
         xCancelBtn = xCrashReportDlg.getChild("btn_cancel")
         self.close_dialog_through_button(xCancelBtn)
     else:
         raise RuntimeException("not a crashreporter")
예제 #9
0
    def scriptURI2StorageUri(self, scriptURI):
        try:
            # base path to the python script location
            sBaseUri = self.m_baseUri + "/"
            xBaseUri = self.m_uriRefFac.parse(sBaseUri)

            # path to the .py file + "$functionname, arguments, etc
            xStorageUri = self.m_uriRefFac.parse(scriptURI)
            sStorageUri = xStorageUri.getName().replace("|", "/")

            # path to the .py file, relative to the base
            sFileUri = sStorageUri[0:sStorageUri.find("$")]
            xFileUri = self.m_uriRefFac.parse(sFileUri)
            if not xFileUri:
                message = "pythonscript: invalid relative uri '" + sFileUri + "'"
                log.debug(message)
                raise RuntimeException(message)

            # absolute path to the .py file
            xAbsScriptUri = self.m_uriRefFac.makeAbsolute(
                xBaseUri, xFileUri, True, RETAIN)
            sAbsScriptUri = xAbsScriptUri.getUriReference()

            # ensure py file is under the base path
            if not sAbsScriptUri.startswith(sBaseUri):
                message = "pythonscript: storage uri '" + sAbsScriptUri + "' not in base uri '" + self.m_baseUri + "'"
                log.debug(message)
                raise RuntimeException(message)

            ret = sBaseUri + sStorageUri
            log.debug("converting scriptURI=" + scriptURI + " to storageURI=" +
                      ret)
            return ret
        except UnoException as e:
            log.error("error during converting scriptURI=" + scriptURI + ": " +
                      e.Message)
            raise RuntimeException(
                "pythonscript:scriptURI2StorageUri: " + e.getMessage(), None)
        except Exception as e:
            log.error("error during converting scriptURI=" + scriptURI + ": " +
                      str(e))
            raise RuntimeException(
                "pythonscript:scriptURI2StorageUri: " + str(e), None)
예제 #10
0
    def storageURI2ScriptUri( self, storageURI ):
        if not storageURI.startswith( self.m_baseUri ):
            message = "pythonscript: storage uri '" + storageURI + "' not in base uri '" + self.m_baseUri + "'"
            log.debug( message )
            raise RuntimeException( message )

        ret = "vnd.sun.star.script:" + \
              storageURI[len(self.m_baseUri)+1:].replace("/","|") + \
              "?language=" + LANGUAGENAME + "&location=" + self.m_scriptUriLocation
        log.debug( "converting storageURI="+storageURI + " to scriptURI=" + ret )
        return ret
예제 #11
0
    def __init__(self, ctx, *args):
        if log.isDebugLevel():
            mystr = ""
            for i in args:
                if len(mystr) > 0:
                    mystr = mystr + ","
                mystr = mystr + str(i)
            log.debug("Entering PythonScriptProvider.ctor" + mystr)

        storageType = ""
        if isinstance(args[0], unicode):
            storageType = args[0]
        else:
            storageType = args[0].SCRIPTING_DOC_URI
        isPackage = storageType.endswith(":uno_packages")

        try:
            #            urlHelper = ctx.ServiceManager.createInstanceWithArgumentsAndContext(
            #                "com.sun.star.script.provider.ScriptURIHelper", (LANGUAGENAME, storageType), ctx)
            urlHelper = MyUriHelper(ctx, storageType)
            log.isDebugLevel() and log.debug("got urlHelper " + str(urlHelper))

            rootUrl = expandUri(urlHelper.getRootStorageURI())
            log.isDebugLevel() and log.debug(storageType + " transformed to " +
                                             rootUrl)

            ucbService = "com.sun.star.ucb.SimpleFileAccess"
            sfa = ctx.ServiceManager.createInstanceWithContext(ucbService, ctx)
            if not sfa:
                log.debug("PythonScriptProvider couldn't instantiate " +
                          ucbService)
                raise RuntimeException(
                    "PythonScriptProvider couldn't instantiate " + ucbService,
                    self)
            self.provCtx = ProviderContext(
                storageType, sfa, urlHelper,
                ScriptContext(uno.getComponentContext(), None))
            if isPackage:
                mapPackageName2Path = getPackageName2PathMap(sfa, storageType)
                self.provCtx.setPackageAttributes(mapPackageName2Path, rootUrl)
                self.dirBrowseNode = PackageBrowseNode(self.provCtx,
                                                       LANGUAGENAME, rootUrl)
            else:
                self.dirBrowseNode = DirBrowseNode(self.provCtx, LANGUAGENAME,
                                                   rootUrl)

        except Exception, e:
            text = lastException2String()
            log.debug(
                "PythonScriptProvider could not be instantiated because of : "
                + text)
            raise e
예제 #12
0
    def box(self, message, kind='infobox', buttons='OK', title=None):
        # Don't show message box in API mode, throw exception instead
        if self.isAPIMode:
            raise RuntimeException(message, self.ctx)

        if kind == 'infobox' and buttons != 'OK':
            kind = 'querybox'  # infobox only supports OK
        if title is None: title = self.localize('title')
        toolkit = self.ctx.ServiceManager.createInstance(
            'com.sun.star.awt.Toolkit')
        rectangle = uno.createUnoStruct('com.sun.star.awt.Rectangle')
        msgbox = toolkit.createMessageBox(
            self.getdesktop().getCurrentFrame().getContainerWindow(), kind,
            uno.getConstantByName(
                'com.sun.star.awt.MessageBoxButtons.BUTTONS_' + buttons),
            title, message)
        return msgbox.execute()
예제 #13
0
def xray(myObject, unoObjs):
    """For debugging.
    Displays a dialog to analyze UNO object attributes.
    To use this function, the XRayTool OpenOffice extension is required.
    """
    if not LOGGING_ENABLED:
        return
    mspf = unoObjs.smgr.createInstanceWithContext(
        "com.sun.star.script.provider.MasterScriptProviderFactory",
        unoObjs.ctx)
    scriptPro = mspf.createScriptProvider("")
    try:
        xScript = scriptPro.getScript(
            "vnd.sun.star.script:XrayTool._Main.Xray?" +
            "language=Basic&location=application")
    except:
        raise RuntimeException("\nBasic library Xray is not installed",
                               unoObjs.ctx)
    xScript.invoke((myObject, ), (), ())
예제 #14
0
 def supportsService(self, implementationName, serviceName):
     entry = self.impls.get(implementationName, None)
     if entry == None:
         raise RuntimeException(implementationName + " is unknown", None)
     return serviceName in entry.serviceNames
예제 #15
0
 def getComponentFactory(self, implementationName, regKey, smgr):
     entry = self.impls.get(implementationName, None)
     if entry == None:
         raise RuntimeException(implementationName + " is unknown", None)
     return createSingleServiceFactory(entry.ctor, implementationName,
                                       entry.serviceNames)
예제 #16
0
    def getModuleFromUrl(self, url):
        if DEBUG:
            print("pythonloader: interpreting url " + url)
        protocol, dependent = splitUrl(url)
        if "vnd.sun.star.expand" == protocol:
            exp = self.ctx.getValueByName(
                "/singletons/com.sun.star.util.theMacroExpander")
            url = exp.expandMacros(dependent)
            protocol, dependent = splitUrl(url)

        if DEBUG:
            print("pythonloader: after expansion " + protocol + ":" +
                  dependent)

        try:
            if "file" == protocol:
                # remove \..\ sequence, which may be useful e.g. in the build env
                url = unohelper.absolutize(url, url)

                # did we load the module already ?
                mod = g_loadedComponents.get(url)
                if not mod:
                    mod = types.ModuleType("uno_component")

                    # check for pythonpath.zip beside .py files
                    checkForPythonPathBesideComponent(url[0:url.rfind('/')])

                    # read the file
                    filename = unohelper.fileUrlToSystemPath(url)

                    with open(filename, encoding='utf_8') as fileHandle:
                        src = fileHandle.read().replace("\r", "")
                        if not src.endswith("\n"):
                            src = src + "\n"

                        # compile and execute the module
                        codeobject = compile(src, encfile(filename), "exec")
                        mod.__file__ = filename
                        exec(codeobject, mod.__dict__)
                        g_loadedComponents[url] = mod
                return mod
            elif "vnd.openoffice.pymodule" == protocol:
                nSlash = dependent.rfind('/')
                if -1 != nSlash:
                    path = unohelper.fileUrlToSystemPath(dependent[0:nSlash])
                    dependent = dependent[nSlash + 1:len(dependent)]
                    if not path in sys.path:
                        sys.path.append(path)
                mod = __import__(dependent)
                path_component, dot, rest = dependent.partition('.')
                while dot == '.':
                    path_component, dot, rest = rest.partition('.')
                    mod = getattr(mod, path_component)
                return mod
            else:
                if DEBUG:
                    print("Unknown protocol '" + protocol + "'")
                raise RuntimeException(
                    "PythonLoader: Unknown protocol " + protocol + " in url " +
                    url, self)
        except Exception as e:
            if DEBUG:
                print("Python import exception " + str(type(e)) + " message " +
                      str(e) + " args " + str(e.args))
            raise RuntimeException(
                "Couldn't load " + url + " for reason " + str(e), None)
        return None
예제 #17
0
def splitUrl(url):
    nColon = url.find(":")
    if -1 == nColon:
        raise RuntimeException("PythonLoader: No protocol in url " + url, None)
    return url[0:nColon], url[nColon + 1:len(url)]
예제 #18
0
 def getSupportedServiceNames(self, implementationName):
     entry = self.impls.get(implementationName, None)
     if entry is None:
         raise RuntimeException(implementationName + " is unknown", None)
     return entry.serviceNames
예제 #19
0
 def raiseRuntimeExceptionOneway(self, Message, Context):
     raise RuntimeException(Message, Context)