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 to_buffer(obj): # ka_debug.info('write %s to_buffer' % type(obj)) try: return MAGIC_NUMBER + _get_my_revision() \ + zlib.compress(pickle.dumps(copy.deepcopy(obj), protocol=2)) except: ka_debug.err('failed writing buffer [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__)
def get_widget(self, widget_name): """ pre: widget_name in self._list post: __return__ is not None """ if widget_name in self._list: return self._list[widget_name] ka_debug.err('missing: ' + widget_name) return None
def create_gui(self): """ """ inner_border = 10 page = gtk.HBox() page.set_border_width(30) self._widget_list.remember('startHpaned', page) teaserBox = gtk.VBox() teaserBox.set_border_width(inner_border) try: image_file = ka_widget.KandidWidget.get_introimage_path() \ + 'kandid-teaser.jpg' image = gtk.Image() image.set_from_file(image_file) teaserBox.pack_start(image, expand=False, fill=False) except: ka_debug.err('locating intro image failed [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) page.pack_start(teaserBox, expand=False, fill=False) controlBox = gtk.VBox() controlBox.set_border_width(inner_border) controlBox.pack_start(gtk.Label(''), expand=True, fill=True) readintroLinkbutton = gtk.Button('') readintroLinkbutton.set_label(_('Read the Introduction')) self._widget_list.remember('readintroLinkbutton', readintroLinkbutton) controlBox.pack_start(readintroLinkbutton, expand=False, fill=False) controlBox.pack_start(gtk.Label(''), expand=True, fill=True) startnewLinkbutton = gtk.Button('') startnewLinkbutton.set_label(_('Show image population')) self._widget_list.remember('startnewLinkbutton', startnewLinkbutton) controlBox.pack_start(startnewLinkbutton, expand=False, fill=False) teaserBox.pack_start(controlBox, expand=False, fill=False) textBox = gtk.VBox() textBox.set_border_width(inner_border) scrolled_window = gtk.ScrolledWindow(hadjustment=None, vadjustment=None) self._widget_list.remember('start_scrolledwindow', scrolled_window) scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) textview = gtk.TextView() self._widget_list.remember('gettingstarted_textview', textview) textview.set_wrap_mode(gtk.WRAP_WORD) textview.set_editable(False) textview.set_left_margin(10) textview.set_right_margin(10) textview.set_border_width(3) textview.set_sensitive(False) scrolled_window.add(textview) textBox.pack_start(scrolled_window, expand=True, fill=True) page.pack_start(textBox, expand=True, fill=True) return page, gtk.Label(_('Getting started'))
def _write_surface_file(target_path, theme, file_name, surface): """Write graphical content to the file system. """ fn = '' try: fn = os.path.join(_make_path(target_path, theme), file_name) if not os.path.exists(fn): surface.write_to_png(fn) except: ka_debug.err('failed writing [%s] [%s] [%s]' % \ (fn, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__)
def find_page(self, page_name): """ pre: page_name is not None and len(page_name) > 1 """ for page_controller in self._pages: pattern1 = "<class 'ep_page_" pattern2 = "." + page_name + "'>" type_str = str(type(page_controller)) if type_str.startswith(pattern1) and type_str.endswith(pattern2): return page_controller ka_debug.err('Missing ' + page_name) return None
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 render(self, task, ctx, width, height): """ pre: ctx is not None pre: width > 0 pre: height > 0 pre: width == height """ if task.quit: # ka_debug.info('quitting task: [%s], %s' % \ # (task.work_for, self.path)) return #!! time.sleep(0.001) try: ctx.save() # ka_debug.matrix_s(ctx.get_matrix()) if (self.left_treenode is None) and (self.right_treenode is None): # I am a leaf, use my own layer painting strategy self.layer.render(task, ctx, width, height) elif (self.left_treenode is not None) and (self.right_treenode is not None): # merge 'left' and 'right' tree node left_surface, left_ctx = self._prepare_surface(ctx, width, height, \ self.left_background) self.left_treenode.render(task, left_ctx, width, height) # left_surface.write_to_png('/dev/shm/left_' + self.left_treenode.get_unique_id() + '.png') right_surface, right_ctx = self._prepare_surface(ctx, width, height, \ self.right_background) right_ctx.set_operator(cairo.OPERATOR_SOURCE) self.right_treenode.render(task, right_ctx, width, height) # right_surface.write_to_png('/dev/shm/right_' + self.right_treenode.get_unique_id() + '.png') if not task.quit: self.merger.merge_layers(left_surface, right_surface, \ ctx, width, height) elif (self.left_treenode is not None) and (self.right_treenode is None): self.modifier.render_single_layer(task, self.layer, self.left_treenode, ctx, width, height) elif (self.left_treenode is None) and (self.right_treenode is not None): self.modifier.render_single_layer(task, self.layer, self.right_treenode, ctx, width, height) # ka_debug.matrix_r(ctx.get_matrix()) ctx.restore() except: ka_debug.err('failed calculating [%s] [%s] [%s]' % \ (self.get_unique_id(), sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__)
def _get_manifest_version(bundle_path): revision = 0 try: cp = ConfigParser() cp.readfp( open(os.path.join(bundle_path, 'activity/activity.info'), 'rb')) if cp.has_option('Activity', 'activity_version'): version = cp.get('Activity', 'activity_version') revision = int(version) except: ka_debug.err('reading manifest version failed [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) return revision
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 write_file(file_path, model): """Write model to the file system. pre: file_path is not None """ out_file = None try: out_file = open(file_path, 'w') out_file.write(to_buffer(model)) except: ka_debug.err('failed writing [%s] [%s] [%s]' % \ (file_path, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) finally: if out_file: out_file.close()
def from_buffer(input_buffer): # ka_debug.info('read from_buffer') obj = None try: if input_buffer.startswith(MAGIC_NUMBER): obj = pickle.loads(zlib.decompress(input_buffer[4:])) if not input_buffer.startswith(MAGIC_NUMBER + _get_my_revision()): obj = obj.copy() else: ka_debug.err('missing magic number') except: ka_debug.err('failed reading input buffer [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) return obj
def localize(self): try: textview = self._widget_list.get_widget('gettingstarted_textview') buf = textview.get_buffer() translated = _('getting_started') translated = translated if not translated == 'getting_started' \ else GettingstartedController._getting_started_text buf.delete(buf.get_start_iter(), buf.get_end_iter()) #!! buf.insert(buf.get_end_iter(), '\n') #!! buf.insert(buf.get_end_iter(), '\n') buf.insert(buf.get_end_iter(), translated) except: ka_debug.err('localizing page "getting started" failed [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__)
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 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 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 scan_os_status(self): """see http://linuxdevcenter.com/pub/a/linux/2006/11/30/linux-out-of-memory.html """ try: proc = open(_proc_status) os_status = proc.read() self._set_process_status(os_status, 'Threads:', SUB_THREADS) self._set_process_status(os_status, 'VmSize:', SUB_VM_SIZE) self._set_process_status(os_status, 'VmPeak:', SUB_VM_PEAK) self._set_process_status(os_status, 'VmRSS:', SUB_VM_RSS) proc.close() except: # non Linux? ka_debug.err('scan_os_status [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__)
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 render(self, task, ctx, width, height): """ pre: ctx is not None pre: width > 0 pre: height > 0 pre: width == height """ self.begin_render(ctx, width, height) ctx.save() # ka_debug.matrix_s(ctx.get_matrix()) ctx.scale(1.0/width, 1.0/height) # ka_debug.matrix(ctx.get_matrix()) pango_ctx = pangocairo.CairoContext(ctx) points = self.sampler.get_sample_points() if len(points) > 0: fi = di = -1 for word in self.buzzwords.wordlist: di = (di+1) % len(points) px = self.center.x_pos + points[di][0] py = self.center.y_pos + points[di][1] try: layout = pango_ctx.create_layout() fi = (fi+1) % len(self.family) desc = pango.FontDescription(self.family[fi]) desc.set_size(int(self.size * width * 0.01 * pango.SCALE)) desc.set_style(self.style) desc.set_weight(self.weight) layout.set_text(word.encode('utf-8')) layout.set_font_description(desc) layout.set_alignment(pango.ALIGN_CENTER) rgba = self.textcolor.rgba pango_ctx.set_source_rgba(rgba[0], rgba[1], rgba[2], rgba[3]) pango_ctx.update_layout(layout) pixel_size = layout.get_pixel_size() dx, dy = 0.5 * pixel_size[0], 0.9 * pixel_size[1] pango_ctx.move_to((width * px) - dx, (height * py) - dy) pango_ctx.show_layout(layout) except: ka_debug.err('failed on pango [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) # ka_debug.matrix_r(ctx.get_matrix()) ctx.restore()
def recall(self): """ """ in_file = None fn = '' try: fn = self._file_name() if os.path.exists(fn): in_file = open(fn, 'r') self._preference_dict = eval(in_file.read()) except: ka_debug.err('failed reading [%s] [%s] [%s]' % \ (fn, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) finally: if in_file: in_file.close()
def _write_file(target_path, theme, file_name, content): """Write textual content to the file system. """ out_file = None fn = '' try: fn = os.path.join(_make_path(target_path, theme), file_name) if not os.path.exists(fn): out_file = open(fn, 'w') out_file.write(content) except: ka_debug.err('failed writing [%s] [%s] [%s]' % \ (fn, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) finally: if out_file: out_file.close()
def store(self): """Write textual content to the file system. """ if self._dirty_flag: out_file = None fn = '' try: fn = self._file_name() out_file = open(fn, 'w') out_file.write(repr(self._preference_dict)) self._dirty_flag = False except: ka_debug.err('failed writing [%s] [%s] [%s]' % \ (fn, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) finally: if out_file: out_file.close()
def write_html_file(self, file_path): """Write HTML to the file system. pre: self._header_occured pre: self._footer_occured pre: self._indent == 0 pre: file_path is not None """ out_file = None try: out_file = open(file_path, 'w') out_file.write(self._page.encode('utf-8')) self.produced_files_list.append(file_path) except: ka_debug.err('failed writing [%s] [%s] [%s]' % \ (file_path, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) finally: if out_file: out_file.close()
def __init__(self, base_name, unique_id, base_folder): """Constructor for HTML formater.""" self._base_name = base_name.replace(' ', '_') self.unique_id = unique_id self._base_folder = base_folder.replace(' ', '_') self._indent = 0 self._page = u'' self.produced_files_list = [] self.id_count = 0 self._header_occured = False # debugging only self._footer_occured = False # debugging only file_path = os.path.join(base_folder, unique_id) if not os.path.exists(file_path): try: os.mkdir(file_path) except: ka_debug.err('creating directory [%s] [%s] [%s]' % \ (file_path, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__)
def render_single_layer(self, task, single_layer, single_treenode, ctx, width, height): """ pre: single_layer is not None pre: ctx is not None pre: width > 0 pre: height > 0 pre: width == height """ try: # paint one layer msk_surface = ctx.get_target().create_similar( cairo.CONTENT_ALPHA, width, height) msk_ctx = cairo.Context(msk_surface) msk_width = msk_surface.get_width() msk_height = msk_surface.get_height() # fill the whole background with an alpha value. msk_ctx.set_operator(cairo.OPERATOR_SOURCE) msk_ctx.set_source_rgba(1.0, 1.0, 1.0, self.border_alpha) msk_ctx.paint() # fill the interior with an alpha value. msk_ctx.set_operator(cairo.OPERATOR_SOURCE) msk_ctx.set_source_rgba(1.0, 1.0, 1.0, 1.0 - self.border_alpha) msk_ctx.rectangle(self.border_weight * msk_width, self.border_weight * msk_height, (1.0 - 2.0 * self.border_weight) * msk_width, (1.0 - 2.0 * self.border_weight) * msk_height) msk_ctx.fill() ctx.save() # ka_debug.matrix_s(ctx.get_matrix()) single_layer.render(task, ctx, width, height) # msk_surface.write_to_png('/dev/shm/mask_' + self.get_unique_id() + '.png') ctx.mask_surface(msk_surface, -0.5 * width, -0.5 * height) single_treenode.render(task, ctx, width, height) # ka_debug.matrix_r(ctx.get_matrix()) ctx.restore() except: ka_debug.err('failed calculating [%s] [%s] [%s]' % \ (self.get_unique_id(), sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__)
def _start(self, *args, **dummy): try: GeneratorTask._internal_serialize_lock.acquire() GeneratorTask._wait(self.work_for) GeneratorTask._enter(self) GeneratorTask._internal_serialize_lock.release() result = self._task_function(self, *args) if not self.quit: # GTK will start this 'completed task' whenever there are no higher # priority events pending to the default main loop. gobject.idle_add(self._on_task_completed, result) else: ka_debug.info('quitting task: [%s], count aprox.= %u' % \ (self.work_for, GeneratorTask._internal_task_count)) except: ka_debug.err('failed calculating [%s] [%s] [%s]' % \ (self._task_function, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) finally: GeneratorTask._leave(self.work_for)
def __init__(self, controller, uri, parent_widget, widget_list): """ pre: parent_widget is not None pre: widget_list is not None """ self._controller = controller self._widget_list = widget_list self._parent_widget = parent_widget self._htmlview = None self._uri = '' if uri is None else uri try: # The XOCom object helps us communicate with the browser # This uses web/index.html as the default page to load #!! from XOCom import XOCom #!! self.xocom = XOCom(self.control_sending_text) #REMEMBER THAT I HAVE STILL TO SEND THE ARGUMENT IN THE XOCOM CLASS #!! self._htmlview = self.xocom.create_webview() self._htmlview = WebView() except: ka_debug.err('failed creating hulahop [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__)
def on_received(self, code_type, code_element, nick): """Update population or protozoon preview when received from others.""" ka_debug.info('on_received: Received %u bytes, type: [%s], from: [%s]' % \ (len(code_element), code_type, nick)) if code_type == kandidtube.SEND_POPULATION: self._status.set(ka_status.TOPIC_COLLABORATION, ka_status.SUB_RECEIVED, 'Population from ' + nick) if self.is_overwrite_allowed(): self._update_model(model_population.from_buffer(code_element)) self.start_all_calculations() else: in_model = model_population.from_buffer(code_element) max_fit, best_ix, second_ix = -1, -1, -1 for index, fit in enumerate(in_model.fitness): if fit > max_fit: second_ix = best_ix best_ix, max_fit = index, fit if best_ix >= 0: self.incoming.append_protozoon( in_model.protozoans[best_ix]) if second_ix >= 0: self.incoming.append_protozoon( in_model.protozoans[second_ix]) if best_ix >= 0 or second_ix >= 0: ka_debug.info( "I've already an evolved population, proposing protozoon %d, %d." % (best_ix, second_ix)) else: ka_debug.info( "I've already an evolved population, ignore incoming protozoon." ) elif code_type == kandidtube.SEND_PROTOZOON: ka_debug.info('Proposing protozoon.') self._status.set(ka_status.TOPIC_COLLABORATION, ka_status.SUB_RECEIVED, 'Protozoon from ' + nick) self.incoming.append_protozoon( model_population.from_buffer(code_element)) else: ka_debug.err('Somebody called me using an illegal type [%s]' % code_type)
def _start_collaboration(self): # Buddy object for you found_buddies = set([]) try: self.connect('shared', self._on_shared) self.connect('joined', self._on_joined) # pservice.get_buddies() is deprecated # ka_debug.info('searching buddies') # buddies = self.pservice.get_buddies() # for buddy in buddies: # ka_debug.info(' buddy nick: %s' % buddy.get_property('nick')) # ka_debug.info(' activity: %s' # % buddy.get_property('current-activity')) # ka_debug.info(' owner: %s' % buddy.get_property('owner')) # found_buddies |= set([buddy.get_property('nick')]) except: ka_debug.err('start collaboration failed [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) self._status.set(ka_status.TOPIC_COLLABORATION, ka_status.SUB_BUDDIES_FOUND, found_buddies) self._status.set(ka_status.TOPIC_COLLABORATION, ka_status.SUB_SHARE, '')
def _post_install(): """ pre: len(_marker) >= 2 and int(_marker[1]) > 2 """ try: tmp_path = get_tmp_path() import_path = get_import_path() install_marker = os.path.join(import_path, 'install.inf') reinstall = not os.path.exists(install_marker) if not reinstall: in_file = None try: in_file = open(install_marker, 'r') marker = in_file.read() reinstall = not marker == _marker except: reinstall = True ka_debug.err('failed reading [%s] [%s] [%s]' % \ (install_marker, sys.exc_info()[0], sys.exc_info()[1])) traceback.print_exc(file=sys.__stderr__) finally: if in_file: in_file.close() if not reinstall: return ka_debug.info('running post installation [%s]' % import_path) _write_file( import_path, 'segment_of_a_circle', 'stamp_circle.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <circle cx ="50" cy ="50" r ="50" style="fill:#000000"/> </svg> ''') _write_file( import_path, 'segment_of_a_circle', 'stamp_halfcircle_bottom.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <path d="M 0,100 A 50 50 180 0 1 100,100" style="fill:#000000;"/> </svg> ''') _write_file( import_path, 'segment_of_a_circle', 'stamp_halfcircle_left.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <path d="M 50,100 A 50 50 180 0 1 50,0" style="fill:#000000;"/> </svg> ''') _write_file( import_path, 'segment_of_a_circle', 'stamp_halfcircle_right.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <path d="M 50,100 A 50 50 180 0 0 50,0" style="fill:#000000;"/> </svg> ''') _write_file( import_path, 'segment_of_a_circle', 'stamp_halfcircle_top.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <path d="M 0,0 A 50 50 180 0 0 100,0" style="fill:#000000;"/> </svg> ''') #---- cybernetic_serendipity _write_file( import_path, 'cybernetic_serendipity', 'stamp_ascending_path.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <line x1="16.666666667" y1="83.333333333320" x2="83.333333333320" y2="16.666666667" style="fill:none; stroke-width:3%; stroke:#000000;"/> </svg> ''') _write_file( import_path, 'cybernetic_serendipity', 'stamp_circle_path.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <circle cx ="50" cy ="50" r ="33.333333333" style="fill:none; stroke-width:3%; stroke:#000000;"/> </svg> ''') _write_file( import_path, 'cybernetic_serendipity', 'stamp_descending_path.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <line x1="16.666666667" y1="16.666666667" x2="83.333333333320" y2="83.333333333320" style="fill:none; stroke-width:3%; stroke:#000000;"/> </svg> ''') _write_file( import_path, 'cybernetic_serendipity', 'stamp_horizontal_path.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <line x1="20" y1="55" x2="80" y2="55" style="fill:none; stroke-dasharray:19.166666667,3.3333333333; stroke-width:3%; stroke:#000000;"/> </svg> ''') _write_file( import_path, 'cybernetic_serendipity', 'stamp_sawtooth_path.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <polyline points="20 50, 30 40, 40 50, 50 40, 60 50, 70 40, 80 50" style="fill:none; stroke-width:3%; stroke:#000000;"/> </svg> ''') _write_file( import_path, 'cybernetic_serendipity', 'stamp_square_path.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <rect x="26.42977396" y="26.42977396" width="47.140452079" height="47.140452079" style="fill:none; stroke-width:3%; stroke:#000000;"/> </svg> ''') _write_file( import_path, 'cybernetic_serendipity', 'stamp_vertical_path.svg', '''<?xml version="1.0"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" > <line x1="50" y1="16.666666667" x2="50" y2="83.333333333320" style="fill:none; stroke-width:3%; stroke:#000000;"/> </svg> ''') #---- marktree _write_file( tmp_path, '', 'marktree.js', ''' /* MarkTree JavaScript code * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Miika Nurminen, 12.7.2004. */ /* cross-browser (tested with ie5, mozilla 1 and opera 5) keypress detection */ function get_keycode(evt) { // IE code = document.layers ? evt.which : document.all ? event.keyCode // event.keyCode!=evt.keyCode! : evt.keyCode; if (code==0) code=evt.which; // for NS return code; } var lastnode=null; var listnodes = null; var list_index=1; var lastnodetype=''; // determines if node is a link, input or text; // up, left, down, right, keypress codes //ijkl //var keys = new Array(105,106,107,108); //num arrows //var keys = new Array(56,52,50,54); //wasd // var press2 = new Array(119,97,115,100); var press = new Array(47,45,42,43); // keydown codes // var keys2=new Array(87,65,83,68); var keys= new Array(38,37,40,39); // keyset 1 = keydown, otherwise press function checkup(keyset,n) { if (keyset==1) return (n==keys[0]); return ((n==press[0]) /*|| (n==press2[0])*/) } function checkdn(keyset,n) { if (keyset==1) return (n==keys[2]); return ((n==press[2]) /*|| (n==press2[2])*/) } function checkl(keyset,n) { if (keyset==1) return (n==keys[1]); return ((n==press[1]) /*|| (n==press2[1])*/) } function checkr(keyset,n) { if (keyset==1) return (n==keys[3]); return ((n==press[3]) /*|| (n==press2[3])*/) } function is_exp(n) { if (n==null) return false; return ((n.className=='exp') || (n.className=='exp_active')); } function is_col(n) { if (n==null) return false; return ((n.className=='col') || (n.className=='col_active')); } function is_basic(n) { if (n==null) return false; return ((n.className=='basic') || (n.className=='basic_active')); } /* returns i>=0 if true */ function is_active(node) { if (node.className==null) return false return node.className.indexOf('_active'); } function toggle_class(node) { if ((node==null) || (node.className==null)) return; str=node.className; result=""; i = str.indexOf('_active'); if (i>0) result= str.substr(0,i); else result= str+"_active"; node.className=result; return node; } function activate(node) { node.style.backgroundColor='#eeeeff'; } function deactivate(node) { node.style.backgroundColor='#ffffff'; } function is_list_node(n) { if (n==null) return false; if (n.className==null) return false; if ( (is_exp(n)) || (is_col(n)) || (is_basic(n)) ) return true; else return false; } function get_href(n) { alist=n.attributes; if (alist!=null) { hr = alist.getNamedItem('href'); if (hr!=null) return hr.nodeValue; } if (n.childNodes.length==0) return ''; for (var i=0; i<n.childNodes.length; i++) { s = get_href(n.childNodes[i]); if (s!='') return s; } return ''; } function get_link(n) { if (n==null) return null; if (n.style==null) return null; // disabling uncontrolled recursion to prevent error messages on IE // when trying to focus to invisible links (readonly mode) // alert(n.nodeName+' '+n.className); if ((n.nodeName=='UL') && (n.className=='sub')) return null; if (n.nodeName=='A') return n; if (n.childNodes.length==0) return null; for (var i=0; i<n.childNodes.length; i++) { s = get_link(n.childNodes[i]); if (s!=null) return s; } return null; } function set_lastnode(n) { /*var d = new Date(); var t_mil = d.getMilliseconds();*/ // testattu nopeuksia explorerilla, ei merkittäviä eroja if (lastnode==n) return; /* deactivate(lastnode) lastnode=n; activate(lastnode);*/ if (is_active(lastnode)>=0) toggle_class(lastnode); lastnode=n; if (!(is_active(lastnode)>=0)) toggle_class(lastnode); /*var d2 = new Date(); var t_mil2 = d2.getMilliseconds(); window.alert(t_mil2-t_mil);*/ } function next_list_node() { tempIndex = list_index; while (tempIndex<listnodes.length-1) { tempIndex++; var x = listnodes[tempIndex]; if (is_list_node(x)) { list_index=tempIndex; return; } } } function prev_list_node() { tempIndex = list_index; while (tempIndex>0) { tempIndex--; var x = listnodes[tempIndex]; if (is_list_node(x)) { list_index=tempIndex; return; } } } function getsub (li) { if (li.childNodes.length==0) return null; for (var c = 0; c < li.childNodes.length; c++) if ( (li.childNodes[c].className == 'sub') || (li.childNodes[c].className == 'subexp') ) return li.childNodes[c]; } function find_listnode_recursive (li) { if (is_list_node(li)) return li; if (li.childNodes.length==0) return null; result=null; for (var c = 0; c < li.childNodes.length; c++) { result=find_listnode_recursive(li.childNodes[c]); if (result!=null) return result; } return null; } function next_child_listnode(li) { var result=null; for (var i=0; i<li.childNodes.length; i++) { result=find_listnode_recursive(li.childNodes[i]); if (result!=null) return result; } return null; } function next_actual_sibling_listnode(li) { if (li==null) return null; var temp=li; while (1) { var n = temp.nextSibling; if (n==null) { n=parent_listnode(temp); return next_actual_sibling_listnode(n); } if (is_list_node(n)) return n; temp=n; } } function next_sibling_listnode(li) { if (li==null) return null; var result=null; var temp=li; if (is_col(temp)) return next_child_listnode(temp); while (1) { var n = temp.nextSibling; if (n==null) { n=parent_listnode(temp); return next_actual_sibling_listnode(n); } if (is_list_node(n)) return n; temp=n; } } function last_sibling_listnode(li) { if (li==null) return null; var temp=li; var last=null; while(1) { var n = temp.nextSibling; if (is_list_node(temp)) last = temp; if (n==null) { if (is_col(last)) return last_sibling_listnode(next_child_listnode(last)); else return last; } temp = n; } } function prev_sibling_listnode(li) { if (li==null) return null; var temp=li; var n = null; while (1) { n = temp.previousSibling; if (n==null) { return parent_listnode(li); } if (is_list_node(n)) { if (is_col(n)) { return last_sibling_listnode(next_child_listnode(n)); } else { return n; } } temp=n; } } function parent_listnode(li) { // added 12.7.2004 to prevent IE error when readonly mode==true if (li==null) return null; n=li; while (1) { n=n.parentNode; if (n==null) return null; if (is_list_node(n)) return n; } } function getVisibleParents(id) { var n = document.getElementById(id); while(1) { expand(n); n = parent_listnode(n); if (n==null) return; } } function onClickHandler (evt) { if (lastnode==null) { listnodes = document.getElementsByTagName('li'); lastnode=listnodes[1]; temp=listnodes[1]; } var target = evt ? evt.target : event.srcElement; if (!is_list_node(target)) return; toggle(target); set_lastnode(target); } function expand(node) { if (!is_exp(node)) return; if (node.className=='exp_active') node.className='col_active'; else node.className='col'; setSubClass(node,'subexp'); // getsub(node).className='subexp'; } function collapse(node) { if (!is_col(node)) return; if (node.className=='col_active') node.className='exp_active' else node.className='exp'; setSubClass(node,'sub'); // getsub(node).className='sub'; } function setSubClass(node,name) { sub = getsub(node); if (sub==null) return; sub.className=name; } function toggle(target) { if (!is_list_node(target)) return; if (is_col(target)) { target.className='exp'; setSubClass(target,'sub'); // getsub(target).className='sub'; } else if (is_exp(target)) { target.className='col'; setSubClass(target,'subexp'); // getsub(target).className='subexp'; } } function expandAll(node) { if (node.className=='exp') { node.className='col'; setSubClass(node,'subexp'); // getsub(node).className='subexp'; } var i; if (node.childNodes!=null) // if (node.hasChildNodes()) for ( i = 0; i<node.childNodes.length; i++) expandAll(node.childNodes[i]); } function collapseAll(node) { if (node.className=='col') { node.className='exp'; setSubClass(node,'sub'); // getsub(node).className='sub'; } var i; if (node.childNodes!=null) // for opera if (node.hasChildNodes()) for ( i = 0; i<node.childNodes.length; i++) collapseAll(node.childNodes[i]); } function unFocus(node) { // unfocuses potential link that is to be hidden (if a==null there is no link so it should not be blurred). // tested with mozilla 1.7, 12.7.2004. /mn ( intemp=parent_listnode(node); a = get_link(intemp); // added 6.4. to get keyboard working with // moved before collapse to prevent an error message with IE when readonly==true if (a!=null) a.blur(); // netscape after collapsing a focused node return intemp; } // mode: 0==keypress, 1==keyup function keyfunc(evt,mode) { var c = get_keycode(evt); var temp = null; var a = null; if (lastnode==null) { listnodes = document.getElementsByTagName('li'); lastnode=listnodes[1]; temp=listnodes[1]; } //window.alert(c); if (checkup(mode,c)) { // i temp=prev_sibling_listnode(lastnode); } else if (checkdn(mode,c)) { // k temp=next_sibling_listnode(lastnode); } else if (checkr(mode,c)) { // l expand(lastnode); // temp=next_child_listnode(lastnode); // if (temp==null) { a = get_link(lastnode); if (a!=null) a.focus(); else self.focus(); //} } else if (checkl(mode,c)) { // j if (is_col(lastnode)) { unFocus(lastnode); collapse(lastnode); } else { temp=unFocus(lastnode); collapse(temp); } // if (temp==null) lastnode.focus(); // forces focus to correct div (try mozilla typesearch) (doesn't seem to work -mn/6.4.2004) } else return; if (temp!=null) set_lastnode(temp); // alert('pressed ' + String.fromCharCode(c) + '(' + c + ')'); return true; } function keytest (evt) { return keyfunc(evt,1); }; function presstest (evt) { return keyfunc(evt,0); }; document.onclick = onClickHandler; document.onkeypress = presstest; document.onkeyup = keytest; ''') _write_file( tmp_path, '', 'treestyles.css', ''' body { background-color: #eeeeee; color: #000000; font-family : 'DejaVu Sans', 'Sans Serif', sans-serif; } :link { color: #0000ff; text-decoration:none;} :visited { color: #6666ff; text-decoration:none; } a:active { color: #0000ff; text-decoration:none;} a:hover {color: #0000ff; text-decoration:underline; } div.basetext { background-color:#ffffff; margin-top:11px; margin-bottom:11px; margin-left:1%; margin-right:1%; padding-top:11px; padding-left:11px; padding-right:11px; padding-bottom:11px; text-align:left; font-weight:normal; border-width:thin; border-style:solid; border-color:#dddddd; } div.basetop { position: fixed; width:auto; height:auto; right:0em; top:0em; left:auto; top:0; background-color:#ffffff; margin-top:0; margin-bottom:0; margin-left:1%; margin-right:1%; padding-top:2px; padding-left:11px; padding-right:11px; padding-bottom:2px; text-align:left; font-weight:normal; text-align:right; border-width:thin; border-style:solid; border-color:#dddddd; } h1 { text-align:center; } span.h2 { font-family : 'DejaVu Sans', 'Sans Serif', sans-serif; font-weight:bold; } div.year { margin-right:2%; background-color:#eeeeee; } div.form { } span.cpt { color:#005500; font-weight:bold; } span.cm { color:#666666; } .fl { color:#0000FF; font-style:italic; } ul { margin-top:1px; margin-bottom:1px; margin-left:0px; padding-left:3%; } li { list-style:outside; margin-top:10px; margin-bottom:10px; } ul li { list-style:square; font-family : 'DejaVu Sans', 'Sans Serif', sans-serif; font-weight:normal; } li.basic { list-style:square; list-style-image:none; margin-top:2px; margin-bottom:2px; } span.links { } .sub { display: none; } .subexp {display: block; } .sub { display: none; } .subexp {display: block; } li.exp { list-style-image:url("plus.png"); margin-top:10px; margin-bottom:10px; cursor:pointer; } li.col { list-style-image:url("minus.png"); margin-top:10px; margin-bottom:10px; cursor:pointer; } li.exp_active { list-style-image:url("plus.png"); margin-top:10px; margin-bottom:10px; background-color:#eeeeff; cursor:pointer; } li.col_active { list-style-image:url("minus.png"); margin-top:10px; margin-bottom:10px; background-color:#eeeeff; cursor:pointer; /* if not included, bullets are not shown right in moz*/ } li.basic_active { list-style:square; list-style-image:none; background-color:#eeeeff; margin-top:2px; margin-bottom:2px; } ''') #---- icons used by marktree #Calculate an '+' and a '-' icon. _write_surface_file(tmp_path, '', 'minus.png', _create_icon(False)) _write_surface_file(tmp_path, '', 'plus.png', _create_icon(True)) #---- write version marker _write_file(import_path, '', 'install.inf', _marker) except: # print 'post install failed [%s] [%s]' % \ # (sys.exc_info()[0], sys.exc_info()[1]) # traceback.print_exc(file=sys.__stderr__) ka_debug.err('post install failed [%s] [%s]' % \ (sys.exc_info()[0], sys.exc_info()[1]))