Esempio n. 1
0
def go():

    print "Igniting Twisted reactor..."
    view.commit()
    Utility.initTwisted()
    Utility.initWakeup(view)
    print "...ready"
Esempio n. 2
0
    def _setLocale(self, primaryLocale, ignoreError=False):
        if wxIsAvailable():
            # Strip the country code for wxLocales
            # since any invalid values raise an
            # uncapturable error in the wx Widgets layer.
            # With the exception of Chinese, all
            # wx localizations use the lang
            # code exclusively.
            # XXX [grant] Also, pt_BR is common. This just seems
            # bogus.
            try:
                setWxLocale(stripCountryCode(primaryLocale), self)
            except I18nException:
                if not ignoreError:
                    raise

        setPyICULocale(primaryLocale)
        setEnvironmentLocale(primaryLocale)

        from application import Utility

        if Utility.getPlatformID() == "osx-ppc" and \
           Utility.getOSName() in ('10.3-Panther', '10.4-Tiger'):
            # On OS X PPC the LC_NUMERIC values will
            # localize unless the Python locale is
            # set to 'C'. Localized numeric values ie.
            # 1234,23 for a float in the 'FR' locale
            # create data exchange issues and needs to
            # be avoided at all costs.
            setPythonLocale('C')
        else:
            setPythonLocale(primaryLocale)
Esempio n. 3
0
def go():

    print "Igniting Twisted reactor..."
    view.commit()
    Utility.initTwisted()
    Utility.initWakeup(view)
    print "...ready"
Esempio n. 4
0
    def setUp(self):
        # This setup is needed because we'd like to be able to use
        # --locale on the command line to test a given locale. So,
        # basically the code below is copy-and-pasted out of Utility.py
        # to make sure that everything gets initialized in the right
        # order.
        needInit = self.view is None

        # We always store a list of all failures, so that we can report them
        # all rather than fail on the first.
        self.failures = []

        if needInit:
            Utility.initLogging(Globals.options)
            type(self).view = NullRepositoryView()

            parcelPath = Utility.initParcelEnv(Globals.options, Globals.chandlerDirectory)
            pluginEnv, pluginEggs = Utility.initPluginEnv(Globals.options, Globals.options.pluginPath)

            Utility.initI18n(Globals.options)

            Utility.initParcels(Globals.options, self.view, parcelPath)
            Utility.initPlugins(Globals.options, self.view, pluginEnv, pluginEggs)
        # We don't want to import these globally, because they will
        # trigger parcel loading, and that will cause i18n to be set
        # up before the above call to initI18n, which will mean --locale
        # won't work on the command line. So, instead, we stash these
        # in instance variables.
        self.Menu = schema.importString("osaf.framework.blocks.Menu")
        self.MenuItem = schema.importString("osaf.framework.blocks.MenuItem")
Esempio n. 5
0
    def setUp(self):
        # This setup is needed because we'd like to be able to use
        # --locale on the command line to test a given locale. So,
        # basically the code below is copy-and-pasted out of Utility.py
        # to make sure that everything gets initialized in the right
        # order.
        needInit = (self.view is None)

        # We always store a list of all failures, so that we can report them
        # all rather than fail on the first.
        self.failures = []

        if needInit:
            Utility.initLogging(Globals.options)
            type(self).view = NullRepositoryView()

            parcelPath = Utility.initParcelEnv(Globals.options,
                                               Globals.chandlerDirectory)
            pluginEnv, pluginEggs = Utility.initPluginEnv(
                Globals.options, Globals.options.pluginPath)

            Utility.initI18n(Globals.options)

            Utility.initParcels(Globals.options, self.view, parcelPath)
            Utility.initPlugins(Globals.options, self.view, pluginEnv,
                                pluginEggs)
        # We don't want to import these globally, because they will
        # trigger parcel loading, and that will cause i18n to be set
        # up before the above call to initI18n, which will mean --locale
        # won't work on the command line. So, instead, we stash these
        # in instance variables.
        self.Menu = schema.importString('osaf.framework.blocks.Menu')
        self.MenuItem = schema.importString('osaf.framework.blocks.MenuItem')
Esempio n. 6
0
    def _setLocale(self, primaryLocale, ignoreError=False):
        if wxIsAvailable():
            # Strip the country code for wxLocales
            # since any invalid values raise an
            # uncapturable error in the wx Widgets layer.
            # With the exception of Chinese, all
            # wx localizations use the lang
            # code exclusively.
            # XXX [grant] Also, pt_BR is common. This just seems
            # bogus.
            try:
                setWxLocale(stripCountryCode(primaryLocale), self)
            except I18nException:
                if not ignoreError:
                    raise

        setPyICULocale(primaryLocale)
        setEnvironmentLocale(primaryLocale)

        from application import Utility

        if Utility.getPlatformID() == "osx-ppc" and \
           Utility.getOSName() in ('10.3-Panther', '10.4-Tiger'):
            # On OS X PPC the LC_NUMERIC values will
            # localize unless the Python locale is
            # set to 'C'. Localized numeric values ie.
            # 1234,23 for a float in the 'FR' locale
            # create data exchange issues and needs to
            # be avoided at all costs.
            setPythonLocale('C')
        else:
            setPythonLocale(primaryLocale)
Esempio n. 7
0
    def setUp(self):

        self.profileDir = os.path.dirname(__file__)
        Utility.initCrypto(self.profileDir)
        super(TestSSL, self).setUp(testdir=self.profileDir)

        self.loadParcel("osaf.framework.certstore")
        self.loadParcel("osaf.framework.certstore.data")
Esempio n. 8
0
def go(port=None):

    print "Igniting Twisted reactor..."
    if view.isNew():
        view.commit()

    if port is not None:
        Globals.options.webserver = [str(port)]
    else:
        if Globals.options.webserver is None:
            Globals.options.webserver = []

    Utility.initTwisted(view, options=Globals.options)
    Utility.initWakeup(view)
    print "...ready"
Esempio n. 9
0
def go(port=None):

    print "Igniting Twisted reactor..."
    if view.isNew():
        view.commit()

    if port is not None:
        Globals.options.webserver = [str(port)]
    else:
        if Globals.options.webserver is None:
            Globals.options.webserver = []

    Utility.initTwisted(view, options=Globals.options)
    Utility.initWakeup(view)
    print "...ready"
Esempio n. 10
0
 def run(self):
     prefs = Utility.loadPrefs(Globals.options).get(PLUGIN_NAME)
     if prefs is not None:
         license = prefs.get('license')
         if license:
             setLicense(license)
     return False  # no need to run again
Esempio n. 11
0
 def run(self):
     prefs = Utility.loadPrefs(Globals.options).get(PLUGIN_NAME)
     if prefs is not None:
         license = prefs.get('license')
         if license:
             setLicense(license)
     return False # no need to run again
Esempio n. 12
0
    def deactivatePlugin(self, project_name, plugin_env):

        view = self.itsView
        prefs = Utility.loadPrefs(Globals.options)
        pluginPrefs = self.widget.GetSubMenu().pluginPrefs

        for egg in plugin_env[project_name]:
            break
        else:
            return None

        def deleteItems(item):
            for child in item.iterChildren():
                deleteItems(child)
            if isinstance(item, Kind):
                for instance in item.iterItems():
                    instance.delete(True)

        for ep in egg.get_entry_map('chandler.parcels').values():
            parcel = Parcel.find_parcel_from_entrypoint(view, ep)
            if parcel is not None:
                deleteItems(parcel)
                parcel.delete(True)
            pluginPrefs[ep.dist.key] = 'inactive'

        if 'plugins' not in prefs:
            prefs['plugins'] = pluginPrefs
        else:
            prefs['plugins'].update(pluginPrefs)
            self.widget.GetSubMenu().pluginPrefs = prefs['plugins']

        prefs.write()

        return egg
Esempio n. 13
0
def showLocalePickerDialog():
    win = LocalePickerDialog()

    win.CenterOnScreen()
    val = win.ShowModal()

    if val == wx.ID_OK:
        # Get the new locale and if it differs from
        # current locale restart Chandler
        currentLocale = getLocale()
        newLocale = win.GetValue()

        if newLocale != currentLocale:
            prefs = Utility.loadPrefs(Globals.options)

            if "options" not in prefs:
                prefs["options"] = {}

            prefs["options"]["locale"] = newLocale
            prefs.write()

            # The locale needs to be passed since
            # restart preserves the command line
            # options from the previous startup.
            # If the previous startup contained
            # a locale command line flag it
            # will override the value for the locale
            # just added to the prefs file and
            # Chandler will not switch the locale
            # as expected.
            wx.GetApp().restart(locale=newLocale)

    win.Destroy()
Esempio n. 14
0
def createHTTPFactory(host, port, username, password, useSSL, repositoryView):

    # See if the user has configured an HTTP proxy
    if repositoryView is not None and not useSSL:
        getProxy = schema.ns("osaf.sharing.accounts", repositoryView).getProxy

        proxy = getProxy(repositoryView, 'HTTP')
        if not proxy.appliesTo(host):
            proxy = None
    else:
        proxy = None

    if proxy is not None and proxy.active:
        proxyPassword = getattr(proxy, 'password', None)
        factory = ChandlerHTTPProxyClientFactory(
            host=proxy.host,
            port=proxy.port,
            username=proxy.username,
            password=waitForDeferred(proxyPassword.decryptPassword()))
    else:
        factory = ChandlerHTTPClientFactory()

    factory.protocol = zanshin.webdav.WebDAVProtocol
    factory.startTLS = useSSL
    factory.host = host
    factory.port = port
    factory.username = username
    factory.password = password
    factory.retries = zanshin.webdav.DEFAULT_RETRIES
    factory.repositoryView = repositoryView
    factory.extraHeaders = {'User-Agent': Utility.getUserAgent()}
    #factory.extraHeaders = { 'Connection' : "close" }

    return factory
Esempio n. 15
0
def createHTTPFactory(host, port, username, password, useSSL, repositoryView):

    # See if the user has configured an HTTP proxy
    if repositoryView is not None and not useSSL:
        getProxy = schema.ns("osaf.sharing.accounts", repositoryView).getProxy
        
        proxy = getProxy(repositoryView, 'HTTP')
        if not proxy.appliesTo(host):
            proxy = None
    else:
        proxy = None
        
    if proxy is not None and proxy.active:
        proxyPassword = getattr(proxy, 'password', None)
        factory = ChandlerHTTPProxyClientFactory(
                      host=proxy.host,
                      port=proxy.port,
                      username=proxy.username,
                      password=waitForDeferred(proxyPassword.decryptPassword())
                  )
    else:
        factory = ChandlerHTTPClientFactory()

    factory.protocol = zanshin.webdav.WebDAVProtocol
    factory.startTLS = useSSL
    factory.host = host
    factory.port = port
    factory.username = username
    factory.password = password
    factory.retries = zanshin.webdav.DEFAULT_RETRIES
    factory.repositoryView = repositoryView
    factory.extraHeaders = { 'User-Agent' : Utility.getUserAgent() }
    #factory.extraHeaders = { 'Connection' : "close" }

    return factory
Esempio n. 16
0
    def deactivatePlugin(self, project_name, plugin_env):

        view = self.itsView
        prefs = Utility.loadPrefs(Globals.options)
        pluginPrefs = self.widget.GetSubMenu().pluginPrefs

        for egg in plugin_env[project_name]:
            break
        else:
            return None

        def deleteItems(item):
            for child in item.iterChildren():
                deleteItems(child)
            if isinstance(item, Kind):
                for instance in item.iterItems():
                    instance.delete(True)

        for ep in egg.get_entry_map('chandler.parcels').values():
            parcel = Parcel.find_parcel_from_entrypoint(view, ep)
            if parcel is not None:
                deleteItems(parcel)
                parcel.delete(True)
            pluginPrefs[ep.dist.key] = 'inactive'

        if 'plugins' not in prefs:
            prefs['plugins'] = pluginPrefs
        else:
            prefs['plugins'].update(pluginPrefs)
            self.widget.GetSubMenu().pluginPrefs = prefs['plugins']

        prefs.write()

        return egg
Esempio n. 17
0
    def instantiateWidget(self):

        menu = wxPluginMenu()
        menu.blockItem = self
        menu.pluginPrefs = Utility.loadPrefs(Globals.options).get('plugins', {})

        # if we don't give the MenuItem a label, i.e. test = " " widgets
        # will use the assume the id is for a stock menuItem and will fail
        return wxMenuItem(None, id=self.getWidgetID(), text=" ", subMenu=menu)
Esempio n. 18
0
    def RemoteFeed(self):

        view = self.view
        Utility.initTwisted(view)

        url = u"http://blog.chandlerproject.org/rss2"
        url = str(url)
        view.refresh(notify=False)
        channel = FeedChannel(itsView=view)
        channel.displayName = url
        channel.url = channel.getAttributeAspect("url", "type").makeValue(url)
        view.commit()  # Make the channel available to feedsView
        status = blockUntil(channel.refresh)
        view.refresh()

        # Only bother checking if the fetch was successful.  If there is a
        # timeout or other network problem, that shouldn"t fail the test.
        if status == FETCH_UPDATED:
            self.assertEqual(channel.displayName, u"The Chandler Project Blog")
Esempio n. 19
0
    def instantiateWidget(self):

        menu = wxPluginMenu()
        menu.blockItem = self
        menu.pluginPrefs = Utility.loadPrefs(Globals.options).get(
            'plugins', {})

        # if we don't give the MenuItem a label, i.e. test = " " widgets
        # will use the assume the id is for a stock menuItem and will fail
        return wxMenuItem(None, id=self.getWidgetID(), text=" ", subMenu=menu)
Esempio n. 20
0
    def RemoteFeed(self):


        view = self.view
        Utility.initTwisted(view)

        url = u"http://blog.chandlerproject.org/rss2"
        url = str(url)
        view.refresh(notify=False)
        channel = FeedChannel(itsView=view)
        channel.displayName = url
        channel.url = channel.getAttributeAspect("url", "type").makeValue(url)
        view.commit() # Make the channel available to feedsView
        status = blockUntil(channel.refresh)
        view.refresh()

        # Only bother checking if the fetch was successful.  If there is a
        # timeout or other network problem, that shouldn"t fail the test.
        if status == FETCH_UPDATED:
            self.assertEqual(channel.displayName,
                u"The Chandler Project Blog")
Esempio n. 21
0
def matchDownloadUrl(urls,
                     platformID=Utility.getPlatformID(),
                     osName=Utility.getOSName()):

    matchedPlatform = ''
    matchedURL = None

    if platformID in ('win', 'win-cygwin'):
        platformID = 'windows'

    components = ("%s-%s" % (platformID, osName)).split('-')

    for platform, url in urls.iteritems():
        theseComponents = platform.split('-')
        if (components[:len(theseComponents)] == theseComponents
                and len(platform) > len(matchedPlatform)):

            matchedPlatform = platform
            matchedURL = url

    return matchedURL
Esempio n. 22
0
 def setUp(self):
     Globals.options = Utility.initOptions()
     Globals.options.ramdb = True
     Utility.initLogging(Globals.options)
     self.views = []
     for i in xrange(2):
         view = Utility.initRepository("", Globals.options, True)
         view.name = "test_view_%d" % i
         self.views.append(view)
         Utility.initTimezone(Globals.options, view)
Esempio n. 23
0
 def setUp(self):
     Globals.options = Utility.initOptions()
     Globals.options.ramdb = True
     Utility.initLogging(Globals.options)
     self.views = []
     for i in xrange(2):
         view = Utility.initRepository("", Globals.options, True)
         view.name = "test_view_%d" % i
         self.views.append(view)
         Utility.initTimezone(Globals.options, view)
Esempio n. 24
0
    def dataReceived(self, data):
        if __debug__:
            log.debug('TwistedProtocolWrapper.dataReceived')

        utils.entropyInitialized = True
        try:
            wrapper.TLSProtocolWrapper.dataReceived(self, data)
        except M2Crypto.BIO.BIOError, e:
            if self.isClient:
                host = self.transport.addr[0]
            else:
                host = self.transport.getPeer().host

            if e.args[1] == 'certificate verify failed':
                raise Utility.CertificateVerificationError(
                    host, e.args[0], e.args[1], self.untrustedCertificates)
            raise
Esempio n. 25
0
    def activatePlugin(self, project_name, plugin_env):

        view = self.itsView
        prefs = Utility.loadPrefs(Globals.options)
        pluginPrefs = self.widget.GetSubMenu().pluginPrefs

        for egg in plugin_env[project_name]:
            pkg_resources.working_set.add(egg)

            for ep in egg.get_entry_map('chandler.parcels').values():
                try:
                    ep.require(plugin_env)
                    requires = egg.requires(ep.extras)
                except pkg_resources.ResolutionError:
                    logger.exception("Activating %s failed", egg.egg_name())
                    return None, None
            break
        else:
            return None, None

        dependencies = pkg_resources.working_set.resolve(requires)

        for ep in pkg_resources.iter_entry_points('chandler.parcels'):
            name = ep.dist.key
            if plugin_env[name]:  # only handle plugin entrypoints
                if ep.dist == egg or ep.dist in dependencies: 
                    if pluginPrefs.get(name, 'inactive') == 'inactive':
                        Parcel.load_parcel_from_entrypoint(view, ep)
                        pluginPrefs[name] = 'active'
                    else:
                        dependencies.remove(ep.dist)

        if 'plugins' not in prefs:
            prefs['plugins'] = pluginPrefs
        else:
            prefs['plugins'].update(pluginPrefs)
            self.widget.GetSubMenu().pluginPrefs = prefs['plugins']

        prefs.write()

        return egg, dependencies
Esempio n. 26
0
    def activatePlugin(self, project_name, plugin_env):

        view = self.itsView
        prefs = Utility.loadPrefs(Globals.options)
        pluginPrefs = self.widget.GetSubMenu().pluginPrefs

        for egg in plugin_env[project_name]:
            pkg_resources.working_set.add(egg)

            for ep in egg.get_entry_map('chandler.parcels').values():
                try:
                    ep.require(plugin_env)
                    requires = egg.requires(ep.extras)
                except pkg_resources.ResolutionError:
                    logger.exception("Activating %s failed", egg.egg_name())
                    return None, None
            break
        else:
            return None, None

        dependencies = pkg_resources.working_set.resolve(requires)

        for ep in pkg_resources.iter_entry_points('chandler.parcels'):
            name = ep.dist.key
            if plugin_env[name]:  # only handle plugin entrypoints
                if ep.dist == egg or ep.dist in dependencies:
                    if pluginPrefs.get(name, 'inactive') == 'inactive':
                        Parcel.load_parcel_from_entrypoint(view, ep)
                        pluginPrefs[name] = 'active'
                    else:
                        dependencies.remove(ep.dist)

        if 'plugins' not in prefs:
            prefs['plugins'] = pluginPrefs
        else:
            prefs['plugins'].update(pluginPrefs)
            self.widget.GetSubMenu().pluginPrefs = prefs['plugins']

        prefs.write()

        return egg, dependencies
Esempio n. 27
0
def promptLicense():

    dialog = LicenseDialog(wx.GetApp().mainFrame, -1)
    dialog.CenterOnScreen()

    if dialog.ShowModal() == wx.ID_OK:
        params = dialog.getParameters()
    else:
        params = None

    dialog.Destroy()

    if params is not None:
        license = params['license']
        if license:
            prefs = Utility.loadPrefs(Globals.options)
            pluginPrefs = prefs.setdefault(PLUGIN_NAME, {})
            pluginPrefs['license'] = license
            prefs.write()
            setLicense(license)
            return True

    return False
Esempio n. 28
0
def promptLicense():

    dialog = LicenseDialog(wx.GetApp().mainFrame, -1)
    dialog.CenterOnScreen()

    if dialog.ShowModal() == wx.ID_OK:
        params = dialog.getParameters()
    else:
        params = None

    dialog.Destroy()

    if params is not None:
        license = params['license']
        if license:
            prefs = Utility.loadPrefs(Globals.options)
            pluginPrefs = prefs.setdefault(PLUGIN_NAME, {})
            pluginPrefs['license'] = license
            prefs.write()
            setLicense(license)
            return True

    return False
Esempio n. 29
0
    def testCrypto(self):
        # First time there should not be anything, so load and save 0
        r = Utility.initCrypto(self.path)
        self.assert_(r == 0, 'First time crypto init should return 0, got %d' % r)
        r = Utility.stopCrypto(self.path)
        self.assert_(r == 0, 'First time crypto stop should return 0, got %d' % r)

        # Trick us into thinking we have initialized entropy
        from osaf.framework.certstore import utils
        utils.entropyInitialized = True

        # Now we should save 1k on stop, after that loading and saving 1k
        r = Utility.initCrypto(self.path)
        self.assert_(r == 0, 'Entropy initialized, crypto init should return 0 first time, got %d' % r)
        
        # Note: the most likely reason why these would fail is if the entropy
        # file was not created, for example if we failed to create the
        # directory in setUp()
        r = Utility.stopCrypto(self.path)
        self.assert_(r == 1024, 'Entropy initialized, should save 1024 entropy first time, got %d' % r)
        r = Utility.initCrypto(self.path)
        self.assert_(r == 1024, 'Entropy initialized, should load 1024 entropy, got %d' % r)
        r = Utility.stopCrypto(self.path)
        self.assert_(r == 1024, 'Entropy initialized, should save 1024 entropy, got %d' % r)
    def testCrypto(self):
        # First time there should not be anything, so load and save 0
        r = Utility.initCrypto(self.path)
        self.assert_(r == 0,
                     'First time crypto init should return 0, got %d' % r)
        r = Utility.stopCrypto(self.path)
        self.assert_(r == 0,
                     'First time crypto stop should return 0, got %d' % r)

        # Trick us into thinking we have initialized entropy
        from osaf.framework.certstore import utils
        utils.entropyInitialized = True

        # Now we should save 1k on stop, after that loading and saving 1k
        r = Utility.initCrypto(self.path)
        self.assert_(
            r == 0,
            'Entropy initialized, crypto init should return 0 first time, got %d'
            % r)

        # Note: the most likely reason why these would fail is if the entropy
        # file was not created, for example if we failed to create the
        # directory in setUp()
        r = Utility.stopCrypto(self.path)
        self.assert_(
            r == 1024,
            'Entropy initialized, should save 1024 entropy first time, got %d'
            % r)
        r = Utility.initCrypto(self.path)
        self.assert_(
            r == 1024,
            'Entropy initialized, should load 1024 entropy, got %d' % r)
        r = Utility.stopCrypto(self.path)
        self.assert_(
            r == 1024,
            'Entropy initialized, should save 1024 entropy, got %d' % r)
Esempio n. 31
0
 def tearDown(self):
     super(TestSSL, self).tearDown()
     Utility.stopCrypto(self.profileDir)
Esempio n. 32
0
 def reopenRepository(self):
     view = self.view
     view.commit()
     view.closeView()
     view.openView(timezone=Default)
     Utility.initTimezone(Globals.options, view)
Esempio n. 33
0
 def setUp(self):
     Globals.options = Utility.initOptions()
     Utility.initLogging(Globals.options)
     self.view = NullRepositoryView()
     Utility.initTimezone(Globals.options, self.view)
Esempio n. 34
0
 def reopenRepository(self):
     view = self.view
     view.commit()
     view.closeView()
     view.openView(timezone=Default)
     Utility.initTimezone(Globals.options, view)
Esempio n. 35
0
def shutdown():
    Utility.stopWakeup()
    Utility.stopTwisted()
    Utility.stopRepository(view)
    Utility.stopCrypto(Globals.options.profileDir)
Esempio n. 36
0
def main():

    # Process any command line switches and any environment variable values
    Globals.options = Utility.initOptions()

    def realMain():

        from application import feedback
        feedback.initRuntimeLog(Globals.options.profileDir)

        Globals.chandlerDirectory = Utility.locateChandlerDirectory()

        os.chdir(Globals.chandlerDirectory)
        Utility.initLogging(Globals.options)

        if __debug__ and Globals.options.wing:
            # Check for -wing command line argument; if specified, try to
            # connect to an already-running WingIDE instance. See
            # http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#wingIDE
            # for details.

            import wingdbstub

        if __debug__ and Globals.options.komodo:
            # Check for -komodo command line argument; if specified, try to
            # connect to an already-running Komodo instance. See
            # http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#Komodo
            # for details.

            import dbgp.client
            dbgp.client.brk()

        from application.Application import wxApplication

        # Redirect stdio and stderr to a dialog if a non-default --catch option
        # was specified. This is done to catch asserts, which otherwise will
        # never get seen by people who run Chandler using the launchers, e.g.
        # Aparna. If you're running release you can also set things up so
        # that you can see stderr and stdout if you run in a shell or from
        # wing with a console.
        redirect = Globals.options.catch == 'normal'

        # useBestVisual: See wxApp.SetUseBestVisual (Only applicable
        # for X-Windows based systems) On some older computers the
        # default visual may only have a depth of 8 although 24-bit
        # visuals are available. (SGI is notorious for this.) Setting
        # this to True will cause the best visual to be used instead.
        # Unfortunatly on some systems with a 32-bit visual available
        # this can cause problems if the default GTK theme expects to
        # use only 24.  (See Bug #9295) So for now we'll default this
        # to False.  If this becomes a problem in the future then we
        # should add a command-line option for it or perhaps find a
        # way to detect if the display depth is < 24.  (Note there is
        # a chicken-and-egg problem with wx.GetDisplayDepth() as it
        # needs to have the app created before it can be called.)
        useBestVisual = False

        app = wxApplication(redirect=redirect, useBestVisual=useBestVisual)

        exitValue = getattr(app, 'exitValue', 0)
        if exitValue:
            return exitValue

        app.MainLoop()

        return getattr(app, 'exitValue', 0)

    if Globals.options.catch != 'normal':
        # When debugging, it's handy to run without the outer exception frame
        return realMain()
    else:
        try:
            # The normal way: wrap the app in an exception frame
            from chandlerdb.persistence.RepositoryError \
                import RepositoryOpenDeniedError, ExclusiveOpenDeniedError

            import logging, wx
            from i18n import ChandlerSafeTranslationMessageFactory as _
            return realMain()

        except (RepositoryOpenDeniedError, ExclusiveOpenDeniedError):
            # This doesn't seem worth the effor to localize, since we don't have a repository
            # which is necessary for localization.
            try:
                logging.error(
                    "Another instance of Chandler currently has the repository open."
                )
                dialog = wx.MessageDialog(
                    None,
                    _(u"Another Chandler is already running off the same data repository."
                      ), u"Chandler", wx.OK | wx.ICON_INFORMATION)
                dialog.ShowModal()
                dialog.Destroy()
            finally:
                return 1

        except Utility.SchemaMismatchError:
            try:
                logging.info(
                    "User chose not to clear the repository.  Exiting.")
            finally:
                return 1

        except:
            try:
                import traceback

                line1 = "Chandler encountered an unexpected problem while trying to start.\n"

                type, value, stack = sys.exc_info()
                backtrace = traceback.format_exception(type, value, stack)

                longMessage = "".join([line1, "\n"] + backtrace)

                logging.error(longMessage)

                if getattr(globals(), 'app',
                           None) is None or wx.GetApp() is None:
                    app = wx.PySimpleApp()
                    app.ignoreSynchronizeWidget = True

                try:
                    # Let's try the best (and most complicated) option
                    # first
                    # See if we already have a window up, and if so, reuse it
                    from application import feedback
                    feedback.destroyAppOnClose = True
                    win = feedback.FeedbackWindow()
                    win.CreateOutputWindow('')
                    for line in backtrace:
                        win.write(line)
                    if not app.IsMainLoopRunning():
                        app.MainLoop()
                except:
                    # Fall back to our custom (but simple) error dialog
                    try:
                        from application.dialogs.UncaughtExceptionDialog import ErrorDialog
                        dialog = ErrorDialog(longMessage)
                    except:
                        # Fall back to MessageDialog
                        frames = 8
                        line = _(
                            u"Start up error.\nHere are the bottom %(numOf)s frames of the stack: %(stacktrace)s\n\n"
                        ) % {
                            'numOf':
                            frames - 1,
                            "stacktrace":
                            unicode("".join(backtrace[-frames:]), "UTF-8",
                                    "ignore")
                        }
                        dialog = wx.MessageDialog(None, line, u"Chandler",
                                                  wx.OK | wx.ICON_INFORMATION)
                    dialog.ShowModal()
                    dialog.Destroy()
            finally:
                return 1
Esempio n. 37
0
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import sys
import unittest
import itertools
from application import schema, Globals, Utility
from chandlerdb.persistence.RepositoryView import NullRepositoryView

Globals.chandlerDirectory = Utility.locateChandlerDirectory()
Globals.options = Utility.initOptions()


class MenuTestCase(unittest.TestCase):
    """
    Tests of consistent mnemonics/shortcuts in Chandler's menus.
    """
    view = None

    def setUp(self):
        # This setup is needed because we'd like to be able to use
        # --locale on the command line to test a given locale. So,
        # basically the code below is copy-and-pasted out of Utility.py
        # to make sure that everything gets initialized in the right
        # order.
Esempio n. 38
0
    def realMain():
        
        from application import feedback
        feedback.initRuntimeLog(Globals.options.profileDir)
        
        Globals.chandlerDirectory = Utility.locateChandlerDirectory()
    
        os.chdir(Globals.chandlerDirectory)
        Utility.initLogging(Globals.options)

        if __debug__ and Globals.options.wing:
            # Check for -wing command line argument; if specified, try to 
            # connect to an already-running WingIDE instance. See
            # http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#wingIDE
            # for details.

            import wingdbstub

        if __debug__ and Globals.options.komodo:
            # Check for -komodo command line argument; if specified, try to 
            # connect to an already-running Komodo instance. See
            # http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#Komodo
            # for details.

            import dbgp.client
            dbgp.client.brk()

        from application.Application import wxApplication

        # Redirect stdio and stderr to a dialog if a non-default --catch option 
        # was specified. This is done to catch asserts, which otherwise will
        # never get seen by people who run Chandler using the launchers, e.g.
        # Aparna. If you're running release you can also set things up so 
        # that you can see stderr and stdout if you run in a shell or from
        # wing with a console.
        redirect = Globals.options.catch == 'normal'
        
        # useBestVisual: See wxApp.SetUseBestVisual (Only applicable
        # for X-Windows based systems) On some older computers the
        # default visual may only have a depth of 8 although 24-bit
        # visuals are available. (SGI is notorious for this.) Setting
        # this to True will cause the best visual to be used instead.
        # Unfortunatly on some systems with a 32-bit visual available
        # this can cause problems if the default GTK theme expects to
        # use only 24.  (See Bug #9295) So for now we'll default this
        # to False.  If this becomes a problem in the future then we
        # should add a command-line option for it or perhaps find a
        # way to detect if the display depth is < 24.  (Note there is
        # a chicken-and-egg problem with wx.GetDisplayDepth() as it
        # needs to have the app created before it can be called.)
        useBestVisual = False
        
        app = wxApplication(redirect=redirect, useBestVisual=useBestVisual)

        exitValue = getattr(app, 'exitValue', 0)
        if exitValue:
            return exitValue

        app.MainLoop()

        return getattr(app, 'exitValue', 0)
Esempio n. 39
0
    def onInstallPluginsEvent(self, event):

        patterns = "%s|*.tar.gz;*.tar|%s (*.*)|*.*" %(_(u"tar archives"),
                                                      _(u"All files"))
        dlg = wx.FileDialog(None, _(u"Install Plugin"), "", "", patterns,
                            wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            archive = dlg.GetPath()
        else:
            archive = None
        dlg.Destroy()

        if archive is not None:
            options = Globals.options

            # find writable path on options.pluginPath
            # it is assumed that, unless the user changed the defaults,
            # that pluginPath contains at least a path relative to CHANDLERHOME
            # and another relative to the user's PROFILEDIR, in that order,
            # so that plugins are installed in a shared directory (when
            # CHANDLERHOME is shared) by default.

            for pluginsDir in options.pluginPath:
                try:
                    if not os.path.exists(pluginsDir):
                        os.makedirs(pluginsDir)
                except OSError:
                    continue
                if os.access(pluginsDir, os.W_OK):
                    break
            else:
                raise ValueError, ('no writable path in pluginPath',
                                   options.pluginPath)

            try:
                from setuptools.command.easy_install import main
                from distutils.log import _global_log
                from util.string_utils import nocase_replace
                
                # patch distutils' logger with logging's
                # distutils logging levels happen to be one tenth of logging's
                # Also ensure that we don't write full profileDir to log,
                # which would be a security issue.
                def log(level, msg, args):
                    if msg:
                        if wx.Platform == '__WXMSW__':
                            msg = nocase_replace(msg,
                                                 Globals.options.profileDir,
                                                '$PROFILEDIR')
                        else:
                            msg = msg.replace(Globals.options.profileDir,
                                              '$PROFILEDIR')
                            
                    logger.log(level * 10, msg, *args)

                _log = _global_log._log
                _global_log._log = log

                try:
                    main(['--multi-version', '--install-dir', pluginsDir, archive])
                except:
                    logger.exception("Plugin installation failed")
                    # Could be a SystemExit exception, since we called a
                    # main() directly.
            finally:
                _global_log._log = _log

            env, eggs = Utility.initPluginEnv(options, options.pluginPath)
            prefs = Utility.initPlugins(options, self.itsView, env, eggs)

            # Update the menus
            self.widget.GetSubMenu().pluginPrefs = prefs.get('plugins', {})
            self.synchronizeWidget()
            self.refreshMenus(self.itsView);
Esempio n. 40
0
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import sys
import unittest
import itertools
from application import schema, Globals, Utility
from chandlerdb.persistence.RepositoryView import NullRepositoryView

Globals.chandlerDirectory = Utility.locateChandlerDirectory()
Globals.options = Utility.initOptions()


class MenuTestCase(unittest.TestCase):
    """
    Tests of consistent mnemonics/shortcuts in Chandler's menus.
    """

    view = None

    def setUp(self):
        # This setup is needed because we'd like to be able to use
        # --locale on the command line to test a given locale. So,
        # basically the code below is copy-and-pasted out of Utility.py
        # to make sure that everything gets initialized in the right
Esempio n. 41
0
cause *all* modules in all sub-packages of that package to be imported.)

"""

import sys

from unittest import main
from application import Globals, Utility
from util import test_finder

if __name__ == '__main__':

    if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):  # XXX
        print __doc__
        sys.exit(2)

    options = Utility.initOptions()
    Utility.initI18n(options)
    Utility.initLogging(options)

    # Rebuild the command line for unittest.main
    args = [sys.argv[0]]
    if options.verbose:
        args.append('-v')
    if options.quiet:
        args.append('-q')
    # options.args has all the leftover arguments from Utility
    sys.argv = args + options.args

    main(module=None, testLoader=test_finder.ScanningLoader())
Esempio n. 42
0
def main():
    message = "while trying to start."

    application.Globals.chandlerDirectory = Utility.locateChandlerDirectory()

    os.chdir(application.Globals.chandlerDirectory)
    """
    Process any command line switches and any environment variable values
    """
    application.Globals.options = Utility.initOptions(
        application.Globals.chandlerDirectory)
    Utility.initLogging(application.Globals.options)

    def realMain():
        if __debug__ and application.Globals.options.wing:
            """
              Check for -wing command line argument; if specified, try to connect to
            an already-running WingIDE instance.  See:
              http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#wingIDE.
            for details.
            """
            import wingdbstub
        if __debug__ and application.Globals.options.komodo:
            """
            Check for -komodo command line argument; if specified, try to connect to
            an already-running Komodo instance.  See:
              http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#Komodo.
            for details.
            """
            import dbgp.client
            dbgp.client.brk()
        from application.Application import wxApplication
        """
          redirect stdio and stderr to a dialog if we're running the debug version.
        This is done to catch asserts, which otherwise will never get seen by
        people who run Chandler using the launchers, e.g. Aparna. If you're
        running release you can also set things up so that you can see
        stderr and stdout if you run in a shell or from wing with a console.
          useBestVisual, uses best screen resolutions on some old computers. See
        wxApp.SetUseBestVisual
        """
        #app = wxApplication(redirect=__debug__, useBestVisual=True)
        app = wxApplication(redirect=False, useBestVisual=True)
        app.MainLoop()

    if application.Globals.options.nocatch:
        # When debugging, it's handy to run without the outer exception frame
        import logging, traceback, wx
        realMain()
    else:
        # The normal way: wrap the app in an exception frame

        try:
            import logging, traceback, wx
            realMain()

        except (RepositoryOpenDeniedError, ExclusiveOpenDeniedError):
            message = "Another instance of Chandler currently has the " \
                      "repository open."
            logging.exception(message)
            dialog = wx.MessageDialog(None, message, "Chandler",
                                      wx.OK | wx.ICON_INFORMATION)
            dialog.ShowModal()
            dialog.Destroy()

        except Utility.SchemaMismatchError:
            logging.info("User chose not to clear the repository.  Exiting.")

        except Exception:
            type, value, stack = sys.exc_info()
            formattedBacktrace = "".join(
                traceback.format_exception(type, value, stack, 5))

            message = ("Chandler encountered an unexpected problem %s\n" + \
                      "Here are the bottom 5 frames of the stack:\n%s") % (message, formattedBacktrace)
            logging.exception(message)
            # @@@ 25Issue - Cannot create wxItems if the app failed to initialize
            dialog = wx.MessageDialog(None, message, "Chandler",
                                      wx.OK | wx.ICON_INFORMATION)
            dialog.ShowModal()
            dialog.Destroy()

            #Reraising the exception, so wing catches it.
            raise
Esempio n. 43
0
    e_options, names = epydoc.cli.parse_arguments()

    e_options.prj_name    = 'Chandler'
    e_options.exclude     = ['tests', 'wx']
    e_options.simple_term = True
    e_options.parse       = True
    e_options.introspect  = True
    e_options.include_log = True
    e_options.target      = os.path.join(outputDir, 'api')
    e_options.verbosity   = 4

    epydoc.cli.main(e_options, names)


if __name__ == '__main__':
    Globals.options = Utility.initOptions()
    Globals.options.create = True
    Globals.options.verify = False

    Globals.chandlerDirectory = Utility.locateChandlerDirectory()

    os.chdir(Globals.chandlerDirectory)
    Utility.initI18n(Globals.options)

    profileDir = os.path.abspath(os.path.join(Globals.chandlerDirectory, '..', 'doc_profile'))

    if not os.path.isdir(profileDir):
        _mkdirs(profileDir)

    print Globals.chandlerDirectory
    print profileDir
Esempio n. 44
0
def startup(**kwds):
    global view

    Globals.chandlerDirectory = Utility.locateChandlerDirectory()
    if not Globals.chandlerDirectory:
        print "Please set CHANDLERHOME"
        return None
    os.chdir(Globals.chandlerDirectory)

    Utility.initLocale('en')

    Globals.options = Utility.initOptions(Globals.chandlerDirectory, **kwds)
    profileDir = Globals.options.profileDir

    Utility.initLogging(Globals.options)

    parcelPath = Utility.initParcelEnv(Globals.chandlerDirectory,
                                       Globals.options.parcelPath)

    view = Utility.initRepository(
        Utility.locateRepositoryDirectory(profileDir), Globals.options)

    if not Utility.verifySchema(view):
        print "Schema mismatch.  Try again with startup(create=True)"
        return None

    Utility.initCrypto(Globals.options.profileDir)
    Utility.initParcels(view, parcelPath)

    if Globals.options.createData:
        import GenerateItemsFromFile
        GenerateItemsFromFile.RunScript(view)

    return view
Esempio n. 45
0
def main():

    # Process any command line switches and any environment variable values
    Globals.options = Utility.initOptions()

    def realMain():
        
        from application import feedback
        feedback.initRuntimeLog(Globals.options.profileDir)
        
        Globals.chandlerDirectory = Utility.locateChandlerDirectory()
    
        os.chdir(Globals.chandlerDirectory)
        Utility.initLogging(Globals.options)

        if __debug__ and Globals.options.wing:
            # Check for -wing command line argument; if specified, try to 
            # connect to an already-running WingIDE instance. See
            # http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#wingIDE
            # for details.

            import wingdbstub

        if __debug__ and Globals.options.komodo:
            # Check for -komodo command line argument; if specified, try to 
            # connect to an already-running Komodo instance. See
            # http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#Komodo
            # for details.

            import dbgp.client
            dbgp.client.brk()

        from application.Application import wxApplication

        # Redirect stdio and stderr to a dialog if a non-default --catch option 
        # was specified. This is done to catch asserts, which otherwise will
        # never get seen by people who run Chandler using the launchers, e.g.
        # Aparna. If you're running release you can also set things up so 
        # that you can see stderr and stdout if you run in a shell or from
        # wing with a console.
        redirect = Globals.options.catch == 'normal'
        
        # useBestVisual: See wxApp.SetUseBestVisual (Only applicable
        # for X-Windows based systems) On some older computers the
        # default visual may only have a depth of 8 although 24-bit
        # visuals are available. (SGI is notorious for this.) Setting
        # this to True will cause the best visual to be used instead.
        # Unfortunatly on some systems with a 32-bit visual available
        # this can cause problems if the default GTK theme expects to
        # use only 24.  (See Bug #9295) So for now we'll default this
        # to False.  If this becomes a problem in the future then we
        # should add a command-line option for it or perhaps find a
        # way to detect if the display depth is < 24.  (Note there is
        # a chicken-and-egg problem with wx.GetDisplayDepth() as it
        # needs to have the app created before it can be called.)
        useBestVisual = False
        
        app = wxApplication(redirect=redirect, useBestVisual=useBestVisual)

        exitValue = getattr(app, 'exitValue', 0)
        if exitValue:
            return exitValue

        app.MainLoop()

        return getattr(app, 'exitValue', 0)

    if Globals.options.catch != 'normal':
        # When debugging, it's handy to run without the outer exception frame
        return realMain()
    else:
        try:
            # The normal way: wrap the app in an exception frame
            from chandlerdb.persistence.RepositoryError \
                import RepositoryOpenDeniedError, ExclusiveOpenDeniedError

            import logging, wx
            from i18n import ChandlerSafeTranslationMessageFactory as _
            return realMain()

        except (RepositoryOpenDeniedError, ExclusiveOpenDeniedError):
            # This doesn't seem worth the effor to localize, since we don't have a repository
            # which is necessary for localization.
            try:
                logging.error("Another instance of Chandler currently has the repository open.")
                dialog = wx.MessageDialog(None,
                                          _(u"Another Chandler is already running off the same data repository."),
                                          u"Chandler", wx.OK | wx.ICON_INFORMATION)
                dialog.ShowModal()
                dialog.Destroy()
            finally:
                return 1

        except Utility.SchemaMismatchError:
            try:
                logging.info("User chose not to clear the repository.  Exiting.")
            finally:
                return 1

        except:
            try:
                import traceback
                
                line1 = "Chandler encountered an unexpected problem while trying to start.\n"
                
                type, value, stack = sys.exc_info()
                backtrace = traceback.format_exception(type, value, stack)
                
                longMessage = "".join([line1, "\n"] + backtrace)
                
                logging.error(longMessage)
                
                if getattr(globals(), 'app', None) is None or wx.GetApp() is None:
                    app = wx.PySimpleApp()
                    app.ignoreSynchronizeWidget = True
                
                try:
                    # Let's try the best (and most complicated) option
                    # first
                    # See if we already have a window up, and if so, reuse it
                    from application import feedback
                    feedback.destroyAppOnClose = True
                    win = feedback.FeedbackWindow()
                    win.CreateOutputWindow('')
                    for line in backtrace:
                        win.write(line)
                    if not app.IsMainLoopRunning():
                        app.MainLoop()
                except:
                    # Fall back to our custom (but simple) error dialog
                    try:
                        from application.dialogs.UncaughtExceptionDialog import ErrorDialog
                        dialog = ErrorDialog(longMessage)
                    except:
                        # Fall back to MessageDialog
                        frames = 8
                        line = _(u"Start up error.\nHere are the bottom %(numOf)s frames of the stack: %(stacktrace)s\n\n") % {'numOf': frames - 1, "stacktrace": unicode("".join(backtrace[-frames:]), "UTF-8", "ignore")}
                        dialog = wx.MessageDialog(None, line, u"Chandler", wx.OK | wx.ICON_INFORMATION)
                    dialog.ShowModal()
                    dialog.Destroy()
            finally:
                return 1
Esempio n. 46
0
def main():
    message = "while trying to start."

    application.Globals.chandlerDirectory = Utility.locateChandlerDirectory()

    os.chdir(application.Globals.chandlerDirectory)

    """
    Process any command line switches and any environment variable values
    """
    application.Globals.options = Utility.initOptions(application.Globals.chandlerDirectory)
    Utility.initLogging(application.Globals.options)

    def realMain():
        if __debug__ and application.Globals.options.wing:
            """
              Check for -wing command line argument; if specified, try to connect to
            an already-running WingIDE instance.  See:
              http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#wingIDE.
            for details.
            """
            import wingdbstub
        if __debug__ and application.Globals.options.komodo:
            """
            Check for -komodo command line argument; if specified, try to connect to
            an already-running Komodo instance.  See:
              http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#Komodo.
            for details.
            """
            import dbgp.client

            dbgp.client.brk()
        from application.Application import wxApplication

        """
          redirect stdio and stderr to a dialog if we're running the debug version.
        This is done to catch asserts, which otherwise will never get seen by
        people who run Chandler using the launchers, e.g. Aparna. If you're
        running release you can also set things up so that you can see
        stderr and stdout if you run in a shell or from wing with a console.
          useBestVisual, uses best screen resolutions on some old computers. See
        wxApp.SetUseBestVisual
        """
        # app = wxApplication(redirect=__debug__, useBestVisual=True)
        app = wxApplication(redirect=False, useBestVisual=True)
        app.MainLoop()

    if application.Globals.options.nocatch:
        # When debugging, it's handy to run without the outer exception frame
        import logging, traceback, wx

        realMain()
    else:
        # The normal way: wrap the app in an exception frame

        try:
            import logging, traceback, wx

            realMain()

        except (RepositoryOpenDeniedError, ExclusiveOpenDeniedError):
            message = "Another instance of Chandler currently has the " "repository open."
            logging.exception(message)
            dialog = wx.MessageDialog(None, message, "Chandler", wx.OK | wx.ICON_INFORMATION)
            dialog.ShowModal()
            dialog.Destroy()

        except Utility.SchemaMismatchError:
            logging.info("User chose not to clear the repository.  Exiting.")

        except Exception:
            type, value, stack = sys.exc_info()
            formattedBacktrace = "".join(traceback.format_exception(type, value, stack, 5))

            message = (
                "Chandler encountered an unexpected problem %s\n" + "Here are the bottom 5 frames of the stack:\n%s"
            ) % (message, formattedBacktrace)
            logging.exception(message)
            # @@@ 25Issue - Cannot create wxItems if the app failed to initialize
            dialog = wx.MessageDialog(None, message, "Chandler", wx.OK | wx.ICON_INFORMATION)
            dialog.ShowModal()
            dialog.Destroy()

            # Reraising the exception, so wing catches it.
            raise
Esempio n. 47
0
"""

import sys

from unittest import main
from application import Globals, Utility
from util import test_finder


if __name__ == '__main__':

    if len(sys.argv)<2 or sys.argv[1] in ('-h','--help'):   # XXX
        print __doc__
        sys.exit(2)

    options = Utility.initOptions()
    Utility.initI18n(options)
    Utility.initLogging(options)

    # Rebuild the command line for unittest.main
    args = [sys.argv[0]]
    if options.verbose:
        args.append('-v')
    if options.quiet:
        args.append('-q')
    # options.args has all the leftover arguments from Utility
    sys.argv = args + options.args

    main(module=None, testLoader=test_finder.ScanningLoader())

Esempio n. 48
0
def startup(**kwds):
    global view

    Globals.chandlerDirectory = Utility.locateChandlerDirectory()
    if not Globals.chandlerDirectory:
        print "Please set CHANDLERHOME"
        return None
    os.chdir(Globals.chandlerDirectory)

    Utility.initLocale('en')

    Globals.options = Utility.initOptions(Globals.chandlerDirectory, **kwds)
    profileDir = Globals.options.profileDir

    Utility.initLogging(Globals.options)

    parcelPath = Utility.initParcelEnv(Globals.chandlerDirectory,
                                       Globals.options.parcelPath)

    view = Utility.initRepository(Utility.locateRepositoryDirectory(profileDir),
                                  Globals.options)

    if not Utility.verifySchema(view):
        print "Schema mismatch.  Try again with startup(create=True)"
        return None

    Utility.initCrypto(Globals.options.profileDir)
    Utility.initParcels(view, parcelPath)

    if Globals.options.createData:
        import GenerateItemsFromFile
        GenerateItemsFromFile.RunScript(view)

    return view
Esempio n. 49
0
def startup(chandlerDirectory=None, **kwds):
    global view, commitOnExit

    Globals.options = Utility.initOptions(**kwds)
    if chandlerDirectory is None:
        Globals.chandlerDirectory = Utility.locateChandlerDirectory()
    else:
        Globals.chandlerDirectory = chandlerDirectory

    os.chdir(Globals.chandlerDirectory)
    Utility.initI18n(Globals.options)

    profileDir = Globals.options.profileDir

    Utility.initLogging(Globals.options)

    parcelPath = Utility.initParcelEnv(Globals.options, 
                                       Globals.chandlerDirectory)
    pluginEnv, pluginEggs = Utility.initPluginEnv(Globals.options,
                                                  Globals.options.pluginPath)

    Globals.options.getPassword = getPassword
    repoDir = Utility.locateRepositoryDirectory(profileDir, Globals.options)
    view = Utility.initRepository(repoDir, Globals.options)

    verify, repoVersion, schemaVersion = Utility.verifySchema(view)
    if not verify:
        print "Schema mismatch (%s vs %s).  Try again with startup(create=True)" %(repoVersion, schemaVersion)
        return None

    Utility.initCrypto(Globals.options.profileDir)
    Utility.initParcels(Globals.options, view, parcelPath)
    Utility.initPlugins(Globals.options, view, pluginEnv, pluginEggs)
    Utility.initTimezone(Globals.options, view)

    if Globals.options.reload:
        from osaf import dumpreload
        dumpreload.reload(view, Globals.options.reload)

    return view
Esempio n. 50
0
    def realMain():

        from application import feedback
        feedback.initRuntimeLog(Globals.options.profileDir)

        Globals.chandlerDirectory = Utility.locateChandlerDirectory()

        os.chdir(Globals.chandlerDirectory)
        Utility.initLogging(Globals.options)

        if __debug__ and Globals.options.wing:
            # Check for -wing command line argument; if specified, try to
            # connect to an already-running WingIDE instance. See
            # http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#wingIDE
            # for details.

            import wingdbstub

        if __debug__ and Globals.options.komodo:
            # Check for -komodo command line argument; if specified, try to
            # connect to an already-running Komodo instance. See
            # http://wiki.osafoundation.org/bin/view/Chandler/DebuggingChandler#Komodo
            # for details.

            import dbgp.client
            dbgp.client.brk()

        from application.Application import wxApplication

        # Redirect stdio and stderr to a dialog if a non-default --catch option
        # was specified. This is done to catch asserts, which otherwise will
        # never get seen by people who run Chandler using the launchers, e.g.
        # Aparna. If you're running release you can also set things up so
        # that you can see stderr and stdout if you run in a shell or from
        # wing with a console.
        redirect = Globals.options.catch == 'normal'

        # useBestVisual: See wxApp.SetUseBestVisual (Only applicable
        # for X-Windows based systems) On some older computers the
        # default visual may only have a depth of 8 although 24-bit
        # visuals are available. (SGI is notorious for this.) Setting
        # this to True will cause the best visual to be used instead.
        # Unfortunatly on some systems with a 32-bit visual available
        # this can cause problems if the default GTK theme expects to
        # use only 24.  (See Bug #9295) So for now we'll default this
        # to False.  If this becomes a problem in the future then we
        # should add a command-line option for it or perhaps find a
        # way to detect if the display depth is < 24.  (Note there is
        # a chicken-and-egg problem with wx.GetDisplayDepth() as it
        # needs to have the app created before it can be called.)
        useBestVisual = False

        app = wxApplication(redirect=redirect, useBestVisual=useBestVisual)

        exitValue = getattr(app, 'exitValue', 0)
        if exitValue:
            return exitValue

        app.MainLoop()

        return getattr(app, 'exitValue', 0)
Esempio n. 51
0
    def onInstallPluginsEvent(self, event):

        patterns = "%s|*.tar.gz;*.tar|%s (*.*)|*.*" % (_(u"tar archives"),
                                                       _(u"All files"))
        dlg = wx.FileDialog(None, _(u"Install Plugin"), "", "", patterns,
                            wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            archive = dlg.GetPath()
        else:
            archive = None
        dlg.Destroy()

        if archive is not None:
            options = Globals.options

            # find writable path on options.pluginPath
            # it is assumed that, unless the user changed the defaults,
            # that pluginPath contains at least a path relative to CHANDLERHOME
            # and another relative to the user's PROFILEDIR, in that order,
            # so that plugins are installed in a shared directory (when
            # CHANDLERHOME is shared) by default.

            for pluginsDir in options.pluginPath:
                try:
                    if not os.path.exists(pluginsDir):
                        os.makedirs(pluginsDir)
                except OSError:
                    continue
                if os.access(pluginsDir, os.W_OK):
                    break
            else:
                raise ValueError, ('no writable path in pluginPath',
                                   options.pluginPath)

            try:
                from setuptools.command.easy_install import main
                from distutils.log import _global_log
                from util.string_utils import nocase_replace

                # patch distutils' logger with logging's
                # distutils logging levels happen to be one tenth of logging's
                # Also ensure that we don't write full profileDir to log,
                # which would be a security issue.
                def log(level, msg, args):
                    if msg:
                        if wx.Platform == '__WXMSW__':
                            msg = nocase_replace(msg,
                                                 Globals.options.profileDir,
                                                 '$PROFILEDIR')
                        else:
                            msg = msg.replace(Globals.options.profileDir,
                                              '$PROFILEDIR')

                    logger.log(level * 10, msg, *args)

                _log = _global_log._log
                _global_log._log = log

                try:
                    main([
                        '--multi-version', '--install-dir', pluginsDir, archive
                    ])
                except:
                    logger.exception("Plugin installation failed")
                    # Could be a SystemExit exception, since we called a
                    # main() directly.
            finally:
                _global_log._log = _log

            env, eggs = Utility.initPluginEnv(options, options.pluginPath)
            prefs = Utility.initPlugins(options, self.itsView, env, eggs)

            # Update the menus
            self.widget.GetSubMenu().pluginPrefs = prefs.get('plugins', {})
            self.synchronizeWidget()
            self.refreshMenus(self.itsView)
Esempio n. 52
0
def startup(chandlerDirectory=None, **kwds):
    global view, commitOnExit

    Globals.options = Utility.initOptions(**kwds)
    if chandlerDirectory is None:
        Globals.chandlerDirectory = Utility.locateChandlerDirectory()
    else:
        Globals.chandlerDirectory = chandlerDirectory

    os.chdir(Globals.chandlerDirectory)
    Utility.initI18n(Globals.options)

    profileDir = Globals.options.profileDir

    Utility.initLogging(Globals.options)

    parcelPath = Utility.initParcelEnv(Globals.options,
                                       Globals.chandlerDirectory)
    pluginEnv, pluginEggs = Utility.initPluginEnv(Globals.options,
                                                  Globals.options.pluginPath)

    Globals.options.getPassword = getPassword
    repoDir = Utility.locateRepositoryDirectory(profileDir, Globals.options)
    view = Utility.initRepository(repoDir, Globals.options)

    verify, repoVersion, schemaVersion = Utility.verifySchema(view)
    if not verify:
        print "Schema mismatch (%s vs %s).  Try again with startup(create=True)" % (
            repoVersion, schemaVersion)
        return None

    Utility.initCrypto(Globals.options.profileDir)
    Utility.initParcels(Globals.options, view, parcelPath)
    Utility.initPlugins(Globals.options, view, pluginEnv, pluginEggs)
    Utility.initTimezone(Globals.options, view)

    if Globals.options.reload:
        from osaf import dumpreload
        dumpreload.reload(view, Globals.options.reload)

    return view
Esempio n. 53
0
    e_options, names = epydoc.cli.parse_arguments()

    e_options.prj_name = 'Chandler'
    e_options.exclude = ['tests', 'wx']
    e_options.simple_term = True
    e_options.parse = True
    e_options.introspect = True
    e_options.include_log = True
    e_options.target = os.path.join(outputDir, 'api')
    e_options.verbosity = 4

    epydoc.cli.main(e_options, names)


if __name__ == '__main__':
    Globals.options = Utility.initOptions()
    Globals.options.create = True
    Globals.options.verify = False

    Globals.chandlerDirectory = Utility.locateChandlerDirectory()

    os.chdir(Globals.chandlerDirectory)
    Utility.initI18n(Globals.options)

    profileDir = os.path.abspath(
        os.path.join(Globals.chandlerDirectory, '..', 'doc_profile'))

    if not os.path.isdir(profileDir):
        _mkdirs(profileDir)

    print Globals.chandlerDirectory
Esempio n. 54
0
 def setUp(self):
     Globals.options = Utility.initOptions()
     Globals.options.ramdb = True
     Utility.initLogging(Globals.options)
     self.view = Utility.initRepository("", Globals.options, True)
     Utility.initTimezone(Globals.options, self.view)
Esempio n. 55
0
def shutdown():
    Utility.stopWakeup()
    Utility.stopTwisted()
    Utility.stopRepository(view, commitOnExit)
    Utility.stopCrypto(Globals.options.profileDir)
Esempio n. 56
0
 def setUp(self):
     Globals.options = Utility.initOptions()
     Utility.initLogging(Globals.options)
     self.view = NullRepositoryView()
     Utility.initTimezone(Globals.options, self.view)
Esempio n. 57
0
 def setUp(self):
     Globals.options = Utility.initOptions()
     Globals.options.ramdb = True
     Utility.initLogging(Globals.options)
     self.view = Utility.initRepository("", Globals.options, True)
     Utility.initTimezone(Globals.options, self.view)