예제 #1
0
    def _comment_activate_cb(self, entry):
        text = entry.props.text
        if 'comments' not in self._reflection.data:
            self._reflection.data['comments'] = []
        data = {
            'nick': profile.get_nick_name(),
            'color': self._reflection.activity.fg_color.get_html(),
            'comment': text
        }
        self._reflection.data['comments'].append(data)
        self.add_new_comment(data)
        # Send the comment
        if self._reflection.activity.sharing:
            send_data = data.copy()
            send_data["obj_id"] = self._reflection.data["obj_id"]
            self._reflection.activity.send_event(COMMENT_CMD, send_data)

        entry.set_text('')

        # Update journal entry
        dsobj = datastore.get(self._reflection.data['obj_id'])
        if 'comments' in dsobj.metadata:
            data = json.loads(dsobj.metadata['comments'])
        else:
            data = []
        data.append({
            'from': profile.get_nick_name(),
            'message': text,
            'icon-color': profile.get_color().to_string()
        })
        dsobj.metadata['comments'] = json.dumps(data)
        datastore.write(dsobj,
                        update_mtime=False,
                        reply_handler=self.datastore_write_cb,
                        error_handler=self.datastore_write_error_cb)
예제 #2
0
    def _comment_activate_cb(self, entry):
        text = entry.props.text
        if not "comments" in self._reflection.data:
            self._reflection.data["comments"] = []
        data = {
            "nick": profile.get_nick_name(),
            "color": self._reflection.activity.fg_color.get_html(),
            "comment": text,
        }
        self._reflection.data["comments"].append(data)
        self.add_new_comment(data)
        # Send the comment
        if self._reflection.activity.sharing:
            self._reflection.activity.send_event(
                "%s|%s|%s|%s|%s"
                % (COMMENT_CMD, self._reflection.data["obj_id"], data["nick"], data["color"], data["comment"])
            )
        entry.set_text("")

        # Update journal entry
        dsobj = datastore.get(self._reflection.data["obj_id"])
        if "comments" in dsobj.metadata:
            data = json.loads(dsobj.metadata["comments"])
        else:
            data = []
        data.append({"from": profile.get_nick_name(), "message": text, "icon-color": profile.get_color().to_string()})
        dsobj.metadata["comments"] = json.dumps(data)
        datastore.write(
            dsobj,
            update_mtime=False,
            reply_handler=self.datastore_write_cb,
            error_handler=self.datastore_write_error_cb,
        )
예제 #3
0
    def _comment_activate_cb(self, entry):
        text = entry.props.text
        if not 'comments' in self._reflection.data:
            self._reflection.data['comments'] = []
        data = {'nick': profile.get_nick_name(),
                'color': self._reflection.activity.fg_color.get_html(),
                'comment': text}
        self._reflection.data['comments'].append(data)
        self.add_new_comment(data)
        # Send the comment
        if self._reflection.activity.sharing:
            send_data = data.copy()
            send_data["obj_id"] = self._reflection.data["obj_id"]
            self._reflection.activity.send_event(COMMENT_CMD, send_data)

        entry.set_text('')

        # Update journal entry
        dsobj = datastore.get(self._reflection.data['obj_id'])
        if 'comments' in dsobj.metadata:
            data = json.loads(dsobj.metadata['comments'])
        else:
            data = []
        data.append({'from': profile.get_nick_name(),
                     'message': text,
                     'icon-color': profile.get_color().to_string()})
        dsobj.metadata['comments'] = json.dumps(data)
        datastore.write(dsobj,
                        update_mtime=False,
                        reply_handler=self.datastore_write_cb,
                        error_handler=self.datastore_write_error_cb)
예제 #4
0
    def __start_teacher_cb(self, button=None):
        if self._service is None:

            # get a free port
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            sock.bind(('', 0))
            sock.listen(socket.SOMAXCONN)
            _ipaddr, self.port = sock.getsockname()
            sock.shutdown(socket.SHUT_RDWR)
            logging.error('Using port %d', self.port)

            # puvblish the server direction
            self._service = ZeroconfService(name="Teacher", port=self.port,
                                            text=profile.get_nick_name())
            logging.error('Publish teacher zeroconf service')
            self._service.publish()

            # start the http server
            httpd = MyHTTPServer(('', self.port),
                                 lambda *args: TeacherRequestHandler(
                                 self._show_received_student_info, *args))

            from threading import Thread
            self._server = Thread(target=httpd.serve_forever)
            self._server.setDaemon(True)
            self._server.start()
            logging.debug("After start server")

        else:
            logging.error('Unpublish teacher zeroconf service')
            self._service.unpublish()
            self._service = None
            self._server.stop()
예제 #5
0
파일: FlipActivity.py 프로젝트: cemeiq/flip
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(FlipActivity, self).__init__(handle)

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self._setup_toolbars()
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)
        self.connect('shared', self._shared_cb)
        self.connect('joined', self._joined_cb)

        self._collab = CollabWrapper(self)
        self._collab.connect('message', self._message_cb)
        self._collab.connect('joined', self._joined_cb)
        self._collab.setup()

        if 'dotlist' in self.metadata:
            self._restore()
        else:
            self._game.new_game()
예제 #6
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(RecallActivity, self).__init__(handle)

        self.path = activity.get_bundle_path()

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self._restoring = False
        self._setup_toolbars(True)

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), \
                                Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas,
                          parent=self,
                          path=self.path,
                          colors=self.colors)
        self._setup_collab()
        if 'dotlist' in self.metadata:
            self._restore()
        else:
            self._game.new_game()
예제 #7
0
파일: irc.py 프로젝트: i5o/irc-activity
def default_nicks():
    try:
        nicks = [conf.get('nick')] + conf.get('altnicks', [])
        if not nicks[0]:

            # We're going to generate a nick based on the user's nick name
            # and their public key.
            from sugar3 import profile
            import hashlib

            user_name = profile.get_nick_name()
            pubkey = profile.get_pubkey()
            m = hashlib.sha1()
            m.update(pubkey)
            hexhash = m.hexdigest()

            # Okay.  Get all of the alphabetic bits of the username:
            user_name_letters = "".join([x for x in user_name if x.isalpha()])

            # If that came up with nothing, make it 'XO'.  Also, shorten it
            # if it's more than 11 characters (as we need 5 for - and the
            # hash).
            if len(user_name_letters) == 0:
                user_name_letters = "XO"
            if len(user_name_letters) > 11:
                user_name_letters = user_name_letters[0:11]

            # Finally, generate a nick by using those letters plus the first
            # four hash bits of the user's public key.
            user_nick = user_name_letters + "-" + hexhash[0:4]

            nicks = [user_nick]
    except:
        nicks = ["purk"]
    return nicks
예제 #8
0
    def start_game(self, numPlayers):
        self._create_domino()
        self.placed_pieces = []
        self.players = []
        auto_player = SimpleAutoPlayer(self, 0)
        auto_player.set_pieces(self.take_pieces(7))
        self.players.append(auto_player)

        if self.ENABLE_AUTO_MODE:
            auto_player2 = SimpleAutoPlayer(self, 1)
            auto_player2.set_pieces(self.take_pieces(7))
            auto_player2.pieces_position = self.table.second_player_position
            self.players.append(auto_player2)
        else:
            for n in range(1, numPlayers):
                player = DominoPlayer(self, n)
                player.set_pieces(self.take_pieces(7))
                self.players.append(player)

        # comienza a jugar el primer jugador
        self.players[0].play()
        self.ui_player = self.players[1]
        self.ui_player.color = profile.get_color()
        self.ui_player.name = profile.get_nick_name()
        self._actual_player = 0
예제 #9
0
 def _on_close(self, ws):
     self._file.close()
     self.send_event(CLOSE_CMD, {
         "nick": profile.get_nick_name(),
         "chunk": self._chunk
     })
     GObject.idle_add(self.emit, 'uploaded', True)
예제 #10
0
    def __init__(self):
        BaseBuddyModel.__init__(self)

        self.props.nick = profile.get_nick_name()
        self.props.color = profile.get_color()

        self.props.key = profile.get_profile().pubkey

        self.connect('notify::nick', self.__property_changed_cb)
        self.connect('notify::color', self.__property_changed_cb)

        bus = dbus.SessionBus()
        bus.add_signal_receiver(self.__name_owner_changed_cb,
                                signal_name='NameOwnerChanged',
                                dbus_interface='org.freedesktop.DBus')

        bus_object = bus.get_object(dbus.BUS_DAEMON_NAME, dbus.BUS_DAEMON_PATH)
        for service in bus_object.ListNames(
                dbus_interface=dbus.BUS_DAEMON_IFACE):
            if service.startswith(CONNECTION + '.'):
                path = '/%s' % service.replace('.', '/')
                Connection(service,
                           path,
                           bus,
                           ready_handler=self.__connection_ready_cb)
예제 #11
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(RecallActivity, self).__init__(handle)

        self.path = activity.get_bundle_path()

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(",")
        else:
            self.colors = ["#A0FFA0", "#FF8080"]

        self._restoring = False
        self._setup_toolbars(True)
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, path=self.path, colors=self.colors)
        self._setup_presence_service()

        if "dotlist" in self.metadata:
            self._restore()
        else:
            self._game.new_game()
예제 #12
0
    def __start_teacher_cb(self, button=None):
        if self._service is None:

            # get a free port
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            sock.bind(('', 0))
            sock.listen(socket.SOMAXCONN)
            _ipaddr, self.port = sock.getsockname()
            sock.shutdown(socket.SHUT_RDWR)
            logging.error('Using port %d', self.port)

            # puvblish the server direction
            self._service = ZeroconfService(name="Teacher",
                                            port=self.port,
                                            text=profile.get_nick_name())
            logging.error('Publish teacher zeroconf service')
            self._service.publish()

            # start the http server
            httpd = MyHTTPServer(('', self.port),
                                 lambda *args: TeacherRequestHandler(
                                     self._show_received_student_info, *args))

            from threading import Thread
            self._server = Thread(target=httpd.serve_forever)
            self._server.setDaemon(True)
            self._server.start()
            logging.debug("After start server")

        else:
            logging.error('Unpublish teacher zeroconf service')
            self._service.unpublish()
            self._service = None
            self._server.stop()
예제 #13
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(PathsActivity, self).__init__(handle)

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self._setup_toolbars()
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)
        self._setup_presence_service()

        # Restore game state from Journal or start new game
        if 'deck' in self.metadata:
            self._restore()
        else:
            self._game.new_game()
예제 #14
0
    def __init__(self, handle):
        """ Initialize the toolbars and the yupana """
        activity.Activity.__init__(self, handle)

        self.nick = profile.get_nick_name()
        self._reload_custom = False
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self._setup_toolbars()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), \
                                Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._yupana = Yupana(canvas, parent=self, colors=self.colors)
        self._setup_collab()

        if 'dotlist' in self.metadata:
            self._restore()
        else:
            self._yupana.new_yupana(mode='ten')

        self._make_custom_toolbar()
        if self._reload_custom:
            self._custom_cb()
예제 #15
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        try:
            super(XOEditorActivity, self).__init__(handle)
        except dbus.exceptions.DBusException as e:
            _logger.error(str(e))

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self.level = 0

        self._setup_toolbars(_have_toolbox)

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(),
                                Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, mycolors=self.colors)

        # Read the dot positions from the Journal
        for i in range(len(colors)):
            if 'x%d' % (i) in self.metadata and 'y%d' % (i) in self.metadata:
                self._game.move_dot(i, int(self.metadata['x%d' % (i)]),
                                    int(self.metadata['y%d' % (i)]))
        if 'xox' in self.metadata and 'xoy' in self.metadata:
            self._game.move_xo_man(int(self.metadata['xox']),
                                   int(self.metadata['xoy']))
    def _start_all_cb(self, widget):
        win = str(self.socket.get_id())

        if (win.endswith("L")):  # L of "Long"
            win = win[:-1]
        
        # Run game
        command = os.path.join(self._bundle_path, "res/sim")  #'SugarCity')

        args = [
            command,
            #'-R', win, # Set root window to socket window id
            '-t',      # Interactive tty mode, so we can send it commands.
        ]

        self._process = subprocess.Popen(args,
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         close_fds=True,
                                         cwd=self._bundle_path,
                                         preexec_fn=lambda: os.chdir(self._bundle_path))

        self._stdout_thread = thread.start_new(self._stdout_thread_function, ())

        uri = self._handle.uri or ''
        self.send_process('SugarStartUp "' + QuoteTCL(uri) + '"\n')

        nick = profile.get_nick_name() or ''
        self.send_process('SugarNickName "' + QuoteTCL(nick) + '"\n')
예제 #17
0
 def _share_stats(self):
     stats = self._generate_stats()
     nick = profile.get_nick_name()
     colors = profile.get_color().to_string()
     self._send_event('S:%s' % (json.dumps([nick, colors, stats])))
     self._restore_cursor()
     self._create_chart(stats)
    def __init__(self, handle):
        sugar3.activity.activity.Activity.__init__(self, handle)
        self.set_title(_("Typing Turtle"))
        self.max_participants = 1

        self.build_toolbox()

        self.screens = []
        self.screenbox = Gtk.VBox()

        self.nick = profile.get_nick_name()

        self.wordlist = []

        # All data which is saved in the Journal entry is placed in this dictionary.
        self.data = {'motd': 'welcome', 'history': [], 'medals': {}}

        # This calls the read_file method when restoring from the Journal.
        self.set_canvas(self.screenbox)

        # Start with the main screen.
        self.mainscreen = mainscreen.MainScreen(self)
        self.push_screen(self.mainscreen)

        self.show_all()

        self.editorbtn = sugar3.graphics.toolbutton.ToolButton('view-source')
        self.editorbtn.set_tooltip(_("Edit Lessons"))
        self.editorbtn.connect('clicked', self.editor_clicked_cb)

        activity_toolbar = self.toolbar_box.toolbar
        activity_toolbar.insert(self.editorbtn, 1)

        self.editorbtn.show_all()
예제 #19
0
 def _create_new_poll(self):
     # Reset vote data to 0
     self._poll = Poll(activity=self,
                       author=profile.get_nick_name(),
                       active=False)
     self.current_vote = None
     self.set_canvas(NewPollCanvas(self._poll))
예제 #20
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(PathsActivity, self).__init__(handle)

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self._setup_toolbars()
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)
        self._setup_presence_service()

        # Restore game state from Journal or start new game
        if 'deck' in self.metadata:
            self._restore()
        else:
            self._game.new_game()
예제 #21
0
class Instance:

    key = profile.get_pubkey()
    # joyride ...
    # keyHash = util.sha_data(key)
    # 8.2...
    # keyHash = util._sha_data(key)
    # keyHashPrintable = util.printable_hash(keyHash)
    nick_name = profile.get_nick_name()

    color_fill = Color()
    color_fill.init_hex(profile.get_color().get_fill_color())
    color_stroke = Color()
    color_stroke.init_hex(profile.get_color().get_stroke_color())

    instance_id = None
    instance_path = None
    data_path = None

    def __init__(self, ca):
        self.__class__.instance_id = ca._activity_id

        self.__class__.instance_path = os.path.join(ca.get_activity_root(),
                                                    "instance")
        recreate_tmp()

        self.__class__.data_path = os.path.join(ca.get_activity_root(), "data")
        recreate_data()
예제 #22
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        try:
            super(FlipActivity, self).__init__(handle)
        except dbus.exceptions.DBusException as e:
            _logger.error(str(e))

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self._setup_toolbars()
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(),
                                Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)
        self._setup_presence_service()

        if 'dotlist' in self.metadata:
            self._restore()
        else:
            self._game.new_game()
    def __init__(self, handle):
        ''' Initiate activity. '''
        super(FractionBounceActivity, self).__init__(handle)

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self._colors = profile.get_color().to_string().split(',')
        else:
            self._colors = ['#A0FFA0', '#FF8080']

        self.max_participants = 4  # sharing
        self._playing = True

        self._setup_toolbars()
        self._setup_dispatch_table()
        canvas = self._setup_canvas()

        # Read any custom fractions from the project metadata
        if 'custom' in self.metadata:
            custom = self.metadata['custom']
        else:
            custom = None

        self._current_ball = 'soccerball'

        self._toolbar_was_expanded = False

        # Initialize the canvas
        self._bounce_window = Bounce(canvas, activity.get_bundle_path(), self)

        Gdk.Screen.get_default().connect('size-changed', self._configure_cb)

        # Restore any custom fractions
        if custom is not None:
            fractions = custom.split(',')
            for f in fractions:
                self._bounce_window.add_fraction(f)

        if self.shared_activity:
            # We're joining
            if not self.get_shared():
                xocolors = XoColor(profile.get_color().to_string())
                share_icon = Icon(icon_name='zoom-neighborhood',
                                  xo_color=xocolors)
                self._joined_alert = NotifyAlert()
                self._joined_alert.props.icon = share_icon
                self._joined_alert.props.title = _('Please wait')
                self._joined_alert.props.msg = _('Starting connection...')
                self._joined_alert.connect('response', self._alert_cancel_cb)
                self.add_alert(self._joined_alert)

                self._label.set_label(_('Wait for the sharer to start.'))

                # Wait for joined signal
                self.connect("joined", self._joined_cb)

        self._setup_sharing()
예제 #24
0
 def _added_bookmark_cb(self, bookmarkmanager, page, title):
     logging.debug('Bookmark added page %d', page)
     title = _('%(title)s (Page %(number)d)') % \
         ({'title': title, 'number': page})
     color = profile.get_color().to_string()
     owner = profile.get_nick_name()
     thumb = self._get_screenshot()
     self._add_link_totray(page, thumb, color, title, owner, 1)
     bookmarkmanager.add_bookmark_preview(page - 1, thumb)
    def __init__(self, handle):
        ''' Initiate activity. '''
        super(FractionBounceActivity, self).__init__(handle)

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self._colors = profile.get_color().to_string().split(',')
        else:
            self._colors = ['#A0FFA0', '#FF8080']

        self.max_participants = 4  # sharing
        self._playing = True

        self._setup_toolbars()
        self._setup_dispatch_table()
        canvas = self._setup_canvas()

        # Read any custom fractions from the project metadata
        if 'custom' in self.metadata:
            custom = self.metadata['custom']
        else:
            custom = None

        self._current_ball = 'soccerball'

        self._toolbar_was_expanded = False

        # Initialize the canvas
        self._bounce_window = Bounce(canvas, activity.get_bundle_path(), self)

        Gdk.Screen.get_default().connect('size-changed', self._configure_cb)

        # Restore any custom fractions
        if custom is not None:
            fractions = custom.split(',')
            for f in fractions:
                self._bounce_window.add_fraction(f)

        if self.shared_activity:
            # We're joining
            if not self.get_shared():
                xocolors = XoColor(profile.get_color().to_string())
                share_icon = Icon(icon_name='zoom-neighborhood',
                                  xo_color=xocolors)
                self._joined_alert = NotifyAlert()
                self._joined_alert.props.icon = share_icon
                self._joined_alert.props.title = _('Please wait')
                self._joined_alert.props.msg = _('Starting connection...')
                self._joined_alert.connect('response', self._alert_cancel_cb)
                self.add_alert(self._joined_alert)

                self._label.set_label(_('Wait for the sharer to start.'))

                # Wait for joined signal
                self.connect("joined", self._joined_cb)

        self._setup_sharing()
예제 #26
0
def _get_identifier():
    path = None
    if os.path.exists(SN_PATH_X86):
        path = SN_PATH_X86
    elif os.path.exists(SN_PATH_ARM):
        path = SN_PATH_ARM
    if path is not None:
        with open(path, 'r') as file:
            return file.read().rstrip('\0\n')
    return profile.get_nick_name()
예제 #27
0
def _get_identifier():
    path = None
    if os.path.exists(SN_PATH_X86):
        path = SN_PATH_X86
    elif os.path.exists(SN_PATH_ARM):
        path = SN_PATH_ARM
    if path is not None:
        with open(path, 'r') as file:
            return file.read().rstrip('\0\n')
    return profile.get_nick_name()
예제 #28
0
 def add_bookmark(self, page):
     bookmark_title = (_("%s's bookmark") % profile.get_nick_name())
     bookmark_content = (_("Bookmark for page %d") % (int(page) + 1))
     dialog = BookmarkAddDialog(
         parent_xid=self.get_toplevel().get_window(),
         dialog_title=_("Add notes for bookmark: "),
         bookmark_title=bookmark_title,
         bookmark_content=bookmark_content, page=page,
         sidebarinstance=self)
     dialog.show_all()
예제 #29
0
 def add_bookmark(self, page):
     bookmark_title = (_("%s's bookmark") % profile.get_nick_name())
     bookmark_content = (_("Bookmark for page %d") % (int(page) + 1))
     dialog = BookmarkAddDialog(parent_xid=self.get_toplevel().get_window(),
                                dialog_title=_("Add notes for bookmark: "),
                                bookmark_title=bookmark_title,
                                bookmark_content=bookmark_content,
                                page=page,
                                sidebarinstance=self)
     dialog.show_all()
예제 #30
0
def register_laptop(url=_REGISTER_URL):

    profile = get_profile()

    if _have_ofw_tree():
        sn = _read_mfg_data(os.path.join(_OFW_TREE, _MFG_SN))
        uuid_ = _read_mfg_data(os.path.join(_OFW_TREE, _MFG_UUID))
    elif _have_proc_device_tree():
        sn = _read_mfg_data(os.path.join(_PROC_TREE, _MFG_SN))
        uuid_ = _read_mfg_data(os.path.join(_PROC_TREE, _MFG_UUID))
    else:
        sn = _generate_serial_number()
        uuid_ = str(uuid.uuid1())
    sn = sn or 'SHF00000000'
    uuid_ = uuid_ or '00000000-0000-0000-0000-000000000000'

    nick = get_nick_name()

    settings = Gio.Settings('org.sugarlabs.collaboration')
    jabber_server = settings.get_string('jabber-server')
    _store_identifiers(sn, uuid_, jabber_server)

    if jabber_server:
        url = 'http://' + jabber_server + ':8080/'

    if sys.hexversion < 0x2070000:
        server = xmlrpclib.ServerProxy(url, _TimeoutTransport())
    else:
        socket.setdefaulttimeout(_REGISTER_TIMEOUT)
        server = xmlrpclib.ServerProxy(url)
    try:
        data = server.register(sn, nick, uuid_, profile.pubkey)
    except (xmlrpclib.Error, TypeError, socket.error):
        logging.exception('Registration: cannot connect to server')
        raise RegisterError(_('Cannot connect to the server.'))
    finally:
        socket.setdefaulttimeout(None)

    if data['success'] != 'OK':
        logging.error('Registration: server could not complete request: %s',
                      data['error'])
        raise RegisterError(_('The server could not complete the request.'))

    settings.set_string('jabber-server', data['jabberserver'])
    settings = Gio.Settings('org.sugarlabs')
    settings.set_string('backup-url', data['backupurl'])

    # DEPRECATED
    from gi.repository import GConf
    client = GConf.Client.get_default()
    client.set_string(
        '/desktop/sugar/collaboration/jabber_server', data['jabberserver'])
    client.set_string('/desktop/sugar/backup_url', data['backupurl'])

    return True
예제 #31
0
 def _do_finish(self):
     self._tarfile.close()
     # Add metadata to the file created
     metadata = model.get(self._checkpoint)
     metadata['description'] = _('Backup from user %s') % \
         profile.get_nick_name()
     metadata['icon_color'] = profile.get_color().to_string()
     metadata['uncompressed_size'] = self._uncompressed_size
     metadata['mime_type'] = 'application/vnd.olpc-journal-backup'
     model.write(metadata, self._checkpoint)
     self.emit('finished')
예제 #32
0
 def _do_finish(self):
     self._tarfile.close()
     # Add metadata to the file created
     metadata = model.get(self._checkpoint)
     metadata['description'] = _('Backup from user %s') % \
         profile.get_nick_name()
     metadata['icon_color'] = profile.get_color().to_string()
     metadata['uncompressed_size'] = self._uncompressed_size
     metadata['mime_type'] = 'application/vnd.olpc-journal-backup'
     model.write(metadata, self._checkpoint)
     self.emit('finished')
예제 #33
0
    def do_GET(self):
        logging.error('do_GET path: %s', self.path)
        student_data = parse_qs(urlparse(self.path).query)
        GObject.idle_add(self._received_data_cb, student_data)

        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        # Send the html message
        teacher_data = {'nick_name': profile.get_nick_name()}
        self.wfile.write(json.dumps(teacher_data))
        return
예제 #34
0
    def do_GET(self):
        logging.error('do_GET path: %s', self.path)
        student_data = parse_qs(urlparse(self.path).query)
        GObject.idle_add(self._received_data_cb, student_data)

        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        # Send the html message
        teacher_data = {'nick_name': profile.get_nick_name()}
        self.wfile.write(json.dumps(teacher_data))
        return
예제 #35
0
    def _service_resolved(self, *args):
        logging.error('service resolved name: %s address %s port %s more %s',
                      args[2], args[7], args[8], args)

        nick_name = profile.get_nick_name()
        teacher_ip = args[7]
        teacher_port = args[8]
        teacher_xo_id = args[5]

        for widget in self._vbox.get_children():
            self._vbox.remove(widget)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("My name is %s \n" % nick_name)
        label.set_text(text)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("Teacher ip: %s \n" % teacher_ip)
        label.set_text(text)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("Teacher port: %s \n" % teacher_port)
        label.set_text(text)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("Teacher xo id: %s \n" % teacher_xo_id)
        label.set_text(text)
        self._vbox.show_all()

        # sent my information to the teacher
        student_data = {}
        student_data['nick_name'] = nick_name
        student_data['age'] = self._age
        student_data['gender'] = self._gender

        url_values = urllib.urlencode(student_data)

        response = urllib2.urlopen(
            'http://%s:%d/student_info?%s' % (teacher_ip, teacher_port,
                                              url_values))
        json_data = response.read()
        teacher_data = json.loads(json_data)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("Teacher name: %s \n" % teacher_data['nick_name'])
        label.set_text(text)
        label.show()
예제 #36
0
def get_user_data():
    """
    Create this structure:
    {"from": "Walter Bender", "icon": ["#FFC169", "#FF2B34"]}
    used to identify the owner of a shared object
    is compatible with how the comments are saved in
    http://wiki.sugarlabs.org/go/Features/Comment_box_in_journal_detail_view
    """
    xo_color = profile.get_color()
    data = {}
    data['from'] = profile.get_nick_name()
    data['icon'] = [xo_color.get_stroke_color(), xo_color.get_fill_color()]
    return data
예제 #37
0
def get_user_data():
    """
    Create this structure:
    {"from": "Walter Bender", "icon": ["#FFC169", "#FF2B34"]}
    used to identify the owner of a shared object
    is compatible with how the comments are saved in
    http://wiki.sugarlabs.org/go/Features/Comment_box_in_journal_detail_view
    """
    xo_color = profile.get_color()
    data = {}
    data['from'] = profile.get_nick_name()
    data['icon'] = [xo_color.get_stroke_color(), xo_color.get_fill_color()]
    return data
예제 #38
0
    def _add_link(self):
        ''' take screenshot and add link info to the model '''

        browser = self._tabbed_view.props.current_browser
        ui_uri = browser.get_uri()

        for link in self.model.data['shared_links']:
            if link['hash'] == sha1(ui_uri).hexdigest():
                _logger.debug('_add_link: link exist already a=%s b=%s',
                              link['hash'], sha1(ui_uri).hexdigest())
                return
        buf = self._get_screenshot()
        timestamp = time.time()
        self.model.add_link(ui_uri, browser.props.title, buf,
                            profile.get_nick_name(),
                            profile.get_color().to_string(), timestamp)

        if self.messenger is not None:
            self.messenger._add_link(ui_uri, browser.props.title,
                                     profile.get_color().to_string(),
                                     profile.get_nick_name(),
                                     base64.b64encode(buf), timestamp)
예제 #39
0
    def _service_resolved(self, *args):
        logging.error('service resolved name: %s address %s port %s more %s',
                      args[2], args[7], args[8], args)

        nick_name = profile.get_nick_name()
        teacher_ip = args[7]
        teacher_port = args[8]
        teacher_xo_id = args[5]

        for widget in self._vbox.get_children():
            self._vbox.remove(widget)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("My name is %s \n" % nick_name)
        label.set_text(text)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("Teacher ip: %s \n" % teacher_ip)
        label.set_text(text)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("Teacher port: %s \n" % teacher_port)
        label.set_text(text)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("Teacher xo id: %s \n" % teacher_xo_id)
        label.set_text(text)
        self._vbox.show_all()

        # sent my information to the teacher
        student_data = {}
        student_data['nick_name'] = nick_name
        student_data['age'] = self._age
        student_data['gender'] = self._gender

        url_values = urllib.urlencode(student_data)

        response = urllib2.urlopen('http://%s:%d/student_info?%s' %
                                   (teacher_ip, teacher_port, url_values))
        json_data = response.read()
        teacher_data = json.loads(json_data)

        label = Gtk.Label()
        self._vbox.add(label)
        text = ("Teacher name: %s \n" % teacher_data['nick_name'])
        label.set_text(text)
        label.show()
예제 #40
0
파일: brain.py 프로젝트: leonardcj/speak
    def load_brain():
        global _kernel
        global _kernel_voice

        is_first_session = _kernel is None

        try:
            if voice.friendlyname in BOTS:
                brain = BOTS[voice.friendlyname]
                brain_name = BOTS[voice.friendlyname]['name']
            else:
                brain = BOTS[_('English')]
                brain_name = BOTS[_('English')]['name']
            logger.debug('Load bot: %s' % brain)

            kernel = aiml.Kernel()

            if brain['brain'] is None:
                warning = _("Sorry, there is no free memory to load my " \
                            "brain. Close other activities and try once more.")
                activity.face.say_notification(warning)
                return

            kernel.loadBrain(brain['brain'])
            for name, value in brain['predicates'].items():
                kernel.setBotPredicate(name, value)

            if _kernel is not None:
                del _kernel
                _kernel = None
                import gc
                gc.collect()

            _kernel = kernel
            _kernel_voice = voice
        finally:
            activity.get_window().set_cursor(old_cursor)

        if is_first_session:
            _kernel.respond(_('my name is %s') % (profile.get_nick_name()))
            _kernel.respond(_('I am %d years old') % (_get_age()))
            hello = \
                _("Hello, I'm a robot \"%s\". Please ask me any question.") \
                % brain_name
            if sorry:
                hello += ' ' + sorry
            activity.face.say_notification(hello)
        elif sorry:
            activity.face.say_notification(sorry)
예제 #41
0
    def load_brain():
        global _kernel
        global _kernel_voice

        is_first_session = _kernel is None

        try:
            if voice.friendlyname in BOTS:
                brain = BOTS[voice.friendlyname]
                brain_name = BOTS[voice.friendlyname]['name']
            else:
                brain = BOTS[_('English')]
                brain_name = BOTS[_('English')]['name']
            logger.debug('Load bot: %s' % brain)

            kernel = Kernel()

            if brain['brain'] is None:
                warning = _("Sorry, there is no free memory to load my "
                            "brain. Close other activities and try once more.")
                activity.face.say_notification(warning)
                return

            kernel.loadBrain(brain['brain'])
            for name, value in list(brain['predicates'].items()):
                kernel.setBotPredicate(name, value)

            if _kernel is not None:
                del _kernel
                _kernel = None
                import gc
                gc.collect()

            _kernel = kernel
            _kernel_voice = voice
        finally:
            activity.get_window().set_cursor(old_cursor)

        if is_first_session:
            _kernel.respond(_('my name is %s') % (profile.get_nick_name()))
            _kernel.respond(_('I am %d years old') % (_get_age()))
            hello = \
                _("Hello, I'm a robot \"%s\". Please ask me any question.") \
                % brain_name
            if sorry:
                hello += ' ' + sorry
            activity.face.say_notification(hello)
        elif sorry:
            activity.face.say_notification(sorry)
예제 #42
0
    def _add_link(self):
        ''' take screenshot and add link info to the model '''

        browser = self._tabbed_view.props.current_browser
        ui_uri = browser.get_uri()

        if self.model.has_link(ui_uri):
            return

        buf = b64encode(self._get_screenshot())
        timestamp = time.time()
        args = (ui_uri, browser.props.title, buf, profile.get_nick_name(),
                profile.get_color().to_string(), timestamp)
        self.model.add_link(*args, by_me=True)
        self._collab.post({'type': 'add_link', 'args': args})
 def _share_favorites(self, data=None):
     logging.debug('SHARE FAVORITES %s' % (str(self.initiating)))
     if self.initiating:
         favorites = self._read_favorites()
         self._send_event('F:%s' % (json.dumps(favorites)))
         data_array = json.loads(data)
         nick = data_array[0]
         colors = data_array[1].encode('ascii', 'replace')
         icon = self._create_icon(colors)
         self._add_buddy(icon, nick)
     else:
         favorites_data = self._read_favorites()
         self._unset_favorites(favorites_data)
         nick = profile.get_nick_name()
         colors = profile.get_color().to_string()
         self._send_event('f:%s' % (json.dumps([nick, colors])))
예제 #44
0
    def _add_link(self):
        ''' take screenshot and add link info to the model '''

        browser = self._tabbed_view.props.current_browser
        ui_uri = browser.get_uri()

        if self.model.has_link(ui_uri):
            return

        buf = b64encode(self._get_screenshot())
        timestamp = time.time()
        args = (ui_uri, browser.props.title, buf,
                profile.get_nick_name(),
                profile.get_color().to_string(), timestamp)
        self.model.add_link(*args, by_me=True)
        self._collab.post({'type': 'add_link', 'args': args})
예제 #45
0
def generate_unique_id():
    """Generate an id based on the user's nick name and their public key
    (Based on schema used by IRC activity).

    """
    nick = profile.get_nick_name()
    pubkey = profile.get_pubkey()
    m = hashlib.sha1()
    m.update(pubkey)
    hexhash = m.hexdigest()

    nick_letters = "".join([x for x in nick if x.isalpha()])

    if not nick_letters:
        nick_letters = 'XO'

    return nick_letters + '_' + hexhash[:4]
예제 #46
0
def generate_unique_id():
    """Generate an id based on the user's nick name and their public key
    (Based on schema used by IRC activity).

    """
    nick = profile.get_nick_name()
    pubkey = profile.get_pubkey()
    m = hashlib.sha1()
    m.update(pubkey)
    hexhash = m.hexdigest()

    nick_letters = "".join([x for x in nick if x.isalpha()])

    if not nick_letters:
        nick_letters = 'XO'

    return nick_letters + '_' + hexhash[:4]
예제 #47
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """

        activity.Activity.__init__(self, handle)

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self.level = 0
        self._correct = 0
        self._playing = True
        self._game_over = False

        self._python_code = None

        self._setup_toolbars()
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)

        self._sharing = False
        self._initiating = False
        self.connect('shared', self._shared_cb)

        self._collab = CollabWrapper(self)
        self._collab.connect('message', self._message_cb)
        self._collab.connect('joined', self._joined_cb)
        self._collab.setup()

        if 'level' in self.metadata:
            self.level = int(self.metadata['level'])
            self.status.set_label(_('Resuming level %d') % (self.level + 1))
            self._game.show_random()
        else:
            self._game.new_game()
예제 #48
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        try:
            super(DeductoActivity, self).__init__(handle)
        except dbus.exceptions.DBusException as e:
            _logger.error(str(e))

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self.level = 0
        self._correct = 0
        self._playing = True
        self._game_over = False

        self._python_code = None

        self._setup_toolbars()
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(),
                                Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)

        self._sharing = False
        self._initiating = False
        self._setup_presence_service()

        if 'level' in self.metadata:
            self.level = int(self.metadata['level'])
            self.status.set_label(_('Resuming level %d') % (self.level + 1))
            self._game.show_random()
        else:
            self._game.new_game()
예제 #49
0
    def __init__(self, filehash):
        self._filehash = filehash

        dbpath = _init_db()

        assert dbpath != None

        self._conn = sqlite3.connect(dbpath)
        _init_db_highlights(self._conn)

        self._conn.text_factory = lambda x: unicode(x, "utf-8", "ignore")

        self._bookmarks = []
        self._populate_bookmarks()
        self._highlights = {0: []}
        self._populate_highlights()

        self._user = profile.get_nick_name()
        self._color = profile.get_color().to_string()
예제 #50
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        try:
            super(DeductoActivity, self).__init__(handle)
        except dbus.exceptions.DBusException as e:
            _logger.error(str(e))

        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self.level = 0
        self._correct = 0
        self._playing = True
        self._game_over = False

        self._python_code = None

        self._setup_toolbars()
        self._setup_dispatch_table()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(),
                                Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)

        self._sharing = False
        self._initiating = False
        self._setup_presence_service()

        if 'level' in self.metadata:
            self.level = int(self.metadata['level'])
            self.status.set_label(_('Resuming level %d') % (self.level + 1))
            self._game.show_random()
        else:
            self._game.new_game()
예제 #51
0
    def __init__(self, filehash):
        GObject.GObject.__init__(self)
        self._filehash = filehash

        dbpath = _init_db()

        assert dbpath is not None

        self._conn = sqlite3.connect(dbpath)
        _init_db_highlights(self._conn)
        _init_db_previews(self._conn)

        self._conn.text_factory = lambda x: unicode(x, "utf-8", "ignore")

        self._bookmarks = []
        self._populate_bookmarks()
        self._highlights = {0:  []}
        self._populate_highlights()

        self._user = profile.get_nick_name()
        self._color = profile.get_color().to_string()
예제 #52
0
    def __init__(self, handle):
        """ Initialize the toolbars and the game board """
        super(TurtlePondActivity, self).__init__(handle)
        self.nick = profile.get_nick_name()
        if profile.get_color() is not None:
            self.colors = profile.get_color().to_string().split(',')
        else:
            self.colors = ['#A0FFA0', '#FF8080']

        self._setup_toolbars()

        # Create a canvas
        canvas = Gtk.DrawingArea()
        canvas.set_size_request(Gdk.Screen.width(), \
                                Gdk.Screen.height())
        self.set_canvas(canvas)
        canvas.show()
        self.show_all()

        self._game = Game(canvas, parent=self, colors=self.colors)

        # TODO: Restore game state from Journal or start new game
        self._game.new_game()
예제 #53
0
파일: buddy.py 프로젝트: AbrahmAB/sugar
    def __init__(self):
        BaseBuddyModel.__init__(self)

        self.props.nick = profile.get_nick_name()
        self.props.color = profile.get_color()

        self.props.key = profile.get_profile().pubkey

        self.connect('notify::nick', self.__property_changed_cb)
        self.connect('notify::color', self.__property_changed_cb)

        bus = dbus.SessionBus()
        bus.add_signal_receiver(
            self.__name_owner_changed_cb,
            signal_name='NameOwnerChanged',
            dbus_interface='org.freedesktop.DBus')

        bus_object = bus.get_object(dbus.BUS_DAEMON_NAME, dbus.BUS_DAEMON_PATH)
        for service in bus_object.ListNames(
                dbus_interface=dbus.BUS_DAEMON_IFACE):
            if service.startswith(CONNECTION + '.'):
                path = '/%s' % service.replace('.', '/')
                Connection(service, path, bus,
                           ready_handler=self.__connection_ready_cb)
예제 #54
0
 def start(self):
     self.collab.send(JOIN_CMD, {"nick": profile.get_nick_name(), "chunk": self._chunk})
예제 #55
0
def get_nick():
    return profile.get_nick_name()
예제 #56
0
파일: chatbox.py 프로젝트: leonardcj/speak
    def add_text(self, buddy, text, status_message=False):
        '''Display text on screen, with name and colors.
        buddy -- buddy object or dict {nick: string, color: string}
        (The dict is for loading the chat log from the journal,
        when we don't have the buddy object any more.)
        text -- string, what the buddy said
        status_message -- boolean
        False: show what buddy said
        True: show what buddy did

        .----- rb ------------.
        |  +----align-------+ |
        |  | +--message---+ | |
        |  | | nick:      | | |
        |  | | text 1     | | |
        |  | | text 2     | | |
        |  | +------------+ | |
        |  +----------------+ |
        `----------------- +--'
                          \|

        The color scheme for owner messages is:
        nick in darker of stroke and fill colors
        background in lighter of stroke and fill colors
        text in black

        The color scheme for buddy messages is:
        nick in darker of stroke and fill colors
        background in light gray
        text in black

        rb has a tail on the right for owner messages and the left for
        buddy messages.
        '''
        if not buddy:
            buddy = self._owner

        if type(buddy) is dict:
            # dict required for loading chat log from journal
            nick = buddy['nick']
            color = buddy['color']
        elif buddy is None:
            nick = 'unknown'
            color = '#000000,#808080'
        else:
            nick = buddy.props.nick
            color = buddy.props.color
        try:
            color_stroke_html, color_fill_html = color.split(',')
        except ValueError:
            color_stroke_html, color_fill_html = ('#000000', '#888888')

        lighter = lighter_color(color.split(','))
        darker = 1 - lighter

        if len(text) > 3 and text[0:4] == '/me ':
            me_message = True
        else:
            me_message = False

        if status_message or me_message:
            text_color = style.COLOR_WHITE
            nick_color = style.COLOR_WHITE
            color_fill = style.Color('#808080')
            highlight_fill = style.COLOR_WHITE
            tail = None
        else:
            highlight_fill = style.COLOR_BUTTON_GREY
            text_color = style.COLOR_BLACK
            if darker == 1:
                color_fill = style.Color(color_stroke_html)
                if is_low_contrast(color.split(',')):
                    nick_color = text_color
                else:
                    nick_color = style.Color(color_fill_html)
            else:
                color_fill = style.Color(color_fill_html)
                if is_low_contrast(color.split(',')):
                    nick_color = text_color
                else:
                    nick_color = style.Color(color_stroke_html)
            if nick == profile.get_nick_name():
                tail = 'right'
            else:
                tail = 'left'

        color_stroke = None

        self._add_log(nick, color, text, status_message)

        # Check for Right-To-Left languages:
        if Pango.find_base_dir(nick, -1) == Pango.Direction.RTL:
            lang_rtl = True
        else:
            lang_rtl = False

        # Check if new message box or add text to previous:
        new_msg = True
        if self._last_msg_sender and buddy == self._last_msg_sender:
            # Add text to previous message
            if not (me_message or status_message):
                new_msg = False

        if not new_msg:
            message = self._last_msg
            message.add_text(text)
        else:
            rb = roundbox.RoundBox()
            rb.background_color = color_fill
            rb.border_color = color_stroke
            rb.tail = tail
            self._rb_list.append(rb)

            grid_internal = Gtk.Grid()
            grid_internal.set_row_spacing(0)
            grid_internal.set_border_width(style.DEFAULT_PADDING)
            grid_internal.set_size_request(
                Gdk.Screen.width() - style.GRID_CELL_SIZE, -1)
            self._grid_list.append(grid_internal)

            row = 0

            if status_message:
                nick = None
            elif me_message:
                text = text[4:]

            message = TextBox(self, nick_color, text_color, color_fill,
                              highlight_fill, lang_rtl, nick, text)
            self._message_list.append(message)
            message.connect('open-on-journal', self.__open_on_journal)

            self._last_msg_sender = buddy
            self._last_msg = message

            grid_internal.attach(message, 0, row, 1, 1)
            row += 1

            align = Gtk.Alignment.new(xalign=0.0, yalign=0.0, xscale=1.0,
                                      yscale=1.0)
            if rb.tail is None:
                bottom_padding = style.zoom(7)
            else:
                bottom_padding = style.zoom(35)
            align.set_padding(style.zoom(7), bottom_padding, style.zoom(30),
                              style.zoom(30))

            align.add(grid_internal)
            grid_internal.show()

            rb.pack_start(align, True, True, 0)
            align.show()

            self._conversation.attach(rb, 0, self._row_counter, 1, 1)
            rb.show()
            self._row_counter += 1
            message.show()

        if status_message:
            self._last_msg_sender = None
예제 #57
0
 def _on_close(self, ws):
     self._file.close()
     self.send_event(CLOSE_CMD, {"nick": profile.get_nick_name(), "chunk": self._chunk})
     GObject.idle_add(self.emit, 'uploaded', True)