<s> import HydrusConstants as HC <EOL> import HydrusData <EOL> import HydrusExceptions <EOL> import Queue <EOL> import threading <EOL> import traceback <EOL> import weakref <EOL> import HydrusGlobals <EOL> class HydrusPubSub ( object ) : <EOL> def __init__ ( self , controller , binding_errors_to_ignore = None ) : <EOL> if binding_errors_to_ignore is None : <EOL> binding_errors_to_ignore = [ ] <EOL> self . _controller = controller <EOL> self . _binding_errors_to_ignore = binding_errors_to_ignore <EOL> self . _pubsubs = [ ] <EOL> self . _lock = threading . Lock ( ) <EOL> self . _topics_to_objects = { } <EOL> self . _topics_to_method_names = { } <EOL> def _GetCallables ( self , topic ) : <EOL> callables = [ ] <EOL> if topic in self . _topics_to_objects : <EOL> try : <EOL> objects = self . _topics_to_objects [ topic ] <EOL> for object in objects : <EOL> method_names = self . _topics_to_method_names [ topic ] <EOL> for method_name in method_names : <EOL> if hasattr ( object , method_name ) : <EOL> try : <EOL> callable = getattr ( object , method_name ) <EOL> callables . append ( callable ) <EOL> except TypeError as e : <EOL> if '<STR_LIT>' not in str ( e ) : raise <EOL> except Exception as e : <EOL> if not isinstance ( e , self . _binding_errors_to_ignore ) : <EOL> raise <EOL> except : pass <EOL> return callables <EOL> def NoJobsQueued ( self ) : <EOL> with self . _lock : <EOL> return len ( self . _pubsubs ) == <NUM_LIT:0> <EOL> def Process ( self ) : <EOL> callables = [ ] <EOL> with self . _lock : <EOL> if len ( self . _pubsubs ) > <NUM_LIT:0> : <EOL> ( topic , args , kwargs ) = self . _pubsubs . pop ( <NUM_LIT:0> ) <EOL> callables = self . _GetCallables ( topic ) <EOL> for callable in callables : <EOL> if HydrusGlobals . pubsub_profile_mode : <EOL> text = '<STR_LIT>' + topic + '<STR_LIT>' + repr ( callable ) <EOL> if topic == '<STR_LIT:message>' : <EOL> HydrusData . Print ( text ) <EOL> else : <EOL> HydrusData . ShowText ( text ) <EOL> HydrusData . Profile ( '<STR_LIT>' , globals ( ) , locals ( ) ) <EOL> else : <EOL> try : <EOL> callable ( * args , ** kwargs ) <EOL> except HydrusExceptions . ShutdownException : <EOL> return <EOL> def pub ( self , topic , * args , ** kwargs ) : <EOL> with self . _lock : <EOL> self . _pubsubs . append ( ( topic , args , kwargs ) ) <EOL> self . _controller . NotifyPubSubs ( ) <EOL> def pubimmediate ( self , topic , * args , ** kwargs ) : <EOL> with self . _lock : <EOL> callables = self . _GetCallables ( topic ) <EOL> for callable in callables : callable ( * args , ** kwargs ) <EOL> def sub ( self , object , method_name , topic ) : <EOL> with self . _lock : <EOL> if topic not in self . _topics_to_objects : self . _topics_to_objects [ topic ] = weakref . WeakSet ( ) <EOL> if topic not in self . _topics_to_method_names : self . _topics_to_method_names [ topic ] = set ( ) <EOL> self . _topics_to_objects [ topic ] . add ( object ) <EOL> self . _topics_to_method_names [ topic ] . add ( method_name ) </s>
