Exemple #1
0
 def paint_pixbuf_gdk(self, coding, img_data, x, y, width, height, options,
                      callbacks):
     """ must be called from UI thread """
     loader = gdk.PixbufLoader(coding)
     loader.write(img_data, len(img_data))
     loader.close()
     pixbuf = loader.get_pixbuf()
     if not pixbuf:
         log.error("failed %s pixbuf=%s data len=%s" %
                   (coding, pixbuf, len(img_data)))
         fire_paint_callbacks(callbacks, False)
         return False
     raw_data = pixbuf.get_pixels()
     rowstride = pixbuf.get_rowstride()
     img_data = self.process_delta(raw_data, width, height, rowstride,
                                   options)
     n = pixbuf.get_n_channels()
     if n == 3:
         self.do_paint_rgb24(img_data, x, y, width, height, rowstride,
                             options, callbacks)
     else:
         assert n == 4, "invalid number of channels: %s" % n
         self.do_paint_rgb32(img_data, x, y, width, height, rowstride,
                             options, callbacks)
     return False
Exemple #2
0
 def load_chunk(self, chunk):
     from gtk import gdk
     loader = gdk.PixbufLoader()
     loader.write(chunk.data, len(chunk.data))
     # TODO: handle area-prepared etc
     self.image.set_from_pixbuf(loader.get_pixbuf())
     loader.close()
Exemple #3
0
 def paint_pixbuf_gdk(self, coding, img_data, x, y, width, height, options, callbacks):
     """ must be called from UI thread """
     if coding.startswith("png"):
         coding = "png"
     else:
         assert coding=="jpeg"
     loader = gdk.PixbufLoader(coding)
     loader.write(img_data, len(img_data))
     loader.close()
     pixbuf = loader.get_pixbuf()
     if not pixbuf:
         msg = "failed to load a pixbuf from %i bytes of %s data" % (len(img_data), coding)
         log.error("Error: %s", msg)
         fire_paint_callbacks(callbacks, False, msg)
         return  False
     raw_data = pixbuf.get_pixels()
     rowstride = pixbuf.get_rowstride()
     img_data = self.process_delta(raw_data, width, height, rowstride, options)
     n = pixbuf.get_n_channels()
     if n==3:
         self.do_paint_rgb24(img_data, x, y, width, height, rowstride, options, callbacks)
     else:
         assert n==4, "invalid number of channels: %s" % n
         self.do_paint_rgb32(img_data, x, y, width, height, rowstride, options, callbacks)
     return False
Exemple #4
0
 def __init__(self, vid, show_description):
     gtk.Widget.__init__(self)
     self.set_can_focus(True)
     self.video = vid
     picture = vid.get_picture()
     if picture:
         loader = gdk.PixbufLoader()
         loader.write(picture)
         self.pic = loader.get_pixbuf()
         loader.close()
     else:
         self.pic = None
     #self.font=gtk.FontSelection().get_font()
     self.create_pango_context()
     #self.font_description=pango.FontDescription('')
     txt = '<b>' + self.video.get_title() + '</b>\n'
     txt += self.get_formated_duration() + ' ' + self.video.get_uploader(
     ) + ' ' + self.get_formated_uploaded()
     if show_description:
         txt += '\n' + self.video.get_short_desc()
     else:
         #self.tooltip_widget=None
         #self.set_property('has-tooltip',True)
         #self.connect('query-tooltip',self.do_query_tooltip)
         self.set_tooltip_text(self.video.get_short_desc())
     txt = txt.replace('&', '&amp;')
     self.text_layout = self.create_pango_layout("")
     self.text_layout.set_markup(txt)
     self.text_layout.set_wrap(pango.WRAP_WORD_CHAR)
     self.text_layout.set_spacing(pango.SCALE * 3)
     self.connect('button-release-event', self.on_button_release)
     self.connect('enter-notify-event', self.on_enter)
     self.connect('leave-notify-event', self.on_leave)
Exemple #5
0
    def monitor_mcast(self):
        """Monitor for multicast messages"""
        while not self.mcast.messages.empty():
            message, sender = self.mcast.messages.get()
            screen_width, screen_height, fullscreen, pos_x, pos_y, step_x, step_y, img = self.protocol.unpack_chunk(message)
            self.logger.debug("Received image at %dx%d-%dx%d (fullscreen=%s)" % (pos_x, pos_y, step_x, step_y, fullscreen))
            # ignore messages received from different teacher
            if sender != self.teacher_addr:
                self.logger.info( "Ignoring multicast request from other teacher (%s instead of %s)" % (sender, self.teacher_addr))
                continue
            try:
                loader = gdk.PixbufLoader(image_type="jpeg")
                loader.write(img)
                loader.close()
                pb = loader.get_pixbuf()

                gc = self.drawing.get_style().fg_gc[gtk.STATE_NORMAL]
                # are we in fullscreen mode ?
                if fullscreen == 1:
                    width = self.screen.width
                    height = self.screen.height
                    if width != screen_width or height != screen_height:
                        self.projection_window.set_size_request(screen_width, screen_height)
                        self.drawing.set_size_request(screen_width, screen_height)
                    if self.projection_window.is_fullscreen == False:
                        self.projection_window.set_has_frame(False)
                        self.projection_window.set_decorated(False)
                        self.block_keyboard_mouse()
                        self.projection_window.fullscreen()
                        self.projection_window.is_fullscreen = True
                    scaling_ratio_x = 1.0 * width / screen_width
                    scaling_ratio_y = 1.0 * height / screen_height
                else:
                    width, height = self.projection_window.get_size()
                    if width != screen_width or height != screen_height:
                        self.projection_window.set_size_request(screen_width, screen_height)
                        self.drawing.set_size_request(screen_width, screen_height)
                    if self.projection_window.is_fullscreen:
                        self.projection_window.set_has_frame(True)
                        self.projection_window.set_decorated(True)
                        self.projection_window.unfullscreen()
                        self.projection_window.is_fullscreen = False
                    scaling_ratio_x = 1
                    scaling_ratio_y = 1
                # drawing or scaling
                if scaling_ratio_x != 1 or scaling_ratio_y != 1:
                    # scaling received stuff
                    new_pos_x = math.ceil(pos_x * scaling_ratio_x)
                    new_pos_y = math.ceil(pos_y * scaling_ratio_y)
                    new_step_x = math.ceil(step_x * scaling_ratio_x)
                    new_step_y = math.ceil(step_y * scaling_ratio_y)
                    pb2 = pb.scale_simple(new_step_x, new_step_y, gtk.gdk.INTERP_BILINEAR)
                    self.drawing.window.draw_pixbuf(gc, pb2, 0, 0, new_pos_x, new_pos_y, new_step_x, new_step_y)
                else:
                    self.drawing.window.draw_pixbuf(gc, pb, 0, 0, pos_x, pos_y, step_x, step_y)

            except:
                self.logger.exception("Processing multicast message")

        gobject.timeout_add(1000, self.monitor_mcast)
Exemple #6
0
 def from_string(self, value, format='png'):
     loader = gdk.PixbufLoader(format)
     try:
         loader.write(value)
         loader.close()
     except gobject.GError, e:
         raise ValidationError(_("Could not load image: %s") % e)
 def _pixbuf_from_stream(fp, feedback_cb=None):
     loader = gdk.PixbufLoader()
     while True:
         if feedback_cb is not None:
             feedback_cb()
         buf = fp.read(LOAD_CHUNK_SIZE)
         if buf == '':
             break
         loader.write(buf)
     loader.close()
     return loader.get_pixbuf()
Exemple #8
0
def pixbuf_from_string(pixbuf_data, format='png', width=None, height=None):
    loader = gdk.PixbufLoader(format)
    loader.write(pixbuf_data)
    loader.close()
    pixbuf = loader.get_pixbuf()
    if width is not None or height is not None:
        scaled_pixbuf = pixbuf.scale_simple(width, height, gdk.INTERP_BILINEAR)
        if scaled_pixbuf is None:
            print 'Warning: could not scale image'
        else:
            pixbuf = scaled_pixbuf
    return pixbuf
Exemple #9
0
    def show_screenshot(self, client, width, height, shot):
        """Displays a student screenshot"""
        self.shot_window.resize(width, height)
        self.shot_label.set_text(_("Viewing display of %s") % client)
        self.shot_refresh.current_client = client

        loader = gdk.PixbufLoader(image_type="jpeg")
        loader.write(shot)
        loader.close()
        pb = loader.get_pixbuf()

        self.shot_drawing.set_from_pixbuf(pb)

        self.shot_window.show()
def get_pixbuf(filename):
    try:
        if os.path.splitext(filename)[1].lower() == ".ora":
            ora = zipfile.ZipFile(filename)
            data = ora.read("Thumbnails/thumbnail.png")
            loader = gdk.PixbufLoader("png")
            loader.write(data)
            loader.close()
            return loader.get_pixbuf()
        else:
            return gdk.pixbuf_new_from_file(filename)
    except:
        # filename is a directory, or just nothing image-like
        return
Exemple #11
0
def image_surface_to_pixbuf(surf):
    if gtk2compat.USE_GTK3:
        w = surf.get_width()
        h = surf.get_height()
        return gdk.pixbuf_get_from_surface(surf, 0, 0, w, h)
    # GTK2.
    # Ugly PNG-based fudge to work around cairo.ImageSurface.get_data()
    # returning packed BGRA or ARGB pixels depending on endianness.
    png_dp = StringIO()
    surf.write_to_png(png_dp)
    pixbuf_loader = gdk.PixbufLoader()
    pixbuf_loader.write(png_dp.getvalue())
    pixbuf_loader.close()
    return pixbuf_loader.get_pixbuf()
def ora_thumbnail(infile, outfile, size):
    """Saves an OpenRaster file's thumbnail to a PNG file, with scaling.
    """

    # Extract a GdkPixbuf from the OpenRaster file
    png_data = zipfile.ZipFile(infile).read('Thumbnails/thumbnail.png')
    loader = gdk.PixbufLoader()
    loader.write(png_data)
    loader.close()
    pixbuf = loader.get_pixbuf()

    # Don't scale if not needed
    orig_w, orig_h = pixbuf.get_width(), pixbuf.get_height()
    if orig_w < size and orig_h < size:
        pixbuf.save(outfile, 'png')
        return

    # Scale and save
    scale_factor = float(size) / max(orig_w, orig_h)
    new_w, new_h = int(orig_w * scale_factor), int(orig_h * scale_factor)
    scaled_pixbuf = pixbuf.scale_simple(new_w, new_h, gdk.INTERP_BILINEAR)
    scaled_pixbuf.save(outfile, 'png')
Exemple #13
0
    def monitor(self):
        """Monitors new machines connections"""
        # update machine timestamp
        timestamp = time.time()
        while not self.clients_queue.empty():
            action, addr, params = self.clients_queue.get()
            self.machines_alive[addr] = timestamp
            timestamp_s = time.asctime(time.localtime(timestamp))
            if action == "new":
                # adding a new machine
                if addr not in self.machines:
                    # Maquina nova
                    gtk.gdk.threads_enter()
                    name = params.get("name", addr)

                    machine = self.mkmachine(name)
                    machine.fullname = name
                    machine.button.connect('button_press_event',
                                           self.cb_machine, machine)
                    self.put_machine(machine)
                    self.machines[addr] = machine
                    self.machines_map[machine] = addr
                    self.machines_status[addr] = "registered"
                    # show default image
                    machine.button.set_image(self.image_connected)
                    machine.show_all()
                    gtk.gdk.threads_leave()
                else:
                    # do not process events from already rejected machines
                    if self.machines_status[addr] == "rejected":
                        continue
                    elif self.machines_status[addr] == "pending":
                        self.machines_status[addr] = "registered"
                    machine = self.machines[addr]
                    shot = params.get("shot")
                    if shot:
                        loader = gdk.PixbufLoader(image_type="jpeg")
                        loader.write(shot[0])
                        loader.close()
                        pb = loader.get_pixbuf()
                        img = gtk.Image()
                        img.set_from_pixbuf(pb)
                        machine.button.set_image(img)
                    name = params.get("name")
                    if name:
                        machine.label.set_markup(self.mkname(name))
                        machine.fullname = name
                    tooltip = "%s\n" % name
                    tooltip += "(%s)\n" % addr
                    tooltip += _("Updated on %s") % timestamp_s
                    self.tooltip.set_tip(machine, tooltip)
            elif action == "reject":
                machine = self.machines[addr]
                machine.button.set_image(self.image_disconnected)
            elif action == "shot":
                # show a student screenshot
                width = params["width"]
                height = params["height"]
                shot = params["shot"]

                self.show_screenshot(addr, width, height, shot)
            elif action == "raisehand":
                message = params["message"]
                # shows a raisehand request from students
                name = addr
                if addr in self.machines:
                    name = self.machines[addr].machine
                self.show_message(_("Message received from %s") % name,
                                  message,
                                  timeout=0)

        # nuke old clients
        for addr in self.machines_alive:
            client_ts = self.machines_alive[addr]
            if client_ts < 0:
                # skip already dead clients
                continue
            timeout = int(timestamp - client_ts)
            if timeout > self.max_client_timeout:
                self.logger.warning("Error: client %s has lost connection" %
                                    addr)
                self.machines_alive[addr] = -1
                try:
                    machine = self.machines[addr]
                    reject = False
                    if self.machines_status[addr] == "rejected":
                        reject = True
                    self.disconnect(machine, reject=reject)
                except:
                    self.logger.exception(
                        "Attempting to disconnect idle machine")
        gobject.timeout_add(self.events_frequency, self.monitor)
Exemple #14
0
    def __init__(self):
        threads_enter()
        gobject.type_register(VideoWidget)
        gobject.type_register(ShowBox)
        gobject.type_register(Configer)
        gobject.type_register(DescriptionWindow)
        gobject.type_register(SearchBar)

        locale.setlocale(locale.LC_ALL, locale.getdefaultlocale())

        factory = gtk.IconFactory()
        try:
            f = self.get_resource('pixmaps/bookmark.png')
            loader = gtk.gdk.PixbufLoader()
            loader.write(f.read())
            f.close()
            factory.add(self.STOCK_BOOKMARK, gtk.IconSet(loader.get_pixbuf()))
            loader.close()
        except:
            raise
        factory.add_default()
        gtk.stock_add(((
            self.STOCK_BOOKMARK,
            "_Bookmarks",
            gtk.gdk.CONTROL_MASK,
            gtk.gdk.keyval_from_name('B'),
            "youtube-show",
        ), ))

        self.userDir = UserDir()
        self.config = Config(self.userDir.get_conf_file())
        self.config.load()
        self.bookmarks = Bookmarks.Bookmarks(
            self.userDir.get_file('bookmarks'))
        self.bookmarks.load()
        self.caches = YoutubeConnector.CacheSaver(
            self.userDir.get_file('caches.txt'))

        self.cookies = CookieJar()
        self.downloader = urllib2.build_opener(
            urllib2.HTTPCookieProcessor(self.cookies))
        self.ytsearcher = YoutubeConnector.YTSearcher(self.downloader)
        self.ytconnector = YoutubeConnector.YTConnector(
            self.downloader, self.caches)

        self.searching = threading.Event()
        self.is_fullscreen = False
        self.history = History()

        self.viewer = Viewer.Viewer()
        self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        if not self.win:
            raise RuntimeError()
        self.win.connect('delete_event', self.cleanup)
        self.win.connect('destroy', self.destroy)
        self.win.connect('key_press_event', self.on_key_press)
        self.win.connect_object('window-state-event',
                                self.on_window_state_change, self)

        self.build_menu_bar()

        self.build_tool_bar()
        self.showbox = ShowBox()
        self.showbox.connect('scroll-end-event', self.do_next_search)
        self.showbox.show()
        self.statusbar = gtk.Statusbar()
        self.statusbar.show()
        self.progressbar = gtk.ProgressBar()
        self.statusbar.add(self.progressbar)

        self.align = gtk.VBox()
        self.align.pack_start(self.menubar, expand=False, fill=True)
        self.align.pack_start(self.toolbar, expand=False, fill=True)
        self.align.pack_start(self.showbox, expand=True, fill=True)
        self.align.pack_start(self.statusbar, expand=False, fill=True)

        self.statusbar.push(1, 'Ready')
        self.apply_config()
        self.align.show()
        self.win.add(self.align)
        self.win.set_title("youtube-show")

        theme = gtk.icon_theme_get_for_screen(gtk.gdk.screen_get_default())
        try:
            icon = theme.load_icon('youtube_show', 48, 0)
            self.win.set_icon(icon)
        except:
            try:
                with self.get_resource('pixmaps/youtube-show.png') as iconfile:
                    loader = gdk.PixbufLoader()
                    loader.write(iconfile.read())
                    self.win.set_icon(loader.get_pixbuf())
                    loader.close()
            except:
                pass

        w, h = self.config['size']
        if w > -1 and h > -1:
            self.win.resize(w, h)
        else:
            self.win.resize(500, 600)
        self.win.show()
        threads_leave()