def __init__(self, win, parser='rst', writer='html4', style=''): super(Renderer, self).__init__() self.webview = WebView() self.webview.connect("mouse-target-changed", self.on_mouse) self.webview.connect("context-menu", self.on_context_menu) self.webview.connect("button-release-event", self.on_button_release) self.add(self.webview) controller = self.webview.get_find_controller() self.search_done = None controller.connect("found-text", self.on_found_text) controller.connect("failed-to-find-text", self.on_faild_to_find_text) self.label = Label() self.label.set_halign(Align.START) self.label.set_valign(Align.END) self.add_overlay(self.label) self.link_uri = None self.context_button = 3 # will be rewrite by real value self.set_writer(writer) self.set_parser(parser) self.style = style self.tab_width = 8 self.__win = win
def __init__(self, activity, deck): """Constructs a new SlideRenderer that will render slides from deck""" self.__logger = logging.getLogger('Renderer') self.__logger.setLevel('ERROR') self.__deck = deck self.__activity = activity self.__wv = WebView() self.__wv.show() self.__htmlflag = True
def __init__(self): Gtk.VBox.__init__(self) self.set_spacing(8) wv = WebView() print 'show', WORKFILE, path(WORKFILE).exists() wv.load_uri(WORKFILE) wv.show() self.pack_start(wv, True, True, 0) # self.add(wv) self.show_all()
def __init__(self, win, parser='rst', writer='html4', style=''): super(Renderer, self).__init__() scrolled = ScrolledWindow.new(None, None) scrolled.set_policy(PolicyType.AUTOMATIC, PolicyType.AUTOMATIC) self.sb = scrolled.get_vscrollbar() self.add(scrolled) self.webview = WebView() self.webview.connect("mouse-target-changed", self.on_mouse) scrolled.add(self.webview) self.label = Label() self.label.set_halign(Align.START) self.label.set_valign(Align.END) self.add_overlay(self.label) self.set_writer(writer) self.set_parser(parser) self.style = style self.tab_width = 8 self.__win = win
class Renderer(Overlay): def __init__(self, win, parser='rst', writer='html4', style=''): super(Renderer, self).__init__() scrolled = ScrolledWindow.new(None, None) scrolled.set_policy(PolicyType.AUTOMATIC, PolicyType.AUTOMATIC) self.sb = scrolled.get_vscrollbar() self.add(scrolled) self.webview = WebView() self.webview.connect("mouse-target-changed", self.on_mouse) scrolled.add(self.webview) self.label = Label() self.label.set_halign(Align.START) self.label.set_valign(Align.END) self.add_overlay(self.label) self.set_writer(writer) self.set_parser(parser) self.style = style self.tab_width = 8 self.__win = win def on_mouse(self, web_view, hit_test_result, modifiers): if hit_test_result.context_is_link(): text = "link: %s" % hit_test_result.get_link_uri() elif hit_test_result.context_is_image(): text = "image: %s" % hit_test_result.get_image_uri() elif hit_test_result.context_is_media(): text = "media: %s" % hit_test_result.get_media_uri() else: if self.label.is_visible(): self.label.hide() return self.label.set_markup(MARKUP % text) self.label.show() def set_writer(self, writer): assert writer in WRITERS self.__writer = WRITERS[writer] klass = self.__writer['class'] self.writer_instance = klass() if klass is not None else None idle_add(self.do_render) def get_writer(self): return self.__writer['key'] def set_parser(self, parser): assert parser in PARSERS self.__parser = PARSERS[parser] klass = self.__parser['class'] self.parser_instance = klass() if klass is not None else None idle_add(self.do_render) def get_parser(self): return self.__parser['key'] def set_style(self, style): self.style = style idle_add(self.do_render) def get_style(self): return self.style def set_tab_width(self, width): self.tab_width = width def render_output(self): if getattr(self, 'src', None) is None: return False, "", "text/plain" try: if self.__parser['class'] is None: html = NOT_FOUND.format(**self.__parser) elif self.__writer['class'] is None: html = NOT_FOUND.format(**self.__writer) elif issubclass(self.__parser['class'], JSONPreview): try: json = loads(self.src) return (False, dumps(json, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')), 'application/json') except ValueError as e: return False, DATA_ERROR % ('JSON', str(e)), "text/html" else: if not issubclass(self.__parser['class'], HtmlPreview): settings = { 'warning_stream': StringIO(), 'embed_stylesheet': True, 'tab_width': self.tab_width } if self.style: settings['stylesheet'] = self.style settings['stylesheet_path'] = [] kwargs = {'source': self.src, 'parser': self.parser_instance, 'writer': self.writer_instance, 'writer_name': 'html', 'settings_overrides': settings} if self.__writer['key'] == 'pep': kwargs['reader_name'] = 'pep' kwargs.pop('parser') # pep is allways rst html = publish_string(**kwargs).decode('utf-8') return True, html, 'text/html' else: if version_info.major == 2: html = self.src.decode("utf-8") else: html = self.src # output to file or html preview return False, html, 'text/html' except DataError as e: return False, DATA_ERROR % ('Data', e), 'text/html' except BaseException: exc_str = format_exc() return False, EXCEPTION_ERROR % exc_str, 'text/html' def do_render(self): state, html, mime_type = self.render_output() if state: a, b = len(self.src[:self.pos]), len(self.src[self.pos:]) position = (float(a)/(a+b)) if a or b else 0 html += SCROLL % position if html and self.__win.runing: file_name = self.file_name or get_home_dir() self.webview.load_bytes(Bytes(html.encode("utf-8")), mime_type, "UTF-8", "file://"+file_name) def render(self, src, file_name, pos=0): self.src = src self.pos = pos self.file_name = file_name idle_add(self.do_render) def print_page(self): po = PrintOperation.new(self.webview) po.connect("failed", self.on_print_failed) po.run_dialog(self.__win) def on_print_failed(self, po, error): # FIXME: if dialog is used, application will lock :-( log_default_handler("Application", LogLevelFlags.LEVEL_WARNING, error.message)
class Renderer(object): def __init__(self, activity, deck): """Constructs a new SlideRenderer that will render slides from deck""" self.__logger = logging.getLogger('Renderer') self.__logger.setLevel('ERROR') self.__deck = deck self.__activity = activity self.__wv = WebView() self.__wv.show() self.__htmlflag = True def getSlideDimensionsFromFirstLayer(self, n=None): """Returns the [width, height] of the first slide layer""" if n is None: n = self.__deck.getIndex() layers = self.__deck.getSlideLayers(n) # return some default reasonable value if this is an empty slide if len(layers) == 0: return [640.0, 480.0] ftype = utils.getFileType(layers[0]) # This may be optimizable to avoid having to open the first layer to get its size, # or at least keeping it around to re-use it when the slide is first # rendered if ftype == "svg": handle = Rsvg.Handle.new_from_file(layers[0]) return [handle.width, handle.height] elif ftype == "png": surface = cairo.ImageSurface.create_from_png(layers[0]) return [float(surface.get_width()), float(surface.get_height())] elif ftype == "jpg": pbuf = GdkPixbuf.Pixbuf.new_from_file(layers[0]) return [float(pbuf.get_width()), float(pbuf.get_height())] else: return [640.0, 480.0] def getSlideDimensions(self, n=None): """Returns the slide dimensions, using the value in the XML file first, if it exists, and then the size of the first layer""" if n is None: n = self.__deck.getIndex() dims = self.__deck.getSlideDimensionsFromXML(n) if not dims: return self.getSlideDimensionsFromFirstLayer(n) else: w, h = dims return [w, h] def renderSlideToSurface(self, surface, n=None): if n is None: n = self.__deck.getIndex() timerstart = time.time() self.__logger.debug("rendering slide " + str(n)) ##ctx = gtk.gdk.CairoContext(cairo.Context(surface)) ctx = cairo.Context(surface) self.__logger.debug("Got context at " + str(time.time() - timerstart)) # Get the slide dimensions and set up a Cairo transformation matrix srcw, srch = self.getSlideDimensions(n) if srcw > 640: srcw = 640 if srch > 480: srch = 480 targw = float(surface.get_width()) targh = float(surface.get_height()) x_scale = targw / srcw y_scale = targh / srch print 'rendering slide', str( n), "w=", targw, srcw, x_scale, "h=", targh, srch, y_scale self.__logger.debug("Surface is " + str(targw) + "x" + str(targh)) scale = x_scale if y_scale < x_scale: scale = y_scale if scale < .98 or scale > 1.02: ctx.transform(cairo.Matrix(scale, 0, 0, scale, 0, 0)) self.__logger.debug("Got transformation matrix at " + str(time.time() - timerstart)) # Paint the slide background ctx.set_source_rgb(1.0, 1.0, 1.0) ctx.rectangle(0, 0, srcw, srch) ctx.fill() self.__logger.debug("Filled background at " + str(time.time() - timerstart)) # Paint the layers layers = self.__deck.getSlideLayers(n) self.__logger.debug("Got layers at " + str(time.time() - timerstart)) for layer in layers: type = utils.getFileType(layer) print 'Drawing layer ', type, layer self.__logger.debug("Drawing layer " + str(layer) + " " + str(scale) + " at " + str(time.time() - timerstart)) print 'drawing layer', type, str(layer) if type == "svg": handle = Rsvg.Handle.new_from_file(layer) handle.render_cairo(ctx) elif type == "png": png_surface = cairo.ImageSurface.create_from_png(layer) self.__logger.debug("Got PNG surface at " + str(time.time() - timerstart)) ctx.set_source_surface(png_surface, 0, 0) ctx.rectangle(0, 0, png_surface.get_width(), png_surface.get_height()) ctx.fill() elif type == "jpg": jpg_pixbuf = GdkPixbuf.Pixbuf.new_from_file(layer) self.__logger.debug("Got JPG pixbuf at " + str(time.time() - timerstart)) ctx.set_source_pixbuf(jpg_pixbuf, 0, 0) ctx.rectangle(0, 0, jpg_pixbuf.get_width(), jpg_pixbuf.get_height()) ctx.fill() elif type == "html": # use hulahop to display print 'html slide', self.__htmlflag, layer scrn4 = self.__activity.set_screen(3) if self.__htmlflag: scrn4.add(self.__wv) self.__htmlflag = False self.__wv.load_uri('file://' + layer) self.__wv.show() self.__logger.debug("Finished drawing layer at " + str(time.time() - timerstart))
class Renderer(Overlay): def __init__(self, win, parser='rst', writer='html4', style=''): super(Renderer, self).__init__() self.webview = WebView() self.webview.connect("mouse-target-changed", self.on_mouse) self.webview.connect("context-menu", self.on_context_menu) self.webview.connect("button-release-event", self.on_button_release) self.add(self.webview) controller = self.webview.get_find_controller() self.search_done = None controller.connect("found-text", self.on_found_text) controller.connect("failed-to-find-text", self.on_faild_to_find_text) self.label = Label() self.label.set_halign(Align.START) self.label.set_valign(Align.END) self.add_overlay(self.label) self.link_uri = None self.context_button = 3 # will be rewrite by real value self.set_writer(writer) self.set_parser(parser) self.style = style self.tab_width = 8 self.__win = win @property def position(self): self.__position = -1 self.webview.run_javascript(JS_POSITION, None, self.on_position_callback, None) while self.__position < 0: # this call at this place do problem, when Gdk.threads_init main_iteration() return self.__position def on_position_callback(self, webview, result, data): try: js_res = webview.run_javascript_finish(result) self.__position = js_res.get_js_value().to_double() except Error: self.__position = 0 def on_mouse(self, webview, hit_test_result, modifiers): self.link_uri = None if hit_test_result.context_is_link(): self.link_uri = hit_test_result.get_link_uri() text = "link: %s" % self.link_uri elif hit_test_result.context_is_image(): text = "image: %s" % hit_test_result.get_image_uri() elif hit_test_result.context_is_media(): text = "media: %s" % hit_test_result.get_media_uri() else: if self.label.is_visible(): self.label.hide() return self.label.set_markup(MARKUP % text.replace("&", "&")) self.label.show() def on_context_menu(self, webview, menu, event, hit_test_result): self.context_button = event.button.button return True # disable context menu for now def on_button_release(self, webview, event): """Catch release-button only when try to follow link. Context menu is catch by webview before this callback. """ if event.button == self.context_button: return True if self.link_uri: if self.link_uri.startswith("file://"): # try to open source self.find_and_opendocument(self.link_uri[7:].split('#')[0]) else: show_uri_on_window(None, self.link_uri, 0) return True def find_and_opendocument(self, file_path): ext = splitext(file_path)[1] if not ext: for EXT in LANGS.keys(): tmp = file_path + EXT if exists(tmp): file_path = tmp ext = EXT break if ext in LANGS: self.__win.open_document(file_path) elif exists(file_path): show_uri_on_window(None, "file://" + file_path, 0) else: dialog = FileNotFoundDialog(self.__win, file_path) dialog.run() dialog.destroy() def set_writer(self, writer): assert writer in WRITERS self.__writer = WRITERS[writer] klass = self.__writer['class'] self.writer_instance = klass() if klass is not None else None idle_add(self.do_render) def get_writer(self): return self.__writer['key'] def set_parser(self, parser): assert parser in PARSERS self.__parser = PARSERS[parser] klass = self.__parser['class'] self.parser_instance = klass() if klass is not None else None idle_add(self.do_render) def get_parser(self): return self.__parser['key'] def set_style(self, style): self.style = style idle_add(self.do_render) def get_style(self): return self.style def set_tab_width(self, width): self.tab_width = width def render_output(self): if getattr(self, 'src', None) is None: return False, "", "text/plain" try: if self.__parser['class'] is None: html = NOT_FOUND.format(**self.__parser) elif self.__writer['class'] is None: html = NOT_FOUND.format(**self.__writer) elif issubclass(self.__parser['class'], JSONPreview): try: json = loads(self.src) return (False, dumps(json, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')), 'application/json') except ValueError as e: return False, DATA_ERROR % ('JSON', str(e)), "text/html" else: if not issubclass(self.__parser['class'], HtmlPreview): settings = { 'warning_stream': StringIO(), 'embed_stylesheet': True, 'tab_width': self.tab_width, 'file_name': self.file_name } if self.style: settings['stylesheet'] = self.style settings['stylesheet_path'] = [] kwargs = { 'source': self.src, 'parser': self.parser_instance, 'writer': self.writer_instance, 'writer_name': 'html', 'settings_overrides': settings } if self.__writer['key'] == 'pep': kwargs['reader_name'] = 'pep' kwargs.pop('parser') # pep is allways rst html = publish_string(**kwargs).decode('utf-8') return True, html, 'text/html' else: if version_info.major == 2: html = self.src.decode("utf-8") else: html = self.src # output to file or html preview return False, html, 'text/html' except DataError as e: return False, DATA_ERROR % ('Data', e), 'text/html' except NotImplementedError: exc_str = format_exc() return False, NOT_IMPLEMENTED_ERROR % exc_str, 'text/html' except BaseException: exc_str = format_exc() return False, EXCEPTION_ERROR % exc_str, 'text/html' def do_render(self): state, html, mime_type = self.render_output() if state: if self.pos > 1: # vim a, b = len(self.src[:self.pos]), len(self.src[self.pos:]) position = (float(a) / (a + b)) if a or b else 0 else: position = self.pos html += SCROLL % position if html and self.__win.runing: file_name = self.file_name or get_home_dir() self.webview.load_bytes(Bytes(html.encode("utf-8")), mime_type, "UTF-8", "file://" + file_name) def render(self, src, file_name, pos=0): self.src = src self.pos = pos self.file_name = file_name idle_add(self.do_render) def print_page(self): po = PrintOperation.new(self.webview) po.connect("failed", self.on_print_failed) po.run_dialog(self.__win) def on_print_failed(self, po, error): # FIXME: if dialog is used, application will lock :-( log_default_handler("Application", LogLevelFlags.LEVEL_WARNING, error.message) def do_next_match(self, text): controller = self.webview.get_find_controller() if controller.get_search_text() != text: self.search_done = None controller.search(text, FindOptions.WRAP_AROUND, MAXUINT) while self.search_done is None: main_iteration() elif self.search_done: controller.search_next() return self.search_done def do_previous_match(self, text): controller = self.webview.get_find_controller() if controller.get_search_text() != text: self.search_done = None controller.search(text, FindOptions.WRAP_AROUND | FindOptions.BACKWARDS, MAXUINT) while self.search_done is None: main_iteration() elif self.search_done: controller.search_previous() return self.search_done def stop_search(self): controller = self.webview.get_find_controller() controller.search_finish() def on_found_text(self, controller, count): self.search_done = True def on_faild_to_find_text(self, controller): self.search_done = False def scroll_to_position(self, position): if position is not None: self.pos = position if self.pos > 1: # vim a, b = len(self.src[:self.pos]), len(self.src[self.pos:]) position = (float(a) / (a + b)) if a or b else 0 else: position = self.pos self.webview.run_javascript(JS_SCROLL % position, None, None, None)
def func(web_view: WebKit2.WebView, load_event: WebKit2.LoadEvent) -> None: if load_event is WebKit2.LoadEvent.FINISHED: web_view.run_javascript(script)