Beispiel #1
0
    def test_differentOnDisk(self):
        path = tempfile.mktemp()
        try:
            # Init the test file with some content.
            _writefile(path, "blah\nblah\nblah\n")

            koDoc = self._koDocFromPath(path, load=False)
            # Make it look like a remote file.
            rawFile = UnwrapObject(koDoc.file)
            rawFile.isLocal = 0
            rawFile.isRemoteFile = 1
            koDoc.load()

            # Wait one second, so we generate a different mtime.
            import time
            time.sleep(1.1)
            _writefile(path, "blah\nblah\nblah\nblah\n")

            self.assertTrue(koDoc.differentOnDisk(), "Remote file change was not detected")
            # Next time we call it - it should still detect the file as being changed - bug 95690.
            self.assertTrue(koDoc.differentOnDisk(), "Remote file change was not detected a second time")
            # Because we are using a fake koIFileEx (or really a local file),
            # this test can fail if the timestamp between the save and the
            # differentOnDisk calls has changed. To work around that, we run
            # multiple checks and only accept one failure.
            success_count = 0
            for tries in range(3):
                koDoc.save(True)
                if not koDoc.differentOnDisk():
                    success_count += 1
            self.assertTrue(success_count >= 2, "Remote file change detected after saving the file")
        finally:
            if os.path.exists(path):
                os.unlink(path) # clean up
 def deleteRows(self, dataTreeView, rowNums):
     # @param dataTreeView { koIDBXTableDumpTreeView }
     #  koIDBXTableDumpTreeView: koDatabaseExplorerTreeView.koDatabaseExplorerTreeView
     # @param rowNums {array of int}
     column_names = self.getColumnNames()
     query_names = []
     dataTreeView = UnwrapObject(dataTreeView)
     schemaTreeView = UnwrapObject(dataTreeView.get_schemaTreeView())
     for i in range(len(column_names)):
         is_key = (schemaTreeView.getCellText(i, dbxlib.Column('is_primary_key')).lower()
                   in ('true', '1')) # windows: 'true', linux: '1'
         if is_key:
             query_names.append(column_names[i])
     if not query_names:
         raise dbxlib.DBXception("No attributes are keys, can't delete")
     table_name = self._table_name
     # return True if any rows are deleted
     final_res = ""
     for rowNum in rowNums:
         query_values = []
         for column_name in query_names:
             query_values.append(dataTreeView.getCellText(rowNum,
                                                          dbxlib.Column(column_name)))
         res = self._db.deleteRowByKey(self._table_name,
                                 query_names,
                                 query_values)
         if not (res or final_res):
             final_res = ("Failed to delete keys:%s, values:%s" %
                         (", ".join(query_names),
                          ", ".join([str(x) for x in query_values])))
     return final_res
Beispiel #3
0
    def test_language_reset(self):
        manifest = [
            ("Python", tempfile.mktemp(".py"), """\
#!/usr/bin/env python
print 'should be py'
"""),
            ("Python3", tempfile.mktemp(".py"), """\
#  -*- python3 -*-
print('should be py3')
"""),
            ("JavaScript", tempfile.mktemp(".js"), """\
alert('should be js')
"""),
        ]
        for lang, name, content in manifest:
            path = join(self.data_dir, name)
            _writefile(path, content)
            koDoc = self._koDocFromPath(path)
            self.assertEqual(koDoc.language, lang)
            koDoc.language = "Perl"
            self.assertEqual(koDoc.language, "Perl")
            koDoc.language = ""
            self.assertEqual(koDoc.language, lang)
            # Validate the documents preference chain - bug 97728.
            doc = UnwrapObject(koDoc)
            doc._walkPrefChain(doc.prefs, doPrint=False)
    def DOMDeserialize(self, rootElement, parentPref, prefFactory, basedir=None, chainNotifications=0):
        """We know how to deserialize preferent-set elements."""
        # Create a new preference set and rig it into the preference set hierarchy.
        xpPrefSet = components.classes["@activestate.com/koPreferenceSet;1"] \
                  .createInstance(components.interfaces.koIPreferenceSet)
        newPrefSet = UnwrapObject(xpPrefSet)
        newPrefSet.chainNotifications = chainNotifications
        try:
            newPrefSet.id = rootElement.getAttribute('id') or ""
        except KeyError:
            newPrefSet.id = ""
        try:
            newPrefSet.idref = rootElement.getAttribute('idref') or ""
        except KeyError:
            newPrefSet.idref = ""

        # Iterate over the elements of the preference set,
        # deserializing them and fleshing out the new preference
        # set with content.
        childNodes = rootElement.childNodes

        for node in childNodes:
            if node and node.nodeType == minidom.Node.ELEMENT_NODE:
                if node.hasAttribute('validate'):
                    newPrefSet.setValidation(node.getAttribute('id'), node.getAttribute('validate'))
                pref = _dispatch_deserializer(self, node, newPrefSet, prefFactory, basedir, chainNotifications)
                if pref:
                    if pref.id:
                        newPrefSet.setPref(pref.id, pref)
                    else:
                        log.error("Preference has no id - dumping preference:")
                        pref.dump(0)

        return xpPrefSet 
Beispiel #5
0
    def DOMDeserialize(self, rootElement, parentPref, prefFactory, basedir=None, chainNotifications=0):
        """We know how to deserialize ordered-preference elements."""

        # Create a new ordered preference.
        xpOrderedPref = components.classes["@activestate.com/koOrderedPreference;1"].createInstance(
            components.interfaces.koIOrderedPreference
        )
        newOrderedPref = UnwrapObject(xpOrderedPref)
        try:
            newOrderedPref.id = rootElement.getAttribute("id") or ""
        except KeyError:
            newOrderedPref.id = ""

        # Iterate over the elements of the preference set,
        # deserializing them and fleshing out the new preference
        # set with content.
        childNodes = rootElement.childNodes

        for childNode in childNodes:
            if childNode and childNode.nodeType == minidom.Node.ELEMENT_NODE:
                pref = _dispatch_deserializer(self, childNode, newOrderedPref, prefFactory, basedir)
                if pref:
                    newOrderedPref.appendPref(pref)

        return xpOrderedPref
Beispiel #6
0
class KoTerminalProcess(KoRunProcess):

    _terminal = None

    def linkIOWithTerminal(self, terminal):
        # Need to unwrap the terminal handler because we are not actually
        # passing in koIFile xpcom objects as described by the API, we are
        # using the subprocess python file handles instead.
        self._terminal = UnwrapObject(terminal)
        self._terminal.hookIO(self._process.stdin, self._process.stdout,
                              self._process.stderr, "KoTerminalProcess")

    # Override the KoRunProcess.wait() method.
    def wait(self, timeout=None):
        retval = KoRunProcess.wait(self, timeout)
        if self._terminal:
            # Need to wait until the IO is fully synchronized (due to threads)
            # before returning. Otherwise additional data could arrive after
            # this call returns.
            # 
            # Set timeout to 5 seconds due to bugs 89280 and 88439
            self._terminal.waitForIOToFinish(timeout=5)
            self._terminal = None
        return retval

    def waitAsynchronously(self, runTerminationListener):
        t = threading.Thread(target=_terminalProcessWaiter,
                             args=(self, runTerminationListener))
        t.setDaemon(True)
        t.start()
Beispiel #7
0
 def initialize(self, toolbox_db_svc):
     global _tbdbSvc
     _tbdbSvc = self.toolbox_db = toolbox_db_svc
     self._koToolbox2Service = UnwrapObject(components.classes["@activestate.com/koToolbox2Service;1"].getService(components.interfaces.koIToolbox2Service))
     self._koProjectService = UnwrapObject(components.classes["@activestate.com/koPartService;1"].getService(components.interfaces.koIPartService))
     self._globalPrefs = components.classes["@activestate.com/koPrefService;1"].\
                    getService(components.interfaces.koIPrefService).prefs
class KoCodeIntelXPCOMSupportReigstrationHelper(object):
    """Helper class for codeintel command extension registration; See kd290 /
    KoCodeIntelManager._send_init_requests.initialization_completed"""
    _com_interfaces_ = []
    _reg_clsid_ = "{3ae458a3-b767-47d8-a5a6-1731d415c54b}"
    _reg_contractid_ = "@activestate.com/codeintel/xpcom/registration-helper;1"
    _reg_desc_ = "Komodo XPCOM Code Intelligence Backend Registration Helper"
    _reg_categories_ = [
        ("codeintel-command-extension", _reg_contractid_),
    ]
    def __init__(self):
        self.completer = \
            UnwrapObject(Cc[KoCodeIntelXPCOMSupport._reg_contractid_]
                           .getService())
        self.data = [
            (dirname(__file__), "xpcomJSElements"),
        ]
    def __iter__(self):
        """Iteration for codeintel command extension registration"""
        return self
    def next(self):
        try:
            return self.data.pop(0)
        except IndexError:
            self.completer.send_connection_request()
            raise StopIteration
Beispiel #9
0
    def test_differentOnDisk(self):
        path = tempfile.mktemp()
        try:
            # Init the test file with some content.
            _writefile(path, "blah\nblah\nblah\n")

            koDoc = self._koDocFromPath(path)
            # Make it look like a remote file.
            rawFile = UnwrapObject(koDoc.file)
            rawFile.isLocal = 0
            rawFile.isRemoteFile = 1
            koDoc.load()

            # Wait one second, so we generate a different mtime.
            import time
            time.sleep(1.1)
            _writefile(path, "blah\nblah\nblah\nblah\n")

            self.assertTrue(koDoc.differentOnDisk(), "Remote file change was not detected")
            # Next time we call it - it should still detect the file as being changed - bug 95690.
            self.assertTrue(koDoc.differentOnDisk(), "Remote file change was not detected a second time")
            koDoc.save(True)
            self.assertFalse(koDoc.differentOnDisk(), "Remote file change detected after saving the file")
        finally:
            if os.path.exists(path):
                os.unlink(path) # clean up
Beispiel #10
0
def _setup_for_xpcom():
    # Use a temporary user data dir
    userDataRoot = tempfile.mkdtemp(prefix="ko-test-userdata-")
    atexit.register(shutil.rmtree, userDataRoot)
    os.environ["KOMODO_USERDATADIR"] = userDataRoot

    # The tests are run outside of Komodo. If run with PyXPCOM up
    # parts codeintel will try to use the nsIDirectoryService and
    # will query dirs only provided by nsXREDirProvider -- which
    # isn't registered outside of Komodo (XRE_main() isn't called).
    # The KoTestService provides a backup.
    from xpcom import _xpcom
    from xpcom import components
    from xpcom.server import UnwrapObject
    koTestSvc = components.classes["@activestate.com/koTestService;1"] \
        .getService(components.interfaces.koITestService)
    koTestSvc.init()

    # Reset the startup-env.tmp file (normally done by komodo.exe), otherwise
    # we'll be reading stale environment settings from whenever Komodo was last
    # run on this machine.
    koEnvironSvc = components.classes["@activestate.com/koUserEnviron;1"] \
        .getService(components.interfaces.koIUserEnviron)
    pyEnvironSvc = UnwrapObject(koEnvironSvc)
    try:
        os.remove(pyEnvironSvc.startupEnvFileName)
    except OSError:
        # Doesn't exist, or we don't have the correct permissions... ignore.
        pass
    pyEnvironSvc._UpdateFromStartupEnv()
Beispiel #11
0
    def addNewItemToParent(self, parent, item, showNewItem=True):
        """
        This code has a model part and a view part.  Call the view
        part if we need to update it.
        """
        # TODO: if parent is null, use the std toolbox node
        item = UnwrapObject(item)
        parent = UnwrapObject(parent)
        parent_path = self.toolbox_db.getPath(parent.id)
        item_name = item.name
        itemIsContainer = item.isContainer
        if itemIsContainer:
            # Bug 96486: Can't create folders named "*" on Windows
            # Now that we're encouraging people to create folders with this name,
            # we need to quietly change the "*"s to "_"s.  I don't
            # remember why I decided not to do this in general.
            system_item_name = item_name.replace("*", "_")

            # Don't do anything else to this name.  If there's a dup, or
            # it contains bad characters, give the user the actual
            # error message.  Which is why we need to try creating
            # the folder first, before adding its entry.
            path = join(parent_path, system_item_name)
            if system_item_name != item_name:
                # Make sure it's new
                if os.path.exists(path):
                    for i in range(20):
                        suffix = i + 1
                        new_path = "%s-%d" % (path, suffix)
                        if not os.path.exists(new_path):
                            path = new_path
                            break
            item.trailblazeForPath(path)
        else:
            path = self._prepareUniqueFileSystemName(parent_path, item_name)
        try:
            itemDetailsDict = {}
            item.fillDetails(itemDetailsDict)
            if itemIsContainer:
                new_id = self.toolbox_db.addContainerItem(itemDetailsDict, item.typeName, path, item_name, parent.id)
            else:
                new_id = self.toolbox_db.addTool(itemDetailsDict, item.typeName, path, item_name, parent.id)

            old_id = item.id
            item.id = new_id
            # Even if the old and new IDs are the same, we don't want
            # to keep the old item in the cache.
            try:
                del self._tools[old_id]
            except KeyError:
                log.error("No self._tools[%r]", old_id)
            self._tools[new_id] = item
            item.saveNewToolToDisk(path)
            if showNewItem:
                self._koToolboxHView.addNewItemToParent(parent, item)
            item.added()
        except:
            log.exception("addNewItemToParent: failed")
            raise
 def _clonePartList(self, newproject, partList):
     # clone parts and add them to the project
     for part in partList:
         part = UnwrapObject(part)
         if part.type == 'project':
             self._clonePartList(newproject, part.children)
         else:
             newpart = part.copyToProject(newproject)
             newproject.addChild(newpart)
Beispiel #13
0
 def lint(self, request):
     try:
         html_linter = UnwrapObject(self._koLintService.getLinterForLanguage("HTML"))
         return html_linter.lint(request, TPLInfo=self._tplPatterns)
     except:
         if "lint" not in self._checkValidVersion_complained:
             self._checkValidVersion_complained["lint"] = True
             log.exception("Problem in koPHPLinter.lint")
         return koLintResults()
Beispiel #14
0
 def KGit_hookFunction(self):
     wm = components.classes["@mozilla.org/appshell/window-mediator;1"].getService(components.interfaces.nsIWindowMediator)
     win = wm.getMostRecentWindow("Komodo")
     tree = win.document.getElementById('places-files-tree')
     treebox = tree.boxObject.QueryInterface(components.interfaces.nsITreeBoxObject)
     pview = UnwrapObject(treebox.view)
     if pview._buildCellProperties == self.KGit_buildCellProperties:
       return
     self._buildCellProperties_old = pview._buildCellProperties
     pview._buildCellProperties = self.KGit_buildCellProperties
Beispiel #15
0
class KoTemplateCategoriesView(TreeView):
    _com_interfaces_ = [components.interfaces.koITemplateCategoriesView,
                        components.interfaces.nsITreeView]
    _reg_clsid_ = "{0723776F-EE9D-4F20-B438-3AF893192346}"
    _reg_contractid_ = "@activestate.com/koTemplateCategoriesView;1"
    _reg_desc_ = "Komodo Template Categories nsITreeView"

    def __init__(self):
        TreeView.__init__(self) #, debug="categories") #XXX
        self._tree = None
        self._sortedBy = None
        # The table used to fill in the tree. It is a list of dicts. Each
        # dict represents one row in the tree/outliner. This dictionary is
        # also (because it is convenient) used to store data in addition to
        # the named rows of the XUL tree. e.g.,
        #  [ {"category-name": "My Templates",  # row 0
        #     "node": <Node instance for this category>},
        #    ... ]
        # This attribute is re-generated from self.templateTree whenever
        # the rows change (say, by the user opening a category with
        # sub-categories).
        self._data = []
        
        self._prefSvc = components.classes["@activestate.com/koPrefService;1"]\
                        .getService().prefs # global prefs
        self.templateTree = None # Working copy of template tree Nodes.
        self.selectedTemplateByCategory = None
        self.categoryIsOpen = None
        self.atomSvc = components.classes["@mozilla.org/atom-service;1"].\
                  getService(components.interfaces.nsIAtomService)
        self.folderOpenAtom = self.atomSvc.getAtom("folderOpen")
                               
        self.folderClosedAtom = self.atomSvc.getAtom("folderClosed")

    def initialize(self, templateSvc, templatesView):
        # Need to unwrap these Python XPCOM object because we access
        # methods on them that are not in the IDL.
        self.templateSvc = UnwrapObject(templateSvc)
        self.templatesView = UnwrapObject(templatesView)
        
        if not self.templateSvc.loaded:
            self.templateSvc.loadTemplates()
        self.templateTree = self.templateSvc.getTemplateTree() # a working copy
        
        # Restore the user selections from prefs
        stbcStr = self._prefSvc.getStringPref("%s_selected_template_by_category" % self.templateSvc.basename)
        try:
            self.selectedTemplateByCategory = eval(stbcStr)
        except SyntaxError, ex:
            self.selectedTemplateByCategory = {}
        ocStr = self._prefSvc.getStringPref("%s_open_categories" % self.templateSvc.basename)
        try:
            self.categoryIsOpen = eval(ocStr)
        except SyntaxError, ex:
            self.categoryIsOpen = {}
Beispiel #16
0
 def _loadAllLanguages(self):
     self._allRows = []
     langRegistry = components.classes["@activestate.com/koLanguageRegistryService;1"].getService(components.interfaces.koILanguageRegistryService)
     langRegistry = UnwrapObject(langRegistry)
     langNames = langRegistry.getLanguageNames()
     for langName in langNames:
         isPrimary = langRegistry._primaryLanguageNames.get(langName, False)
         self._allRows.append({'name':langName,
                               'name_lc':langName.lower(),
                               'status':isPrimary,
                               'origStatus':isPrimary})
 def _gatherIconsAux(self, part, icons):
     part = UnwrapObject(part)
     icon = part.get_iconurl()
     if self.test:
         print "icon [%s]"%icon
     if not icon.startswith(('chrome://', 'moz-icon://stock/')):
         newicon = os.path.join('.icons', os.path.basename(icon))
         part.set_iconurl(newicon)
         icons.append((uriparse.URIToLocalPath(icon),newicon))
     if hasattr(part, 'getChildren'):
         for p in part.getChildren():
             self._gatherIconsAux(p, icons)
Beispiel #18
0
 def save(self, prefs):
     if not self._wasChanged:
         return
     langRegistry = UnwrapObject(Cc["@activestate.com/koLanguageRegistryService;1"]
                                   .getService(Ci.koILanguageRegistryService))
     for row in self._rows:
         langName, status, origStatus = row['name'], row['status'], row['origStatus']
         if status != origStatus:
             langRegistry.changeLanguageStatus(langName, status)
             # Update the pref
             primaryLanguagePref = "languages/%s/primary" % (langName,)
             prefs.setBoolean(primaryLanguagePref, bool(status))
     self.notifyObservers(None, 'primary_languages_changed', '')
Beispiel #19
0
 def savePrefs(self, kpf):
     prefSvc = components.classes["@activestate.com/koPrefService;1"]\
                         .getService().prefs # global prefs
     # multi tree, we want JUST the project passed in.  Get all the
     # id's from the project, and then get the matching id's from
     # nodeIsOpen
     kpf = UnwrapObject(kpf)
     nodeIsOpen = {}
     for id in self._nodeIsOpen.keys():
         if kpf.getChildById(id):
             nodeIsOpen[id] = self._nodeIsOpen[id]
     prefSvc.setStringPref("kpf_open_nodes_%s" % kpf.id,
                           repr(nodeIsOpen))
 def paths(self):
     """Generate all paths for this collection."""
     for type, item in self.items:
         if type == "path":
             yield item
         elif type == "file":
             path = _local_path_from_url(item.url)
             if path is not None:
                 yield path
         elif type == "container":
             container = UnwrapObject(item)
             for path in container.genLocalPaths():
                 yield path                
Beispiel #21
0
 def lint_with_text(self, request, text):
     linters = self._koLintService.getTerminalLintersForLanguage(self._languageName)
     finalLintResults = koLintResults()
     for linter in linters:
         try:
             newLintResults = UnwrapObject(linter).lint_with_text(request, text)
         except:
             log.exception("lint_with_text exception")
         else:
             if newLintResults and newLintResults.getNumResults():
                 if finalLintResults.getNumResults():
                     finalLintResults = finalLintResults.addResults(newLintResults)
                 else:
                     finalLintResults = newLintResults
     return finalLintResults
    def _get(self, kind, callback):
        def on_have_catalogs(request, response):
            try:
                cb = callback.callback
            except AttributeError:
                cb = callback # not XPCOM?
            items = response.get(kind)
            if items is None or not response.get("success"):
                cb(Ci.koIAsyncCallback.RESULT_ERROR, [])
            else:
                cb(Ci.koIAsyncCallback.RESULT_SUCCESSFUL, items)

        cisvc = UnwrapObject(Cc["@activestate.com/koCodeIntelService;1"]
                               .getService())
        cisvc.send(command="get-xml-catalogs", callback=on_have_catalogs)
class KoXBLCompileLinter(object):
    _com_interfaces_ = [components.interfaces.koILinter]
    _reg_desc_ = "Komodo XBL Compile Linter"
    _reg_clsid_ = "{4e023df3-4fda-4c74-abe0-b6623d72862e}"
    _reg_contractid_ = "@activestate.com/koLinter?language=XBL;1"
    _reg_categories_ = [
         ("category-komodo-linter", 'XBL'),
         ]

    def __init__(self):
        koLintService = components.classes["@activestate.com/koLintService;1"].getService(components.interfaces.koILintService)
        self._html_linter = koLintService.getLinterForLanguage("HTML")
        self._js_linter = UnwrapObject(koLintService.getLinterForLanguage("JavaScript"))

    def lint(self, request):
        try:
            return UnwrapObject(self._html_linter).lint(request,
                                                        linters={"JavaScript":self})
        except:
            log.exception("Error linting XBL")

    # We can't use standard JS linting to handle XBL methods,
    # so wrap the JSLinter, and filter out results complaining
    # about return stmts outside functions.
    def lint_with_text(self, request, text):
        #log.debug("XBL text: %s", text)
        jsResults = self._js_linter.lint_with_text(request, text)
        #log.debug("XBL lint results: %s",
        #          [str(x) for x in jsResults.getResults()])
        fixedResults = koLintResults()
        for res in jsResults.getResults():
            if 'return not in function' not in res.description:
                fixedResults.addResult(res)
        return fixedResults
Beispiel #24
0
class KoEpMojoLinter(object):
    _com_interfaces_ = [components.interfaces.koILinter]
    _reg_desc_ = "epMojo Template Linter"
    _reg_clsid_ = "{3b69f94f-4fb6-47bb-a387-9d3ac372195a}"
    _reg_contractid_ = "@activestate.com/koLinter?language=epMojo;1"
    _reg_categories_ = [
        ("category-komodo-linter", 'epMojo'),
    ]

    def __init__(self):
        self._koLintService = components.classes[
            "@activestate.com/koLintService;1"].getService(components.interfaces.koILintService)
        self._html_linter = UnwrapObject(
            self._koLintService.getLinterForLanguage("HTML"))

    _tplPatterns = ("epMojo", re.compile(
        '<%='), re.compile(r'%>\s*\Z', re.DOTALL))

    def lint(self, request):
        return self._html_linter.lint(request, TPLInfo=self._tplPatterns)

    def lint_with_text(self, request, text):
        # With revised html_linter template processing, the html linter will
        # pull out Perl parts and dispatch them to the perl linter, so there's
        # nothing to do here.
        return None
Beispiel #25
0
 def linkIOWithTerminal(self, terminal):
     # Need to unwrap the terminal handler because we are not actually
     # passing in koIFile xpcom objects as described by the API, we are
     # using the subprocess python file handles instead.
     self._terminal = UnwrapObject(terminal)
     self._terminal.hookIO(self._process.stdin, self._process.stdout,
                           self._process.stderr, "KoTerminalProcess")
 def __init__(self):
     koLintService = components.classes["@activestate.com/koLintService;1"].getService(
         components.interfaces.koILintService
     )
     # Still need to use HTML's _lint_common_html_request to pull out the
     # erb directives
     self._html_linter = UnwrapObject(koLintService.getLinterForLanguage("HTML5"))
 def __init__(self):
     self.completer = \
         UnwrapObject(Cc[KoCodeIntelXPCOMSupport._reg_contractid_]
                        .getService())
     self.data = [
         (dirname(__file__), "xpcomJSElements"),
     ]
Beispiel #28
0
 def __init__(self, methodName):
     unittest.TestCase.__init__(self, methodName)
     self.__fileStatusSvc = components.classes["@activestate.com/koFileStatusService;1"] \
                      .getService(components.interfaces.koIFileStatusService)
     from xpcom.server import UnwrapObject
     UnwrapObject(self.__fileStatusSvc).init()
     self.__filesvc = components.classes["@activestate.com/koFileService;1"] \
                      .getService(components.interfaces.koIFileService)
Beispiel #29
0
 def deleteRows(self, dataTreeView, rowNums):
     # @param dataTreeView { koIDBXTableDumpTreeView }
     #  koIDBXTableDumpTreeView: koDatabaseExplorerTreeView.koDatabaseExplorerTreeView
     # @param rowNums {array of int}
     column_names = self.getColumnNames()
     query_names = []
     dataTreeView = UnwrapObject(dataTreeView)
     schemaTreeView = UnwrapObject(dataTreeView.get_schemaTreeView())
     for i in range(len(column_names)):
         is_key = (schemaTreeView.getCellText(i, dbxlib.Column('is_primary_key'))
                   == '1')
         if is_key:
             query_names.append(column_names[i])
     if not query_names:
         raise dbxlib.DBXception("No attributes are keys, can't delete")
     table_name = self._table_name
     # return True if any rows are deleted
     final_res = ""
     for rowNum in rowNums:
         query_values = []
         for column_name in query_names:
             query_values.append(dataTreeView.getCellText(rowNum,
                                                          dbxlib.Column(column_name)))
         res = self._db.deleteRowByKey(self._table_name,
                                 query_names,
                                 query_values)
         if not (res or final_res):
             final_res = ("Failed to delete keys:%s, values:%s" %
                         (", ".join(query_names),
                          ", ".join([str(x) for x in query_values])))
     return final_res
Beispiel #30
0
    def test_12_python_actions(self):
        """Test Python API with actions"""
        self.assertEquals(self.nm.notificationCount, 0)
        nm = UnwrapObject(self.nm)
        a0_data = {
            "identifier": "action0",
            "label": "action0-label",
            "accessKey": "a",
            "iconURL": "action-url",
            "visible": True,
            "enabled": True
        }
        notif = nm.add("summary", ["tags"],
                       "notif-action-py",
                       actions=[a0_data])
        self.assertEquals(notif,
                          self._wrap(notif))  # should already be wrapped
        notif.QueryInterface(Ci.koINotification)  # should implement this
        notif.QueryInterface(Ci.koINotificationActionable)  # due to actions=
        self.assertEquals(self.nm.notificationCount,
                          1)  # added one notification
        try:
            self.assertEquals(len(notif.getActions()), 1)
            self.assertEquals(len(notif.getActions("bad-id")), 0)
            self.assertEquals(len(notif.getActions("action0")), 1)
            action = notif.getActions()[0]
            self.assertEquals(action, self._wrap(action))
            for k, v in a0_data.items():
                self.assertEquals(getattr(action, k), v)
            for k in ("label", "accessKey", "iconURL"):
                with self.check_called(notif, will_call=False):
                    # changing the action won't force an update
                    self.assertNotEquals(getattr(action, k), k)
                    setattr(action, k, k)
                    self.assertEquals(getattr(action, k), k)
            with self.check_called(notif, old_index=0, new_index=0):
                # calling the right update API, however, will fire listeners
                nm.update(notif,
                          actions=[{
                              "identifier": "action0",
                              "label": "new label"
                          }])
                self.assertEquals(action.label, "new label")
            self.assertRaises(COMException,
                              nm.update,
                              notif,
                              actions=[{
                                  "label": "foo"
                              }])
            self.assertRaises(COMException,
                              nm.update,
                              notif,
                              actions=[{
                                  "identifier": "action0",
                                  "invalid": "key"
                              }])

        finally:
            nm.remove(notif)
            self.assertEquals(self.nm.notificationCount, 0)
Beispiel #31
0
 def __init__(self):
     try:
         self.phpInfoEx = components.classes["@activestate.com/koAppInfoEx?app=PHP;1"].\
                          getService(components.interfaces.koIPHPInfoEx)
         koLintService = components.classes["@activestate.com/koLintService;1"].getService(components.interfaces.koILintService)
         self._html_linter = UnwrapObject(koLintService.getLinterForLanguage("HTML"))
     except:
         log.exception("Problem getting phpInfoEx")
         raise
Beispiel #32
0
 def lint(self, request):
     # With the "squelching" the multi-language linter does to pull
     # <% and %>-like tokens out of the lint input stream, there's no
     # need to map all Ruby code to RHTML
     if rails_role_from_path(request.koDoc.displayPath):
         TPLInfo = list(self._tplPatterns) + [{"supportRERB": True}]
     else:
         TPLInfo = self._tplPatterns
     return UnwrapObject(self._html_linter).lint(request, TPLInfo=TPLInfo)
    def initialize(self, templateSvc, templatesView):
        # Need to unwrap these Python XPCOM object because we access
        # methods on them that are not in the IDL.
        self.templateSvc = UnwrapObject(templateSvc)
        self.templatesView = UnwrapObject(templatesView)

        if not self.templateSvc.loaded:
            self.templateSvc.loadTemplates()
        self.templateTree = self.templateSvc.getTemplateTree(
        )  # a working copy

        # Restore the user selections from prefs
        stbcStr = self._prefSvc.getStringPref(
            "%s_selected_template_by_category" % self.templateSvc.basename)
        try:
            self.selectedTemplateByCategory = eval(stbcStr)
        except SyntaxError, ex:
            self.selectedTemplateByCategory = {}
Beispiel #34
0
 def lint_with_text(self, request, text):
     linters = self._koLintService.getTerminalLintersForLanguage(
         self._languageName)
     finalLintResults = koLintResults()
     for linter in linters:
         try:
             newLintResults = UnwrapObject(linter).lint_with_text(
                 request, text)
         except:
             log.exception("lint_with_text exception")
         else:
             if newLintResults and newLintResults.getNumResults():
                 if finalLintResults.getNumResults():
                     finalLintResults = finalLintResults.addResults(
                         newLintResults)
                 else:
                     finalLintResults = newLintResults
     return finalLintResults
    def initialize(self):
        if self._inited:
            return
        self._inited = True
        koDirSvc = components.classes["@activestate.com/koDirs;1"].getService()
        self.toolbox_db = UnwrapObject(components.classes["@activestate.com/KoToolboxDatabaseService;1"].\
                       getService(components.interfaces.koIToolboxDatabaseService))
        self._toolsMgrSvc = UnwrapObject(components.classes["@activestate.com/koToolbox2ToolManager;1"].\
                      getService(components.interfaces.koIToolbox2ToolManager));
        self._toolsMgrSvc.initialize(self.toolbox_db)

        self.db_path = os.path.join(koDirSvc.userDataDir, 'toolbox.sqlite')
        schemaFile = os.path.join(koDirSvc.supportDir, 'toolbox', 'koToolbox.sql')
        try:
            self.db = self.toolbox_db.initialize(self.db_path, schemaFile)
            self.loadMainToolboxes()
        except:
            log.exception("Error initializing toolboxes")
 def removeObserver(self, anObserver, aTopic):
     try:
         anObserver = UnwrapObject(anObserver)
     except ValueError:
         pass
     self.cv.acquire()
     try:
         self._removeObserver(anObserver, aTopic)
     finally:
         self.cv.release()
    def initialize(self):
        if self._inited:
            return
        self._inited = True
        koDirSvc = components.classes["@activestate.com/koDirs;1"].getService()
        self.toolbox_db = UnwrapObject(components.classes["@activestate.com/KoToolboxDatabaseService;1"].\
                       getService(components.interfaces.koIToolboxDatabaseService))
        self._toolsMgrSvc = UnwrapObject(components.classes["@activestate.com/koToolbox2ToolManager;1"].\
                      getService(components.interfaces.koIToolbox2ToolManager))
        self._toolsMgrSvc.initialize(self.toolbox_db)

        self.db_path = os.path.join(koDirSvc.userDataDir, 'toolbox.sqlite')
        schemaFile = os.path.join(koDirSvc.supportDir, 'toolbox',
                                  'koToolbox.sql')
        try:
            self.db = self.toolbox_db.initialize(self.db_path, schemaFile)
            self.loadMainToolboxes()
        except:
            log.exception("Error initializing toolboxes")
Beispiel #38
0
 def runCommandInTerminal(self, async_callback, terminalHandler, args, env):
     # Run asynchronously
     self.terminalHandler = UnwrapObject(terminalHandler)
     import koprocessutils
     currentEnv = koprocessutils.getUserEnv()
     newEnvParts = env.split(";")
     for part in newEnvParts:
         parts = part.split("=")
         if len(parts) == 2:
             currentEnv[parts[0]] = parts[1]
         else:
             currentEnv[parts[0]] = ""
     self.env = currentEnv
     async_svc = components.classes["@activestate.com/koAsyncService;1"].\
                     getService(components.interfaces.koIAsyncService)
     async_op = koAsyncOperationBase(self._doRunCommandInTerminal, args)
     async_svc.run("Stackato %s" % (args[0]), async_op, async_callback, [],
                   False)
     return async_op
Beispiel #39
0
 def lint_with_text(self, request, text):
     linters = self._koLintService.getTerminalLintersForLanguage(self._languageName)
     finalLintResults = None  # Becomes the first results that has entries.
     for linter in linters:
         try:
             newLintResults = UnwrapObject(linter).lint_with_text(request, text)
         except:
             log.exception("lint_with_text exception")
         else:
             if finalLintResults is None:
                 finalLintResults = newLintResults
             elif newLintResults:
                 # Keep the lint results that has the most entries, then copy
                 # the other result with lesser entries into it.
                 if newLintResults.getNumResults() > finalLintResults.getNumResults():
                     # Swap them around, so final has the most entries.
                     finalLintResults, newLintResults = newLintResults, finalLintResults
                 finalLintResults.addResults(newLintResults)
     return finalLintResults
 def run(self, name, aOp, aOpCallback, affected_uris, lock_these_uris):
     # Test if we can unwrap the operation. This ensure's that aOp is a
     # Python object! If it is not, then an exception will be raised.
     aOp = UnwrapObject(aOp)
     log.debug("Running asynchronous command: %r", name)
     t = threading.Thread(name=name,
                          target=self.__run,
                          args=(name, aOp, aOpCallback, affected_uris,
                                lock_these_uris))
     t.setDaemon(True)
     t.start()
Beispiel #41
0
def KoUserEnviron(startupEnvFileName=None):
    koEnviron = components.classes[ "@activestate.com/koUserEnviron;1"] \
                .createInstance(components.interfaces.koIUserEnviron)
    if startupEnvFileName:
        environ = UnwrapObject(koEnviron)
        environ.__init__(startupEnvFileName)
        current_encoding = locale.getlocale()[1]
        # For some reason this can be the value 'None' when running in
        # the pyxpcom test suite, so fall back to the expected default
        # platform encoding.
        if not current_encoding:
            if sys.platform.startswith('win'):
                current_encoding = 'mbcs'
            elif sys.platform.startswith('darwin'):
                current_encoding = 'mac-roman'
            elif sys.platform.startswith('linux'):
                current_encoding = 'utf-8'
        environ.startupEnvironEncoding = current_encoding

    return koEnviron
Beispiel #42
0
    def removeProject(self, kpfWrapped):
        self._partSvc.removeProject(kpfWrapped)
        kpf = UnwrapObject(kpfWrapped)
        self.savePrefs(kpf)
        needNewCurrentProject = kpfWrapped == self.get_currentProject()
        # remove rows for project
        index = self._getIndexByPart(kpf)
        if index == -1:
            log.debug("removeProject: can't find project %s", kpf.get_name())
            return
        sibling = self.getNextSiblingIndex(index)
        if needNewCurrentProject:
            if index == 0:
                # first project becomes active, if there is one
                if sibling < len(self._rows):
                    newCurrentIndex = 0
                else:
                    newCurrentIndex = -1
            else:
                # previous project becomes active
                newCurrentIndex = self._getPrevSiblingIndex(index)  #@@@@
        self._rows = self._rows[:index] + self._rows[sibling:]
        if not self._tree:
            # bug 101553: Could happen at shutdown: there is no more project tree
            log.warn(
                "koKPFTreeView.p.py: removeProject: there is no self._tree")
            return
        self._tree.rowCountChanged(index, (index - sibling))

        if needNewCurrentProject:
            self._tree.beginUpdateBatch()
            try:
                self._tree.invalidateRow(index)
                if newCurrentIndex != -1:
                    self.set_currentProject(self._rows[newCurrentIndex].part)
                    self._tree.invalidateRow(newCurrentIndex)
                else:
                    # closing the only project we have, no current project
                    self.set_currentProject(None)
            finally:
                self._tree.endUpdateBatch()
Beispiel #43
0
 def addResults(self, other):
     # Returns a new object
     newLintResults = koLintResults()
     try:
         other_results = other._results
     except AttributeError:
         other_results = UnwrapObject(other)._results
     newLintResults._results = self._results
     newLintResults._resultMap = self._resultMap
     for result in other_results:
         newLintResults.addResult(result)
     return newLintResults
Beispiel #44
0
 def equals(self, other):
     """ Equality comparision for XPCOM """
     if _xpcom_:
         try:
             other = UnwrapObject(other)
         except:
             pass
     for attr in ("lang", "path", "blobname", "lpath", "name", "line", "ilk",
                  "citdl", "doc", "signature", "attributes", "returns"):
         if getattr(self, attr) != getattr(other, attr):
             return False
     return True
Beispiel #45
0
 def packageProject(self, packagePath, project, overwrite):
     try:
         if project.isDirty:
             err = 'Save project before packaging'
             self.lastErrorSvc.setLastError(1, err)
             raise ServerException(nsError.NS_ERROR_ILLEGAL_VALUE, err)
         project = UnwrapObject(project)
         self._packageParts(packagePath, orig_project=project,
                            live=project.live, extradir=0,
                            overwrite=overwrite)
     except Exception, e:
         log.exception(e)
 def addFileStatusChecker(self, checkerInstance):
     self._tlock.acquire()
     try:
         log.info("addFileStatusChecker:: added %r", checkerInstance.name)
         # Try to get the native Python checker instance instead of XPCOM
         # one - saves CPU cycles by not having to go through XPCOM.
         try:
             checkerInstance = UnwrapObject(checkerInstance)
         except:
             pass  # Keep the XPCOM version then.
         checkerInstance.initialize()
         for i in range(len(self._statusCheckers)):
             checker = self._statusCheckers[i]
             if checkerInstance.ranking_weight < checker.ranking_weight:
                 self._statusCheckers.insert(i, checkerInstance)
                 break
         else:
             self._statusCheckers.append(checkerInstance)
         #print "Order now: %r" % ([x.name for x in self._statusCheckers])
     finally:
         self._tlock.release()
Beispiel #47
0
    def _buildCellProperties(self, row, column):
        prop = []
        prop.append("primaryColumn")
        part = self._rows[row].part
        prop.append(part.type)

        if not hasattr(part, 'file'):
            # We hold a reference to the koFile instance, this causes the file
            # status service to check/maintain the file's status information.
            part.file = part.getFile()
        if part.file and not part.file.isLocal:
            prop.append("remote")
        if part.file:
            f = UnwrapObject(part.file)
            # missing, sccOk, sccSync, sccConflict, add, delete, edit,
            # isReadOnly, branch, integrate
            if hasattr(f, 'exists') and not f.exists:
                prop.append("missing")
            else:
                if hasattr(f, 'get_scc'):
                    scc = f.get_scc()
                    if scc['sccAction']:
                        prop.append(scc['sccAction'])
                    if scc['sccOk']:
                        if isinstance(scc['sccOk'], basestring):
                            if int(scc['sccOk']):
                                prop.append("sccOk")
                        else:
                            prop.append("sccOk")
                    if scc['sccSync']:
                        if isinstance(scc['sccSync'], basestring):
                            if int(scc['sccSync']):
                                prop.append("sccSync")
                        else:
                            prop.append("sccSync")
                    if scc['sccConflict']:
                        prop.append("sccConflict")
                if hasattr(f, 'isReadOnly') and f.isReadOnly:
                    prop.append("isReadOnly")
        return prop
Beispiel #48
0
    def DOMDeserialize(self,
                       rootElement,
                       parentPref,
                       prefFactory,
                       basedir=None,
                       chainNotifications=0):
        """We know how to deserialize ordered-preference elements."""

        # Create a new ordered preference.
        xpOrderedPref = components.classes["@activestate.com/koOrderedPreference;1"] \
                  .createInstance(components.interfaces.koIOrderedPreference)
        newOrderedPref = UnwrapObject(xpOrderedPref)
        try:
            newOrderedPref.id = rootElement.getAttribute("id") or ""
        except KeyError:
            newOrderedPref.id = ""

        # Iterate over the elements of the preference set,
        # deserializing them and fleshing out the new preference
        # set with content.
        childNodes = rootElement.childNodes

        for childNode in childNodes:
            if childNode and childNode.nodeType == minidom.Node.ELEMENT_NODE:
                pref = _dispatch_deserializer(self, childNode, newOrderedPref,
                                              prefFactory, basedir)
                if pref:
                    newOrderedPref.appendPref(pref)

        return xpOrderedPref
Beispiel #49
0
    def registerLanguage(self, language):
        import warnings
        warnings.warn("registerLanguage is deprecated - no longer needed",
                      category=DeprecationWarning)

        name = language.name
        assert not self.__languageFromLanguageName.has_key(name), \
               "Language '%s' already registered" % (name)
        log.info("registering language [%s]", name)
        
        self.__languageFromLanguageName[name] = language
        language = UnwrapObject(language)
        self.__accessKeyFromLanguageName[name] = language.accessKey

        # Update fields based on user preferences:
        primaryLanguagePref = "languages/%s/primary" % (language.name,)
        if self._globalPrefs.hasPref(primaryLanguagePref):
            language.primary = self._globalPrefs.getBoolean(primaryLanguagePref)

        # So that we can tell that, for example:
        #     -*- mode: javascript -*-
        # means language name "JavaScript".
        if language.modeNames:
            for modeName in language.modeNames:
                self._modeName2LanguageName[modeName.lower()] = name
        else:
            self._modeName2LanguageName[name.lower()] = name
        if language.primary:
            self._primaryLanguageNames[name] = True
        if language.internal:
            self._internalLanguageNames[name] = True
        for pat in language.shebangPatterns:
            self.shebangPatterns.append((name, pat))
        for ns in language.namespaces:
            self._namespaceMap[ns] = name
        for id in language.publicIdList:
            self._publicIdMap[id] = name
        for id in language.systemIdList:
            self._systemIdMap[id] = name
Beispiel #50
0
 def __init__(self, buf, priority, force=False, mtime=None, on_complete=None):
     if _xpcom_:
         buf = UnwrapObject(buf)
     self.buf = buf
     self.id = buf.path
     self.priority = priority
     self.force = force
     if mtime is None:
         self.mtime = time.time()
     else:
         self.mtime = mtime
     self.on_complete = on_complete
     self.complete_event = threading.Event() #XXX use a pool
Beispiel #51
0
    def test_differentOnDisk(self):
        path = tempfile.mktemp()
        try:
            # Init the test file with some content.
            _writefile(path, "blah\nblah\nblah\n")

            koDoc = self._koDocFromPath(path, load=False)
            # Make it look like a remote file.
            rawFile = UnwrapObject(koDoc.file)
            rawFile.isLocal = 0
            rawFile.isRemoteFile = 1
            koDoc.load()

            # Wait one second, so we generate a different mtime.
            import time
            time.sleep(1.1)
            _writefile(path, "blah\nblah\nblah\nblah\n")

            self.assertTrue(koDoc.differentOnDisk(),
                            "Remote file change was not detected")
            # Next time we call it - it should still detect the file as being changed - bug 95690.
            self.assertTrue(
                koDoc.differentOnDisk(),
                "Remote file change was not detected a second time")
            # Because we are using a fake koIFileEx (or really a local file),
            # this test can fail if the timestamp between the save and the
            # differentOnDisk calls has changed. To work around that, we run
            # multiple checks and only accept one failure.
            success_count = 0
            for tries in range(3):
                koDoc.save(True)
                if not koDoc.differentOnDisk():
                    success_count += 1
            self.assertTrue(
                success_count >= 2,
                "Remote file change detected after saving the file")
        finally:
            if os.path.exists(path):
                os.unlink(path)  # clean up
    def observe(self, subject, topic, data):
        #print "file status service observed %r %s %s" % (subject, topic, data)
        try:
            log.debug("status observer received %s:%s", topic, data)
            if topic == 'komodo-startup-service':
                self.init()
                return
            if topic == 'xpcom-shutdown':
                log.debug("file status got xpcom-shutdown, unloading")
                self.unload()
                return
            if topic in ('idle', 'idle-daily'):
                log.info("Idle - take a break kid")
                self._is_idle = True
                return
            if topic in ('active', 'back'):
                log.info("Get back to work")
                self._is_idle = False
                self._cv.acquire()
                self._cv.notify()
                self._cv.release()
                return

            # These are other possible topics, they just force the
            # file status service to update itself immediately
            #elif topic == "file_changed":
            #elif topic == "file_update_now":

            self._cv.acquire()
            try:
                if topic in ("file_changed", "file_status_now"):
                    # This notification can come with just about anything for
                    # the subject element, so we need to find the matching
                    # koIFile for the given uri, supplied by the "data" arg.
                    koIFile = self._fileSvc.getFileFromURI(data)
                    self._items_to_check.add((UnwrapObject(koIFile), data,
                                              self.REASON_FILE_CHANGED))
                    log.debug("Forced recheck of uri: %r", data)
                    self._cv.notify()
                elif topic in ("file_update_now"):
                    import warnings
                    warnings.warn(
                        "'file_update_now' is deprecated, use "
                        "koIFileStatusService.updateStatusForAllFiles "
                        "instead.", DeprecationWarning)
                    self._cv.notify()
            finally:
                self._cv.release()
        except Exception, e:
            log.exception("Unexpected error in observe")
Beispiel #53
0
def _runCommand(cmd, *args, **kwargs):
    argv = [stackatoPath, cmd]
    if args:
        argv += args
    if not kwargs.get('noJSON', False):
        argv.append("--json")
    #qlog.debug("_runCommand: <<%s>>", argv)
    p = process.ProcessOpen(argv, cwd=None, env=None, stdin=None)
    stdout, stderr = p.communicate()
    #qlog.debug("cmd: %s, stdout: %s, stderr: %s", argv, stdout, stderr)
    koResult = components.classes["@activestate.com/KoStackatoResultBlock;1"].\
        createInstance(components.interfaces.koIStackatoResultBlock)
    UnwrapObject(koResult).initialize(stdout, stderr)
    return koResult
Beispiel #54
0
    def is_same(self, trg):
        """Return True iff the given trigger is (effectively) the same
        as this one.

        Dev Note: "Effective" is currently left a little fuzzy. Just
        comparing enough to fix Komodo Bug 55378.
        """
        if _xpcom_:
            trg = UnwrapObject(trg)
        if (self.pos == trg.pos and self.type == trg.type
                and self.form == trg.form and self.lang == trg.lang):
            return True
        else:
            return False
Beispiel #55
0
    def registerLanguage(self, language):
        name = language.name
        assert not self.__languageFromLanguageName.has_key(name), \
               "Language '%s' already registered" % (name)
        log.info("registering language [%s]", name)

        self.__languageFromLanguageName[name] = language
        language = UnwrapObject(language)
        self.__accessKeyFromLanguageName[name] = language.accessKey

        # Update fields based on user preferences:
        languageKey = "languages/" + language.name
        if self._languageSpecificPrefs.hasPref(languageKey):
            languagePrefs = self._languageSpecificPrefs.getPref(languageKey)
            if languagePrefs.hasPref("primary"):
                language.primary = languagePrefs.getBooleanPref("primary")

        # So that we can tell that, for example:
        #     -*- mode: javascript -*-
        # means language name "JavaScript".
        if language.modeNames:
            for modeName in language.modeNames:
                self._modeName2LanguageName[modeName.lower()] = name
        else:
            self._modeName2LanguageName[name.lower()] = name
        if language.primary:
            self._primaryLanguageNames[name] = True
        if language.internal:
            self._internalLanguageNames[name] = True
        for pat in language.shebangPatterns:
            self.shebangPatterns.append((name, pat))
        for ns in language.namespaces:
            self._namespaceMap[ns] = name
        for id in language.publicIdList:
            self._publicIdMap[id] = name
        for id in language.systemIdList:
            self._systemIdMap[id] = name
Beispiel #56
0
 def _loadAllLanguages(self):
     self._allRows = []
     langRegistry = components.classes[
         "@activestate.com/koLanguageRegistryService;1"].getService(
             components.interfaces.koILanguageRegistryService)
     langNames = langRegistry.getLanguageNames()
     for langName in langNames:
         lang = UnwrapObject(langRegistry.getLanguage(langName))
         if not lang.internal:
             self._allRows.append({
                 'name': langName,
                 'name_lc': langName.lower(),
                 'status': lang.primary,
                 'origStatus': lang.primary
             })
Beispiel #57
0
 def _addProjectPrologue(self, kpf):
     self._partSvc.addProject(kpf)
     unwrapped_kpf = UnwrapObject(kpf)
     self.restorePrefs(unwrapped_kpf)
     self._partSvc.currentProject = unwrapped_kpf
     url = kpf.url
     # If the project is being added while restoring the view state,
     # it's possible that this project is already in the tree as
     # an unopened project in single-project view mode.
     # Ref bug 92356
     for i, row in enumerate(self._rows):
         if row.uri == url:
             del self._rows[i]
             self._tree.rowCountChanged(i, 1)
             break
     return unwrapped_kpf
 def findDocumentByDisplayPath(self, displayPath):
     self._cDoc.acquire()
     try:
         if displayPath in self._documents:
             wrappedDoc = self._documents[displayPath]()
             if not wrappedDoc:
                 del self._documents[displayPath]
                 return None
             doc = UnwrapObject(wrappedDoc)
             if doc._refcount == 0:
                 del self._documents[displayPath]
                 return None
             return wrappedDoc
     finally:
         self._cDoc.release()
     return None
Beispiel #59
0
 def _getLinterByCID(self, linterCID):
     if linterCID not in self._linterCache:
         try:
             if linterCID.startswith(self.GENERIC_LINTER_AGGREGATOR_CID):
                 languageName = linterCID[len(self.GENERIC_LINTER_AGGREGATOR_CID) + 1:]
                 linter = components.classes[self.GENERIC_LINTER_AGGREGATOR_CID].createInstance(components.interfaces.koILinter)
                 UnwrapObject(linter).initialize(languageName, self)
             elif linterCID not in components.classes.keys():
                 linter = None
             else:
                 linter = components.classes[linterCID].createInstance(components.interfaces.koILinter)
         except COMException, ex:
             errmsg = "Internal Error creating a linter with CID '%s': %s"\
                 % (linterCID, ex)
             raise ServerException(nsError.NS_ERROR_UNEXPECTED, errmsg)
         self._linterCache[linterCID] = linter