Ejemplo n.º 1
0
 def update_txt(self, message, color=None):
     gdk.threads_enter()
     self.cfvGtk.append_string(message, color)
     self.cfvGtk.progressbar.set_pulse_step(0.05)
     self.cfvGtk.progressbar.pulse()
     self.cfvGtk.progressbar.set_text("checking...")
     gdk.threads_leave()
Ejemplo n.º 2
0
    def get(self, timeout=None):
        """
        'get' will block until the processed function returns, timeout
        happens, or the work is cancelled.  You can test if you were
        cancelled by the isCancelled() method, and you can test if you
        reached the timeout by the isAlive() method.  Notice,
        cancelling will not make 'get' unblock, besides if you build
        'isCancelled' calls into your function.

        Warning: the get function assumes that if you are the MainThread you
        have the gdklock and if you are not the MainThread you don't have
        the gdklock.

        If this is not true, and the work is not done, calling get
        will result in a deadlock.

        If you haven't used the gtk.gdk.threads_enter nor
        gtk.gdk.threads_leave function, everything should be fine."""

        if not self.isDone():
            if type(currentThread()) == _MainThread:
                threads_leave()
            self.join(timeout)
            if type(currentThread()) == _MainThread:
                threads_enter()
            if self.isAlive():
                return None
            self.done = True
        return self.result
Ejemplo n.º 3
0
	def update_mem_map(self, mem_map):
		if self.mem_map == None:
			self.m_lock.acquire()
			self.mem_map = mem_map;
			self.m_lock.release()
			threads_enter()	
			self.expose_cb(self.da, None)
			threads_leave()
		else:
			i ,x ,y = 0, 10, 26
			cx, cy = self.get_size()
			while i < self.max_mapnr:
				if self.mem_map[i] == mem_map[i]:
					pass
				else:
					self.m_lock.acquire()
					self.mem_map[i] = mem_map[i]
					self.m_lock.release()
					threads_enter()
					v =  int(self.mem_map[i], 16)
					self.da.window.draw_rectangle(self.gcs[v], True, x, y , 6, 6)
					self.da.window.draw_rectangle(self.style.black_gc, 
						False, x, y , 6, 6)
					threads_leave()
				x = x + 8
				i = i + 1
				if x>= cx - 8:
					y = y + 8
					x = 10
Ejemplo n.º 4
0
def acquire():
    me = currentThread()
    t = time.strftime("%H:%M:%S")
    if me.ident not in gdklocks:
        gdklocks[me.ident] = 0
    # Ensure we don't deadlock if another thread is waiting on threads_enter
    # while we wait on _rlock.acquire()
    if me.getName() == "MainThread" and not has():
        if debug:
            print >> debug_stream, "%s %s: %s: glock.acquire: ---> threads_leave()" % (t, me.ident, me.name)
        threads_leave()
        gdklocks[me.ident] -= 1
        if debug:
            print >> debug_stream, "%s %s: %s: glock.acquire: <--- threads_leave()" % (t, me.ident, me.name)
    # Acquire the lock, if it is not ours, or add one to the recursive counter
    if debug:
        print >> debug_stream, "%s %s: %s: glock.acquire: ---> _rlock.acquire()" % (t, me.ident, me.name)
    _rlock.acquire()
    if debug:
        print >> debug_stream, "%s %s: %s: glock.acquire: <--- _rlock.acquire()" % (t, me.ident, me.name)
    # If it is the first time we lock, we will acquire the gdklock
    if _rlock._RLock__count == 1:
        if debug:
            print >> debug_stream, "%s %s: %s: glock.acquire: ---> threads_enter()" % (t, me.ident, me.name)
        threads_enter()
        gdklocks[me.ident] += 1
        if debug:
            print >> debug_stream, "%s %s: %s: glock.acquire: <--- threads_enter()" % (t, me.ident, me.name)
Ejemplo n.º 5
0
 def loop(self):
     gdk.threads_enter()
     try:
         gtk.main()
     except KeyboardInterrupt:
         print "Leaving on ^C"
     gdk.threads_leave()
Ejemplo n.º 6
0
    def get(self, timeout=None):
        """
        'get' will block until the processed function returns, timeout
        happens, or the work is cancelled.  You can test if you were
        cancelled by the isCancelled() method, and you can test if you
        reached the timeout by the isAlive() method.  Notice,
        cancelling will not make 'get' unblock, besides if you build
        'isCancelled' calls into your function.

        Warning: the get function assumes that if you are the MainThread you
        have the gdklock and if you are not the MainThread you don't have
        the gdklock.

        If this is not true, and the work is not done, calling get
        will result in a deadlock.

        If you haven't used the gtk.gdk.threads_enter nor
        gtk.gdk.threads_leave function, everything should be fine."""

        if not self.isDone():
            if type(currentThread()) == _MainThread:
                threads_leave()
            self.join(timeout)
            if type(currentThread()) == _MainThread:
                threads_enter()
            if self.isAlive():
                return None
            self.done = True
        return self.result
Ejemplo n.º 7
0
    def run(self):
	while True:
            threads_enter()
#	    logging.debug("LoopingThread")
	    self.process()
	    threads_leave()
	    time.sleep(self.speed)
Ejemplo n.º 8
0
 def run (self):
     self.result = self.func(self)
     self.done = True
     if self.connections["done"] >= 1:
         threads_enter()
         # In python 2.5 we can use self.publishQueue.join() to wait for all
         # publish items to have been processed.
         self.emit("done")
         threads_leave()
Ejemplo n.º 9
0
    def start(self):
        reactor.callWhenRunning(self._on_reactor_start)

        # Initialize gdk threading
        threads_enter()
        reactor.run()
        # Reactor no longer running so async callbacks (Deferreds) cannot be
        # processed after this point.
        threads_leave()
Ejemplo n.º 10
0
    def start(self):
        reactor.callWhenRunning(self._on_reactor_start)

        # Initialize gdk threading
        threads_enter()
        reactor.run()
        # Reactor no longer running so async callbacks (Deferreds) cannot be
        # processed after this point.
        threads_leave()
Ejemplo n.º 11
0
def initial_setup():
    """
    * set up gdk threading
    * enter it
    * set up glib mainloop threading
    """
    gdk.threads_init()
    gdk.threads_enter()
    gobject.threads_init() #the glib mainloop doesn't love us else
Ejemplo n.º 12
0
 def add_gdk_calls(*args, **kwargs):
     global gtk_fiddle_count
     gtk_fiddle_count += 1
     if not gtk_fiddle_count > 1:
         gdk.threads_enter()
     method(*args, **kwargs)
     gtk_fiddle_count -= 1
     if gtk_fiddle_count == 0:
         gdk.threads_leave()
Ejemplo n.º 13
0
 def run(self):
     # print self.func_args
     # print self.func_kwargs
     self.result = self.func(self, *self.func_args, **self.func_kwargs)
     self.done = True
     if self.connections["done"] >= 1:
         threads_enter()
         # In python 2.5 we can use self.publishQueue.join() to wait for all
         # publish items to have been processed.
         self.emit("done")
         threads_leave()
Ejemplo n.º 14
0
    def On_Expose(canvas, evt):
      gc = canvas.window.new_gc()
      lb = canvas.window.new_gc()
      cm = gc.get_colormap()

      gdk.threads_enter()
      for i in xrange(7):
        color = cm.alloc_color(*index2rgb(i))
        gc.set_foreground(color)
        canvas.window.draw_rectangle(gc, True , 75,  (2 * i + 1) * RowHght , canvas.ThrdInfo[i][1] , RowHght )
        canvas.layout.set_text("%8d" % (canvas.ThrdInfo[i][0],))
        canvas.window.draw_layout(lb, 5 , (2 * i + 1) * RowHght + canvas.TxtPad , canvas.layout)
      #end for
      gdk.threads_leave()
Ejemplo n.º 15
0
def acquire():
    me = currentThread()
    if me.ident not in gdklocks:
        gdklocks[me.ident] = 0
    # Ensure we don't deadlock if another thread is waiting on threads_enter
    # while we wait on _rlock.acquire()
    if me.getName() == "MainThread" and not has():
        threads_leave()
        gdklocks[me.ident] -= 1
    # Acquire the lock, if it is not ours, or add one to the recursive counter
    _rlock.acquire()
    # If it is the first time we lock, we will acquire the gdklock
    if _rlock._RLock__count == 1:
        threads_enter()
        gdklocks[me.ident] += 1
Ejemplo n.º 16
0
 def __init__(self, conn):
     self.__conn = conn
     self.__path = SPEED_METER_PATH
     # initiate parent class
     super(SpeedMeter, self).__init__(self.__conn, self.__path)
     # list for caculate typing speed
     self.list = [(0, time.time(), 0)]
     # do gui part here
     self.create_ui()
     # timer
     self.full = False
     self.c_time = 0
     self.timer = Timer(self.update_speed)
     gdk.threads_enter()
     self.timer.start()
     gdk.threads_leave()
     # showing
     self.run ()
Ejemplo n.º 17
0
 def run (self):
     while True:
         v = self.queue.get()
         if v == None:
             break
         threads_enter()
         l = [v]
         while True:
             try:
                 v = self.queue.get_nowait()
             except Queue.Empty:
                 break
             else: l.append(v)
         try:
             if self.sendPolicy == self.SEND_LIST:
                 self.parrent.emit(self.signal, l)
             elif self.sendPolicy == self.SEND_LAST:
                 self.parrent.emit(self.signal, l[-1])
         finally:
             threads_leave()
Ejemplo n.º 18
0
 def run (self):
     while True:
         v = self.queue.get()
         if v == None:
             break
         threads_enter()
         l = [v]
         while True:
             try:
                 v = self.queue.get_nowait()
             except Queue.Empty:
                 break
             else: l.append(v)
         try:
             if self.sendPolicy == self.SEND_LIST:
                 self.parrent.emit(self.signal, l)
             elif self.sendPolicy == self.SEND_LAST:
                 self.parrent.emit(self.signal, l[-1])
         finally:
             threads_leave()
Ejemplo n.º 19
0
	def download(self):
		threads_enter()
		try:
			self.lock.acquire()
			self.magic = self.uri
			self.lock.release()

			infile = urllib2.urlopen(self.uri)
			outfile = open(self.filename,'wb')
			outfile.truncate()
			outfile.write(infile.read())
			self.expires = datetime.datetime.now()+self.lifetime

			self.lock.acquire()
			self.magic = self.filename
			self.lock.release()

			if self.done != None:
				self.done()
		finally:
			threads_leave()
Ejemplo n.º 20
0
	def run(self):
		threads_enter()
		try:
			f = open(self.filename,'rw+')
		except:
			f = open(self.filename, 'w')
		try:
			allconfig = json.loads(f.read())
		except:
			allconfig = {}
		if self.namespace in allconfig:
			results = self.action(self.context,allconfig[self.namespace])
		else:
			results = self.action(self.context,{})
		if results != None:
			f.seek(0)
			allconfig[self.namespace] = results
			f.write(json.dumps(allconfig))
			f.truncate()
		f.close()
		threads_leave()
Ejemplo n.º 21
0
	def save(self, threaded = True):
		''' Save a cacheitem to disk '''
		print "Trying to get into save"
		if threaded: threads_enter()
		print "threads_enter success"
		self.lock.acquire()
		print "lock acquired"
		try:
			print "Trying to save"
			self.lastSave = datetime.datetime.now()
			index = open(os.path.join(self.dir, 'index'), 'w')
			index.truncate()
			res = {}
			for resource in self.resources:
				res[resource] = self.resources[resource].toJSON()
			index.write(json.dumps({'index':self.index,
				'resources':res
			}))
			print "saved"
		finally:
			index.close()
			self.lock.release()
			if threaded: threads_leave()
Ejemplo n.º 22
0
  def Adjust(self, ThrdIx, Time, Value):
    gdk.threads_enter()
    gc = self.window.new_gc()
    lb = self.window.new_gc()
    cm = gc.get_colormap()

    OldValue = self.ThrdInfo[ThrdIx][1]
    if OldValue < Value:
      color = cm.alloc_color(*index2rgb(ThrdIx))
      base = 75 + OldValue
    else:
      color = self.style.bg[0]
      base = 75 + Value
    #end if
    gc.set_foreground(color)
    self.window.draw_rectangle(gc, True , base , (2 * ThrdIx + 1) * RowHght , abs(Value - OldValue)  , RowHght)
    self.layout.set_text("%8d" % (Time,))
    self.window.begin_paint_rect((0, (2 * ThrdIx + 1) * RowHght, 75 , RowHght))
    self.window.draw_layout(lb, 5 , (2 * ThrdIx + 1) * RowHght + self.TxtPad , self.layout)
    self.window.end_paint()
    gdk.flush()
    gdk.threads_leave()
    self.ThrdInfo[ThrdIx] = [Time, Value]
Ejemplo n.º 23
0
    def __init__(self, func, *func_args, **func_kwargs):
        """ Initialize a new GtkWorker around a specific function """

        # WARNING: This deadlocks if calling code already has the gdk lock and
        # is not the MainThread
        if type(currentThread()) != _MainThread:
            threads_enter()
        GObject.__init__(self)
        if type(currentThread()) != _MainThread:
            threads_leave()

        Thread.__init__(self, args=func_args, kwargs=func_kwargs)
        self.func_args = func_args
        self.func_kwargs = func_kwargs
        self.setDaemon(True)

        # By some reason we cannot access __gsignals__, so we have to do a
        # little double work here
        self.connections = {"progressed": 0, "published": 0, "done": 0}
        self.handler_ids = {}

        self.func = func
        self.cancelled = False
        self.done = False
        self.progress = 0

        #######################################################################
        # Publish and progress queues                                         #
        #######################################################################

        class Publisher(Thread):
            SEND_LIST, SEND_LAST = range(2)

            def __init__(self, parrent, queue, signal, sendPolicy):
                Thread.__init__(self)
                self.setDaemon(True)
                self.parrent = parrent
                self.queue = queue
                self.signal = signal
                self.sendPolicy = sendPolicy

            def run(self):
                while True:
                    v = self.queue.get()
                    if v is None:
                        break
                    threads_enter()
                    l = [v]
                    while True:
                        try:
                            v = self.queue.get_nowait()
                        except Queue.Empty:
                            break
                        else:
                            l.append(v)
                    try:
                        if self.sendPolicy == self.SEND_LIST:
                            self.parrent.emit(self.signal, l)
                        elif self.sendPolicy == self.SEND_LAST:
                            self.parrent.emit(self.signal, l[-1])
                    finally:
                        threads_leave()

        self.publishQueue = Queue.Queue()
        self.publisher = Publisher(self, self.publishQueue, "published",
                                   Publisher.SEND_LIST)
        self.publisher.start()

        self.progressQueue = Queue.Queue()
        self.progressor = Publisher(self, self.progressQueue, "progressed",
                                    Publisher.SEND_LAST)
        self.progressor.start()
Ejemplo n.º 24
0
 def update_done(self, message):
     gdk.threads_enter()
     self.cfvGtk.append_string(message)
     self.cfvGtk.progressbar.set_fraction(1.0)
     self.cfvGtk.progressbar.set_text("done")
     gdk.threads_leave()
Ejemplo n.º 25
0
 def serve_forever(self):
     gdk.threads_enter()
     gtk.main()
     gdk.threads_leave()
Ejemplo n.º 26
0
 def run (self):
     gdk.threads_enter()
     gtk.main()
Ejemplo n.º 27
0
    def __init__(self, func, *func_args, **func_kwargs):
        """ Initialize a new GtkWorker around a specific function """

        # WARNING: This deadlocks if calling code already has the gdk lock and
        # is not the MainThread
        if type(currentThread()) != _MainThread:
            threads_enter()
        GObject.__init__(self)
        if type(currentThread()) != _MainThread:
            threads_leave()

        Thread.__init__(self, args=func_args, kwargs=func_kwargs)
        self.func_args = func_args
        self.func_kwargs = func_kwargs
        self.setDaemon(True)

        # By some reason we cannot access __gsignals__, so we have to do a
        # little double work here
        self.connections = {"progressed": 0, "published": 0, "done": 0}
        self.handler_ids = {}

        self.func = func
        self.cancelled = False
        self.done = False
        self.progress = 0

        #######################################################################
        # Publish and progress queues                                         #
        #######################################################################

        class Publisher(Thread):
            SEND_LIST, SEND_LAST = range(2)

            def __init__(self, parrent, queue, signal, sendPolicy):
                Thread.__init__(self)
                self.setDaemon(True)
                self.parrent = parrent
                self.queue = queue
                self.signal = signal
                self.sendPolicy = sendPolicy

            def run(self):
                while True:
                    v = self.queue.get()
                    if v is None:
                        break
                    threads_enter()
                    l = [v]
                    while True:
                        try:
                            v = self.queue.get_nowait()
                        except Queue.Empty:
                            break
                        else:
                            l.append(v)
                    try:
                        if self.sendPolicy == self.SEND_LIST:
                            self.parrent.emit(self.signal, l)
                        elif self.sendPolicy == self.SEND_LAST:
                            self.parrent.emit(self.signal, l[-1])
                    finally:
                        threads_leave()

        self.publishQueue = Queue.Queue()
        self.publisher = Publisher(self, self.publishQueue, "published", Publisher.SEND_LIST)
        self.publisher.start()

        self.progressQueue = Queue.Queue()
        self.progressor = Publisher(self, self.progressQueue, "progressed", Publisher.SEND_LAST)
        self.progressor.start()
Ejemplo n.º 28
0
    def __init__(self):
        threads_enter()
        gobject.type_register(VideoWidget)
        gobject.type_register(ShowBox)
        gobject.type_register(Configer)
        gobject.type_register(DescriptionWindow)
        gobject.type_register(SearchBar)
        
        locale.setlocale(locale.LC_ALL,locale.getdefaultlocale())
        
        factory=gtk.IconFactory()
        try:
            f=self.get_resource('pixmaps/bookmark.png')
            loader=gtk.gdk.PixbufLoader()
            loader.write(f.read())
            f.close()
            factory.add(self.STOCK_BOOKMARK,gtk.IconSet(loader.get_pixbuf()))
            loader.close()
        except:
            raise
        factory.add_default()
        gtk.stock_add(((self.STOCK_BOOKMARK, "_Bookmarks", gtk.gdk.CONTROL_MASK, gtk.gdk.keyval_from_name('B'), "youtube-show",),))
        
        self.userDir=UserDir()
        self.config=Config(self.userDir.get_conf_file())
        self.config.load()
        self.bookmarks=Bookmarks.Bookmarks(self.userDir.get_file('bookmarks'))
        self.bookmarks.load()
        self.caches=YoutubeConnector.CacheSaver(self.userDir.get_file('caches.txt'))

        self.cookies=CookieJar()
        self.downloader=urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookies))
        self.ytsearcher = YoutubeConnector.YTSearcher(self.downloader)
        self.ytconnector = YoutubeConnector.YTConnector(self.downloader, self.caches)
        
        self.searching = threading.Event()
        self.is_fullscreen=False
        self.history=History()
        
        self.viewer = Viewer.Viewer()
        self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        if not self.win:
            raise RuntimeError()
        self.win.connect('delete_event', self.cleanup)
        self.win.connect('destroy', self.destroy)
        self.win.connect('key_press_event', self.on_key_press)
        self.win.connect_object('window-state-event', self.on_window_state_change,self)

        self.build_menu_bar()
        
        self.build_tool_bar()
        self.showbox = ShowBox()
        self.showbox.connect('scroll-end-event', self.do_next_search)
        self.showbox.show()
        self.statusbar = gtk.Statusbar()
        self.statusbar.show()
        self.progressbar = gtk.ProgressBar()
        self.statusbar.add(self.progressbar)
        
        self.align = gtk.VBox()
        self.align.pack_start(self.menubar, expand=False, fill=True)
        self.align.pack_start(self.toolbar, expand=False, fill=True)
        self.align.pack_start(self.showbox, expand=True, fill=True)
        self.align.pack_start(self.statusbar, expand=False, fill=True)

        self.statusbar.push(1, 'Ready')
        self.apply_config()
        self.align.show()
        self.win.add(self.align)
        self.win.set_title("youtube-show")
    
        theme=gtk.icon_theme_get_for_screen(gtk.gdk.screen_get_default())
        try:
            icon=theme.load_icon('youtube_show',48,0)
            self.win.set_icon(icon)
        except:
            try:
                with self.get_resource('pixmaps/youtube-show.png') as iconfile:
                    loader=gdk.PixbufLoader()
                    loader.write(iconfile.read())
                    self.win.set_icon(loader.get_pixbuf())
                    loader.close()
            except:
                pass
        
        w,h=self.config['size']
        if w>-1 and h>-1:
            self.win.resize(w,h)
        else:
            self.win.resize(500, 600)
        self.win.show()
        threads_leave()
Ejemplo n.º 29
0
 def wrapper(obj, *args):
   gdk.threads_leave()
   handler(obj, *args)
   gdk.threads_enter()
Ejemplo n.º 30
0
 def serve_forever(self):
     gdk.threads_enter()
     gtk.main()
     gdk.threads_leave()
Ejemplo n.º 31
0
 def run(self):
     threads_enter()
     pipe = popen(self.command,"r")
     threads_leave()
     self.output = pipe.read()
Ejemplo n.º 32
0
    def __init__(self):
        threads_enter()
        gobject.type_register(VideoWidget)
        gobject.type_register(ShowBox)
        gobject.type_register(Configer)
        gobject.type_register(DescriptionWindow)
        gobject.type_register(SearchBar)

        locale.setlocale(locale.LC_ALL, locale.getdefaultlocale())

        factory = gtk.IconFactory()
        try:
            f = self.get_resource('pixmaps/bookmark.png')
            loader = gtk.gdk.PixbufLoader()
            loader.write(f.read())
            f.close()
            factory.add(self.STOCK_BOOKMARK, gtk.IconSet(loader.get_pixbuf()))
            loader.close()
        except:
            raise
        factory.add_default()
        gtk.stock_add(((
            self.STOCK_BOOKMARK,
            "_Bookmarks",
            gtk.gdk.CONTROL_MASK,
            gtk.gdk.keyval_from_name('B'),
            "youtube-show",
        ), ))

        self.userDir = UserDir()
        self.config = Config(self.userDir.get_conf_file())
        self.config.load()
        self.bookmarks = Bookmarks.Bookmarks(
            self.userDir.get_file('bookmarks'))
        self.bookmarks.load()
        self.caches = YoutubeConnector.CacheSaver(
            self.userDir.get_file('caches.txt'))

        self.cookies = CookieJar()
        self.downloader = urllib2.build_opener(
            urllib2.HTTPCookieProcessor(self.cookies))
        self.ytsearcher = YoutubeConnector.YTSearcher(self.downloader)
        self.ytconnector = YoutubeConnector.YTConnector(
            self.downloader, self.caches)

        self.searching = threading.Event()
        self.is_fullscreen = False
        self.history = History()

        self.viewer = Viewer.Viewer()
        self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        if not self.win:
            raise RuntimeError()
        self.win.connect('delete_event', self.cleanup)
        self.win.connect('destroy', self.destroy)
        self.win.connect('key_press_event', self.on_key_press)
        self.win.connect_object('window-state-event',
                                self.on_window_state_change, self)

        self.build_menu_bar()

        self.build_tool_bar()
        self.showbox = ShowBox()
        self.showbox.connect('scroll-end-event', self.do_next_search)
        self.showbox.show()
        self.statusbar = gtk.Statusbar()
        self.statusbar.show()
        self.progressbar = gtk.ProgressBar()
        self.statusbar.add(self.progressbar)

        self.align = gtk.VBox()
        self.align.pack_start(self.menubar, expand=False, fill=True)
        self.align.pack_start(self.toolbar, expand=False, fill=True)
        self.align.pack_start(self.showbox, expand=True, fill=True)
        self.align.pack_start(self.statusbar, expand=False, fill=True)

        self.statusbar.push(1, 'Ready')
        self.apply_config()
        self.align.show()
        self.win.add(self.align)
        self.win.set_title("youtube-show")

        theme = gtk.icon_theme_get_for_screen(gtk.gdk.screen_get_default())
        try:
            icon = theme.load_icon('youtube_show', 48, 0)
            self.win.set_icon(icon)
        except:
            try:
                with self.get_resource('pixmaps/youtube-show.png') as iconfile:
                    loader = gdk.PixbufLoader()
                    loader.write(iconfile.read())
                    self.win.set_icon(loader.get_pixbuf())
                    loader.close()
            except:
                pass

        w, h = self.config['size']
        if w > -1 and h > -1:
            self.win.resize(w, h)
        else:
            self.win.resize(500, 600)
        self.win.show()
        threads_leave()