def run(self): while not self.killed: try: frame = self.inqueue.get(True, 0.1) except queue.Empty: pass else: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) wid, hei = self.vid_size # ~ frame = cv2.resize( # faster at BILINEAR scaling # ~ frame, None, (wid, hei), # ~ interpolation=cv2.INTER_LINEAR # ~ ) bytes1 = frame.tobytes() bytes2 = GLib.Bytes(bytes1) pb = GdkPixbuf.Pixbuf.new_from_bytes(bytes2, GdkPixbuf.Colorspace.RGB, False, 8, WIDTH, HEIGHT, WIDTH * 3) pb = pb.scale_simple( # Faster at NEAREST scaling wid, hei, GdkPixbuf.InterpType.BILINEAR) self.outqueue.put(pb)
def receive_data(self, s): save_path = prefs.get_save_path() path = os.path.join(save_path, s.relative_path) if path != self.current_path: if self.current_stream: self.current_stream.close() self.current_stream = None self.current_gfile = None self.current_path = path if s.file_type == FileType.DIRECTORY: os.makedirs(path, exist_ok=True) elif s.file_type == FileType.SYMBOLIC_LINK: absolute_symlink_target_path = os.path.join( save_path, s.symlink_target) make_symbolic_link(self.op, path, absolute_symlink_target_path) else: if not self.current_gfile: self.current_gfile = Gio.File.new_for_path(path) flags = Gio.FileCreateFlags.REPLACE_DESTINATION self.current_stream = self.current_gfile.replace( None, False, flags, None) length = len(s.chunk) if length == 0: return self.current_stream.write_bytes(GLib.Bytes(s.chunk), None) self.op.progress_tracker.update_progress(length)
def _on_epub_scheme(self, request): """Callback function for epub scheme requests Finish a WebKit2.URISchemeRequest by setting the contents of the request and its mime type. Args: request (WebKit2.URISchemeRequest) """ if not self.doc: return uri = request.get_uri() try: path, fragment = self._get_path_fragment(uri) except BookError as e: error_str = e.args[1] request.finish_error(GLib.Error(error_str)) return if self.doc.is_page(path): self.set_chapter_path_fragment(path, fragment) return resource_content = self.doc.get_resource_content(path) resource_gbytes = GLib.Bytes(resource_content) stream = Gio.MemoryInputStream.new_from_bytes(resource_gbytes) stream_length = resource_gbytes.get_size() mime = self.doc.get_resource_mime(path) request.finish(stream, stream_length, mime)
def get_message(self, source_object, res, *user_data): """Callback function to read network data, split it into WeeChat messages that are passed on to the application. """ try: gbytes = self.input.read_bytes_finish(res) except GLib.Error as err: self.handle_network_error(err) return if gbytes is None: # Error, try again self.input.read_bytes_async( 4096, 0, self.cancel_network_reads, self.get_message) return bytes_received = gbytes.get_size() if bytes_received <= 0: # Empty message or error, try another read print("Empty message error") return self.message_buffer = self.message_buffer+gbytes.get_data() while len(self.message_buffer) >= 4: length = struct.unpack('>i', self.message_buffer[0:4])[0] if length <= len(self.message_buffer): self.emit("messageFromWeechat", GLib.Bytes( self.message_buffer[0:length])) self.message_buffer = self.message_buffer[length:] else: break self.input.read_bytes_async( 4096, 0, self.cancel_network_reads, self.get_message)
def add(prefix, content, data, suffix): """ Add info to store @param prefix as str @param content as str @param data as bytes @param suffix as str """ filepath = "%s/%s_%s" % (InfoCache._INFO_PATH, escape(prefix), suffix) if content is not None: f = Gio.File.new_for_path(filepath + ".txt") fstream = f.replace(None, False, Gio.FileCreateFlags.REPLACE_DESTINATION, None) if fstream is not None: fstream.write(content, None) fstream.close() if data is None: f = Gio.File.new_for_path(filepath + ".jpg") fstream = f.replace(None, False, Gio.FileCreateFlags.REPLACE_DESTINATION, None) fstream.close() else: bytes = GLib.Bytes(data) stream = Gio.MemoryInputStream.new_from_bytes(bytes) bytes.unref() pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale( stream, ArtSize.ARTIST, -1, True, None) stream.close() pixbuf.savev( filepath + ".jpg", "jpeg", ["quality"], [str(Lp().settings.get_value("cover-quality").get_int32())])
def redraw_rect(self, widget, cairo_ctx): result, r = Gdk.cairo_get_clip_rectangle(cairo_ctx) if result: x, y, w, h = r.x, r.y, r.width, r.height else: print("Skipping drawing because entire context clipped") return try: buf = self.image.image_buffer(x, y) except MemoryError as err: # suppress these errors return pixbuf = GdkPixbuf.Pixbuf.new_from_bytes( GLib.Bytes(buf), GdkPixbuf.Colorspace.RGB, False, 8, min(self.width - x, w), min(self.height - y, h), self.width * 3) Gdk.cairo_set_source_pixbuf(cairo_ctx, pixbuf.copy(), x, y) cairo_ctx.paint() if self.selection_rect: cairo_ctx.set_source_rgb(1.0, 1.0, 1.0) cairo_ctx.set_line_width(T.SELECTION_LINE_WIDTH) cairo_ctx.rectangle(*self.selection_rect) cairo_ctx.stroke()
def pixbuf_from_tags(self, uri, size): """ Return cover from tags @param uri as str @param size as int """ pixbuf = None if uri.startswith("http:") or uri.startswith("https:"): return try: info = self.get_info(uri) exist = False if info is not None: (exist, sample) = info.get_tags().get_sample_index("image", 0) # Some file store it in a preview-image tag if not exist: (exist, sample) = info.get_tags().get_sample_index( "preview-image", 0) if exist: (exist, mapflags) = sample.get_buffer().map(Gst.MapFlags.READ) if exist: bytes = GLib.Bytes(mapflags.data) stream = Gio.MemoryInputStream.new_from_bytes(bytes) bytes.unref() pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale( stream, size, size, False, None) stream.close() except Exception as e: print("AlbumArt::pixbuf_from_tags():", e) return pixbuf
def connection_from_dict(data): con = NM.SimpleConnection.new() for setting_name, setting_data in data.items(): typ = NM.Setting.lookup_type(setting_name).pytype setting = typ() for k, v in setting_data.items(): if not v: continue if k == 'mac-address': v = ':'.join("%02X" % x for x in v) elif k == 'ssid': if isinstance(v, str): v = v.encode() v = GLib.Bytes(v) elif k == 'addresses': # setting addresses via the property doesn't seem to work for x in v: setting.add_address(address_from_str(x)) v = None if not v: continue try: setting.set_property(k, v) except TypeError as e: raise TypeError("Failed to set propery {}".format(k)) from e con.add_setting(setting) return con
def remote_load_request(self, request: RequestFromScrapy): # WebKitGTK does not support setting headers or method when loading # request. Instead, make the request and set it as the content. remote_req = RequestFromBrowser( url=request.url, method=request.method, headers=request.headers, body=request.body, is_first_request=True, cookiejarkey=self._options.get('cookiejarkey')) response = yield self._downloader.callRemote('make_request', remote_req) # Scrapy's Headers object keeps headers in title case. ctype = response.headers.get(b'Content-Type') if ctype: mime_type, mime_type_params = cgi.parse_header(ctype[0].decode()) enconding = mime_type_params.get('charset') else: mime_type = None enconding = None load_finished = self._load_finished(self._webview) self._webview.load_bytes(GLib.Bytes(response.body), mime_type, enconding, request.url) yield load_finished # TODO: report load errors. return (True, response.status, response.headers, None)
def __add_pixbuf(self, uri, loaded, content, callback, *args): """ Add uri to the view and load callback @param uri as str @param loaded as bool @param content as bytes @param callback as function """ if self.__cancellable.is_cancelled(): return try: if loaded: scale_factor = self.get_scale_factor() bytes = GLib.Bytes(content) stream = Gio.MemoryInputStream.new_from_bytes(bytes) if stream is not None: big = GdkPixbuf.Pixbuf.new_from_stream_at_scale( stream, ArtSize.BIG * scale_factor, ArtSize.BIG * scale_factor, True, None) stream.close() image = Gtk.Image() image.get_style_context().add_class("cover-frame") image.set_property("halign", Gtk.Align.CENTER) image.set_property("valign", Gtk.Align.CENTER) self.__contents[image] = content surface = Gdk.cairo_surface_create_from_pixbuf( big, scale_factor, None) image.set_from_surface(surface) image.show() self.__view.add(image) except Exception as e: Logger.error("ArtworkSearch::__add_pixbuf: %s" % e) callback(*args)
def __save_artwork_tags(self, data, album): """ Save artwork in tags @param data as bytes @param album as Album """ if album.is_web: return # https://bugzilla.gnome.org/show_bug.cgi?id=747431 bytes = GLib.Bytes(data) stream = Gio.MemoryInputStream.new_from_bytes(bytes) bytes.unref() pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale( stream, ArtSize.MONSTER, ArtSize.MONSTER, True, None) stream.close() pixbuf.savev( "%s/lollypop_cover_tags.jpg" % self._CACHE_PATH, "jpeg", ["quality"], [str(Lp().settings.get_value("cover-quality").get_int32())]) f = Lio.File.new_for_path("%s/lollypop_cover_tags.jpg" % self._CACHE_PATH) if f.query_exists(): dbus_helper = DBusHelper() dbus_helper.call("CanSetCover", None, self.__on_save_artwork_tags, album.id)
def show_preview(self): if self.preview_image != None: byte_in = GLib.Bytes(self.preview_image.tobytes()) input_in = Gio.MemoryInputStream.new_from_bytes(byte_in) pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale( input_in, self.preview_size, self.preview_size, True) self.builder.get_object('image2').set_from_pixbuf(pixbuf)
def load_catalog_clicked(self, button=None): scale = self.builder.get_object('scale1') size = scale.get_value() self.catalog_store.clear() self.cursor.execute( "SELECT p.id, barcode, p.name, ext_name, description, " "COALESCE(price, 0.00), image FROM products AS p " "LEFT JOIN products_markup_prices AS pmp " "ON pmp.product_id = p.id " "LEFT JOIN customer_markup_percent AS cmp " "ON cmp.id = pmp.markup_id " "WHERE (catalog, standard) = (True, True) " "ORDER BY catalog_order") for row in self.cursor.fetchall(): p_id = row[0] barcode = row[1] name = row[2] ext_name = row[3] description = row[4] price = row[5] image_bytes = row[6] if image_bytes == None: pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, True, 8, size, size) else: byte_in = GLib.Bytes(image_bytes.tobytes()) input_in = Gio.MemoryInputStream.new_from_bytes(byte_in) pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale( input_in, size, size, True) self.catalog_store.append( [p_id, barcode, name, ext_name, description, price, pixbuf])
def set_content(self, prefix, content, image_url, suffix): """ populate widget with content @param prefix as str @param content as str @param image url as str @param suffix as str @thread safe """ try: data = None stream = None if content is not None: if image_url is not None: f = Lio.File.new_for_uri(image_url) (status, data, tag) = f.load_contents(self.__cancel) if status: bytes = GLib.Bytes(data) stream = Gio.MemoryInputStream.new_from_bytes(bytes) bytes.unref() else: data = None InfoCache.add(prefix, content, data, suffix) GLib.idle_add(self.__set_content, content, stream) except Exception as e: print("InfoContent::set_content: %s" % e)
def add_artist_artwork(self, artist, data, is_web=False): """ Add artist artwork to store @param artist as str @param data as bytes @param is_web as bool @thread safe """ self.uncache_artist_artwork(artist) if is_web: filepath = "%s/web_%s.jpg" % (self._INFO_PATH, escape(artist)) else: filepath = "%s/%s.jpg" % (self._INFO_PATH, escape(artist)) if data is None: f = Gio.File.new_for_path(filepath) fstream = f.replace(None, False, Gio.FileCreateFlags.REPLACE_DESTINATION, None) fstream.close() else: bytes = GLib.Bytes(data) stream = Gio.MemoryInputStream.new_from_bytes(bytes) pixbuf = GdkPixbuf.Pixbuf.new_from_stream(stream, None) stream.close() pixbuf.savev(filepath, "jpeg", ["quality"], ["100"]) GLib.idle_add(self.emit, "artist-artwork-changed", artist)
def on_epub_scheme(self, request): """Callback function for epub scheme requests Finish a WebKit2.URISchemeRequest by setting the contents of the request and its mime type. Args: request (WebKit2.URISchemeRequest) """ if not self.doc: return uri = request.get_uri() logger.info('Resource request:' + uri) try: path, fragment = self.get_path_fragment(uri) if self.jump_to_path_fragment(path, fragment): return except BookError as e: error_str = str(e) logger.error('Could not get resource:' + error_str) request.finish_error(GLib.Error(error_str)) else: bytes = self.doc.get_resource(path) gbytes = GLib.Bytes(bytes) stream = Gio.MemoryInputStream.new_from_bytes(gbytes) stream_length = gbytes.get_size() mime = self.doc.get_resource_mime(path) request.finish(stream, stream_length, mime)
def receive_data(self, s): save_path = prefs.get_save_path() path = os.path.join(save_path, s.relative_path) if path != self.current_path: self.close_current_file() self.current_path = path self.current_mode = s.file_mode self.current_mtime = s.time.mtime self.current_mtime_usec = s.time.mtime_usec if not self.current_gfile: self.current_gfile = Gio.File.new_for_path(path) if s.file_type == FileType.DIRECTORY: os.makedirs(path, mode=s.file_mode if (s.file_mode > 0) else 0o777, exist_ok=True) elif s.file_type == FileType.SYMBOLIC_LINK: make_symbolic_link(self.op, path, s.symlink_target) else: if self.current_stream == None: flags = Gio.FileCreateFlags.REPLACE_DESTINATION self.current_stream = self.current_gfile.replace( None, False, flags, None) if not s.chunk: return self.current_stream.write_bytes(GLib.Bytes(s.chunk), None) self.op.progress_tracker.update_progress(len(s.chunk))
def _do_paint_rgb(self, cairo_format, has_alpha, img_data, x, y, width, height, rowstride, options): """ must be called from UI thread """ log( "cairo._do_paint_rgb(%s, %s, %s %s, %s, %s, %s, %s, %s, %s) set_image_surface_data=%s, use pixbuf=%s", FORMATS.get(cairo_format, cairo_format), has_alpha, len(img_data), type(img_data), x, y, width, height, rowstride, options, set_image_surface_data, CAIRO_USE_PIXBUF) rgb_format = options.strget(b"rgb_format", "RGB") if set_image_surface_data and not CAIRO_USE_PIXBUF: if (cairo_format==cairo.FORMAT_RGB24 and rgb_format in ("RGB", "BGR")) or \ (cairo_format==cairo.FORMAT_ARGB32 and rgb_format in ("BGRX", "BGRA")): img_surface = cairo.ImageSurface(cairo_format, width, height) set_image_surface_data(img_surface, rgb_format, img_data, width, height, rowstride) self.cairo_paint_surface(img_surface, x, y, options) return True if rgb_format in ("RGB", "RGBA", "RGBX"): data = GLib.Bytes(img_data) pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(data, GdkPixbuf.Colorspace.RGB, has_alpha, 8, width, height, rowstride) self.cairo_paint_pixbuf(pixbuf, x, y, options) return True img_data = memoryview(img_data) self.nasty_rgb_via_png_paint(cairo_format, has_alpha, img_data, x, y, width, height, rowstride, rgb_format) return True
class AppRootView(View['AppRootPresenter', None]): APP_ICON = GdkPixbuf.Pixbuf.new_from_stream( Gio.MemoryInputStream.new_from_bytes( GLib.Bytes( pkg_resources.resource_stream( 'opendrop.res', 'images/icon_256x256.png').read()))) def _do_init(self) -> None: Gtk.Window.set_default_icon(self.APP_ICON) _, self._main_menu_window = self.new_component( main_menu_cs.factory(model=self.presenter.main_menu_model)) self._ift_window_cid = None self._conan_window_cid = None self.presenter.view_ready() def start_ift(self, session: IFTSession) -> None: assert self._ift_window_cid is None self._ift_window_cid, ift_window = self.new_component( ift_root_cs.factory(session=session)) self._main_menu_window.hide() ift_window.show() def _end_ift(self) -> None: assert self._ift_window_cid is not None self.remove_component(self._ift_window_cid) self._ift_window_cid = None def start_conan(self, session: ConanSession) -> None: assert self._conan_window_cid is None self._conan_window_cid, conan_window = self.new_component( conan_root_cs.factory(session=session)) self._main_menu_window.hide() conan_window.show() def _end_conan(self) -> None: assert self._conan_window_cid is not None self.remove_component(self._conan_window_cid) self._conan_window_cid = None def return_to_main_menu(self) -> None: if self._ift_window_cid is not None: self._end_ift() if self._conan_window_cid is not None: self._end_conan() self._main_menu_window.show() def hide_all_windows(self) -> None: self._main_menu_window.hide() self._ift_window.hide()
def __set_artwork(self): """ Set artist artwork """ artwork_height = 0 if Lp().settings.get_value("artist-artwork"): if len(self._artist_ids) == 1 and\ Lp().settings.get_value("artist-artwork"): artist = Lp().artists.get_name(self._artist_ids[0]) size = ArtSize.ARTIST_SMALL * 2 * self.__scale_factor for suffix in ["lastfm", "spotify", "wikipedia"]: uri = InfoCache.get_artwork(artist, suffix, size) if uri is not None: f = Gio.File.new_for_path(uri) (status, data, tag) = f.load_contents(None) if not status: continue bytes = GLib.Bytes(data) stream = Gio.MemoryInputStream.new_from_bytes(bytes) bytes.unref() pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale( stream, size, size, True, None) stream.close() surface = Gdk.cairo_surface_create_from_pixbuf( pixbuf, self.__scale_factor, None) self.__artwork.set_from_surface(surface) artwork_height = ArtSize.ARTIST_SMALL * 2 self.__artwork.get_style_context().remove_class( "artwork-icon") self.__artwork.show() self.__artwork_box.show() break # Add a default icon if len(self._artist_ids) == 1 and artwork_height == 0: self.__artwork.set_from_icon_name( "avatar-default-symbolic", Gtk.IconSize.DND) artwork_height = 32 self.__artwork.get_style_context().add_class("artwork-icon") self.__artwork.show() self.__artwork_box.show() # Create an self.__empty widget with header height ctx = self.__label.get_pango_context() layout = Pango.Layout.new(ctx) layout.set_text("a", 1) # Font scale 2 font_height = int(layout.get_pixel_size()[1]) * 2 if artwork_height > font_height: self.__empty.set_property("height-request", artwork_height) else: self.__empty.set_property("height-request", font_height)
def get_pixbuf_from_frame(self, frame): height, width, channels = frame.shape return GdkPixbuf.Pixbuf.new_from_bytes( data=GLib.Bytes(frame.tobytes()), colorspace=0, has_alpha=True, bits_per_sample=8, width=width, height=height, rowstride = width*4)
def parse_doc(self, uri): data = None import urllib.request with urllib.request.urlopen(uri) as response: data = response.read() input_stream = Gio.MemoryInputStream.new_from_bytes(GLib.Bytes(data)) document = Poppler.Document.new_from_stream(input_stream, -1, None, None) return document
def add_bytes(self, _bytes): try: self.loader.write_bytes(GLib.Bytes(_bytes)) except GLib.Error: try: self.loader.close() except: pass self.emit("error")
def print_pdf_clicked(self, button): import printing print_op = printing.Operation() print_op.set_parent(self.window) pdf_data = Gio.MemoryInputStream.new_from_bytes(GLib.Bytes(self.bytes)) print_op.set_bytes_to_print(pdf_data) if self.landscape: setup = Gtk.PageSetup() setup.set_orientation(Gtk.PageOrientation.LANDSCAPE) print_op.set_default_page_setup(setup) print_op.print_dialog()
def get_image(self, name): # get the data back: decode b64 and uncompress the pixels data = self.images[name]["pixels"] data = base64.b64decode(data) data = zlib.decompress(data) pb = GdkPixbuf.Pixbuf.new_from_bytes( GLib.Bytes(data), GdkPixbuf.Colorspace.RGB, self.images[name]["has_alpha"], self.images[name]["bits_per_sample"], self.images[name]["width"], self.images[name]["height"], self.images[name]["rowstride"]) return pb
def make_launcher(filename, dropins_dir=DROPINS_DIR): dropins = find_dropins(filename, dropins_dir) if not dropins: return Gio.DesktopAppInfo.new_from_filename(filename) desktop_entry = load_desktop_entry_with_dropins(filename, dropins) data = GLib.Bytes(ini_to_string(desktop_entry).encode('utf-8')) keyfile = GLib.KeyFile() keyfile.load_from_bytes(data, 0) return Gio.DesktopAppInfo.new_from_keyfile(keyfile)
def create_pixbuf(self, width, height): pixbuf = GdkPixbuf.Pixbuf.new_from_bytes( data=GLib.Bytes(self.memory), colorspace=GdkPixbuf.Colorspace.RGB, has_alpha=False, bits_per_sample=8, width=self.interface.size[0], height=self.interface.size[1], rowstride=self.memory_stride, ) return pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)
def _handle_data_from_javascript(self, request): assert request.get_scheme() == 'mathpaste-gtk-data' assert request.get_uri().startswith('mathpaste-gtk-data://') data_part_of_uri = request.get_uri()[len('mathpaste-gtk-data://'):] id_, encoded_uri_component = data_part_of_uri.split(',', 1) json_string = urllib.parse.unquote(encoded_uri_component) python_object = json.loads(json_string) self._callback_dict.pop(int(id_))(python_object) empty_gstream = Gio.MemoryInputStream.new_from_bytes(GLib.Bytes(b'')) request.finish(empty_gstream, 0)
def __init__(self, image_base64): Result.__init__(self) self.get_style_context().add_class('resultimageview') self.image_base64 = image_base64 image_bytes = GLib.Bytes(base64.b64decode(self.image_base64)) image_stream = Gio.MemoryInputStream.new_from_bytes(image_bytes) self.pixbuf = GdkPixbuf.Pixbuf.new_from_stream(image_stream) self.image = Gtk.Image.new_from_pixbuf(self.pixbuf) self.centerbox.set_center_widget(self.image) self.show_all()
def save_album_artwork(self, data, album_id): """ Save data for album id @param data as bytes @param album id as int """ try: album = Album(album_id) arturi = None save_to_tags = Lp().settings.get_value("save-to-tags") uri_count = Lp().albums.get_uri_count(album.uri) filename = self.get_album_cache_name(album) + ".jpg" if save_to_tags: helper = TaskHelper() helper.run(self.__save_artwork_tags, data, album) store_path = self._STORE_PATH + "/" + filename if album.uri == "" or is_readonly(album.uri): arturi = GLib.filename_to_uri(store_path) # Many albums with same path, suffix with artist_album name elif uri_count > 1: arturi = album.uri + "/" + filename favorite_uri = album.uri + "/" + self.__favorite favorite = Gio.File.new_for_uri(favorite_uri) if favorite.query_exists(): favorite.trash() else: arturi = album.uri + "/" + self.__favorite # Save cover to uri dst = Gio.File.new_for_uri(arturi) if not save_to_tags or dst.query_exists(): bytes = GLib.Bytes(data) stream = Gio.MemoryInputStream.new_from_bytes(bytes) bytes.unref() pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale( stream, ArtSize.MONSTER, ArtSize.MONSTER, True, None) stream.close() pixbuf.savev(store_path, "jpeg", ["quality"], [str(Lp().settings.get_value( "cover-quality").get_int32())]) dst = Gio.File.new_for_uri(arturi) src = Gio.File.new_for_path(store_path) src.move(dst, Gio.FileCopyFlags.OVERWRITE, None, None) self.clean_album_cache(album) GLib.idle_add(self.album_artwork_update, album.id) except Exception as e: print("Art::save_album_artwork(): %s" % e)