def __init__(self, drone):
        gobject.threads_init()
        
        self.drone = drone
        self.wifi_sensor = self.drone.get_wifi_sensor()
        self.posmap = self.drone.get_map()

        self.selected_position = None
        self.start_pos = None
        self.end_pos = None
       
        self.selected_segment = None
        
        self.mode = 0
        self.world_mode = 0
        self.tour_mode = 1

        self.world_mode_sub = 0
        
        self.select_mode = 0
        self.add_mode = 1
        self.del_mode = 2
        self.add_wifi_mode = 3
        self.clear_wifi_mode = 4

        self.dragging = False
        self.connecting = True
Пример #2
0
def main():
    from xpra.platform import init, clean
    try:
        init("Platform-Events", "Platform Events Test")
        import sys
        if "-v" in sys.argv or "--verbose" in sys.argv:
            from xpra.platform.win32.win32_events import log as win32_event_logger
            log.enable_debug()
            win32_event_logger.enable_debug()

        def suspend():
            log.info("suspend event")
        def resume():
            log.info("resume event")
        fake_client = AdHocStruct()
        fake_client.window_with_grab = None
        fake_client.suspend = suspend
        fake_client.resume = resume
        fake_client.keyboard_helper = None
        ClientExtras(fake_client)

        import gobject
        gobject.threads_init()

        log.info("Event loop is running")
        loop = gobject.MainLoop()
        try:
            loop.run()
        except KeyboardInterrupt:
            log.info("exiting on keyboard interrupt")
    finally:
        #this will wait for input on win32:
        clean()
Пример #3
0
    def start(self):
        """
        Starts the modules, views classes.

        Arguments:
        - self: The main object pointer.
        """

        if self.cfg is None:
            self.cfg = settings.load()

        if not self.dbusd.start():
            self.httpd.start()

        if self.cfg.getboolean("main", "startCam"):
            # Lets start the module
            idm = pocv.get_idm(self.cfg.get("main", "algorithm"))
            self.idm = idm.Module(self)
            self.idm.set_capture(self.cfg.getint("cam", "inputDevIndex"))

            gobject.timeout_add(10, self.update_frame)
            gobject.timeout_add(10, self.update_pointers)

            debug.info("mousetrap", "Idm loaded and started")

        # Lets build the interface
        self.itf = MainGui(self)
        self.itf.build_interface()
        self.itf.load_addons()
        debug.info("mousetrap", "MouseTrap's Interface Builded and Loaded")

        gobject.threads_init()
        self.loop.run()
Пример #4
0
def main():
    #init logger
    logger = logging.getLogger('psp')
    hdlr = logging.FileHandler('psp.log')
    strm_out = logging.StreamHandler(sys.__stdout__)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    strm_out.setFormatter(formatter)
    logger.addHandler(hdlr) 
    logger.addHandler(strm_out) 
    logger.setLevel(logging.INFO) 

    mdns_client = mdns.Mdns_client('laptop', 'haris.sp', 8080, logger)

    #init web server 
    site = server.Site(signpost_server.Singpost_server(logger))

    # run method in thread
    reactor.suggestThreadPoolSize(30)
    factory = Factory()
    reactor.listenSSL(8080, site, HTTPSVerifyingContextFactory()) #myContextFactory)
    mdns_client.setup_mdns()
    
    #service discovery module
    discovery = server_discovery.Server_discovery(logger)
    discovery.service_update() #initial discovery to fetch entries
    gobject.timeout_add(30000, discovery.service_update)
    
    # run the loop
    gobject.threads_init()
    gobject.MainLoop().run() 
Пример #5
0
    def run(self):
        self.log_initial_info()
        gobject.set_application_name(app.config.get(prefs.SHORT_APP_NAME))
        os.environ["PULSE_PROP_media.role"] = "video"

        gobject.threads_init()
        self._setup_webkit()
        associate_protocols(self._get_command())
        gtkdirectorywatch.GTKDirectoryWatcher.install()
        self.menubar = gtkmenus.MainWindowMenuBar()
        renderers.init_renderer()
        self.startup()
        langs = ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG")
        langs = [(l, os.environ.get(l)) for l in langs if os.environ.get(l)]
        logging.info("Language:          %s", langs)
        try:
            import libtorrent

            logging.info("libtorrent:        %s", libtorrent.version)
        except AttributeError:
            logging.info("libtorrent:        unknown version")
        except ImportError:
            logging.exception("libtorrent won't load")
        try:
            import pycurl

            logging.info("pycurl:            %s", pycurl.version)
        except ImportError:
            logging.exception("pycurl won't load")
        try:
            gtk.main()
        except (KeyboardInterrupt, SystemExit):
            self.do_quit()
        app.controller.on_shutdown()
Пример #6
0
def install_gobject_iteration():
    '''Import and install gobject context iteration inside our event loop.
    This is used as soon as gobject is used (like gstreamer)
    '''

    from kivy.clock import Clock
    import gobject
    if hasattr(gobject, '_gobject_already_installed'):
        # already installed, don't do it twice.
        return

    gobject._gobject_already_installed = True

    # get gobject mainloop / context
    loop = gobject.MainLoop()
    gobject.threads_init()
    context = loop.get_context()

    # schedule the iteration each frame
    def _gobject_iteration(*largs):
        # XXX we need to loop over context here, otherwise, we might have a lag.
        loop = 0
        while context.pending() and loop < 10:
            context.iteration(False)
            loop += 1
    Clock.schedule_interval(_gobject_iteration, 0)
Пример #7
0
 def __init__(self, uac=True, shred_paths=None):
     if uac and 'nt' == os.name and Windows.elevate_privileges():
         # privileges escalated in other process
         sys.exit(0)
     import RecognizeCleanerML
     RecognizeCleanerML.RecognizeCleanerML()
     register_cleaners()
     self.create_window()
     gobject.threads_init()
     if shred_paths:
         self.shred_paths(shred_paths)
         return
     if options.get("first_start") and 'posix' == os.name:
         pref = PreferencesDialog(self.window, self.cb_refresh_operations)
         pref.run()
         options.set('first_start', False)
     if online_update_notification_enabled and options.get("check_online_updates"):
         self.check_online_updates()
     if 'nt' == os.name:
         # BitDefender false positive.  BitDefender didn't mark BleachBit as infected or show
         # anything in its log, but sqlite would fail to import unless BitDefender was in "game mode."
         # http://bleachbit.sourceforge.net/forum/074-fails-errors
         try:
             import sqlite3
         except ImportError, e:
             print e
             print dir(e)
             self.append_text(
                 _("Error loading the SQLite module: the antivirus software may be blocking it."), 'error')
Пример #8
0
 def __init__(self, path="autitux.glade",
              root="mainWindow",
              domain=app_name, **kwargs):
     path = os.path.join(glade_dir, path)
     SimpleGladeApp.__init__(self, path, root, domain, **kwargs)
     gobject.threads_init()
     self.coma = autituxhelper.relayCommand()
Пример #9
0
def main():
    gobject.threads_init()
    qApp = QApplication(sys.argv)
    #qApp.connect(qApp, SIGNAL('lastWindowClosed()'), qApp, SLOT('quit()'))
    widget = VideoViewWidget()
    widget.show()
    sys.exit(qApp.exec_())
Пример #10
0
def main():
    parser = argparse.ArgumentParser(description = "Run the GROTARAPI demonstrator.",
                                     epilog = "Easy, isn't it?")
    parser.add_argument('-m',
                        '--master', 
                        action = 'store_true',
                        help = 'run master or slave terminal')
    parser.add_argument('-q',
                        '--quiet', 
                        action = 'store_true',
                        help = 'output no debug information.')
    parser.add_argument('-r',
                        '--run-module', 
                        type = str,
                        default = 'default',
                        help = "which module to run at startup. Default is 'default'")
    args = parser.parse_args()

    loop = gobject.MainLoop()
    gobject.threads_init()
    print "[INFO] Starting Controller with pid %u" % os.getpid()
    myController = Controller.Controller(verbose = not args.quiet, master = args.master)
    print "[INFO] available on dbus at '/org/gnuradio/grotarapi/%s'" % ('master' if args.master else 'slave')
    myController.start_module(args.run_module)
    loop.run()
Пример #11
0
def main():
    """
    Where everything start.
    """
    locale.setlocale(locale.LC_ALL, '')

    got_locales = False
    locales_path = None
    for (fr_locale_path, locales_path) in LOCALE_PATHS:
        print "Looking for locales in '%s' ..." % (fr_locale_path)
        if os.access(fr_locale_path, os.R_OK):
            print "Will use locales from '%s'" % (locales_path)
            got_locales = True
            break
    if not got_locales:
        print "WARNING: Locales not found"
    else:
        for module in (gettext, gtk.glade):
            module.bindtextdomain('paperwork', locales_path)
            module.textdomain('paperwork')

    gobject.threads_init()

    config = PaperworkConfig()
    config.read()

    main_win = MainWindow(config)
    main_win.actions['new_doc'][1].do()
    main_win.actions['reindex'][1].do()
    gtk.main()
    print "Good bye"
Пример #12
0
def __start():
	if __save_process_exists(): raise SystemExit
	from gobject import threads_init
	threads_init()
	from Manager import Manager
	Manager()
	return
Пример #13
0
    def __init__(self, member):
        global dbus
        self.logger = logging.getLogger("SynCE")

        self.__member = member
        self.engine = None
        self.isPrefilled=False

        gobject.threads_init()
        
	self.MainloopExitEvent    = threading.Event()
	self.SyncCompleteEvent    = threading.Event()
	self.PrefillCompleteEvent = threading.Event()
	
	# How we initialize the dbus comms and main loop
	# is somewhat version-dependent....
	
	DBusVersion = getattr(dbus,'version', (0,0,0))
	if DBusVersion < (0,80,0):
		import dbus.glib
		dbus.glib.init_threads()
	else:
		from dbus.mainloop.glib import DBusGMainLoop
		from dbus.mainloop.glib import threads_init
		dbus.mainloop.glib.threads_init()
		DBusGMainLoop(set_as_default=True)
		
        thread.start_new_thread(self._MainLoopEntry, ())
def _check_libs():
    try:
        import pygtk
        pygtk.require('2.0')
        import gtk
        import gnome
        import gnome.ui
        gnome.ui.authentication_manager_init()
        import gconf
        import gobject
        gobject.threads_init()
        import gnomevfs
    except ImportError:
        print '%s needs pygtk and gnome-python >= 2.12!' % NAME
        sys.exit(1)

    try:
        import pygst
        pygst.require('0.10')
        import gst
    except ImportError:
        print '%s needs python-gstreamer 0.10!' % NAME
        sys.exit(1)

    print '  using Gstreamer version: %s' % (
            '.'.join([str(s) for s in gst.gst_version]))
Пример #15
0
def init():
    """Shared SCBdo program initialisation."""
    print ("\n\
SCBdo(" + VERSION + ") Copyright (C) 2010,2011  Nathan Fraser\n\
This program comes with ABSOLUTELY NO WARRANTY.\n\
This is free software, and you are welcome to redistribute it\n\
under certain conditions.\n\n")

    # prepare for type 1 threads
    gobject.threads_init() 

    # fix the menubar accel mapping
    mset = gtk.settings_get_default()
    mset.set_string_property('gtk-menu-bar-accel', 'F24', 'override')

    # set the global default window icon
    try:
        gtk.window_set_default_icon_from_file(SCB_LOGOFILE)
    except:
        SCB_LOGOFILE = os.path.join(UI_PATH, 'scbdo_icon.png')
        gtk.window_set_default_icon_from_file(SCB_LOGOFILE)

    # Set global logging options
    logging._srcfile = None
    logging.logThreads = 0
    logging.logProcesses = 0

    # Check for data path and change working directory
    mk_data_path()
    os.chdir(DATA_PATH)
Пример #16
0
def main():
    """This function starts PdfShuffler"""
    gtk.gdk.threads_init()
    gobject.threads_init()
    gtk.gdk.threads_enter()     # This line is necessary in Windows
    PdfShuffler()
    gtk.main()
Пример #17
0
def main (server, eventHandler, params):
    params.updateFromServer(server)
    gobject.threads_init()

    # That indicates whether the Hob and the bitbake server are
    # running on different machines
    # recipe model and package model
    recipe_model = RecipeListModel()
    package_model = PackageListModel()

    hobHandler = HobHandler(server, recipe_model, package_model)
    builder = Builder(hobHandler, recipe_model, package_model)

    # This timeout function regularly probes the event queue to find out if we
    # have any messages waiting for us.
    gobject.timeout_add(10, event_handle_idle_func, eventHandler, hobHandler)

    try:
        gtk.main()
    except EnvironmentError as ioerror:
        # ignore interrupted io
        if ioerror.args[0] == 4:
            pass
    finally:
        hobHandler.cancel_build(force = True)
	def run(self):
		# Allows other threads to keep working while MainLoop runs
		# Required for timeout implementation
		gobject.MainLoop().get_context().iteration(True)
		gobject.threads_init()
		self.p2p_interface.Disconnect()
		gobject.MainLoop().run()
Пример #19
0
    def do(self, args):
        import gobject
        gobject.threads_init()

        import gst

        runner = task.SyncRunner()

        for path in filterFiles(self, args):

            t = level.TagReadTask(path)
            runner.run(t)

            self.stdout.write('%s:\n' % path.encode('utf-8'))

            keys = []

            for name, tag in [
                ('Artist', gst.TAG_ARTIST),
                ('Title', gst.TAG_TITLE),
                ('Album', gst.TAG_ALBUM),
            ]:
                if tag in t.taglist:
                    self.stdout.write('- %s: %r\n' % (name, t.taglist[tag]))

            for tag in t.taglist.keys():
                self.stdout.write('- %s: %r\n' % (tag, t.taglist[tag]))
Пример #20
0
def init (server, eventHandler):
    # Initialise threading...
    gobject.threads_init()
    gtk.gdk.threads_init()

    main_window = MainWindow ()
    main_window.show_all ()

    # Set up the build manager stuff in general
    builds_dir = os.path.join (os.getcwd(),  "results")
    manager = BuildManager (server, builds_dir)
    main_window.build_manager_view.set_model (manager.model)

    # Do the running build setup
    running_build = RunningBuild ()
    main_window.running_build_view.set_model (running_build.model)
    running_build.connect ("build-succeeded", running_build_succeeded_cb,
        manager)
    running_build.connect ("build-failed", running_build_failed_cb, manager)

    # We need to save the manager into the MainWindow so that the toolbar
    # button can use it.
    # FIXME: Refactor ?
    main_window.manager = manager

    # Use a timeout function for probing the event queue to find out if we
    # have a message waiting for us.
    gobject.timeout_add (200,
                         event_handle_timeout,
                         eventHandler,
                         running_build)

    gtk.main()
Пример #21
0
 def __init__(self):
     loop = DBusGMainLoop()
     
     self.bus = dbus.SystemBus(mainloop=loop)
     
     raw_server = self.bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER)
     self.server = dbus.Interface(raw_server, avahi.DBUS_INTERFACE_SERVER)
     
     self.browser = dbus.Interface(
                 self.bus.get_object(
                         avahi.DBUS_NAME, 
                         self.server.ServiceBrowserNew(
                                 NetworkInterface().getIndex(),
                                 avahi.PROTO_UNSPEC,
                                 '_folavirt_snapshotsiqn._tcp',
                                 'local',
                                 dbus.UInt32(0)
                         )
                 ),
                 avahi.DBUS_INTERFACE_SERVICE_BROWSER
             )
     
     dbus.mainloop.glib.threads_init()
     self.browser.connect_to_signal('ItemNew', self.handler)
     gobject.threads_init()
     self.main_loop = gobject.MainLoop()
     t = Thread(target=self.main_loop.run)
     t.daemon = True
     t.start()
Пример #22
0
	def run(self):
		print "initializing Object"

		#self.parse_pipeline(self.config.get("Pipeline","VideoSrc2UdpSink"))

		#self.pipeline_array.append(udp_src_to_filesink.UDPSrcToFileSink(self.config))
		#self.pipeline_array[-1].create_pipeline(0)

		#self.pipeline_array.append(file_src_to_v4l2loopback.FileSrcToV4l2Loopback(self.config))
		#self.pipeline_array[-1].create_pipeline(0,"/videos/test.avi")

		#self.pipeline_array.append(video_src_udp_sink.VideoSrcToUDPSink(self.config))
		#self.pipeline_array[-1].create_pipeline(0)	

		#self.pipeline_array.append(udp_src_to_v4l2loopback.UDPSrcToV4l2Loopback(self.config))
		#self.pipeline_array[-1].create_pipeline(0)

		#self.pipeline_array.append(video_src_file_sink.VideoSrcToFileSink(self.config))
		#self.pipeline_array[-1].create_pipeline(0)

		print "Pipeline('s) initialized"
		self.init_OSC()

		gobject.threads_init()
		self.mainloop = gobject.MainLoop()
		self.mainloop.run()
		print "exit"
Пример #23
0
def Run():
    gobject.threads_init()
    app = MainWindow()
    app.window.show()
    if app.pref_window:
        app.pref_window.window.present()
    gtk.main()
Пример #24
0
def main ():    
    import dbus
    import gobject
    from dbus.mainloop.glib import DBusGMainLoop
    DBusGMainLoop(set_as_default=True)
    gobject.threads_init()
    bus = dbus.SessionBus()
    proxy = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
    setupSignals(proxy)
    dbus.mainloop.glib.threads_init()    
    DBUSMAINLOOP = gobject.MainLoop()

    print 'Creating DBus Thread'
    DBUSLOOPTHREAD = threading.Thread(name='glib_mainloop', target=DBUSMAINLOOP.run)
    DBUSLOOPTHREAD.setDaemon(True)
    DBUSLOOPTHREAD.start()
    
    # TODO: Watch out for DBUS signal handlers doing things before the
    # push server is ready.
    print 'Starting TCP Servers'
    # Start the push server (for pushing data to the client)
    startPushServer()
    # Start the pull server (for the client to request data)
    startPullServer()
    while True:
        pass
	def __init__(self,config={'object_name':None,'object_path':None,'SongChanged':None}):
		super(AbstractLyricServer, self).__init__()

		self.quit = False
		self.tc=threading.Condition(threading.Lock())

		menu_items = (
			("/AdjustLyric",None,   self.adjustLyric ,0,None),
		)
		self.song=None
		self.lyric=None
		self.delay=0

		self.lyricApp=lyricApp.LyricApp(menu_items)
		self.lyricApp.confWin.currentSong=self.getSong
		self.lyricApp.confWin.setLyric=self.setLyric
		self.lyricApp.confWin.setSongProperty=self.setSongProperty
		DBusGMainLoop(set_as_default=True)
		self.bus = dbus.SessionBus()

		self.proxy=self.bus.get_object(config['object_name'],config['object_path'])
		self.proxy.connect_to_signal(config["SongChanged"],self.changed)
		if self.isPlaying():
			self.changed(None)
		gobject.threads_init()
def main():
    gobject.threads_init()
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    bus = dbus.SessionBus()
    should_start = False
    try:
        power = bus.get_object('org.freedesktop.PowerManagement',
                               '/org/freedesktop/PowerManagement')
        on_battery = bool(power.GetOnBattery())
        if not on_battery:
            should_start = True
    except:
        print "Unable to query current power state"
        # Power manager may not have started yet

    runner = OIRunner()
    runner.start()

    if should_start:
        runner.onBatteryChanged(False)

    bus.add_signal_receiver(runner.onBatteryChanged,
                            signal_name='OnBatteryChanged')

    loop = gobject.MainLoop()
    loop.run()
Пример #27
0
def main():
    gobject.threads_init() #@UndefinedVariable
    gtk.gdk.threads_init() #@UndefinedVariable
    DBusGMainLoop(set_as_default=True)

    mainloop = gobject.MainLoop()

    session_bus = dbus.SessionBus()
    notification_service_object = session_bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')
    notification_service = dbus.Interface(notification_service_object, dbus_interface='org.freedesktop.Notifications')

    name = dbus.service.BusName('org.freedesktop.Cozy', session_bus)

    backup_provider = BackupProvider()

    config = Configuration()
    system_bus = dbus.SystemBus()
    location_manager = LocationManager(system_bus)
    backup_location = location_manager.get_backup_location(config)

    standard_fallback_restore_client_loader = StandardFallbackRestoreClientLoader(config.data_path)
    restore_client_connector = RestoreClientConnector(session_bus, standard_fallback_restore_client_loader)

    with RestoreBackend(config, backup_provider, backup_location) as restore_backend:
        with RestoreControlCenter(restore_backend) as restore_control_center:
            icon = CozyIcon(config, restore_backend, notification_service, mainloop,
                            restore_client_connector, restore_control_center, location_manager)

            mainloop.run()
Пример #28
0
def main():
    sys.path.append(os.getcwd())
    from PHY import PhysicalLayer
    
    samples_per_symbol = 4
    samp_rate = 4e6
    tb = gr.top_block()

    modulator = blks2.gmsk_mod(samples_per_symbol=samples_per_symbol)
    demodulator = blks2.gmsk_demod(samples_per_symbol=samples_per_symbol)

    sys.stderr.write('Using bitrate %sbits/s\n' % eng_notation.num_to_str(samp_rate / samples_per_symbol / modulator.bits_per_symbol()))
    sys.stderr.flush()
    phy = PhysicalLayer.PhysicalLayer(modulator, demodulator, hint = 'addr=192.168.10.3', access_code = 'slave')

    tb.connect(phy)
    
    phy.tune(1.8e9)
    phy.set_gain(45)
    phy.set_samp_rate(samp_rate)

    child = subprocess.Popen(['cvlc', '-'], stdout = subprocess.PIPE, stdin = subprocess.PIPE, stderr=None)
    #print 'Started vlc with pid', child.pid

    def write_to_child_pipe(ok, data):
        print "[DEBUG] writing to VLC's pipe"
        if(ok):
            child.stdin.write(data)

    phy.set_rx_callback(write_to_child_pipe)
    tb.start()
    gobject.threads_init()
    loop = gobject.MainLoop()
    loop.run()
Пример #29
0
def main():
    from xpra.platform import program_context
    with program_context("Platform-Events", "Platform Events Test"):
        if "-v" in sys.argv or "--verbose" in sys.argv:
            from xpra.platform.win32.win32_events import log as win32_event_logger
            log.enable_debug()
            win32_event_logger.enable_debug()

        import gobject
        gobject.threads_init()      #@UndefinedVariable

        log.info("Event loop is running")
        loop = gobject.MainLoop()

        def suspend():
            log.info("suspend event")
        def resume():
            log.info("resume event")
        fake_client = AdHocStruct()
        fake_client.window_with_grab = None
        fake_client.suspend = suspend
        fake_client.resume = resume
        fake_client.keyboard_helper = None
        def signal_quit(*args):
            loop.quit()
        fake_client.signal_disconnect_and_quit = signal_quit
        ClientExtras(fake_client, None)

        try:
            loop.run()
        except KeyboardInterrupt:
            log.info("exiting on keyboard interrupt")
Пример #30
0
def main():
    sys.path.append(os.getcwd())
    from PHY import PhysicalLayer
    
    samples_per_symbol = 4
    samp_rate = 4e6
    tb = gr.top_block()

    modulator = blks2.gmsk_mod(samples_per_symbol=samples_per_symbol)
    demodulator = blks2.gmsk_demod(samples_per_symbol=samples_per_symbol)

    sys.stderr.write('Using bitrate %sbits/s\n' % eng_notation.num_to_str(samp_rate / samples_per_symbol / modulator.bits_per_symbol()))
    sys.stderr.flush()
    phy = PhysicalLayer.PhysicalLayer(modulator, demodulator, hint = 'addr=192.168.10.2', access_code = 'master')
    tb.connect(phy)
    
    phy.tune(1.8e9)
    phy.set_gain(45)
    phy.set_samp_rate(samp_rate)

    args = shlex.split('cvlc --sout "#transcode{vcodec=theora, vb=128}:std{access=file, mux=ogg, dst=-}" v4l2:///dev/video0')
    child = subprocess.Popen(args, stdout = subprocess.PIPE, stdin = subprocess.PIPE, stderr=None)
    print 'Started vlc with pid', child.pid

    def read_data_from_child():
        print "[DEBUG] reading from child's pipe"
        phy.send_pkt(child.stdout.read(512))
        return True

    tb.start()
    gobject.threads_init()
    gobject.idle_add(read_data_from_child)
    loop = gobject.MainLoop()
    loop.run()
Пример #31
0
def myblock(tw, args):
    ''' Record and playback a sound (Sugar only) '''
    import os
    import gst
    import gobject
    gobject.threads_init()

    from TurtleArt.tautils import get_path
    from TurtleArt.tagplay import play_audio_from_file
    from sugar.datastore import datastore
    from sugar import profile

    from gettext import gettext as _

    class Grecord:
        ''' A class for creating a gstreamer session for recording audio. '''
        def __init__(self, tw):
            ''' Set up the stream. We save to a raw .wav file and then
            convert the sound to .ogg for saving. '''
            datapath = get_path(tw.parent, 'instance')
            self.capture_file = os.path.join(datapath, 'output.wav')
            self.save_file = os.path.join(datapath, 'output.ogg')
            self._eos_cb = None

            self._can_limit_framerate = False
            self._recording = False

            self._audio_transcode_handler = None
            self._transcode_id = None

            self._pipeline = gst.Pipeline("Record")
            self._create_audiobin()
            self._pipeline.add(self._audiobin)

            bus = self._pipeline.get_bus()
            bus.add_signal_watch()
            bus.connect('message', self._bus_message_handler)

        def _create_audiobin(self):
            ''' Assemble all the pieces we need. '''
            src = gst.element_factory_make("alsasrc", "absrc")

            # attempt to use direct access to the 0,0 device, solving
            # some A/V sync issues
            src.set_property("device", "plughw:0,0")
            hwdev_available = src.set_state(gst.STATE_PAUSED) != \
                gst.STATE_CHANGE_FAILURE
            src.set_state(gst.STATE_NULL)
            if not hwdev_available:
                src.set_property("device", "default")

            srccaps = gst.Caps(
                "audio/x-raw-int,rate=16000,channels=1,depth=16")

            # guarantee perfect stream, important for A/V sync
            rate = gst.element_factory_make("audiorate")

            # without a buffer here, gstreamer struggles at the start
            # of the recording and then the A/V sync is bad for the
            # whole video (possibly a gstreamer/ALSA bug -- even if it
            # gets caught up, it should be able to resync without
            # problem)
            queue = gst.element_factory_make("queue", "audioqueue")
            queue.set_property("leaky", True)  # prefer fresh data
            queue.set_property("max-size-time", 5000000000)  # 5 seconds
            queue.set_property("max-size-buffers", 500)
            queue.connect("overrun", self._log_queue_overrun)

            enc = gst.element_factory_make("wavenc", "abenc")

            sink = gst.element_factory_make("filesink", "absink")
            sink.set_property("location", self.capture_file)

            self._audiobin = gst.Bin("audiobin")
            self._audiobin.add(src, rate, queue, enc, sink)

            src.link(rate, srccaps)
            gst.element_link_many(rate, queue, enc, sink)

        def _log_queue_overrun(self, queue):
            ''' We use a buffer, which may overflow. '''
            cbuffers = queue.get_property("current-level-buffers")
            cbytes = queue.get_property("current-level-bytes")
            ctime = queue.get_property("current-level-time")

        def is_recording(self):
            ''' Are we recording? '''
            return self._recording

        def _get_state(self):
            ''' What is the state of our gstreamer pipeline? '''
            return self._pipeline.get_state()[1]

        def start_recording_audio(self):
            ''' Start the stream in order to start recording. '''
            if self._get_state() == gst.STATE_PLAYING:
                return
            self._pipeline.set_state(gst.STATE_PLAYING)
            self._recording = True

        def stop_recording_audio(self):
            ''' Stop recording and then convert the results into a
            .ogg file using a new stream. '''
            self._pipeline.set_state(gst.STATE_NULL)
            self._recording = False

            if not os.path.exists(self.capture_file) or \
                    os.path.getsize(self.capture_file) <= 0:
                return

            # Remove previous transcoding results.
            if os.path.exists(self.save_file):
                os.remove(self.save_file)

            line = 'filesrc location=' + self.capture_file + \
                ' name=audioFilesrc ! wavparse name=audioWavparse \
! audioconvert name=audioAudioconvert ! vorbisenc name=audioVorbisenc \
! oggmux name=audioOggmux ! filesink name=audioFilesink'

            audioline = gst.parse_launch(line)

            # vorbis_enc = audioline.get_by_name('audioVorbisenc')

            audioFilesink = audioline.get_by_name('audioFilesink')
            audioFilesink.set_property("location", self.save_file)

            audioBus = audioline.get_bus()
            audioBus.add_signal_watch()
            self._audio_transcode_handler = audioBus.connect(
                'message', self._onMuxedAudioMessageCb, audioline)
            self._transcode_id = gobject.timeout_add(200,
                                                     self._transcodeUpdateCb,
                                                     audioline)
            audioline.set_state(gst.STATE_PLAYING)

        def _transcodeUpdateCb(self, pipe):
            ''' Where are we in the transcoding process? '''
            position, duration = self._query_position(pipe)
            if position != gst.CLOCK_TIME_NONE:
                value = position * 100.0 / duration
                value = value / 100.0
            return True

        def _query_position(self, pipe):
            ''' Where are we in the stream? '''
            try:
                position, format = pipe.query_position(gst.FORMAT_TIME)
            except:
                position = gst.CLOCK_TIME_NONE

            try:
                duration, format = pipe.query_duration(gst.FORMAT_TIME)
            except:
                duration = gst.CLOCK_TIME_NONE

            return (position, duration)

        def _onMuxedAudioMessageCb(self, bus, message, pipe):
            ''' Clean up at end of stream.'''
            if message.type != gst.MESSAGE_EOS:
                return True

            gobject.source_remove(self._audio_transcode_handler)
            self._audio_transcode_handler = None
            gobject.source_remove(self._transcode_id)
            self._transcode_id = None
            pipe.set_state(gst.STATE_NULL)
            pipe.get_bus().remove_signal_watch()
            pipe.get_bus().disable_sync_message_emission()

            os.remove(self.capture_file)
            return False

        def _bus_message_handler(self, bus, message):
            ''' Handle any messages associated with the stream. '''
            t = message.type
            if t == gst.MESSAGE_EOS:
                if self._eos_cb:
                    cb = self._eos_cb
                    self._eos_cb = None
                    cb()
            elif t == gst.MESSAGE_ERROR:
                # TODO: if we come out of suspend/resume with errors, then
                # get us back up and running...  TODO: handle "No space
                # left on the resource.gstfilesink.c" err, debug =
                # message.parse_error()
                pass

    # We store the audio-record stream instance as tw.grecord so that
    # we can use it repeatedly.
    if not hasattr(tw, 'grecord'):
        tw.grecord = Grecord(tw)

    # Sometime we need to parse multiple arguments, e.g., save, savename
    save_name = '%s_%s' % (tw.activity.name, _('sound'))
    cmd = args[0].lower()
    if len(args) > 1:
        save_name = str(arg[1])

    if cmd == 'start' or cmd == _('start').lower():
        tw.grecord.start_recording_audio()
    elif cmd == 'stop' or cmd == _('stop').lower():
        tw.grecord.stop_recording_audio()
    elif cmd == 'play' or cmd == _('play').lower():
        play_audio_from_file(tw.lc, tw.grecord.save_file)
    elif cmd == 'save' or cmd == _('save').lower():
        if os.path.exists(tw.grecord.save_file) and tw.running_sugar:
            dsobject = datastore.create()
            dsobject.metadata['title'] = save_name
            dsobject.metadata['icon-color'] = profile.get_color().to_string()
            dsobject.metadata['mime_type'] = 'audio/ogg'
            dsobject.set_file_path(tw.grecord.save_file)
            datastore.write(dsobject)
            dsobject.destroy()
Пример #32
0
    _task_return(None)
    return generator

# 2 task examples: sleep_task, threaded_task

def sleep_task(secs):
    """Suspend job for the given number of seconds and return elapsed time."""
    def _task(task_return):
        start_time = time.time()
        def _on_timeout():
            task_return(time.time() - start_time)
        gobject.timeout_add(int(secs * 1000), _on_timeout)
    return _task
  
import threading
gobject.threads_init()  

def threaded_task(function, *args, **kwargs):
    """Run function(*args, **kwargs) inside a thread and return the result."""
    def _task(task_return):
        def _thread():
            result = function(*args, **kwargs)
            gobject.idle_add(task_return, result)
        thread = threading.Thread(target=_thread, args=())
        thread.setDaemon(True)
        thread.start()
    return _task

# Example of usage

import sys
Пример #33
0
def main():
    gobject.threads_init()
    Gui(API_KEY)
    gtk.main()
Пример #34
0
    def __init__(self,
                 hosts=None,
                 patterns_name=None,
                 patterns_owner=None,
                 comms_timeout=None,
                 interval=None):
        gobject.threads_init()
        set_exception_hook_dialog("cylc gscan")
        setup_icons()

        self.window = gtk.Window()
        title = "cylc gscan"
        for opt, items in [("-n", patterns_name), ("-o", patterns_owner)]:
            if items:
                for pattern in items:
                    if pattern is not None:
                        title += " %s %s" % (opt, pattern)
        self.window.set_title(title)
        self.window.set_icon(get_icon())
        self.vbox = gtk.VBox()
        self.vbox.show()

        self.warnings = {}

        self.theme_name = gcfg.get(['use theme'])
        self.theme = gcfg.get(['themes', self.theme_name])

        suite_treemodel = gtk.TreeStore(
            str,  # group
            str,  # host
            str,  # owner
            str,  # suite
            bool,  # is_stopped
            str,  # title
            int,  # update_time
            str,  # states
            str,  # states_text
            str)  # warning_text
        self._prev_tooltip_location_id = None
        self.treeview = gtk.TreeView(suite_treemodel)

        # Visibility of columns
        vis_cols = gsfg.get(["columns"])
        # Doesn't make any sense without suite name column
        if gsfg.COL_SUITE not in vis_cols:
            vis_cols.append(gsfg.COL_SUITE.lower())
        # Construct the group, host, owner, suite, title, update time column.
        for col_title, col_id, col_cell_text_setter in [
            (gsfg.COL_GROUP, self.GROUP_COLUMN, self._set_cell_text_group),
            (gsfg.COL_HOST, self.HOST_COLUMN, self._set_cell_text_host),
            (gsfg.COL_OWNER, self.OWNER_COLUMN, self._set_cell_text_owner),
            (gsfg.COL_SUITE, self.SUITE_COLUMN, self._set_cell_text_name),
            (gsfg.COL_TITLE, self.TITLE_COLUMN, self._set_cell_text_title),
            (gsfg.COL_UPDATED, self.UPDATE_TIME_COLUMN,
             self._set_cell_text_time),
        ]:
            column = gtk.TreeViewColumn(col_title)
            cell_text = gtk.CellRendererText()
            column.pack_start(cell_text, expand=False)
            column.set_cell_data_func(cell_text, col_cell_text_setter)
            column.set_sort_column_id(col_id)
            column.set_visible(col_title.lower() in vis_cols)
            column.set_resizable(True)
            self.treeview.append_column(column)

        # Construct the status column.
        status_column = gtk.TreeViewColumn(gsfg.COL_STATUS)
        status_column.set_sort_column_id(self.STATUS_COLUMN)
        status_column.set_visible(gsfg.COL_STATUS.lower() in vis_cols)
        status_column.set_resizable(True)
        cell_text_cycle = gtk.CellRendererText()
        status_column.pack_start(cell_text_cycle, expand=False)
        status_column.set_cell_data_func(cell_text_cycle,
                                         self._set_cell_text_cycle,
                                         self.CYCLE_COLUMN)
        self.treeview.append_column(status_column)

        # Warning icon.
        warn_icon = gtk.CellRendererPixbuf()
        image = gtk.Image()
        pixbuf = image.render_icon(gtk.STOCK_DIALOG_WARNING,
                                   gtk.ICON_SIZE_LARGE_TOOLBAR)
        self.warn_icon_colour = pixbuf.scale_simple(  # colour warn icon pixbuf
            self.ICON_SIZE, self.ICON_SIZE, gtk.gdk.INTERP_HYPER)
        self.warn_icon_grey = pixbuf.scale_simple(self.ICON_SIZE,
                                                  self.ICON_SIZE,
                                                  gtk.gdk.INTERP_HYPER)
        self.warn_icon_colour.saturate_and_pixelate(
            self.warn_icon_grey, 0, False)  # b&w warn icon pixbuf
        status_column.pack_start(warn_icon, expand=False)
        status_column.set_cell_data_func(warn_icon, self._set_error_icon_state)
        self.warn_icon_blank = gtk.gdk.Pixbuf(  # Transparent pixbuff.
            gtk.gdk.COLORSPACE_RGB, True, 8, self.ICON_SIZE,
            self.ICON_SIZE).fill(0x00000000)
        # Task status icons.
        for i in range(len(TASK_STATUSES_ORDERED)):
            cell_pixbuf_state = gtk.CellRendererPixbuf()
            status_column.pack_start(cell_pixbuf_state, expand=False)
            status_column.set_cell_data_func(cell_pixbuf_state,
                                             self._set_cell_pixbuf_state, i)

        self.treeview.show()
        if hasattr(self.treeview, "set_has_tooltip"):
            self.treeview.set_has_tooltip(True)
            try:
                self.treeview.connect('query-tooltip', self._on_query_tooltip)
            except TypeError:
                # Lower PyGTK version.
                pass
        self.treeview.connect("button-press-event",
                              self._on_button_press_event)

        patterns = {"name": None, "owner": None}
        for label, items in [("owner", patterns_owner),
                             ("name", patterns_name)]:
            if items:
                patterns[label] = r"\A(?:" + r")|(?:".join(items) + r")\Z"
                try:
                    patterns[label] = re.compile(patterns[label])
                except re.error:
                    raise ValueError("Invalid %s pattern: %s" % (label, items))

        self.updater = ScanAppUpdater(self.window,
                                      hosts,
                                      suite_treemodel,
                                      self.treeview,
                                      comms_timeout=comms_timeout,
                                      interval=interval,
                                      group_column_id=self.GROUP_COLUMN,
                                      name_pattern=patterns["name"],
                                      owner_pattern=patterns["owner"])

        self.updater.start()

        self.dot_size = gcfg.get(['dot icon size'])
        self._set_dots()

        self.create_menubar()

        accelgroup = gtk.AccelGroup()
        self.window.add_accel_group(accelgroup)
        key, modifier = gtk.accelerator_parse('<Alt>m')
        accelgroup.connect_group(key, modifier, gtk.ACCEL_VISIBLE,
                                 self._toggle_hide_menu_bar)

        self.create_tool_bar()

        self.menu_hbox = gtk.HBox()
        self.menu_hbox.pack_start(self.menu_bar, expand=True, fill=True)
        self.menu_hbox.pack_start(self.tool_bar, expand=True, fill=True)
        self.menu_hbox.show_all()
        self.menu_hbox.hide_all()

        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrolled_window.add(self.treeview)
        scrolled_window.show()

        self.vbox.pack_start(self.menu_hbox, expand=False)
        self.vbox.pack_start(scrolled_window, expand=True, fill=True)

        self.window.add(self.vbox)
        self.window.connect("destroy", self._on_destroy_event)
        wsize = gsfg.get(['window size'])
        self.window.set_default_size(*wsize)
        self.treeview.grab_focus()
        self.window.show()

        self.theme_legend_window = None
        self.warning_icon_shown = []
Пример #35
0
def main():
    gobject.threads_init()
    gtk.gdk.threads_init()

    parser = argparse.ArgumentParser(description='Plays audio/video stream.',
                                     add_help=False)
    parser.add_argument('--player-help',
                        action="help",
                        help="show this help message and exit")
    parser.add_argument('-l',
                        '--live',
                        action="store_true",
                        help='play in live mode')
    parser.add_argument('-d',
                        '--disable-buffering',
                        action="store_false",
                        help='disable buffering')
    parser.add_argument('-t',
                        '--max-time',
                        default=500,
                        type=float,
                        help='maximum buffer time for multiqueue (in ms)')
    parser.add_argument(
        '-p',
        '--publisher-id',
        help='fetch data only from specific publisher (in base64)')
    parser.add_argument(
        '-r',
        '--retry-count',
        type=int,
        help='how many times retransmit an interest before giving up')
    parser.add_argument(
        '-v',
        '--video-pipeline-size',
        type=int,
        help='Maximum number of pending interests for video stream')
    parser.add_argument(
        '-a',
        '--audio-pipeline-size',
        type=int,
        help='Maximum number of pending interests for audio stream')
    parser.add_argument('URI', help='URI of the video stream')

    cmd_args = parser.parse_args()

    publisher_id = base64.b64decode(
        cmd_args.publisher_id) if cmd_args.publisher_id else None

    name, publisher_id = player.get_latest_version(cmd_args.URI, publisher_id)
    if name is None:
        print "No content found at %s" % cmd_args.URI
        return 1

    print("Fetching data from publisher: %s" % base64.b64encode(publisher_id))

    w = player_gui.PlayerWindow(GstPlayer, cmd_args)
    w.load_file(str(name), publisher_id)
    w.show_all()
    gtk.main()

    return 0
Пример #36
0
def main():
    usage = "usage: %prog [options]"
    parser = OptionParser(usage)
    parser.set_defaults(server=defs.HOST,
                        interval=defs.INTERVAL,
                        invisible=False,
                        connect=False,
                        log=False,
                        maxlog=defs.MAX_LOGCOUNT,
                        debug=False)
    parser.add_option('-i',
                      '--invisible',
                      action='store_true',
                      dest='invisible')
    parser.add_option('-s',
                      '--server',
                      dest='server',
                      help='De server waarmee verbonden moet worden')
    parser.add_option('-c',
                      '--auto-connect',
                      action='store_true',
                      dest='connect',
                      help='Maak onmiddellijk verbinding')
    parser.add_option('-l',
                      '--auto-log',
                      action='store_true',
                      dest='log',
                      help='Begin onmiddellijk te loggen')
    parser.add_option('-I',
                      '--interval',
                      type='int',
                      dest='interval',
                      help='Het update interval in seconden min: %s  max: %s' %
                      (defs.MIN_INTERVAL, defs.MAX_INTERVAL))
    parser.add_option('-m',
                      '--max-log',
                      dest='maxlog',
                      help='Maximum aantal loglijnen per blad')
    parser.add_option('-d', '--debug', action='store_true', dest='debug')

    (options, args) = parser.parse_args()
    if len(args) != 0:
        parser.error("incorrect number of arguments")

    defs.HOST = options.server
    if options.interval < defs.MIN_INTERVAL:
        options.interval = defs.MIN_INTERVAL
    if options.interval > defs.MAX_INTERVAL:
        options.interval = defs.MAX_INTERVAL
    defs.INTERVAL = options.interval
    defs.MAX_LOGCOUNT = options.maxlog
    defs.DEBUG = options.debug

    app = SAMConnectApp()
    if not options.invisible:
        app.window.show_all()
    #activate controllers only after main loop is started
    gobject.timeout_add_seconds(2, _activate_controllers, app, options)

    gobject.threads_init()
    gtk.main()
Пример #37
0
    print('[pygtk_.py] GTK version: %s' % version)

    # Intercept python exceptions. Exit app immediately when exception
    # happens on any of the threads.
    sys.excepthook = ExceptHook

    # Application settings
    settings = {
        "debug":
        True,  # cefpython debug messages in console and in log_file
        "log_severity":
        cefpython.LOGSEVERITY_INFO,  # LOGSEVERITY_VERBOSE
        "log_file":
        GetApplicationPath("debug.log"),  # Set to "" to disable
        # This directories must be set on Linux
        "locales_dir_path":
        cefpython.GetModuleDirectory() + "/locales",
        "resources_dir_path":
        cefpython.GetModuleDirectory(),
        "browser_subprocess_path":
        "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess"),
    }

    cefpython.Initialize(settings)

    gobject.threads_init()  # Timer for the message loop
    PyGTKExample()
    gtk.main()

    cefpython.Shutdown()
Пример #38
0
    def __init__(self,
                 name,
                 service_type='_ros-master._tcp',
                 host=socket.gethostname(),
                 port=11311,
                 domain='local',
                 txt_array=[]):
        '''
        Initialization method of the Zeroconf class.

        :param name: the name of the local ROS master

        :type name:  str

        :param service_type: the avahi service type

        :type service_type:  str

        :param host: the host of the local ROS master

        :type host: str

        :param port: the port of the local ROS master

        :type port: int

        :param domain: the domain name

        :type domain: str

        :param txt_array: (optional) additional information

        :type txt_array: list of strings
        '''
        self.masterInfo = MasterInfo(name, service_type, domain, host, port,
                                     txt_array)

        # FIXME Review thread locking as needed.
        # init thread
        threading.Thread.__init__(self)
        self._lock = threading.RLock()
        # Gobjects are an event based model of evil, do not trust them,
        DBusGMainLoop(set_as_default=True)
        # Magic? Yes, don't start threads without it.
        # Why? I'm sure thats documented somewhere.
        gobject.threads_init()
        dbus.mainloop.glib.threads_init()
        self.__main_loop = gobject.MainLoop()
        self.__bus = dbus.SystemBus()
        # Initialize iterface to DBUS Server
        self.__server = dbus.Interface(
            self.__bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER),
            avahi.DBUS_INTERFACE_SERVER)

        # The DBUS entry group
        self.__group = None
        # Monitor server state changes
        self.__server.connect_to_signal("StateChanged",
                                        self.__avahi_callback_state_changed)

        # the browser to register the updates and new services
        self.__browser = dbus.Interface(
            self.__bus.get_object(
                avahi.DBUS_NAME,
                self.__server.ServiceBrowserNew(avahi.IF_UNSPEC,
                                                avahi.PROTO_UNSPEC,
                                                self.masterInfo.stype,
                                                self.masterInfo.domain,
                                                dbus.UInt32(0))),
            avahi.DBUS_INTERFACE_SERVICE_BROWSER)
        self.__browser.connect_to_signal(
            "ItemNew", self.__avahi_callback_service_browser_new)
        self.__browser.connect_to_signal(
            "ItemRemove", self.__avahi_callback_service_browser_remove)
Пример #39
0
    def __init__(self, title, parent, tmpdir, timeout):

        if timeout:
            self.timeout = float(timeout)
        else:
            self.timeout = None

        self.chosen = None

        self.updater = None
        self.tmpdir = tmpdir
        self.gcapture_windows = []

        gobject.threads_init()

        # self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window = gtk.Dialog(
            "Choose a suite",
            parent,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK,
             gtk.RESPONSE_OK))
        # self.window.set_modal(True)
        self.window.set_title(title)
        self.window.set_size_request(750, 400)
        # TODO: not needed for a dialog window?
        self.window.set_icon(get_icon())
        # self.window.set_border_width(5)

        self.window.connect("delete_event", self.delete_all_event)

        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)

        self.regd_treeview = gtk.TreeView()
        self.regd_treestore = gtk.TreeStore(str, str, str, str, str, str, str)
        self.regd_treeview.set_model(self.regd_treestore)
        self.regd_treeview.set_rules_hint(True)
        # search column zero (Ctrl-F)
        self.regd_treeview.connect('key_press_event', self.on_suite_select)
        self.regd_treeview.connect('button_press_event', self.on_suite_select)
        self.regd_treeview.set_search_column(0)

        regd_ts = self.regd_treeview.get_selection()
        regd_ts.set_mode(gtk.SELECTION_SINGLE)

        cr = gtk.CellRendererText()
        # cr.set_property('cell-background', '#def')
        tvc = gtk.TreeViewColumn(
            'Suite', cr, text=0, foreground=4, background=5)
        tvc.set_resizable(True)
        tvc.set_sort_column_id(0)
        self.regd_treeview.append_column(tvc)

        cr = gtk.CellRendererText()
        tvc = gtk.TreeViewColumn(
            'Host:Port', cr, text=1, foreground=4, background=5)
        tvc.set_resizable(True)
        # not sure how this sorting works
        # tvc.set_sort_column_id(1)
        self.regd_treeview.append_column(tvc)

        cr = gtk.CellRendererText()
        # cr.set_property('cell-background', '#def')
        tvc = gtk.TreeViewColumn(
            'Title', cr, markup=2, foreground=4, background=6)
        tvc.set_resizable(True)
        # vc.set_sort_column_id(2)
        self.regd_treeview.append_column(tvc)

        cr = gtk.CellRendererText()
        tvc = gtk.TreeViewColumn(
            'Location', cr, text=3, foreground=4, background=5)
        tvc.set_resizable(True)
        # vc.set_sort_column_id(3)
        self.regd_treeview.append_column(tvc)

        vbox = self.window.vbox

        sw.add(self.regd_treeview)

        vbox.pack_start(sw, True)

        self.selected_label_text = (
            '(double-click or OK to select; right-click for db options)')
        self.selected_label = gtk.Label(self.selected_label_text)

        filter_entry = EntryTempText()
        filter_entry.set_width_chars(7)  # Reduce width in toolbar
        filter_entry.connect("activate", self.filter)
        filter_entry.set_temp_text("filter")
        filter_toolitem = gtk.ToolItem()
        filter_toolitem.add(filter_entry)
        tooltip = gtk.Tooltips()
        tooltip.enable()
        tooltip.set_tip(
            filter_toolitem, "Filter suites \n(enter a sub-string or regex)")

        expand_button = gtk.ToolButton()
        image = gtk.image_new_from_stock(
            gtk.STOCK_ADD, gtk.ICON_SIZE_SMALL_TOOLBAR)
        expand_button.set_icon_widget(image)
        expand_button.connect(
            'clicked', lambda x: self.regd_treeview.expand_all())

        collapse_button = gtk.ToolButton()
        image = gtk.image_new_from_stock(
            gtk.STOCK_REMOVE, gtk.ICON_SIZE_SMALL_TOOLBAR)
        collapse_button.set_icon_widget(image)
        collapse_button.connect(
            'clicked', lambda x: self.regd_treeview.collapse_all())

        hbox = gtk.HBox()

        eb = gtk.EventBox()
        eb.add(self.selected_label)
        eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#bbc'))
        hbox.pack_start(eb, True)
        hbox.pack_start(expand_button, False)
        hbox.pack_start(collapse_button, False)
        hbox.pack_start(filter_toolitem, False)

        vbox.pack_start(hbox, False)

        self.window.show_all()

        self.start_updater()
Пример #40
0
#!/usr/bin/env python
#
#
#application main user interface
#
#

#(c) Noprianto <*****@*****.**>, 2008-2009, GPL

import sys
import os
import gtk
import pygtk
pygtk.require('2.0')
import gobject
gobject.threads_init()  #for multithreading

#application
from application import Application

#another UI file
from ui_user import UIUser
from ui_product import UIProduct
from ui_password import UIPassword
from ui_about import UIAbout
from ui_statusbar import UIStatusBar
import db_sqlite3 as db

import gtkutils

Пример #41
0
 def run(self):
     gobject.threads_init()
     gtk.gdk.threads_init()
     gtk.main()
     gtkthread.quit.set()
Пример #42
0
def UnityIndicator():
    import gobject
    import gtk
    import appindicator
    try:
        import pynotify
        pynotify.init("Mailpile")
    except ImportError:
        pynotify = None

    ICON_THEME = 'light'

    gobject.threads_init()

    class UnityWebView():
        def __init__(self, mpi):
            import webkit
            self.webview = webkit.WebView()

            self.scroller = gtk.ScrolledWindow()
            self.scroller.add(self.webview)

            self.vbox = gtk.VBox(False, 1)
            self.vbox.pack_start(self.scroller, True, True)

            self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
            self.window.set_size_request(1100, 600)
            self.window.connect('delete-event', lambda w, e: w.hide() or True)
            self.window.add(self.vbox)

            self.browser_settings = self.webview.get_settings()
            self.browser_settings.set_property("enable-java-applet", False)
            self.browser_settings.set_property("enable-plugins", False)
            self.browser_settings.set_property("enable-scripts", True)
            self.browser_settings.set_property("enable-private-browsing", True)
            self.browser_settings.set_property("enable-spell-checking", True)
            self.browser_settings.set_property("enable-developer-extras", True)
            self.webview.set_settings(self.browser_settings)

        def show_url(self, url):
            self.webview.open('about:blank')  # Clear page while loading
            self.webview.open(url)
            self.window.show_all()

    class MailpileIndicator(Indicator):
        def __init__(self, config):
            Indicator.__init__(self, config)
            self.splash = None

        def _menu_setup(self):
            self.items = {}
            self.menu = gtk.Menu()
            self._create_menu_from_config()

        def _add_menu_item(self, item='item', label='Menu item',
                                 sensitive=False,
                                 op=None, args=None,
                                 **ignored_kwarg):
            menu_item = gtk.MenuItem(label)
            menu_item.set_sensitive(sensitive)
            if op:
                def activate(o, a):
                    return lambda d: self._do(o, a)
                menu_item.connect("activate", activate(op, args or []))
            menu_item.show()
            self.items[item] = menu_item
            self.menu.append(menu_item)

        def _ind_setup(self):
            self.ind = appindicator.Indicator(
                self.config.get('app_name', 'app').lower() + "-indicator",
                # FIXME: Make these two configurable...
                "indicator-messages", appindicator.CATEGORY_COMMUNICATIONS)
            self._set_status('startup', now=True)
            self.ind.set_menu(self.menu)

        def update_splash_screen(self, progress=None, message=None):
            if self.splash:
                if message is not None and 'message' in self.splash:
                    self.splash['message'].set_markup(message)
                if progress is not None and 'progress' in self.splash:
                    self.splash['progress'].set_fraction(progress)

        def show_splash_screen(self, height=None, width=None,
                               progress_bar=False, image=None, message=None,
                               now=False):
            def show(self):
                window = gtk.Window(gtk.WINDOW_TOPLEVEL)
                vbox = gtk.VBox(False, 1)

                if message:
                    lbl = gtk.Label()
                    lbl.set_markup(message or '')
                    lbl.set_alignment(0.5, 0.5)
                    vbox.pack_start(lbl, True, True)
                else:
                    lbl = None

                if image:
                    themed_image = self._theme_image(image)
                    img = gtk.gdk.pixbuf_new_from_file(themed_image)
                    def draw_background(widget, ev):
                        alloc = widget.get_allocation()
                        pb = img.scale_simple(alloc.width, alloc.height,
                                              gtk.gdk.INTERP_BILINEAR)
                        widget.window.draw_pixbuf(
                            widget.style.bg_gc[gtk.STATE_NORMAL],
                            pb, 0, 0, alloc.x, alloc.y)
                        if (hasattr(widget, 'get_child') and
                                widget.get_child() is not None):
                            widget.propagate_expose(widget.get_child(), ev)
                        return False
                    vbox.connect('expose_event', draw_background)

                if progress_bar:
                    pbar = gtk.ProgressBar()
                    pbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
                    vbox.pack_end(pbar, False, True)
                else:
                    pbar = None

                window.set_title(self.config['app_name'])
                window.set_decorated(False)
                window.set_position(gtk.WIN_POS_CENTER)
                window.set_size_request(width or 240, height or 320)
                window.add(vbox)
                window.show_all()

                self.hide_splash_screen(now=True)
                self.splash = {
                    'window': window,
                    'vbox': vbox,
                    'message': lbl,
                    'progress': pbar
                }
            if now:
                show(self)
            else:
                gobject.idle_add(show, self)

        def hide_splash_screen(self, now=False):
            def hide(self):
                for k in self.splash or []:
                    if self.splash[k] is not None:
                        self.splash[k].destroy()
                self.splash = None
            if now:
                hide(self)
            else:
                gobject.idle_add(hide, self)

        def _get_webview(self):
            if not self._webview:
                try:
                    self._webview = UnityWebView(self)
                except ImportError:
                    pass
            return self._webview

        def notify_user(self, message='Hello'):
            if pynotify:
                notification = pynotify.Notification(
                    "Mailpile", message, "dialog-warning")
                notification.set_urgency(pynotify.URGENCY_NORMAL)
                notification.show()
            else:
                print 'FIXME: Notify: %s' % message

        _STATUS_MODES = {
            'startup': appindicator.STATUS_ACTIVE,
            'normal': appindicator.STATUS_ACTIVE,
            'working': appindicator.STATUS_ACTIVE,
            'attention': appindicator.STATUS_ATTENTION,
            'shutdown': appindicator.STATUS_ATTENTION,
        }
        def _set_status(self, mode, now=False):
            if now:
                do = lambda o, a: o(a)
            else:
                do = gobject.idle_add
            if 'indicator_icons' in self.config:
                icon = self.config['indicator_icons'].get(mode)
                if not icon:
                    icon = self.config['indicator_icons'].get('normal')
                if icon:
                    do(self.ind.set_icon, self._theme_image(icon))
            do(self.ind.set_status, self._STATUS_MODES[mode])

        def set_menu_label(self, item=None, label=None):
            if item and item in self.items:
                gobject.idle_add(self.items[item].set_label, label)

        def set_menu_sensitive(self, item=None, sensitive=True):
            if item and item in self.items:
                gobject.idle_add(self.items[item].set_sensitive, sensitive)

        def run(self):
            self._menu_setup()
            self._ind_setup()
            self.ready = True
            try:
                gtk.main()
            except:
                traceback.print_exc()

    return MailpileIndicator
Пример #43
0
def import_gobject2():
    import gobject  #@UnresolvedImport
    gobject.threads_init()
    return gobject
Пример #44
0
def main():
    parser = ArgumentParser(description=sys.argv[0])
    parser.add_argument('inputs', nargs='+', help='Path to digital input')
    args = parser.parse_args()

    DBusGMainLoop(set_as_default=True)
    dbusservice = VeDbusService('com.victronenergy.digitalinput')

    inputs = dict(enumerate(args.inputs, 1))
    pulses = EpollPulseCounter()  # callable that iterates over pulses

    def register_gpio(path, gpio, f):
        print "Registering GPIO {} for function {}".format(gpio, f)
        dbusservice.add_path('/Count/{}'.format(gpio), value=0)
        dbusservice['/Count/{}'.format(gpio)] = settings[gpio]['count']
        if f == INPUT_FUNCTION_COUNTER:
            dbusservice.add_path('/Volume/{}'.format(gpio), value=0)
            dbusservice['/Volume/{}'.format(
                gpio)] = settings[gpio]['count'] * settings[gpio]['rate']
        elif f == INPUT_FUNCTION_ALARM:
            dbusservice.add_path('/Alarms/{}'.format(gpio), value=0)
        pulses.register(path, gpio)

    def unregister_gpio(gpio):
        print "unRegistering GPIO {}".format(gpio)
        pulses.unregister(gpio)
        for pth in ('Count', 'Volume', 'Alarms'):
            k = '/{}/{}'.format(pth, gpio)
            if k in dbusservice:
                del dbusservice[k]

    # Interface to settings
    def handle_setting_change(inp, setting, old, new):
        if setting == 'function':
            if new:
                # Input enabled. If already enabled, unregister the old one first.
                if pulses.registered(inp):
                    unregister_gpio(inp)
                register_gpio(inputs[inp], inp, int(new))
            elif old:
                # Input disabled
                unregister_gpio(inp)

    settings = {}
    for inp, pth in inputs.items():
        supported_settings = {
            'function':
            ['/Settings/DigitalInput/{}/Function'.format(inp), 0, 0, 2],
            'rate': [
                '/Settings/DigitalInput/{}/LitersPerPulse'.format(inp), 1, 1,
                100
            ],
            'count':
            ['/Settings/DigitalInput/{}/Count'.format(inp), 0, 0, MAXCOUNT, 1]
        }
        settings[inp] = sd = SettingsDevice(dbusservice.dbusconn,
                                            supported_settings,
                                            partial(handle_setting_change,
                                                    inp),
                                            timeout=10)
        if sd['function'] > 0:
            register_gpio(pth, inp, int(sd['function']))

    def poll(mainloop):
        from time import time
        #stamps = { inp: [0] * 5 for inp in gpios }
        idx = 0

        try:
            for inp, level in pulses():
                function = settings[inp]['function']

                # Only increment Count on rising edge.
                if level:
                    countpath = '/Count/{}'.format(inp)
                    v = (dbusservice[countpath] + 1) % MAXCOUNT
                    dbusservice[countpath] = v
                    if function == INPUT_FUNCTION_COUNTER:
                        dbusservice['/Volume/{}'.format(
                            inp)] = v * settings[inp]['rate']

                if function == INPUT_FUNCTION_ALARM:
                    dbusservice['/Alarms/{}'.format(inp)] = bool(
                        level) * 2  # Nasty way of limiting to 0 or 2.
        except:
            traceback.print_exc()
            mainloop.quit()

    # Need to run the gpio polling in separate thread. Pass in the mainloop so
    # the thread can kill us if there is an exception.
    gobject.threads_init()
    mainloop = gobject.MainLoop()

    poller = Thread(target=lambda: poll(mainloop))
    poller.daemon = True
    poller.start()

    # Periodically save the counter
    def _save_counters():
        for inp in inputs:
            if settings[inp]['function'] > 0:
                settings[inp]['count'] = dbusservice['/Count/{}'.format(inp)]

    def save_counters():
        _save_counters()
        gobject.timeout_add(SAVEINTERVAL, save_counters)

    gobject.timeout_add(SAVEINTERVAL, save_counters)

    # Save counter on shutdown
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))

    try:
        mainloop.run()
    except KeyboardInterrupt:
        pass
    finally:
        _save_counters()
Пример #45
0
try:
    import pygtk
    if not sys.platform == 'win32':
        pygtk.require("2.0")
except ImportError:
    logging.error('PyGTK not found. Please install it (python-gtk2).')
    sys.exit(1)

try:
    import gtk
    import gobject
    # Some notes on threads_init:
    # only gtk.gdk.threads_init(): pdf export works, but gui hangs afterwards
    # only gobject.threads_init(): pdf export works, gui works
    # both: pdf export works, gui hangs afterwards
    gobject.threads_init(
    )  # only initializes threading in the glib/gobject module
except (ImportError, AssertionError), e:
    logging.error(e)
    logging.error('gtk not found. Please install PyGTK (python-gtk2)')
    sys.exit(1)

from rednotebook.util import dates
from rednotebook import backup

from rednotebook.util.statistics import Statistics
from rednotebook.gui.main_window import MainWindow
from rednotebook import storage
from rednotebook.data import Month


class Journal:
Пример #46
0
def main():
    lv = ListView()
    lv.show_all()
    gobject.threads_init()
    gtk.main()
Пример #47
0
 def fake_main_loop(self):
     gobject.threads_init()
     dbus.glib.init_threads()
     self.main_loop = gobject.MainLoop()
     self.main_loop.run()
Пример #48
0
    def evaluate(self, evaluee):
        self.frame_rate_counter = 0
        self.step_time = time.time()

        global ctrl_client
        if ctrl_client and not self.ctrl_thread_started:
            thread.start_new_thread(check_stop, (self, ))
            self.ctrl_thread_started = True

        self.evaluations_taken = 0
        self.energy = INITIAL_ENERGY
        self.fitness = 0
        self.presence = self.prev_presence = (None, None)
        gobject.threads_init()
        dbus.mainloop.glib.threads_init()
        self.loop = gobject.MainLoop()

        def update_energy(task, energy):
            task.energy += energy

        def main_lambda(task):
            if task.energy <= 0 or task.evaluations_taken >= MAX_STEPS:
                task.motorLock.acquire()
                stopThymio(thymioController)
                task.motorLock.release()
                task.loop.quit()

                if task.energy <= 0:
                    print 'Energy exhausted'
                else:
                    print 'Time exhausted'

                return False

            if not self.goalReached:
                callback = lambda (psvalues): task.cameraCallback(evaluee, lambda (energy): update_energy(task, energy),
                                                                  psvalues)
            else:
                callback = self.goal_reach_camera_callback
                self.camera.update_callback(callback)
                print '===== Goal reached!'

                self.goalReachedCounter += 1

                self.motorLock.acquire()
                stopThymio(self.thymioController)
                self.motorLock.release()

                self.camera.update_callback(self.goal_reach_camera_callback)

                self.conditionGoalReached.acquire()
                self.puckRemoved = False
                while not self.puckRemoved:
                    self.thymioController.SendEventName('PlayFreq', [700, 0], reply_handler=dbusReply, error_handler=dbusError)
                    time.sleep(.3)
                    self.thymioController.SendEventName('PlayFreq', [0, -1], reply_handler=dbusReply, error_handler=dbusError)
                    self.conditionGoalReached.wait(0.7)

                self.conditionGoalReached.release()
                time.sleep(15)
                print "finished puck wait loop"
                self.goalReached = False
                self.prev_presence = list(self.prev_presence)
                if len(self.prev_presence) >= 3:
                    self.prev_presence[0] = self.prev_presence[2] = self.camera.MAX_DISTANCE
                time.sleep(2)


            if not self.camera.isAlive():
                print "starting camera"
                #Call the camera asynchroniously. Call the callback when the presence values are ready.
                self.camera.start_camera(callback, task.cameraErrorCallback)
                print "camera started"
            else:
                self.camera.update_callback(callback)
            self.cameraWait()
            return True
        gobject.timeout_add(int(self.timeStep * 1000), lambda: main_lambda(self))


        print 'Starting loop...'
        self.loop.run()

        fitness = self.getFitness()
        print 'Fitness at end: %d' % fitness

        if self.camera.isAlive():
            # self.camera.stop()
            self.camera.pause()
            # self.camera.join()

        self.motorLock.acquire()
        stopThymio(self.thymioController)
        self.motorLock.release()

        time.sleep(1)

        self.individuals_evaluated += 1

        return {'fitness': fitness}
Пример #49
0
def run(server_, port, type_):
    '''
	Will get called from a child process once the autoreload system is ready
	everything will be setup so the rpc client can work.
    '''
    global server, manager, bus, loop

    loop = gobject.MainLoop()

    # first connect to the server, we can't do much without it
    try:
        server = rpyc.connect(server_, int(port))
    except:
        import time
        logger.info("server is not running")
        time.sleep(10)
        autoreload.RELOAD = True
        sys.exit(3)

    # now try to get into dbus and init gobject
    bus = dbus.SystemBus()
    gobject.threads_init()
    dbus.glib.init_threads()

    # register for a few signals
    bus.add_signal_receiver(handle_name_owner_changed, 'NameOwnerChanged',
                            'org.freedesktop.DBus', 'org.freedesktop.DBus',
                            '/org/freedesktop/DBus')

    bus.add_signal_receiver(handle_adapter_added_or_removed,
                            signal_name='AdapterAdded',
                            dbus_interface='org.bluez.Manager',
                            member_keyword='signal')

    bus.add_signal_receiver(handle_adapter_added_or_removed,
                            signal_name='AdapterRemoved',
                            dbus_interface='org.bluez.Manager',
                            member_keyword='signal')

    # create the manager and register for init
    try:
        if type_ == 'scanner':
            from scanner import ScanManager
            logger.info("init scanner")
            manager = ScanManager(bus, rpc=server)
        elif type_ == 'uploader':
            logger.info("init uploader")
            from uploader import UploadManager
            manager = UploadManager(bus, rpc=server, loop=loop)
        else:
            for i in pluginsystem.get_plugins('serverxr'):
                if type_ == i.provides['serverxr_type']:
                    logger.info("init %s" % i.provides['serverxr_type'])
                    module = __import__("%s.serverxr" % i.name,
                                        fromlist=[
                                            i.provides['serverxr_manager'],
                                        ])
                    klass = getattr(module, i.provides['serverxr_manager'])
                    manager = klass(bus, rpc=server)
                    break
        if manager is None:
            raise Exception("Not valid type")
        gobject.timeout_add(100,
                            init)  # delay initialization 'til loop is running
    except dbus.DBusException, err:
        logger.info("bluez isn't ready, delaying init")
Пример #50
0
def main():
    print("Peephole.")
    usage = "%prog: [--disable <driver_name>]"

    parser = OptionParser(usage)
    parser.add_option("-d",
                      "--disable",
                      dest="disable",
                      default="",
                      help="Comma separated list of LCD drivers to disable")
    (options, args) = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG)

    gobject.threads_init()

    mainloop = gobject.MainLoop()
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    system_bus = dbus.SystemBus()
    name = dbus.service.BusName(PEEPHOLE_WELL_KNOWN_NAME, system_bus)
    #my_lcd = peephole.drivers.picolcd.PicoLCD()

    disabled_drivers = options.disable.split(',')

    lcds = []
    if "gtk" not in disabled_drivers:
        lcds += peephole.drivers.gtklcd.probe()
    if "picolcd" not in disabled_drivers:
        lcds += peephole.drivers.picolcd.probe()

    if len(lcds) < 1:
        logging.error("No LCD devices available.")
        return -1
    dbus_lcds = []

    for lcd in lcds:
        logging.info("Initialising detected LCD: '%s'." % lcd.get_name())
        dbus_lcds.append(DBusLCD(lcd, system_bus, lcd.get_name()))
        lcd.start()
        lcd.clear()
        lcd.set_text(
            "\x06\x05\x04\x03\x02\x01Peephole\x01\x02\x03\x04\x05\x06", 0, 0)
        #         import time
        #         for i in range(0, 12):
        #             string1 = ""

        #             begin = i * 20
        #             if begin == 0:
        #                 begin = 1
        #             end = (i + 1) * 20

        #             print "BEGIN AT : %s" % begin

        #             for n in range(begin, end):
        #                 string1 += chr(n)

        #             print len(string1)

        #             lcd.set_text(string1, 0, 0)
        #             lcd.set_text(hex(begin) + "    ", 1, 0)

        #             time.sleep(2)

        lcd.set_backlight(1)

    root_obj = DBusPeephole(dbus_lcds, system_bus)

    try:
        mainloop.run()
    except KeyboardInterrupt:
        # user pressed ^C, most likely.
        for lcd in lcds:
            lcd.stop()
Пример #51
0
    def __init__(self,
                 size=None,
                 view_port_center=(0, 0),
                 view_port_width=None,
                 view_port_height=None,
                 recording=True,
                 max_num_frames=None,
                 flip_y=False,
                 title='Euv',
                 time_step=0.1):
        gobject.threads_init()
        gtk.gdk.threads_init()

        if size is None:
            size = (800, 600)
        self.view_port_center = view_port_center
        if view_port_width == None and view_port_height == None:
            raise Exception(
                "Either view_port_width or view_port_height must be set!")
        self.view_port_width = view_port_width
        self.view_port_height = view_port_height

        super(App, self).__init__(gtk.WINDOW_TOPLEVEL)
        self.set_title(title)

        settings = gtk.settings_get_default()
        settings.set_long_property("gtk-button-images", 1, '*')

        self.set_resizable(True)
        self.vbox = gtk.VBox(False, 0)
        self.add(self.vbox)
        self.canvas = gtk.DrawingArea()
        self.set_default_size(size[0], size[1])
        self.canvas.connect("expose_event", self.on_canvas_expose)
        self.vbox.pack_start(self.canvas, True, True, 0)
        hbox = gtk.HBox(False, 0)
        self.vbox.pack_start(hbox, False, True, 0)
        self.recording = recording
        self.flip_y = flip_y
        self.time_step = time_step
        if recording:
            self.buttonbox = gtk.HBox(False, 0)
            hbox.pack_start(self.buttonbox, True, False, 0)
            self.button_previous = image_button(stock=gtk.STOCK_MEDIA_REWIND)
            self.button_previous.connect("clicked",
                                         self.on_button_previous_clicked)
            self.buttonbox.pack_start(self.button_previous, False, False, 0)

            self.button_pause = image_button(stock=gtk.STOCK_MEDIA_PAUSE)
            self.button_pause.connect("clicked", self.on_button_pause_clicked)
            self.buttonbox.pack_start(self.button_pause, False, False, 0)

            self.button_next = image_button(stock=gtk.STOCK_MEDIA_FORWARD)
            self.button_next.connect("clicked", self.on_button_next_clicked)
            self.buttonbox.pack_start(self.button_next, False, False, 0)

            self.frame_scale = gtk.HScale()
            self.frame_adjustment = self.frame_scale.get_adjustment()
            self.frame_scale.set_digits(0)
            self.frame_adjustment.connect(
                "value-changed", self.on_frame_adjustment_value_changed)
            self.frame_scale.set_size_request(400, -1)
            self.buttonbox.pack_start(self.frame_scale, True, True, 0)
            if not max_num_frames is None:
                self.set_max_num_frames(max_num_frames)

        self.connect("delete_event", self.on_delete_event)
        self._user_break = False
        self.frames = []
        self.current_frame = -1
        self.pause = False
        gobject.timeout_add(int(self.time_step * 1000), self.play)
Пример #52
0
 def run(self):
     # Prepare Gtk to run neatly in a thread and not hold the global lock
     gtk.gdk.threads_init()
     gobject.threads_init()
     # Go to the main loop, which will only end if the window's closed
     gtk.main()
Пример #53
0
 def run(self):
     gobject.threads_init()
     self.loop = gobject.MainLoop()
     self.loop.run()
Пример #54
0
 def setUp(self):
     gobject.threads_init()
     self.view = WebView()
     self.mainFrame = self.view.get_main_frame()
Пример #55
0
def main(args=None):
    if args is None:
        args = sys.argv
        pass
    positionals = []
    guis = []
    configfiles = []
    explogfile = None
    appendlog = False
    dpdfiles = []
    paramupdates = []

    argc = 1

    while argc < len(args):
        arg = args[argc]

        if arg == "-f":
            argc += 1
            configfiles.append(args[argc])
            pass
        elif arg == "-g":
            argc += 1
            guis.append(args[argc])
            pass
        elif arg == "-d":
            argc += 1
            dpdfiles.append(args[argc])
            pass
        elif arg == '-h' or arg == "--help":
            print("""Usage: %s [--gtk3] [-f <config.dcc>]  [-g gui.glade] ...
        
Flags:
  -f <config.dcc>     Open this config file (multiple OK)
  -g <gui.glade>      Open this gui (multiple OK)
  -d <params.dpd>     Load parameters from this .dpd file (multiple OK)
""" % (args[0]))
            sys.exit(0)
            pass
        elif arg == "--gtk3":
            pass  # handled at import stage, above
        elif arg[0] == '-':
            raise ValueError("Unknown command line switch %s" % (arg))
        else:
            positionals.append(arg)
            pass
        argc += 1
        pass

    if len(positionals) > 0:
        raise ValueError(
            "Too many positional parameters (see -h for command line help")

    if "gobject" in sys.modules:  # only for GTK2
        gobject.threads_init()
        pass

    import_widgets()

    iohandlers = {}  #=dg_io.io()

    paramdb = pdb.paramdb(iohandlers)

    # define universal parameters

    # parameters that are supposed to go in the summary need to have an adddoc() call in explogwindow.syncexplog
    #  and a corresponding remdoc call in explogwindow.unsyncexplog

    paramdb.addparam("hostname", stringv)
    paramdb.addparam("specimen", stringv)
    paramdb.addparam("perfby", stringv)
    paramdb.addparam("date", stringv)

    paramdb.addparam("notes", stringv)

    # auto-set date
    if paramdb["date"].dcvalue.isblank():
        curdate = datetime.datetime.now()
        paramdb["date"].requestvalstr_sync(curdate.isoformat().split("T")[0])
        pass
    # print str(paramdb["date"].dcvalue)

    dc2_misc.set_hostname(paramdb)

    # Connect to dbus (barcode reader)
    dbuslink = dc_dbus_barcode(paramdb)

    ## Create dbus paramserver
    #paramserver=dc_dbus_paramserver(paramdb,explogwin.checklists)
    # paramserver is now created within createparamserver() on demand by the dcc file and stored as a member of explogwin
    paramserver = None

    guistate = create_guistate(
        iohandlers, paramdb
    )  # can add search directories as additional parameters here [os.path.split(fname)[0]])

    for dpdfile in dpdfiles:
        (dpdconfigfiles, dpdguis, dpdchxfiles, dpdplans, dpdexplog,
         dpdparamupdates, dpdSingleSpecimen) = paramdbfile.load_params(dpdfile)
        configfiles.extend(dpdconfigfiles)
        guis.extend(dpdguis)
        #checklists.extend(dpdchxfiles)
        #plans.extend(dpdplans)
        paramupdates.append(dpdparamupdates)

        for configfile in configfiles:
            dc2_misc.load_config(configfile, paramdb, iohandlers,
                                 createparamserver)
            pass

        pass

    dpdlog = []
    for paramupdate in paramupdates:
        dpdlog.extend(paramdbfile.apply_paramdb_updates(paramupdate, paramdb))
        pass

    for (paramname, status, val1, val2) in dpdlog:
        if status == "dangerous":
            sys.stderr.write(
                "Warning loading %s: Dangerous parameter %s ignored\n" %
                (dpdfile, paramname))
            pass
        elif status == "mismatch":
            sys.stderr.write(
                "Warning loading %s: Parameter %s request mismatch (requested: %s; actual: %s)\n"
                % (dpdfile, paramname, str(val1), str(val2)))
            pass
        elif status == "error":
            sys.stderr.write(
                "Warning loading %s: Parameter %s request error (requested: %s)\n"
                % (dpdfile, paramname, str(val1)))
            pass
        elif status != "match":
            raise ValueError("Unknown status message loading paramdb from %s" %
                             (dpdfile))

        pass

    guiwins = []

    for gui in guis:
        open_gui(gui)
        pass

    # open paramdb2 editor
    editor = paramdb2_editor.paramdb2_editor(paramdb)
    editor.connect("delete-event", handle_gui_close)

    MenuBar = gtk.MenuBar()

    FileMenuItem = gtk.MenuItem("File")
    MenuBar.append(FileMenuItem)
    FileMenu = gtk.Menu()
    FileMenuItem.set_submenu(FileMenu)
    SaveDPDMenuItem = gtk.MenuItem("Save params...")
    SaveDPDMenuItem.connect("activate", handle_savedpd, paramdb, guis,
                            configfiles)
    FileMenu.append(SaveDPDMenuItem)
    editor.vbox.pack_start(MenuBar, expand=False, fill=True)
    editor.vbox.reorder_child(MenuBar, 0)
    MenuBar.show_all()

    gtk.main()

    pass
Пример #56
0
 def __init__(self):
     self.queue = []  # Will be a list
     gobject.threads_init()
Пример #57
0
 def __init__(self, x_in=123456, x_out=123456):
     gobject.threads_init()
     EegpyWin.__init__(self, x_in, x_out)
     self.setupOptions()
     self.show_all()
Пример #58
0
def main():
    parser = argparse.ArgumentParser(
        description='Publishes values from the D-Bus to an MQTT broker')
    parser.add_argument('-d',
                        '--debug',
                        help='set logging level to debug',
                        action='store_true')
    parser.add_argument('-q',
                        '--mqtt-server',
                        nargs='?',
                        default=None,
                        help='name of the mqtt server')
    parser.add_argument('-u',
                        '--mqtt-user',
                        default=None,
                        help='mqtt user name')
    parser.add_argument('-P',
                        '--mqtt-password',
                        default=None,
                        help='mqtt password')
    parser.add_argument(
        '-c',
        '--mqtt-certificate',
        default=None,
        help='path to CA certificate used for SSL communication')
    parser.add_argument('-b', '--dbus', default=None, help='dbus address')
    parser.add_argument('-k',
                        '--keep-alive',
                        default=60,
                        help='keep alive interval in seconds',
                        type=int)
    parser.add_argument(
        '-i',
        '--init-broker',
        action='store_true',
        help='Tries to setup communication with VRM MQTT broker')
    args = parser.parse_args()

    print("-------- dbus_mqtt, v{} is starting up --------".format(
        SoftwareVersion))
    logger = setup_logging(args.debug)

    # This allows us to use gobject code in new threads
    gobject.threads_init()

    mainloop = gobject.MainLoop()
    # Have a mainloop, so we can send/receive asynchronous calls to and from dbus
    DBusGMainLoop(set_as_default=True)
    keep_alive_interval = args.keep_alive if args.keep_alive > 0 else None
    handler = DbusMqtt(mqtt_server=args.mqtt_server,
                       ca_cert=args.mqtt_certificate,
                       user=args.mqtt_user,
                       passwd=args.mqtt_password,
                       dbus_address=args.dbus,
                       keep_alive_interval=keep_alive_interval,
                       init_broker=args.init_broker)
    # Start and run the mainloop
    try:
        mainloop.run()
    except KeyboardInterrupt:
        pass
Пример #59
0
def main(argv):
    """
	Parse the command line arguments, then start the application.
	"""

    # set working directory to current script directory
    startDir = os.getcwd()
    os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
    lvExtensions.init()

    # force locale to US to avoid (partial) translation of menus and buttons
    locale.setlocale(locale.LC_ALL, 'C')

    # avoid threads + gtk issues
    gobject.threads_init()

    # initializations
    os.environ['HARPIA_DATA_DIR'] = lvExtensions.harpia_data_dir
    batchMode = False
    experimentalMode = False
    userFiles = []

    # parse command line arguments
    argParser = argparse.ArgumentParser()
    argParser.add_argument('-b',
                           '--batch',
                           help='turn batch mode on',
                           action='store_true')
    argParser.add_argument('-e',
                           '--experimental',
                           help='active experimental blocks',
                           action='store_true')
    argParser.add_argument('-c', '--config-file', help='configuration file')
    args, unknown = argParser.parse_known_args()
    userFiles = unknown
    if args.batch and userFiles:
        batchMode = True
    if args.experimental:
        experimentalMode = True
    if args.config_file:
        lvExtensions.setConfigurationFileName(os.path.abspath(
            args.config_file))

    if not batchMode:
        m = splashScreen()
        m.setup()
        m.show_window()
        sleep(2)

    # fix user files path due to changing dir to Starling dir
    userFiles = [os.path.join(startDir, fileName) for fileName in userFiles]

    ## initialize the frontend
    HarpiaFrontend = harpiagcfrontend.S2iHarpiaFrontend(
        userFiles, batchMode, experimentalMode)

    if not batchMode:
        m.window.set_transient_for(HarpiaFrontend.gtkTopWindow)
        HarpiaFrontend.show(center=0)
        sleep(1)
        m.window.destroy()
        #splScr.window.destroy()
        gtk.main()
Пример #60
0
 def run(self):
     gobject.threads_init()
     gtk.main()