Beispiel #1
0
    def async_eval_at_trg(self, buf, trg, ctlr):
        if _xpcom_:
            trg = UnwrapObject(trg)
            ctlr = UnwrapObject(ctlr)
        pos = trg.pos
        ctlr.start(buf, trg)

        if trg.id == (self.lang, TRG_FORM_CPLN, "placeholders"):
            ctlr.set_cplns(self._get_all_placeholders_in_buffer(buf, pos))
            ctlr.done("success")
            return

        if trg.id == (self.lang, TRG_FORM_CPLN, "tags"):
            ctlr.set_cplns(self._get_all_tags_in_buffer(buf, pos))
            ctlr.done("success")
            return

        if trg.id == (self.lang, TRG_FORM_CPLN, "keywords"):
            kw_prefix = trg.extra.get("kw_prefix")
            cplns = [x for x in keywords if x.startswith(kw_prefix)]
            cplns = [("keyword", x)
                     for x in sorted(cplns, cmp=CompareNPunctLast)]
            ctlr.set_cplns(cplns)
            ctlr.done("success")
            return

        ctlr.error("Unknown trigger type: %r" % (trg, ))
        ctlr.done("error")
Beispiel #2
0
    def async_eval_at_trg(self, buf, trg, ctlr):
        if not self.gocode_present:
            return
        if _xpcom_:
            trg = UnwrapObject(trg)
            ctlr = UnwrapObject(ctlr)

        pos = trg.pos
        if trg.type == "call-signature":
            pos = pos - 1

        env = koprocessutils.getUserEnv()
        cmd = ['gocode', '-f=json', 'autocomplete', buf.path, '%s' % pos]
        p = process.ProcessOpen(cmd, env=env)

        output, error = p.communicate(buf.accessor.text)

        try:
            completion_data = json.loads(output)
            completion_data = completion_data[1]
        except IndexError:
            # exit on empty gocode output
            return
        except ValueError, e:
            log.exception('Exception while parsing json')
            return
Beispiel #3
0
    def async_eval_at_trg(self, buf, trg, ctlr):
        if _xpcom_:
            trg = UnwrapObject(trg)
            ctlr = UnwrapObject(ctlr)
        ctlr.start(buf, trg)

        if trg.id == (self.lang, TRG_FORM_CPLN, "complete-tags"):
            ctlr.set_cplns(self.jj_tag_completion)
            ctlr.done("success")
            return
        if trg.id == (self.lang, TRG_FORM_CPLN, "complete-filters"):
            ctlr.set_cplns(self.jj_filter_completion)
            ctlr.done("success")
            return

        if trg.id == (self.lang, TRG_FORM_CPLN, "identifiers"):
            word_start = trg.extra.get("word_start")
            word_end = trg.extra.get("word_end")
            if word_start is not None and word_end is not None:
                # Only return keywords that start with the given 2-char prefix.
                prefix = buf.accessor.text_range(word_start, word_end)[:2]
                words = tuple(x for x in jj_nontag_keywords if x.startswith(prefix))
                source = tuple(('keyword', x) for x in words)
                ctlr.set_cplns(source)
                ctlr.done("success")
                return

        ctlr.done("success")
Beispiel #4
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 #5
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
Beispiel #6
0
    def async_eval_at_trg(self, buf, trg, ctlr):
        if _xpcom_:
            trg = UnwrapObject(trg)
            ctlr = UnwrapObject(ctlr)

        # if a definition lookup, use godef
        if trg.type == "defn":
            return self.lookup_defn(buf, trg, ctlr)

        # otherwise use gocode
        return self.invoke_gocode(buf, trg, ctlr)
Beispiel #7
0
    def _async_eval_at_trg(self, buf, trg, ctlr, styleClassifier):
        if _xpcom_:
            trg = UnwrapObject(trg)
            ctlr = UnwrapObject(ctlr)
        # Handle ambiguous property-names here
        DEBUG = DebugStatus
        # DEBUG = True
        if DEBUG:
            print "Less: _async_eval_at_trg: trg: %s(%r)" % (trg, trg)
        if trg.id != (self.lang, TRG_FORM_CPLN, "tag-or-property-names"):
            CSSLangIntel._async_eval_at_trg(
                self, buf, trg, ctlr, styleClassifier)
            return
        if DEBUG:
            print "\n----- async_eval_at_trg(trg=%r) -----"\
                  % (trg)

        # Setup the AccessorCache
        extra = trg.extra
        ac = None
        # print "Extra: %r" % (extra)
        if isinstance(extra, dict):
            extra = extra.get("extra", None)
            if isinstance(extra, dict):
                ac = extra.get("ac", None)
                if ac and DEBUG:
                    print "  _async_eval_at_trg:: Trigger had existing AC"
                    ac.dump()
        if ac is None:
            if DEBUG:
                print "  _async_eval_at_trg:: Created new trigger!"
            ac = AccessorCache(buf.accessor, trg.pos, fetchsize=20)

        ctlr.start(buf, trg)
        pos = trg.pos
        try:
            cplns1 = [("property", v + ": ") for v in self.CSS_PROPERTY_NAMES]
            cplns2 = [("element", v) for v in self.CSS_HTML_TAG_NAMES]
            cplns = sorted(cplns1 + cplns2, key=_OrdPunctLastOnSecondItem)
            # Note: we add the colon as well - see bug 89913.
            ctlr.set_cplns(cplns)
            # print "  _async_eval_at_trg:: cplns:", cplns
            ctlr.done("success")
            trg.retriggerOnCompletion = True
        except IndexError:
            # Tried to go out of range of buffer, nothing appropriate found
            if DEBUG:
                print "  _async_eval_at_trg:: ** Out of range error **"
            ctlr.done("success")
Beispiel #8
0
    def updateStatusForFiles(self, koIFiles, forceRefresh, callback):
        self._cv.acquire()
        try:
            reason = self.REASON_FILE_CHANGED
            if forceRefresh:
                reason = self.REASON_FORCED_CHECK
            items = [(UnwrapObject(koIFile), koIFile.URI, reason)
                     for koIFile in koIFiles]
            for item in items:
                self._items_to_check.add(item)
                log.debug("updateStatusForFiles:: uri: %r", item[1])
            if callback:
                self._processing_done_event.clear()
            self._cv.notify()
        finally:
            self._cv.release()

        if callback:

            def wait_till_done(fileStatusSvc, check_items, callback):
                self._processing_done_event.wait(60)
                # Proxy the notification back to the UI thread.
                uiCallbackProxy = getProxyForObject(
                    1, components.interfaces.koIFileStatusCallback, callback,
                    PROXY_ALWAYS | PROXY_ASYNC)
                uiCallbackProxy.notifyDone()

            t = threading.Thread(target=wait_till_done,
                                 args=(self, items, callback))
            t.setDaemon(True)
            t.start()
Beispiel #9
0
 def __init__(self):
     self.completer = \
         UnwrapObject(Cc[KoCodeIntelXPCOMSupport._reg_contractid_]
                        .getService())
     self.data = [
         (dirname(__file__), "xpcomJSElements"),
     ]
Beispiel #10
0
 def save(self, prefs):
     if not self._wasChanged:
         return
     langRegistry = UnwrapObject(
         Cc["@activestate.com/koLanguageRegistryService;1"].getService(
             Ci.koILanguageRegistryService))
     languageSpecificPrefs = prefs.getPref("languages")
     if not prefs.hasPrefHere("languages"):
         languageSpecificPrefs = languageSpecificPrefs.clone()
         prefs.setPref("languages", languageSpecificPrefs)
     for row in self._rows:
         langName, status, origStatus = row['name'], row['status'], row[
             'origStatus']
         if status != origStatus:
             langRegistry.changeLanguageStatus(langName, status)
             # Update the pref
             languageKey = "languages/" + langName
             if languageSpecificPrefs.hasPref(languageKey):
                 languageSpecificPrefs.getPref(languageKey).setBooleanPref(
                     "primary", bool(status))
             else:
                 prefSet = components.classes["@activestate.com/koPreferenceSet;1"].\
                     createInstance(components.interfaces.koIPreferenceSet)
                 prefSet.setBooleanPref("primary", bool(status))
                 languageSpecificPrefs.setPref(languageKey, prefSet)
     self.notifyObservers(None, 'primary_languages_changed', '')
Beispiel #11
0
        def serializePrefSet(prefset):
            path = tempfile.mktemp(suffix=".xml")
            prefset.serializeToFile(path)
            try:
                result = (Cc["@activestate.com/koPreferenceSetObjectFactory;1"]
                          .getService().deserializeFile(path))
            finally:
                os.remove(path)
                try:
                    os.remove(path + "c")
                except OSError as ex:
                    import errno
                    if ex.errno != errno.ENONET:
                        raise
            try:
                result.QueryInterface(Ci.koIPreferenceRoot)
            except COMException as ex:
                if ex.errno == Cr.NS_ERROR_NO_INTERFACE:
                    self.fail("Unserialized from file but not a root")
                raise

            def check_for_shadow_prefs(pref):
                for name, (child, typ) in pref.prefs.items():
                    if typ != "object":
                        continue
                    child = UnwrapObject(child)
                    self.assertFalse(getattr(child, "_is_shadow", False),
                                     "Child %s is a shadow pref" % (name, ))
                    check_for_shadow_prefs(child)

            check_for_shadow_prefs(UnwrapObject(result))
            return result
Beispiel #12
0
 def setShortcut(self, hit, shortcut):
     # Delete existing shortcuts with that name
     try:
         hit = UnwrapObject(hit)
     except:
         pass # not a wrapped Python object
     self._go_gatherer.setShortcut(hit, shortcut)
Beispiel #13
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)
Beispiel #14
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 #15
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")
Beispiel #16
0
 def _unwrap(self, aObject):
     try:
         # try to unwrap the object if possible so we get the
         # benefit of __repr__
         return UnwrapObject(aObject)
     except:
         return aObject
    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 #18
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 #19
0
 def set_currentProject(self, prj):
     self._partSvc.currentProject = prj
     project = UnwrapObject(prj)
     if project is None:
         return
     index = self._getIndexByPart(project)
     if index == -1:
         raise Exception(
             "Add the project to the view before making it the current project"
         )
     # if the project is not already visible, make it so
     firstVisRow = self._tree.getFirstVisibleRow()
     lastVisRow = self._tree.getLastVisibleRow()
     numVisRows = self._tree.getPageLength()
     #print "set_currentProject"
     #print "numVisRows: %d" % (numVisRows)
     #print "firstVisRow: %d" % (firstVisRow)
     #print "lastVisRow: %d" % (lastVisRow)
     # If completely outside the range
     # Or if there is un-utilized (empty) rows shown in the tree
     # Or the index is in the visible range, but the tree contents
     # scroll past the end of the visible range
     nextSibling = self.getNextSiblingIndex(index)
     if (index < firstVisRow or index >= lastVisRow
             or (len(self._rows) > numVisRows and
                 ((nextSibling - index) > numVisRows or len(self._rows) <
                  (firstVisRow + numVisRows)))):
         scrollToIndex = min(index, len(self._rows) - numVisRows)
         #print "Scrolling to row: %d" % (scrollToIndex)
         self._tree.scrollToRow(scrollToIndex)
         self._tree.invalidateRow(index)
    def updateStatusForFiles(self, koIFiles, forceRefresh, callback):
        self._cv.acquire()
        try:
            reason = self.REASON_FILE_CHANGED
            if forceRefresh:
                reason = self.REASON_FORCED_CHECK
            items = [(UnwrapObject(koIFile), koIFile.URI, reason)
                     for koIFile in koIFiles]
            for item in items:
                self._items_to_check.add(item)
                log.debug("updateStatusForFiles:: uri: %r", item[1])
            if callback:
                self._processing_done_event.clear()
            self._cv.notify()
        finally:
            self._cv.release()

        if callback:

            def wait_till_done(fileStatusSvc, check_items, callback):
                self._processing_done_event.wait(60)

                @components.ProxyToMainThreadAsync
                def fireCallback():
                    callback.notifyDone()

                fireCallback()

            t = threading.Thread(target=wait_till_done,
                                 args=(self, items, callback))
            t.setDaemon(True)
            t.start()
Beispiel #21
0
    def test_autoSaveFile(self):
        path = tempfile.mktemp()
        buffer = "blah\nblah\nblah"
        try:
            # Init the test file with some content.
            _writefile(path, buffer)

            koDoc = self._koDocFromPath(path)
            assert not koDoc.haveAutoSave()

            # test the autosave path
            doc_asfn = os.path.basename(
                UnwrapObject(koDoc)._getAutoSaveFileName())
            my_asfn = "%s-%s" % (md5(
                koDoc.file.URI).hexdigest(), koDoc.file.baseName)
            assert doc_asfn == my_asfn

            # document is not dirty yet
            koDoc.doAutoSave()
            assert not koDoc.haveAutoSave()

            # make the document dirty then save
            koDoc.isDirty = 1
            koDoc.doAutoSave()
            assert koDoc.haveAutoSave()

            koDoc.buffer = "tada"
            koDoc.restoreAutoSave()
            assert koDoc.buffer == buffer
            koDoc.removeAutoSaveFile()
            assert not koDoc.haveAutoSave()
        finally:
            if os.path.exists(path):
                os.unlink(path)  # clean up
Beispiel #22
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")
            # 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
Beispiel #23
0
 def gatherersAndCwds(self):
     if self._gatherers_cache is None:
         g = fastopen.Gatherers()
         cwds = []
         if self.views:
             kovg = KomodoOpenViewsGatherer(self.views)
             if self.pref_enable_open_views_gatherer:
                 g.append(kovg)
             cwds = list(kovg.cwds)
         if self.currentPlace and self.currentPlace.startswith("file://"):
             from uriparse import URIToLocalPath
             cwds.append(URIToLocalPath(self.currentPlace))
         if self.pref_enable_project_gatherer and self.project:
             g.append(
                 fastopen.CachingKomodoProjectGatherer(
                     UnwrapObject(self.project),
                     self.pref_enable_project_dir_gatherer,
                     self.pref_follow_symlinks))
         if self.pref_enable_cwd_gatherer and cwds:
             g.append(
                 fastopen.DirGatherer("cwd", cwds, True,
                                      self.pref_path_excludes))
         if self.pref_enable_go_tool:
             gog = fastopen.GoGatherer()
             g.append(gog)
             dirShortcuts = gog.getShortcuts()
         else:
             dirShortcuts = None
         if self.pref_enable_history_gatherer:
             g.append(
                 KomodoHistoryURIsGatherer(self.historySessionName,
                                           self.pref_history_num_entries))
         self._gatherers_cache = (g, cwds, dirShortcuts)
     return self._gatherers_cache
 def getAutoSaveDocuments(self):
     # this does about the same as getAllDocuments, but doesn't
     # remove documents from the list.  This is important as a
     # document does not have a refcount until after it is loaded,
     # but the autoSave thread may get to the document before it
     # is loaded.  So this now only returns dirty documents and does
     # not care about the refcount
     self._cDoc.acquire()
     try:
         docs = []
         # clear out all of the objects w/ no references to them
         for displayPath, wrappedDocRef in self._documents.items():
             try:
                 wrappedDoc = wrappedDocRef()
             except COMException:
                 wrappedDoc = None  # dead object
             if not wrappedDoc:
                 del self._documents[displayPath]
                 continue
             doc = UnwrapObject(wrappedDoc)
             if doc._isDirty:
                 docs.append(doc)
         return docs
     finally:
         self._cDoc.release()
Beispiel #25
0
 def __init__(self, buf, priority, force=False):
     if _xpcom_:
         buf = UnwrapObject(buf)
     self.buf = buf
     self.id = buf.path + "#xml-parse"
     self.priority = priority
     self.force = force
 def findDocumentByURI(self, uri):
     from URIlib import URIParser
     p = URIParser()
     uri = p.URI = uri  # cleanup uri
     self._cDoc.acquire()
     try:
         for displayPath, wrappedDocRef in self._documents.items():
             try:
                 wrappedDoc = wrappedDocRef()
             except COMException:
                 wrappedDoc = None  # dead object
             if not wrappedDoc:
                 del self._documents[displayPath]
             elif ((wrappedDoc.isUntitled
                    and fequal(wrappedDoc.baseName, uri))
                   or (not wrappedDoc.isUntitled
                       and fequal(wrappedDoc.file.URI, uri))):
                 doc = UnwrapObject(wrappedDoc)
                 if doc._refcount == 0:
                     log.debug("deleting reference to %s", displayPath)
                     del self._documents[displayPath]
                     return None
                 return wrappedDoc
     finally:
         self._cDoc.release()
     return None
 def __init__(self):
     koLintService = components.classes[
         "@activestate.com/koLintService;1"].getService(
             components.interfaces.koILintService)
     self._ruby_linter = UnwrapObject(
         koLintService.getLinterForLanguage("Ruby"))
     self._html_linter = koLintService.getLinterForLanguage("HTML")
Beispiel #28
0
 def init(self, ciSvc, prefSet, prefName):
     self.ciSvc = UnwrapObject(ciSvc)
     self.send = self.ciSvc.send
     self.prefSet = prefSet
     self.prefName = prefName
     self.load()
     self._wasChanged = False
Beispiel #29
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 #30
0
 def buf_from_koIDocument(self, doc, env=None):
     lang = doc.language
     path = doc.displayPath
     if doc.isUntitled:
         path = join("<Unsaved>", path)
     accessor = KoDocumentAccessor(
         doc, self.silvercity_lexer_from_lang.get(lang))
     encoding = doc.encoding.python_encoding_name
     try:
         buf_class = self.buf_class_from_lang[lang]
     except KeyError:
         # No langintel is defined for this class, check if the koILanguage
         # defined is a UDL koILanguage.
         from koUDLLanguageBase import KoUDLLanguage
         if isinstance(UnwrapObject(doc.languageObj), KoUDLLanguage):
             return UDLBuffer(self,
                              accessor,
                              env,
                              path,
                              encoding,
                              lang=lang)
         # Not a UDL language - use the implicit buffer then.
         return ImplicitBuffer(lang, self, accessor, env, path, encoding)
     else:
         buf = buf_class(self, accessor, env, path, encoding)
     return buf