Esempio n. 1
0
def boot(path, gtk=False, gst=True, installReactor=True):
    # python 2.5 and twisted < 2.5 don't work together
    pythonMM = sys.version_info[0:2]
    from twisted.copyright import version
    twistedMM = tuple([int(n) for n in version.split('.')[0:2]])
    if pythonMM >= (2, 5) and twistedMM < (2, 5):
        raise SystemError("Twisted versions older than 2.5.0 do not work with "
                          "Python 2.5 and newer.  "
                          "Please upgrade Twisted or downgrade Python.")

    if gtk or gst:
        init_gobject()

    if gtk:
        init_kiwi()

    if gst:
        from flumotion.configure import configure
        configure.gst_version = init_gst()

    global USE_GTK, USE_GST
    USE_GTK = gtk
    USE_GST = gst
    init_option_parser(gtk, gst)

    # installing the reactor could override our packager's import hooks ...
    if installReactor:
        from twisted.internet import gtk2reactor
        try:
            gtk2reactor.install(useGtk=gtk)
        except RuntimeError, e:
            safeprintf(sys.stderr, 'ERROR: %s\n', e)
            sys.exit(1)
Esempio n. 2
0
 def activate(self, shell):
     from twisted.internet import gtk2reactor
     try:
         gtk2reactor.install()
     except AssertionError, e:
         # sometimes it's already installed
         print e
Esempio n. 3
0
def client():
    from twisted.internet import gtk2reactor
    gtk2reactor.install()
    from twisted.internet import reactor
#    import gobject
#    reactor.callWhenRunning(gobject.threads_init)
#    gobject.threads_init()

    options = ClientOptions()
    options.parseOptions()

    from afm.ui.app import Application
    app = Application(options)

    reactor.addSystemEventTrigger('before', 'shutdown',
                                  logging.getLogger(__name__).info,
                                  'Stopping AFM Client')

    logging.getLogger(__name__).info("AFM Client Started")
    try:
        reactor.run()
    except KeyboardInterrupt:
        reactor.stop()
    except:
        raise
        from twisted.python import log
        log.err()
Esempio n. 4
0
 def activate(self, shell):
     from twisted.internet import gtk2reactor
     try:
         gtk2reactor.install()
     except AssertionError, e:
         # sometimes it's already installed
         self.warning("gtk2reactor already installed %r" % e)
Esempio n. 5
0
def cptsoul():
    # cmdline
    parser = ArgumentParser(prog='cptsoul')
    parser.add_argument('-v',
                        '--verbose',
                        action='count',
                        dest='verbose',
                        help='Set verbose mode',
                        default=0)
    parser.add_argument('-t',
                        action='store_true',
                        dest='tray',
                        help='Start in tray')
    parser.add_argument('-d',
                        action='store_true',
                        dest='debug',
                        help='Start with debug window')
    CptCommon.cmdline = parser.parse_args()
    # imports
    from twisted.internet import gtk2reactor
    gtk2reactor.install()
    from twisted.internet import reactor
    from cptsoul.config import createConfigFile
    from cptsoul.manager import Manager
    # start
    configLogging()
    CptCommon.config = createConfigFile()
    manager = Manager()
    manager()
    reactor.run()
Esempio n. 6
0
def install_reactor():
    from twisted.internet import gtk2reactor
    from twisted.internet.error import ReactorAlreadyInstalledError
    try:
        # needed for glib.idle_add, and signals
        gtk2reactor.install()
    except ReactorAlreadyInstalledError:
        pass
Esempio n. 7
0
def configure(factory):
    """Set the right reactor up and get the GUI going."""
    from twisted.internet import gtk2reactor
    gtk2reactor.install()
    gui = GUI(factory.realm)
    macros = {from_string("<page up>"): gui.forward_page_up_cb,
              from_string('<page down>'): gui.forward_page_down_cb,
              from_string("C-c"): gui.maybe_forward_copy_cb}
    factory.realm.macros.update(macros)
    factory.realm.baked_in_macros.update(macros)
Esempio n. 8
0
def main():
    from twisted.internet import gtk2reactor
    try:
        gtk2reactor.install()
    except:
        pass
    from twisted.internet import reactor
    con = pynaoqi.getDefaultConnection()
    notes = NotesMain(con)
    notes._w.show_all()
    reactor.run()
Esempio n. 9
0
def maybeInstallDBus():
    import shtoom.dbus
    if shtoom.dbus.isAvailable():
        try:
            from twisted.internet import glib2reactor
            glib2reactor.install()
        except:
            try:
                from twisted.internet import gtk2reactor
                gtk2reactor.install()
            except:
                shtoom.dbus._setUnavailable()
Esempio n. 10
0
def installDbusReactor():
    try:
        from twisted.internet import glib2reactor
        glib2reactor.install()
        return True
    except:
        try:
            from twisted.internet import gtk2reactor
            gtk2reactor.install()
            return True
        except:
            return False
Esempio n. 11
0
def installDbusReactor():
    try:
        from twisted.internet import glib2reactor
        glib2reactor.install()
        return True
    except:
        try:
            from twisted.internet import gtk2reactor
            gtk2reactor.install()
            return True
        except:
            return False
Esempio n. 12
0
File: shell.py Progetto: burst/burst
def installgtkreactor():
    import pynaoqi
    options = pynaoqi.getDefaultOptions()
    using_gtk = False
    if options.twisted and not options.nogtk:
        # Try to throw in gtk support
        try:
            from twisted.internet import gtk2reactor
            gtk2reactor.install()
            using_gtk = True
        except AssertionError, e:
            using_gtk = True
        except:
Esempio n. 13
0
def main():   
    """Launch the client.

    This is the main entry point. This will first initialise the GUI, then
    load the main module specified on the command line.
    """
    
    options = parser.parse_args()
    if options.module_directory != "":
        directory = options.module_directory
        import sys
        sys.path.append(directory)
    if options.gui == 'gtk':
        from twisted.internet import gtk2reactor
        gtk2reactor.install()
    
    from twisted.internet import reactor    
    modclass = load_file(options.modulename)
    factory = TelnetClientFactory(modclass.name, modclass.encoding, 
                                  options.modulename, reactor)

    if options.gui == 'gtk':
        from pymudclient.gui.gtkgui import configure
        factory.realm.gui = ImperianGui(factory.realm)

    configure(factory)
    factory.realm.module_settings_dir=options.settings_directory
    modinstance = factory.realm.load_module(modclass)
    factory.realm.gmcp_handler = modinstance.gmcp_handler
    

    modinstance.is_main(factory.realm)

    from twisted.internet import reactor

    #pylint kicks up a major fuss about these lines, but that's because 
    #Twisted does some hackery with the reactor namespace.
    #pylint: disable-msg=E1101

    reactor.connectTCP(modclass.host, modclass.port, factory)
    if not options.profile:
        reactor.run()
    else:
        import cProfile
        cProfile.runctx("reactor.run()", globals(), locals(),
                        filename = "pymudclient.prof")
Esempio n. 14
0
File: gui.py Progetto: alon/burst
def main(clazz=Joints):
    global con
    con = pynaoqi.getDefaultConnection(with_twisted=True)
    class Main(clazz):

        def _onDestroy(self, *args):
            super(Main, self)._onDestroy(*args)
            print "quitting.."
            reactor.stop()

    from twisted.internet import gtk2reactor
    try:
        gtk2reactor.install()
    except:
        pass
    window = Main(con)
    reactor.run()
Esempio n. 15
0
def run_gtk2(config):
    from twisted.internet import gtk2reactor
    gtk2reactor.install()
    from twisted.spread.ui import gtk2util
    sys.argv[:] = ['manhole']
    from twisted.manhole.ui import gtk2manhole
    o = config.opts
    defaults = {
        'host': o['host'],
        'port': o['port'],
        'identityName': o['user'],
        'password': o['password'],
        'serviceName': o['service'],
        'perspectiveName': o['perspective']
        }
    w = gtk2manhole.ManholeWindow()
    w.setDefaults(defaults)
    w.login()
Esempio n. 16
0
def main(argv):
    from mushin.common import log
    log.init()
    log.debug('maemo', 'main')

    from twisted.internet import gtk2reactor
    gtk2reactor.install()
    from twisted.internet import reactor

    # set paisley to non-strict since we only have simplejson on maemo
    from mushin.extern.paisley import pjson

    assert not pjson.STRICT

    log.logTwisted()

    reactor.callWhenRunning(start)

    reactor.run()
Esempio n. 17
0
def main():
    from twisted.internet import gtk2reactor
    reactor = gtk2reactor.install()

    from fbuploader.main_window import MainWindow
    log.info('Starting Main Window')
    main_window = MainWindow()
    main_window.show()

    reactor.run()
Esempio n. 18
0
def main(application):
    import gnome
    global gnomeProgram
    gnomeProgram = gnome.init("Shtoom", "Whatever Version")

    from twisted.internet import gtk2reactor
    gtk2reactor.install()

    from shtoom.ui.gnomeui.main import ShtoomWindow

    UI = ShtoomWindow()
    UI.connectApplication(application)

    from shtoom import log
    if application.getPref('stdout'):
        import sys
        log.startLogging(sys.stdout, setStdout=False)
    else:
        log.startLogging(UI.getLogger(), setStdout=False)

    return UI
Esempio n. 19
0
def main(application):
    import gnome
    global gnomeProgram
    gnomeProgram = gnome.init("Shtoom", "Whatever Version")

    from twisted.internet import gtk2reactor
    gtk2reactor.install()

    from shtoom.ui.gnomeui.main import ShtoomWindow

    UI = ShtoomWindow()
    UI.connectApplication(application)

    from shtoom import log
    if application.getPref('stdout'):
        import sys
        log.startLogging(sys.stdout, setStdout=False)
    else:
        log.startLogging(UI.getLogger(), setStdout=False)

    return UI
Esempio n. 20
0
def run_gtk2(config):
    # Put these off until after we parse options, so we know what reactor
    # to load.
    from twisted.internet import gtk2reactor
    gtk2reactor.install()

    # Put this off until after we parse options, or else gnome eats them.
    sys.argv[:] = ['manhole']
    from twisted.manhole.ui import gtk2manhole

    o = config.opts
    defaults = {
        'host': o['host'],
        'port': o['port'],
        'identityName': o['user'],
        'password': o['password'],
        'serviceName': o['service'],
        'perspectiveName': o['perspective']
        }
    w = gtk2manhole.ManholeWindow()
    w.setDefaults(defaults)
    w.login()
def run_gtk2(config):
    # Put these off until after we parse options, so we know what reactor
    # to load.
    from twisted.internet import gtk2reactor
    gtk2reactor.install()

    # Put this off until after we parse options, or else gnome eats them.
    sys.argv[:] = ['manhole']
    from twisted.manhole.ui import gtk2manhole

    o = config.opts
    defaults = {
        'host': o['host'],
        'port': o['port'],
        'identityName': o['user'],
        'password': o['password'],
        'serviceName': o['service'],
        'perspectiveName': o['perspective']
        }
    w = gtk2manhole.ManholeWindow()
    w.setDefaults(defaults)
    w.login()
Esempio n. 22
0
File: gtk.py Progetto: lzimm/360io
def main(argv, reactor=None):
    """Run the client GUI.

    Typical use:
    >>> sys.exit(main(sys.argv))

    @param argv: The arguments to run it with, e.g. sys.argv.
    @param reactor: The reactor to use. Must be compatible with gtk as this
        module uses gtk API"s.
    @return exitcode: The exit code it returned, as per sys.exit.
    """
    if reactor is None:
        from twisted.internet import gtk2reactor
        gtk2reactor.install()
        from twisted.internet import reactor
    try:
        AWSStatusIcon(reactor)
        gobject.set_application_name("aws-status")
        reactor.run()
    except ValueError:
        # In this case, the user cancelled, and the exception bubbled to here.
        pass
Esempio n. 23
0
def run_gtk2(config):
    # Put these off until after we parse options, so we know what reactor
    # to load.
    from twisted.internet import gtk2reactor

    gtk2reactor.install()

    # Put this off until after we parse options, or else gnome eats them.
    sys.argv[:] = ["manhole"]
    from twisted.manhole.ui import gtk2manhole

    o = config.opts
    defaults = {
        "host": o["host"],
        "port": o["port"],
        "identityName": o["user"],
        "password": o["password"],
        "serviceName": o["service"],
        "perspectiveName": o["perspective"],
    }
    w = gtk2manhole.ManholeWindow()
    w.setDefaults(defaults)
    w.login()
def maybeInstallReactor():
    import sys
    try:
        from twisted.internet import gtk3reactor  # s/2/3 if you're using gtk3
        reactor = gtk3reactor.install()
        reactor.startRunning()
        reactor._simulate()
        return reactor
    except:
        try:
            from twisted.internet import gtk2reactor
            reactor = gtk2reactor.install()
            reactor.startRunning()
            reactor._simulate()
            return reactor
        except:
            print "This plugin requires twisted to be installed"
            exit(-1)
def maybeInstallReactor():
    import sys
    try:
        from twisted.internet import gtk3reactor # s/2/3 if you're using gtk3
        reactor = gtk3reactor.install()
        reactor.startRunning()
        reactor._simulate()
        return reactor
    except:
        try:
            from twisted.internet import gtk2reactor
            reactor = gtk2reactor.install()
            reactor.startRunning()
            reactor._simulate()
            return reactor
        except:
            print "This plugin requires twisted to be installed"
            exit(-1)
Esempio n. 26
0
 def install():
   """Start up the Twisted networking support.  Returns the new, running reactor."""
   #This works fine anyway I think?  Not really sure why this is here, just keeping it how it was in Twisted
   if runtime.platform.getType() == 'posix':
     reactor = gtk2reactor.install(ProgramState.USE_GTK)
   #Windows needs this custom class
   else:
     try:
       reactor = GtkReactor()
       installReactor(reactor)
     except socket.error, e:
       #NOTE:  10022 is a bit suspect.  I saw it once (it's "invalid argument"), 
       #but it can apparently happen in cases that might be caused by a firewall...
       #10013 is "forbidden"
       #10047 is "cannot bind"
       #10049 is "Can't assign requested address"
       if e[0] not in (10013, 10047, 10049, 10022):
         raise e
       import win32api
       win32api.MessageBox(0, "You must allow incoming and outgoing connections for both BitBlinder.exe and Tor.exe in your firewall.  Otherwise, BitBlinder will not work correctly.", "Firewalled")
       sys.exit(-5)
Esempio n. 27
0
# Copyright (c) 2014 Sartaj Singh
# Licensed under the MIT license.
##

"""
Development script
To run without actually installing
Picks up local changes
"""

# system imports
import sys

# twisted imports
from twisted.internet import gtk2reactor
gtk2reactor.install() # install reactor for gui
from twisted.internet import reactor

# Other imports
import main
from client import options

if __name__ == '__main__':
    args = options.parse_args() # parse the arguments

    addresses = []
    client = args.client
    host, port, server = args.iface, args.port, args.server
    if host != None:
        addresses.append((host, port, server))
    try:
Esempio n. 28
0
def install_gtk2(app): # not tested
    del sys.modules['twisted.internet.reactor']
    from twisted.internet import gtk2reactor
    gtk2reactor.install()
    from twisted.internet import reactor
Esempio n. 29
0
def run():
    """
    Runs the application.
    """
    parser = OptionParser(usage="%prog [config file] [options]",
                          version="%prog " + __version__,
                          description=DESCRIPTION)
    parser.add_option(
        "-f",
        "--config-file",
        type="string",
        help=
        "Specifies the python config file. You can also simply specify the config file as the first argument."
    )
    parser.add_option(
        "-l",
        "--logging-directory",
        type="string",
        default="/var/tmp/lunch",
        help=
        "Specifies the logging and pidfile directory for the master. Default is /var/tmp/lunch"
    )
    parser.add_option(
        "-q",
        "--log-to-file",
        action="store_true",
        help=
        "Enables logging master infos to file and disables logging to standard output."
    )
    parser.add_option("-g",
                      "--graphical",
                      action="store_true",
                      help="Enables the graphical user interface.")
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      help="Makes the logging output verbose.")
    parser.add_option("-d",
                      "--debug",
                      action="store_true",
                      help="Makes the logging output very verbose.")
    parser.add_option(
        "-k",
        "--kill",
        action="store_true",
        help=
        "Kills another lunch master that uses the same config file and logging directory. Exits once it's done."
    )
    (options, args) = parser.parse_args()
    # --------- set configuration file
    if options.config_file:
        config_file = options.config_file
    DEFAULT_CONFIG_FILE = os.path.expanduser("~/.lunchrc")
    if len(args) == 1 and not options.config_file:
        #log.msg("DEBUG: overriding config_file with %s" % (args[0]))
        config_file = args[0]
    else:
        config_file = DEFAULT_CONFIG_FILE
    # --------- set if logging
    if options.log_to_file:
        file_logging_enabled = True
    else:
        file_logging_enabled = False
    logging_dir = options.logging_directory

    # ---------- load the right reactor
    if options.graphical:
        try:
            from twisted.internet import gtk2reactor
            gtk2reactor.install()  # has to be done before importing reactor
            import gtk  # just for a test
            GUI_ENABLED = True
            #print("Successfully loaded the GTK+ graphical user interface.")
        except ImportError, e:
            print("Could not load the GTK+ graphical user interface. " +
                  str(e))
            GUI_ENABLED = False
Esempio n. 30
0
OTHER DEALINGS IN THE SOFTWARE.
"""

import os, sys, platform, subprocess, locale, pickle, json, psutil

import pygtk
pygtk.require('2.0')
import gtk

SHARE = os.getenv('TBL_SHARE', sys.prefix+'/share/torbrowser-launcher')

import gettext
gettext.install('torbrowser-launcher', os.path.join(SHARE, 'locale'))

from twisted.internet import gtk2reactor
gtk2reactor.install()

class Common:

    def __init__(self, tbl_version):
        self.tbl_version = tbl_version

        # initialize the app
        self.default_mirror = 'https://dist.torproject.org/'
        self.discover_arch_lang()
        self.build_paths()
        for d in self.paths['dirs']:
            self.mkdir(self.paths['dirs'][d])
        self.load_mirrors()
        self.load_settings()
        self.mkdir(self.paths['download_dir'])
Esempio n. 31
0
#** All rights reserved
#** Modification, distribution, and sale of this work is prohibited without
#**  permission from Washington State University
#**
#** If this code is used for public research, any resulting publications need
#** to cite work done by Brian L. Thomas at the Center for Advanced Study of
#** Adaptive Systems (CASAS) at Washington State University.
#**
#** Contact: Brian L. Thomas ([email protected])
#** Contact: Diane J. Cook ([email protected])
#*****************************************************************************#
import sys

if "pygtk" in sys.modules:
    from twisted.internet import gtk2reactor
    gtk2reactor.install()

from twisted.words.protocols.jabber import client, jid, xmlstream
from twisted.words.xish import domish
from twisted.internet import reactor

import copy
import datetime
import json
import re
import signal
import time
import uuid
import xml.dom.minidom
import xml.etree.ElementTree as ETree
import xml.parsers.expat
Esempio n. 32
0
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Lunch is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Lunch.  If not, see <http://www.gnu.org/licenses/>.
"""
Main GUI of the Lunch Master 
"""
if __name__ == "__main__":
    from twisted.internet import gtk2reactor
    gtk2reactor.install() # has to be done before importing reactor
from twisted.internet import reactor
from twisted.internet import defer
from twisted.internet import utils
from twisted.python import procutils

import gtk
import pango
import sys
import os
import textwrap
import webbrowser
from lunch import __version__
from lunch import dialogs
from lunch.states import *
from lunch import logger
Esempio n. 33
0
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members


from twisted.internet import gtk2reactor
gtk2reactor.install()  # @UndefinedVariable

import sys
import time

import pygtk  # @UnresolvedImport
pygtk.require("2.0")
import gobject
import gtk  # @UnresolvedImport
assert(gtk.Window)  # in gtk1 it's gtk.GtkWindow

from twisted.spread import pb

#from buildbot.clients.base import Builder, Client
from buildbot.clients.base import StatusClient
from buildbot.clients.text import TextClient
Esempio n. 34
0
def boot(path, gtk=False, gst=True, installReactor=True):
    # python 2.5 and twisted < 2.5 don't work together
    pythonMM = sys.version_info[0:2]
    from twisted.copyright import version
    twistedMM = tuple([int(n) for n in version.split('.')[0:2]])
    if pythonMM >= (2, 5) and twistedMM < (2, 5):
        raise SystemError("Twisted versions older than 2.5.0 do not work with "
                          "Python 2.5 and newer.  "
                          "Please upgrade Twisted or downgrade Python.")

    if gtk or gst:
        init_gobject()

    if gtk:
        init_kiwi()

    if gst:
        from flumotion.configure import configure
        configure.gst_version = init_gst()

    global USE_GTK, USE_GST
    USE_GTK = gtk
    USE_GST = gst
    init_option_parser(gtk, gst)

    # installing the reactor could override our packager's import hooks ...
    if installReactor:
        from twisted.internet import gtk2reactor
        gtk2reactor.install(useGtk=gtk)
    from twisted.internet import reactor

    # ... so we install them again here to be safe
    from flumotion.common import package
    package.getPackager().install()

    # this monkeypatched var exists to let reconnecting factories know
    # when they should warn about a connection being closed, and when
    # they shouldn't because the system is shutting down.
    #
    # there is no race condition here -- the reactor doesn't handle
    # signals until it is run().
    reactor.killed = False

    def setkilled(killed):
        reactor.killed = killed

    reactor.addSystemEventTrigger('before', 'startup', setkilled, False)
    reactor.addSystemEventTrigger('before', 'shutdown', setkilled, True)

    from flumotion.twisted import reflect
    from flumotion.common import errors
    from flumotion.common import setup

    setup.setup()

    from flumotion.common import log
    log.logTwisted()

    main = reflect.namedAny(path)

    wrapped = wrap_for_profiling(main)
    wrapped.__name__ = main.__name__

    try:
        sys.exit(wrapped(sys.argv))
    except (errors.FatalError, SystemError), e:
        safeprintf(sys.stderr, 'ERROR: %s\n', e)
        sys.exit(1)
Esempio n. 35
0
import gtk
from twisted.internet.protocol import Protocol, ClientCreator
from twisted.internet import gtk2reactor # for gtk-2.0
gtk2reactor.install() #this installs the gtk reactor

class MyProg(Protocol):
	button_send_data = []
	larr = ""
	text = ""

	def sendMessage(self, msg):
                self.transport.write("%s\n" % msg)

        def dataReceived(self, data):
                self.larr.get_buffer().insert_at_cursor(data)

	def window(self):
#                app_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		app_window =gtk.Dialog()
                app_window.set_size_request(500, 350)
                app_window.set_border_width(10)
                app_window.set_title("Chat Client")
                app_window.connect("delete_event", lambda w,e: gtk.main_quit())
                app_window.show()
                return app_window

	def entry(self, w):
                entry = gtk.Entry()
                entry.set_max_length(80)
                entry.set_width_chars(50)
                entry.connect("changed", self.enter_callback, entry)
Esempio n. 36
0
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members

from twisted.internet import gtk2reactor
gtk2reactor.install()  #@UndefinedVariable

import sys, time

import pygtk  #@UnresolvedImport
pygtk.require("2.0")
import gobject, gtk  #@UnresolvedImport
assert (gtk.Window)  # in gtk1 it's gtk.GtkWindow

from twisted.spread import pb

#from buildbot.clients.base import Builder, Client
from buildbot.clients.base import TextClient, StatusClient
from buildbot.util import now

from buildbot.status.builder import SUCCESS, WARNINGS, FAILURE, EXCEPTION
Esempio n. 37
0
#    You must obey the GNU General Public License in all respects for all of
#    the code used other than OpenSSL. If you modify file(s) with this
#    exception, you may extend this exception to your version of the file(s),
#    but you are not obligated to do so. If you do not wish to do so, delete
#    this exception statement from your version. If you delete this exception
#    statement from all source files in the program, then also delete it here.
#
#
from deluge.log import LOG as log

import gobject
gobject.set_prgname("deluge")

# Install the twisted reactor
from twisted.internet import gtk2reactor
reactor = gtk2reactor.install()

import gettext
import locale
import pkg_resources
import gtk, gtk.glade
import sys

try:
    from setproctitle import setproctitle, getproctitle
except ImportError:
    setproctitle = lambda t: None
    getproctitle = lambda: None

# Initialize gettext
try:
Esempio n. 38
0
def run():
    """
    Main function of the application
    """
    from scenic import configure

    # command line parsing
    parser = OptionParser(usage="%prog",
                          version=str(configure.VERSION),
                          description=configure.DESCRIPTION)
    parser.add_option("-k",
                      "--kiosk",
                      action="store_true",
                      help="Run in kiosk mode")
    parser.add_option("-l",
                      "--enable-logging",
                      action="store_true",
                      help="Enables logging to file.")
    parser.add_option(
        "-L",
        "--log-file-name",
        type="string",
        help=
        "Specifies the path to the log file. Default is %s. Logging must be enabled for this option value to be useful."
        % (LOG_FILE_NAME),
        default=LOG_FILE_NAME)
    parser.add_option("-f",
                      "--fullscreen",
                      action="store_true",
                      help="Run in fullscreen mode")
    parser.add_option(
        "-n",
        "--disable-v4l2-settings-restoration",
        action="store_true",
        help=
        "Disables the state restoring for the V4L2 input number and video standard at startup"
    )
    parser.add_option(
        "-v",
        "--verbose",
        action="store_true",
        help="Enables a verbose logging output with info level messages.")
    parser.add_option(
        "-d",
        "--debug",
        action="store_true",
        help=
        "Enables a very verbose logging output with debug level messages. Also add a debug tab in the user interface."
    )
    parser.add_option("-M",
                      "--moo",
                      action="store_true",
                      help="There is no easter egg in this program")
    (options, args) = parser.parse_args()

    if not os.environ.has_key('DISPLAY'):
        print "You need an X11 display to run Scenic."
        sys.exit(1)
    level = "warning"
    if options.verbose:
        level = "info"
    if options.debug:
        level = "debug"
    if options.enable_logging:
        start_file_logging(level, os.path.expanduser(options.log_file_name))
        log_file_name = options.log_file_name
    else:
        start_logging_to_stdout(level)
    log_file_name = None
    # FIXME: why are we setting log_file_name to Null before passing it to the Application contructor?

    from scenic import process
    process.save_environment_variables(os.environ)

    if not os.environ.has_key(
            'GTK2_RC_FILES'):  # FIXME: is this check needed and desired?
        name = "Darklooks"
        file_name = os.path.join(
            os.path.join(configure.THEMES_DIR, name, "gtkrc"))
        os.environ[
            "GTK2_RC_FILES"] = file_name  # has to be done before gtk2reactor.install()
    if "/sbin" not in os.environ["PATH"]:  # for ifconfig
        os.environ["PATH"] += ":/sbin"

    from twisted.internet import gtk2reactor
    gtk2reactor.install()  # has to be done before importing reactor
    from twisted.internet import reactor
    from twisted.internet import error
    from scenic import application
    import gtk

    try:
        gtk.gdk.Display(os.environ["DISPLAY"])
    except RuntimeError, e:
        msg = "Invalid X11 display: %s. \nYou need an X11 display to run Scenic." % (
            os.environ["DISPLAY"])
        log.error(msg)
        print msg
        sys.exit(1)
Esempio n. 39
0
def install_gtk2():
    """ Install gtk2 reactor, needs to be called bef """
    from twisted.internet import gtk2reactor
    gtk2reactor.install()
Esempio n. 40
0
def install():
    """Configure the twisted mainloop to be run inside the glib mainloop.
    """
    return gtk2reactor.install(False)
Esempio n. 41
0
#!/usr/bin/env python
'''
Modified on 2014-11-07

Created on 2009-11-15

@original_author: [email protected]
'''

from twisted.internet import gtk2reactor

gtk2reactor.install(True)

from twisted.internet import reactor, defer
from twisted.internet.protocol import ReconnectingClientFactory
from starpy.manager import AMIProtocol, AMIFactory
from twisted.internet import task
import logging
import logging.handlers
import yaml

from pyslack import SlackClient

#asterisk AMI login
server = "ASTRISKSERVERNAME"
port = 5038
username = "******"
secret = "PASSWORD"
extensions = {"SIP/200": "YOU", "SIP/201": "Someone else"}

log = logging.getLogger("server")
Esempio n. 42
0
def entry():
    """
    """

    ## Phase 1:
    ##  cortex should not have been imported anywhere, so
    ##  we should not have already chosen a twisted reactor.
    ##  do as much as we can before importing anything else,
    ##  to keep the bootstrap sacred
    parser        = build_parser()
    options, args = parser.parse_args()
    nodeconf_file = options.conf

    #  python interpretter compatability:
    #    shell$ cortex -c"import cortex; print cortex.__file__"
    if args and len(args)==1:
        fname = args[0]
        if os.path.exists(fname):
            print "cortex: assuming this is a file.."
            interpreter = Interpreter(fname)

            sandbox = interpreter.namespace()
            interpreter.ex(sandbox)
            instructions = sandbox.get('__instructions__', [])
            agent_specs = sandbox.get('__agents__', [])
            if instructions and options.conf:
                raise RuntimeError(
                    "cant use '__instructions__' and "
                    "still pass --conf="+options.conf)
            elif not instructions and options.conf:
                sandbox['__universe__'].nodeconf_file = options.conf
            elif instructions and not options.conf:
                sandbox['__universe__'].set_instructions(instructions)

            for agent_spec in agent_specs:
                if isinstance(agent_spec, (list,tuple)):
                    args, kargs = agent_spec
                else:
                    args, kargs = [agent_spec], {}
                sandbox['__universe__'].agents.manage(*args, **kargs)

            if '.play()' not in open(fname).read():
                # FIXME: hack
                report_if_verbose("This file did not start the universe.  allow me")
                sandbox['__universe__'].play()
            report_if_verbose("finished running this universe.")
            return

    # use the gtk-reactor?
    if options.gtk_reactor:
        print "using gtk reactor"
        from twisted.internet import gtk2reactor # for gtk-2.0
        gtk2reactor.install()

    ## Phase 2:
    ##  trigger the first cortex imports.
    ##  there goes the neighborhood.
    from cortex.core.universe import Universe
    from cortex.bin.phase2 import install_nodeconf
    from cortex.bin.client import use_client
    from cortex.contrib.reloading_helpers import run as RUN
    #Universe.directives = options.directives.split(",")

    # reflect command-line options in universe's config
    olist = [ x for x in dir(options) if not x.startswith('_') \
              and x not in 'read_file read_module ensure_value'.split() ]
    [setattr(Universe.command_line_options, x, getattr(options,x)) for x in olist]
    if options.verbose:
        import cortex
        cortex.VERBOSE = True

    # use the cortex api client?
    if options.client:
        return use_client(options, args)

    #  python interpretter compatability:
    #    shell$ cortex -c"print 3"
    #  NB: comes after options.client because it might want to consume that
    elif options.command:
        exec(options.command)
        return

    # run tests?
    if options.run_tests:
        from cortex.tests import main
        return main()

    # deserialize a saved universe and resume it?
    if options.universe:
        verify_file(options.universe)
        U = pickle.loads(open(options.universe).read())
        return U.play() # Invoke the Universe


    ## After this point it's assumed we're using a node-conf,
    ## whether it is specified explicitly or assumed.  the cases for
    ## the command-line options should not use 'return'

    # augment nodeconf with additional services?
    if options.services:
        from cortex.core import api
        services = options.services.split(',')
        for s in services:
            api.do([['load_service', (s.strip(),), {}]])

    if nodeconf_file:
        verify_file(nodeconf_file)
        install_nodeconf(nodeconf_file, options, args)
        return Universe.play() # Invoke the Universe
Esempio n. 43
0
def run():
    from twisted.internet import gtk2reactor
    gtk2reactor.install()
    app.run_app(app.LockedApplication(make_application), app.Options())
Esempio n. 44
0
# lots of little imports done before anything else so that
# we don't get weird stray module errors

from flumotion.common import boot

boot.init_gobject()
boot.init_gst()

import gst
import gst.interfaces
e = gst.element_factory_make('fakesrc')

from twisted.internet import gtk2reactor
gtk2reactor.install(useGtk=True)

import pyexpat

# fake out pychecker
import gobject
import gtk
import gtk.glade
loop = gobject.MainLoop()
gtk.main_iteration()

m = pyexpat
Esempio n. 45
0
def run():
    """
    Runs the application.
    """
    parser = OptionParser(
        usage="%prog [config file] [options]", version="%prog " + __version__, description=DESCRIPTION
    )
    parser.add_option(
        "-f",
        "--config-file",
        type="string",
        help="Specifies the python config file. You can also simply specify the config file as the first argument.",
    )
    parser.add_option(
        "-l",
        "--logging-directory",
        type="string",
        default="/var/tmp/lunch",
        help="Specifies the logging and pidfile directory for the master. Default is /var/tmp/lunch",
    )
    parser.add_option(
        "-q",
        "--log-to-file",
        action="store_true",
        help="Enables logging master infos to file and disables logging to standard output.",
    )
    parser.add_option("-g", "--graphical", action="store_true", help="Enables the graphical user interface.")
    parser.add_option("-v", "--verbose", action="store_true", help="Makes the logging output verbose.")
    parser.add_option("-d", "--debug", action="store_true", help="Makes the logging output very verbose.")
    parser.add_option(
        "-k",
        "--kill",
        action="store_true",
        help="Kills another lunch master that uses the same config file and logging directory. Exits once it's done.",
    )
    (options, args) = parser.parse_args()
    # --------- set configuration file
    if options.config_file:
        config_file = options.config_file
    DEFAULT_CONFIG_FILE = os.path.expanduser("~/.lunchrc")
    if len(args) == 1 and not options.config_file:
        # log.msg("DEBUG: overriding config_file with %s" % (args[0]))
        config_file = args[0]
    else:
        config_file = DEFAULT_CONFIG_FILE
    # --------- set if logging
    if options.log_to_file:
        file_logging_enabled = True
    else:
        file_logging_enabled = False
    logging_dir = options.logging_directory

    # ---------- load the right reactor
    if options.graphical:
        try:
            from twisted.internet import gtk2reactor

            gtk2reactor.install()  # has to be done before importing reactor
            import gtk  # just for a test

            GUI_ENABLED = True
            # print("Successfully loaded the GTK+ graphical user interface.")
        except ImportError, e:
            print("Could not load the GTK+ graphical user interface. " + str(e))
            GUI_ENABLED = False
Esempio n. 46
0
# lots of little imports done before anything else so that
# we don't get weird stray module errors

from flumotion.common import boot

boot.init_gobject()
boot.init_gst()

import gst
import gst.interfaces

e = gst.element_factory_make("fakesrc")

from twisted.internet import gtk2reactor

gtk2reactor.install(useGtk=True)

import pyexpat

# fake out pychecker
import gobject
import gtk
import gtk.glade

loop = gobject.MainLoop()
gtk.main_iteration()

m = pyexpat
Esempio n. 47
0
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Lunch is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Lunch.  If not, see <http://www.gnu.org/licenses/>.
"""
Main GUI of the Lunch Master 
"""
if __name__ == "__main__":
    from twisted.internet import gtk2reactor
    gtk2reactor.install()  # has to be done before importing reactor
from twisted.internet import reactor
from twisted.internet import defer
from twisted.internet import utils
from twisted.python import procutils

import gtk
import pango
import sys
import os
import textwrap
import webbrowser
from lunch import __version__
from lunch import dialogs
from lunch.states import *
from lunch import logger
Esempio n. 48
0
def boot(path, gtk=False, gst=True, installReactor=True):
    # python 2.5 and twisted < 2.5 don't work together
    pythonMM = sys.version_info[0:2]
    from twisted.copyright import version
    twistedMM = tuple([int(n) for n in version.split('.')[0:2]])
    if pythonMM >= (2, 5) and twistedMM < (2, 5):
        raise SystemError(
            "Twisted versions older than 2.5.0 do not work with "
            "Python 2.5 and newer.  "
            "Please upgrade Twisted or downgrade Python.")

    if gtk or gst:
        init_gobject()

    if gst:
        from flumotion.configure import configure
        configure.gst_version = init_gst()

    global USE_GTK, USE_GST
    USE_GTK=gtk
    USE_GST=gst
    init_option_parser(gtk, gst)

    # installing the reactor could override our packager's import hooks ...
    if installReactor:
        from twisted.internet import gtk2reactor
        gtk2reactor.install(useGtk=gtk)
    from twisted.internet import reactor

    # ... so we install them again here to be safe
    from flumotion.common import package
    package.getPackager().install()

    # this monkeypatched var exists to let reconnecting factories know
    # when they should warn about a connection being closed, and when
    # they shouldn't because the system is shutting down.
    #
    # there is no race condition here -- the reactor doesn't handle
    # signals until it is run().
    reactor.killed = False

    def setkilled(killed):
        reactor.killed = killed

    reactor.addSystemEventTrigger('before', 'startup', setkilled, False)
    reactor.addSystemEventTrigger('before', 'shutdown', setkilled, True)

    from flumotion.twisted import reflect
    from flumotion.common import errors
    from flumotion.common import setup

    setup.setup()

    from flumotion.common import log
    log.logTwisted()

    # we redefine catching
    __pychecker__ = 'no-reuseattr'

    if os.getenv('FLU_PROFILE'):

        def catching(proc, *args, **kwargs):
            import statprof
            statprof.start()
            try:
                return proc(*args, **kwargs)
            finally:
                statprof.stop()
                statprof.display()
    elif os.getenv('FLU_ATEXIT'):

        def catching(proc, *args, **kwargs):
            env = os.getenv('FLU_ATEXIT').split(' ')
            fqfn = env.pop(0)
            log.info('atexit', 'FLU_ATEXIT set, will call %s(*%r) on exit',
                     fqfn, env)
            atexitproc = reflect.namedAny(fqfn)

            try:
                return proc(*args, **kwargs)
            finally:
                log.info('atexit', 'trying to call %r(*%r)',
                         atexitproc, env)
                atexitproc(*env)
    else:

        def catching(proc, *args, **kwargs):
            return proc(*args, **kwargs)

    main = reflect.namedAny(path)

    try:
        sys.exit(catching(main, sys.argv))
    except (errors.FatalError, SystemError), e:
        safeprintf(sys.stderr, 'ERROR: %s\n', e)
        sys.exit(1)
Esempio n. 49
0
#
# Copyright (c) 2014 Sartaj Singh
# Licensed under the MIT license.
##
"""
Development script
To run without actually installing
Picks up local changes
"""

# system imports
import sys

# twisted imports
from twisted.internet import gtk2reactor
gtk2reactor.install()  # install reactor for gui
from twisted.internet import reactor

# Other imports
import main
from client import options

if __name__ == '__main__':
    args = options.parse_args()  # parse the arguments

    addresses = []
    client = args.client
    host, port, server = args.iface, args.port, args.server
    if host != None:
        addresses.append((host, port, server))
    try:
Esempio n. 50
0
def install():
    """Configure the twisted mainloop to be run inside the glib mainloop.
    """
    return gtk2reactor.install(False)
Esempio n. 51
0
    print "Not importing misc.setup"
    pass

# we import docutils before installing the packager to prevent
# messing with the datadir which causes epydoc to crash
try:
    import docutils
except ImportError:
    print "Not importing docutils"
    pass

from flumotion.common import boot
boot.init_gobject()
boot.init_gst()
from twisted.internet import gtk2reactor
gtk2reactor.install(useGtk=False)

# reinstall our import hooks that could have been overridden by
# pygtk/pygst ltihooks
from flumotion.common import package
package.getPackager().install()

# monkey patching twisted doc errors
from twisted.spread import pb


def login(self, credentials, client=None):
    """Login and get perspective from remote PB server.

    Currently only credentials implementing IUsernamePassword are
    supported.
Esempio n. 52
0
def install_gtk2():
    """ Install gtk2 reactor, needs to be called bef """
    from twisted.internet import gtk2reactor
    gtk2reactor.install()
Esempio n. 53
0
def start_client(interacting_function, queue_dict):
    from rafcon.gui.config import global_gui_config
    import os

    from rafcon.gui.controllers.main_window import MainWindowController
    from rafcon.gui.views.main_window import MainWindowView
    import rafcon.gui.singleton as gui_singletons
    from rafcon.gui.runtime_config import global_runtime_config
    from rafcon.gui.start import signal_handler

    import rafcon
    from rafcon.utils import log
    from rafcon.utils import plugins

    from rafcon.core.config import global_config
    from rafcon.core.storage import storage as global_storage
    from rafcon.core.state_machine import StateMachine
    from rafcon.core.states.hierarchy_state import HierarchyState
    import rafcon.core.singleton as core_singletons
    from rafcon.core.start import setup_environment

    # load all plugins specified in the RAFCON_PLUGIN_PATH
    plugins.load_plugins()
    import testing_utils

    # check if twisted is imported
    if "twisted" in sys.modules.keys():
        from twisted.internet import gtk2reactor
        # needed for glib.idle_add, and signals
        gtk2reactor.install()
        from twisted.internet import reactor
    else:
        print "Twisted not imported! Thus the gkt2reatcor is not installed!"
        exit()

    plugins.run_pre_inits()

    setup_logger()
    logger = log.get_logger("start")
    logger.info("RAFCON launcher")

    setup_environment()

    signal.signal(signal.SIGINT, signal_handler)

    global_config.load(path=os.path.dirname(os.path.abspath(__file__)))
    global_gui_config.load(path=os.path.dirname(os.path.abspath(__file__)))
    global_runtime_config.load(path=os.path.dirname(os.path.abspath(__file__)))

    setup_config = dict()
    setup_config["net_config_path"] = os.path.abspath(path=os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "client"))

    # Initialize library
    core_singletons.library_manager.initialize()

    # Create the GUI
    main_window_view = MainWindowView()

    state_machine = global_storage.load_state_machine_from_path(
        testing_utils.get_test_sm_path(
            os.path.join("unit_test_state_machines",
                         "99_bottles_of_beer_monitoring")))

    sm_id = rafcon.core.singleton.state_machine_manager.add_state_machine(
        state_machine)
    rafcon.core.singleton.state_machine_manager.active_state_machine_id = sm_id

    sm_manager_model = gui_singletons.state_machine_manager_model
    main_window_controller = MainWindowController(sm_manager_model,
                                                  main_window_view)

    plugins.run_post_inits(setup_config)

    import threading
    # this is not recognized by pycharm as the module is loaded in plugins.load_plugins()
    from monitoring.monitoring_manager import global_monitoring_manager
    interacting_thread = threading.Thread(
        target=interacting_function,
        args=[main_window_controller, global_monitoring_manager, queue_dict])
    testing_utils.wait_for_gui()
    interacting_thread.start()

    # check if twisted is imported
    if "twisted" in sys.modules.keys():
        reactor.run()
    else:
        logger.error(
            "Client: Twisted is not in sys.modules or twisted is not working! Exiting program ... !"
        )
        os._exit(0)

    logger.info("Joined root state")

    # If there is a running state-machine, wait for it to be finished before exiting
    sm = core_singletons.state_machine_manager.get_active_state_machine()
    if sm:
        sm.root_state.join()

    logger.info("Exiting ...")

    # this is a ugly process shutdown method but works if gtk or twisted process are still blocking
    os._exit(0)
Esempio n. 54
0
# vi:si:et:sw=4:sts=4:ts=4

# PYTHONPATH should be set so that if this is part of a Flumotion project,
# it points to misc so we can import setup.py from there
try:
    from misc import setup
    setup.setup()
except ImportError:
    print "Not importing misc.setup"
    pass

from flumotion.common import boot
boot.init_gobject()
boot.init_gst()
from twisted.internet import gtk2reactor
gtk2reactor.install(useGtk=False)

# reinstall our import hooks that could have been overridden by
# pygtk/pygst ltihooks
from flumotion.common import package
package.getPackager().install()

# monkey patching twisted doc errors
from twisted.spread import pb


def login(self, credentials, client=None):
    """Login and get perspective from remote PB server.

    Currently only credentials implementing IUsernamePassword are
    supported.
Esempio n. 55
0
# Copyright (c) 2009 Entertainer Developers - See COPYING - GPLv2
'''Entertainer client.'''

import sys

import gtk
from twisted.internet import gtk2reactor

gtk2reactor.install(
)  # Install the gtk2 reactor before import the real reactor
from twisted.internet import reactor
from twisted.internet.protocol import ClientCreator
from twisted.python.log import startLogging

from entertainerlib.client.medialibrary.music import MusicLibrary
from entertainerlib.client.medialibrary.images import ImageLibrary
from entertainerlib.client.medialibrary.videos import VideoLibrary
from entertainerlib.configuration import Configuration
from entertainerlib.gui.user_interface import UserInterface
from entertainerlib.gui.system_tray_icon import SystemTrayIcon
from entertainerlib.network.local.client import EntertainerLocalClientProtocol


class Client(object):
    '''This is a client application of Entertainer. Entertainer's client
    hooks into the server, and then provides a user interface for the data the
    server creates.'''
    def __init__(self):
        config = Configuration()
        music_library = MusicLibrary()
        image_library = ImageLibrary()
Esempio n. 56
0
#    You must obey the GNU General Public License in all respects for all of
#    the code used other than OpenSSL. If you modify file(s) with this
#    exception, you may extend this exception to your version of the file(s),
#    but you are not obligated to do so. If you do not wish to do so, delete
#    this exception statement from your version. If you delete this exception
#    statement from all source files in the program, then also delete it here.
#
#
from deluge.log import LOG as log

import gobject
gobject.set_prgname("deluge")

# Install the twisted reactor
from twisted.internet import gtk2reactor
reactor = gtk2reactor.install()

import gettext
import locale
import pkg_resources
import gtk, gtk.glade
import sys

try:
    from setproctitle import setproctitle, getproctitle
except ImportError:
    setproctitle = lambda t: None
    getproctitle = lambda: None

# Initialize gettext
try: