def _print_greetings(self, handle): if handle.object_id is None: ka_debug.info('Activity is started anew (from the home view).') else: ka_debug.info( 'Activity is started from the journal and the object id is %s' % handle.object_id)
def add_hello_handler(self): ka_debug.info('I am initiating. Adding hello handler.') self._tube.add_signal_receiver(self.on_hello, 'Hello', IFACE, path=PATH, sender_keyword='sender')
def on_accept_incoming(self, menu_item): ka_debug.info('on_accept_incoming [%s]' % menu_item.parent.name) protozoon = self.accept_protozoon( ka_controller.name_to_index(menu_item.parent.name)) if protozoon is not None: new_at = self._parent.model.replace(protozoon.copy()) self._parent.start_calculation([new_at])
def get_buddy_by_handle(self, cs_handle): """Get a Buddy from a channel specific handle.""" try: ka_debug.info('Trying to find owner of handle %u...' % cs_handle) group = self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP] my_csh = group.GetSelfHandle() ka_debug.info('My handle in that group is %u' % my_csh) if my_csh == cs_handle: handle = self.telepathy_conn.GetSelfHandle() ka_debug.info('CS handle %u belongs to me, %u' % \ (cs_handle, handle)) elif group.GetGroupFlags( ) & telepathy.CHANNEL_GROUP_FLAG_CHANNEL_SPECIFIC_HANDLES: handle = group.GetHandleOwners([cs_handle])[0] ka_debug.info('CS handle %u belongs to %u' % \ (cs_handle, handle)) else: handle = cs_handle ka_debug.info('non-CS handle %u belongs to itself' % handle) #TODO: deal with failure to get the handle owner return self.pservice.get_buddy_by_telepathy_handle( self.telepathy_conn.service_name, self.telepathy_conn.object_path, handle) except: ka_debug.err('buddy added failed [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) return None
def _on_buddy_left(self, left_activity, buddy): """Called when a buddy leaves the shared activity. """ ka_debug.info('Buddy [%s] left' % buddy.props.nick) self._joined_buddies -= set([buddy.props.nick]) self._status.set(ka_status.TOPIC_COLLABORATION, ka_status.SUB_BUDDIES_JOINED, self._joined_buddies)
def add_publish_handler(self): ka_debug.info('I am entered. Adding input handler.') self._tube.add_signal_receiver(self.on_publish_protozoon, 'PublishProtozoon', IFACE, path=PATH, sender_keyword='sender')
def on_hello(self, sender=None): """Somebody helloed me. Send them my population.""" if sender == self._tube.get_unique_name(): # sender is my bus name, so ignore my own signal return ka_debug.info('on_hello: Newcomer [%s] has joined. World them.' % sender) self.send_population(self._controller.serialize_model(), sender)
def send_population(self, code_element, sender=None): code_element_base64 = base64.b64encode(code_element) code_md5 = hashlib.md5(code_element).hexdigest() ka_debug.info('send_population: Sent %u bytes, type: [%s] md5: [%s]' % \ (len(code_element), SEND_POPULATION, code_md5)) self._tube.get_object(sender, PATH).SendPopulation(SEND_POPULATION, code_element_base64, code_md5)
def _get_my_id(self): """Get my channel ID and nick.""" group = self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP] my_csh = group.GetSelfHandle() my_buddy = self.get_buddy_by_handle(my_csh) my_nick = my_buddy.props.nick if my_buddy is not None else '?' ka_debug.info('I am %s, my handle in that group is %u' % \ (my_nick, my_csh)) return my_nick, my_csh
def on_explain_activate(self, *args): """Publish single protozoon to all other buddies. pre: len(args) >= 1 """ ka_debug.info('on_explain_activate [%s]' % args[0].get_name()) details_controller = self._controller.find_page('DetailsController') if details_controller is not None: pix = ka_controller.name_to_index(args[0].get_name()) details_controller.start_calculation(self.model.protozoans[pix])
def __init__(self, init_size): self._state = STATE_INIT self.size = init_size self.fade_away = init_size / 2 self.protozoans = [ model_protozoon.Protozoon() for dummy in range(self.size) ] self.fitness = [3.0 for dummy in range(self.size)] ka_debug.info('initializing model with population size %u' % init_size)
def on_publishprotozoon_activate(self, *args): """Publish single protozoon to all other buddies. pre: len(args) >= 1 """ ka_debug.info('on_publishprotozoon_activate [%s]' % args[0].get_name()) if self._tube: proto = self.model.protozoans[ka_controller.name_to_index( args[0].get_name())] self._tube.publish_protozoon(model_population.to_buffer(proto))
def on_random_generation(self, *args): if ka_task.GeneratorTask.is_completed(): # ka_debug.info('on_random_generation entry') self._gencount += 1 ka_task.GeneratorTask(self.task_random_generation, self.on_model_completed, 'random_' + str(self._gencount)).start() # ka_debug.info('on_random_generation exit') else: ka_debug.info('on_random_generation ignored')
def write_file(self, file_path): """Implement writing to the journal This is called within sugar.activity.Activity code which provides the file_path. """ ka_debug.info('write_file [%s]' % file_path) population_controller = self._controller.find_page( 'PopulationController') if population_controller is not None: population_controller.write_file(file_path)
def get_data_path(): """ post: os.path.exists(__return__) """ data_path = ka_debug.DEBUG_PROFILE_PATH # default path for debugging if 'SUGAR_BUNDLE_PATH' in os.environ: import sugar.env ka_debug.info('profile_path ' + sugar.env.get_profile_path()) data_path = sugar.env.get_profile_path() data_path = os.path.join(data_path, 'net.sourceforge.kandid/data/') return data_path
def on_exportpng_activate(self, *args): """Publish single protozoon to all other buddies. pre: len(args) >= 1 """ ka_debug.info('on_exportpng_activate [%s]' % args[0].get_name()) pix = ka_controller.name_to_index(args[0].get_name()) exporter = ka_extensionpoint.create('exporter_png', self.model.protozoans[pix], self._activity_root) preference = ka_preference.Preference.instance() export_size = preference.get(ka_preference.EXPORT_SIZE) exporter.export(*export_size)
def export(self, width, height): """ pre: width > 0 pre: height > 0 pre: width == height """ task = ka_task.GeneratorTask( self.task_render, self.on_render_completed, 'export_png' + self._protozoon.get_unique_id()) task.start(self._protozoon, -1, width, height) ka_debug.info('export: start_calculation %ux%u for %s' % (width, height, self._protozoon.get_unique_id()))
def __init__(self, handle): activity.Activity.__init__(self, handle) self._name = handle self.metadata['mime_type'] = 'application/x-kandid-activity' self._print_greetings(handle) self._status = ka_status.Status.instance() self._joined_buddies = set([]) self._new_tubes = [] # Set title for our Activity self.set_title('Kandid') # Attach sugar toolbox (Share, ...) try: # try sugar 0.86 ka_debug.info('searching sugar 0.86, sugar.graphics.toolbarbox') import sugar.graphics.toolbarbox toolbar_box = sugar.graphics.toolbarbox.ToolbarBox() self._add_toolbar_buttons(toolbar_box) self.set_toolbar_box(toolbar_box) except: ka_debug.err('failed sugar 0.86 toolbarbox [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) # try sugar 0.82 toolbox = activity.ActivityToolbox(self) self.set_toolbox(toolbox) # Create the main container main_view = gtk.HBox() self._widget = ka_widget.KandidWidget() main_view.pack_start(self._widget.get_widget_tree()) # Create a controller to connect view and model self._controller = ka_controller.KandidController( \ self._widget, self.get_activity_root(), handle.object_id is None) self._controller.create_pages() self.set_canvas(main_view) self.kandidtube = None # Shared session self.initiating = False self.telepathy_conn = None self.tubes_chan = None self.text_chan = None # get the Presence Service self.pservice = presenceservice.get_instance() self._start_collaboration() self.show_all() if handle.object_id is None: self._controller.switch_page('GettingstartedController')
def on_changed(self, widget): index = widget.get_active() ka_debug.info('on_changed %d' % (index)) preference = ka_preference.Preference.instance() if index == 0: preference.set(ka_preference.EXPORT_SIZE, (200, 200)) elif index == 1: preference.set(ka_preference.EXPORT_SIZE, (400, 400)) elif index == 2: preference.set(ka_preference.EXPORT_SIZE, (600, 600)) elif index == 3: preference.set(ka_preference.EXPORT_SIZE, (1000, 1000)) preference.store()
def read_file(self, file_path): """Implement reading from journal This is called within sugar.activity.Activity code which provides file_path. """ ka_debug.info('read_file [%s] [%s]' % \ (self.metadata['mime_type'], file_path)) population_controller = self._controller.find_page( 'PopulationController') if population_controller is not None: population_controller.read_file(file_path) population_controller.start_all_calculations()
def scann(): global revision_number bundle_path = get_bundle_path() revision_number = _get_manifest_version(bundle_path) ka_debug.info('This is Kandid, release v' + str(revision_number)) ka_debug.info('Searching for extensions in ' + bundle_path) for element in os.listdir(bundle_path): if element.startswith(_PREFIX) and element.endswith(_PYEXT) \ and os.path.isfile(os.path.join(bundle_path, element)): name_parts = element.split(_SEP) if len(name_parts) == 3: _add(name_parts[1], name_parts[2].replace(_PYEXT, '')) _extension_types.sort() _extensions.sort()
def SendPopulation(self, code_type, code_element_base64, code_md5, sender=None): """Send to all participants.""" code_element = base64.b64decode(code_element_base64) ka_debug.info('SendPopulation: Received %u bytes, type: [%s] md5: [%s]' \ % (len(code_element), code_type, code_md5)) if hashlib.md5(code_element).hexdigest() == code_md5: nick = self._map_to_nick(sender) self._controller.on_received(code_type, code_element, nick) else: ka_debug.err('Somebody called me with a corrupt data model.')
def _wait(work_for): GeneratorTask._internal_task_list_lock.acquire() if GeneratorTask._internal_task_list.has_key(work_for): GeneratorTask._internal_task_list[work_for].quit = True ka_debug.info('set quit task: [%s], count aprox.= %u' % \ (work_for, GeneratorTask._internal_task_count)) ka_debug.print_call_stack() GeneratorTask._internal_task_list_lock.release() GeneratorTask._internal_leave_condition.acquire() while GeneratorTask._internal_task_list.has_key(work_for): # ka_debug.info('wait task: [%s], count aprox.= %u' % \ # (work_for, GeneratorTask._internal_task_count)) GeneratorTask._internal_leave_condition.wait() GeneratorTask._internal_leave_condition.release()
def on_notebook_switch_page(self, *args): """Test if introduction page will be displayed. Lazy evaluation to fill the page with text. pre: len(args) >= 3 """ visible = args[2] == self._controller.find_page_number(self.__class__.__name__) # ka_debug.info('on_notebook_switch_page %s %s' % (visible, args[2])) if visible and len(self._uri) > 0: if ka_debug.locale_testrun: # Only for testing on my computer result = webbrowser.open(self._uri) ka_debug.info('webbrowser.open: [%s] %s' % (self._uri, str(result))) if self._htmlview is not None: self._htmlview.load_uri(self._uri)
def get_import_path(): """ post: os.path.exists(__return__) """ import_path = os.path.join(get_data_path(), 'collection') if not os.path.exists(import_path): try: os.makedirs(import_path) except: # print 'failed writing [%s] [%s] [%s]' % \ # (import_path, sys.exc_info()[0], sys.exc_info()[1]) # traceback.print_exc(file=sys.__stderr__) ka_debug.err('failed writing [%s] [%s] [%s]' % \ (import_path, sys.exc_info()[0], sys.exc_info()[1])) ka_debug.info('import_path ' + import_path) return import_path
def read_file(file_path): model = None if os.path.isfile(file_path): in_file = None try: ka_debug.info('input file [%s]' % file_path) in_file = open(file_path, 'r') model = from_buffer(in_file.read()) model._state = STATE_INIT except: ka_debug.err('failed reading [%s] [%s] [%s]' % \ (file_path, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) finally: if in_file: in_file.close() return model
def task_render(self, task, *args, **kwargs): """Render bitmap for exporting protozoon. pre: len(args) == 4 """ protozoon, dummy, width, height = \ args[0], args[1], args[2], args[3] ka_debug.info('export: task_render entry: ') self._export_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context(self._export_surface) protozoon.render(task, ctx, width, height) self._thumb_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, _THUMB_SIZE, _THUMB_SIZE) ctx = cairo.Context(self._thumb_surface) protozoon.render(task, ctx, _THUMB_SIZE, _THUMB_SIZE) ka_debug.info('export: task_render exit: ')
def on_render_completed(self, *args): """Rendering protozoon is completed. pre: self._export_surface is not None pre: self._thumb_surface is not None """ ka_debug.info('export: on_render_completed: ' + str(args[0])) unique_id = 'kandidimage' + self._protozoon.get_unique_id() export_filename = unique_id + '.png' export_path = os.path.join(self._activity_root, 'instance', export_filename) # Create a datastore object file_dsobject = datastore.create() # Write any metadata (here we specifically set the title of the file # and specify that this is a portable network graphics file). file_dsobject.metadata['title'] = 'Kandid Image ' + \ self._protozoon.get_unique_id()[1:] file_dsobject.metadata['mime_type'] = 'image/png' #Write the actual file to the data directory of this activity's root. try: self._export_surface.write_to_png(export_path) except: ka_debug.err('export: failed exporting to [%s] [%s] [%s]' % \ (export_path, sys.exc_info()[0], sys.exc_info()[1])) #insert thumbnail image into metadata thumb_filename = unique_id + '.thumb.png' thumb_path = os.path.join(self._activity_root, 'instance', thumb_filename) try: self._thumb_surface.write_to_png(thumb_path) thumb_in = open(thumb_path, 'rb') file_dsobject.metadata['preview'] = \ base64.b64encode(thumb_in.read()) thumb_in.close() os.unlink(thumb_path) except: ka_debug.err('export: failed creating preview image [%s] [%s] [%s]' % \ (thumb_path, sys.exc_info()[0], sys.exc_info()[1])) #Set the file_path in the datastore. file_dsobject.set_file_path(export_path) datastore.write(file_dsobject) file_dsobject.destroy()
def on_publish_protozoon(self, code_type, code_element_base64, code_md5, sender=None): """Somebody published. Process received parameters.""" if sender == self._tube.get_unique_name(): # sender is my bus name, so ignore my own signal return code_element = base64.b64decode(code_element_base64) ka_debug.info('on_publish_protozoon: I got %u bytes, type: [%s] md5: [%s]' \ % (len(code_element), code_type, code_md5)) if hashlib.md5(code_element).hexdigest() == code_md5: nick = self._map_to_nick(sender) self._controller.on_received(code_type, code_element, nick) else: ka_debug.err('Somebody called me with a corrupt data model.')
def _on_joined(self, joined_activity): if not self._shared_activity: return ka_debug.info('Joined an existing shared activity [%s]' % \ joined_activity) self.initiating = False if self._sharing_setup(): self._status.set(ka_status.TOPIC_COLLABORATION, ka_status.SUB_SHARE, _('Joined an existing shared activity.')) my_nick, my_csh = self._get_my_id() self._status.set( ka_status.TOPIC_COLLABORATION, ka_status.SUB_ID, _("I am '%s', my handle in that group is %u.") % (my_nick, my_csh)) #TODO If a tube already exist, use it. ka_debug.info('This is not my activity: waiting for a tube...') self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes( reply_handler=self._on_list_tubes_reply, error_handler=self._on_list_tubes_error)