Пример #1
0
class YorgMainPageGui(MainPageGui):

    def __init__(self, mediator, mainpage_props):
        self.__feed_type = ''
        self.__date_field = ''
        self.props = mainpage_props
        self.load_settings()
        self.conn_attempted = False
        self.ver_check = VersionChecker()
        MainPageGui.__init__(self, mediator, self.props.gameprops.menu_args)
        if self.ver_check.is_uptodate():
            options = self.props.opt_file
            user = options['settings']['xmpp']['usr']
            password = options['settings']['xmpp']['pwd']
            parser = argparse.ArgumentParser()
            parser.add_argument('--user')
            parser.add_argument('--pwd')
            parser.add_argument('--win_orig')
            args = parser.parse_args()
            if args.user and args.pwd:
                user = args.user
                password = args.pwd
            if user and password and not self.eng.xmpp.client:
            # if user:
                # if platform.startswith('linux'): set_keyring(Keyring())
                # pwd = get_password('ya2_rog', user)
                # if not pwd:
                    pwd = password
                    # set_password('ya2_rog', user, pwd)
                # self.eng.xmpp.start(user, pwd)
                    self.eng.xmpp.start(user, pwd, self.on_ok, self.on_ko, self.props.gameprops.xmpp_debug)
            if not (user and password):
                self.on_ko()

    def show(self):
        MainPageGui.show(self)
        self.widgets[5]['text'] = self.get_label()

    def on_ok(self):
        self.conn_attempted = True
        self.widgets[5]['text'] = self.get_label()
        self.eng.xmpp.send_connected()
        # self.notify('on_login')

    def on_ko(self, msg=None):  # unused msg
        self.conn_attempted = True
        self.widgets[5]['text'] = self.get_label()

    def on_logout(self):
        self.eng.xmpp.disconnect()
        options = self.props.opt_file
        options['settings']['xmpp']['usr'] = ''
        options['settings']['xmpp']['pwd'] = ''
        options.store()
        self.widgets[5]['text'] = self.get_label()
        self.notify('on_logout')

    def on_login(self):
        self.notify('on_push_page', 'login', [self.props])

    def on_loginout(self):
        if self.eng.xmpp.client and self.eng.xmpp.client.authenticated:
            self.on_logout()
        elif self.conn_attempted:
            self.on_login()

    def load_settings(self):
        sett = self.props.opt_file['settings']
        self.joystick = sett['joystick']
        self.keys = sett['keys']
        self.lang = sett['lang']
        self.volume = sett['volume']
        self.fullscreen = sett['fullscreen']
        self.antialiasing = sett['antialiasing']
        self.cars_num = sett['cars_number']
        self.shaders = sett['shaders']

    def get_label(self):
        if not self.ver_check.is_uptodate():
            return _('Not up-to-date')
        if self.eng.xmpp.client and self.eng.xmpp.client.authenticated:
            return _('Log out') + \
                ' \1small\1(%s)\2' % self.eng.xmpp.client.boundjid.bare
        elif self.conn_attempted:
            return _('Log in') + ' \1small\1(' + _('multiplayer') + ')\2'
        return _('Connecting')

    def build(self):
        sp_cb = lambda: self.notify('on_push_page', 'singleplayer',
                                    [self.props])
        supp_cb = lambda: self.eng.open_browser(self.props.support_url)
        cred_cb = lambda: self.notify('on_push_page', 'credits')
        menu_data = [
            ('Single Player', _('Single Player'), sp_cb),
            ('Options', _('Options'), self.on_options),
            ('Support us', _('Support us'), supp_cb),
            ('Credits', _('Credits'), cred_cb),
            ('Not up-to-date', self.get_label(), self.on_loginout),
            ('Quit', _('Quit'), lambda: self.notify('on_exit'))]
        widgets = [
            Btn(text='', pos=(0, 1, .64-i*.23), command=menu[2],
                tra_src=menu_data[i][0], tra_tra=menu_data[i][1],
                **self.props.gameprops.menu_args.btn_args)
            for i, menu in enumerate(menu_data)]
        logo_img = Img(
            self.props.title_img, scale=(.64, 1, .64 * (380.0 / 772)),
            parent=base.a2dTopLeft, pos=(.65, 1, -.32))
        widgets += [logo_img]
        lab_args = self.props.gameprops.menu_args.label_args
        lab_args['scale'] = .12
        lab_args['text_fg'] = self.props.gameprops.menu_args.text_err
        wip_lab = Label(
            text='', pos=(.05, 1, -.76), parent=base.a2dTopLeft,
            text_wordwrap=10, text_align=TextNode.A_left,
            tra_src='Note: the game is work-in-progress',
            tra_tra=_('Note: the game is work-in-progress'),
            **lab_args)
        self.widgets += [wip_lab]
        self.add_widgets(widgets)
        self.set_news()
        MainPageGui.build(self)
        if not self.ver_check.is_uptodate():
            self.widgets[5]['state'] = DISABLED

    def on_options(self):
        self.load_settings()
        option_props = OptionPageProps(
            self.joystick, self.keys, self.lang, self.volume, self.fullscreen,
            self.antialiasing, self.shaders, self.cars_num,
            self.props.opt_file)
        self.notify('on_push_page', 'options', [option_props])

    def set_news(self):
        menu_args = self.props.gameprops.menu_args
        feeds = parse(self.props.feed_url)
        if not feeds['entries']: return
        self.__feed_type = \
            'rss' if 'published' in feeds['entries'][0] else 'atom'
        self.__date_field = \
            'published' if self.__feed_type == 'rss' else 'updated'
        publ = lambda entry: self.__conv(entry[self.__date_field])
        rss = sorted(feeds['entries'], key=publ)
        conv_time = lambda ent: datetime.strftime(self.__conv(ent), '%b %d')
        rss = [(conv_time(ent[self.__date_field]), ent['title'])
               for ent in rss]
        rss.reverse()
        rss = rss[:5]
        rss = [(_rss[0], self.__ellipsis_str(_rss[1])) for _rss in rss]
        frm = Frame(
            frameSize=(0, 1.0, 0, .75), frameColor=(.2, .2, .2, .5),
            pos=(.05, 1, .1), parent=base.a2dBottomLeft)
        texts = [Text(
            _('Last news:'), pos=(.55, .75), scale=.055, wordwrap=32,
            parent='bottomleft', fg=menu_args.text_normal,
            font=menu_args.font, tra_src='Last news:',
            tra_tra=_('Last news:'))]
        rss = [map(self.__to_unicode, rss_str) for rss_str in rss]
        texts += [Text(
            ': '.join(rss[i]), pos=(.1, .65 - i*.1), scale=.055,
            wordwrap=32, parent='bottomleft', align='left',
            fg=menu_args.text_normal, font=menu_args.font)
                  for i in range(min(5, len(rss)))]
        btn_args = self.props.gameprops.menu_args.btn_args.copy()
        btn_args['scale'] = .055
        show_btn = Btn(
            text=_('show'), pos=(.55, 1, .15), command=self.eng.open_browser,
            extraArgs=[self.props.site_url], parent=base.a2dBottomLeft,
            tra_src='show', tra_tra=_('show'), **btn_args)
        self.add_widgets([frm] + texts + [show_btn])

    def __conv(self, datestr):
        if self.__feed_type == 'rss':
            months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
                      'Sep', 'Oct', 'Nov', 'Dec']
            date_el = datestr.split()[1:-2]
            month = months.index(date_el[1]) + 1
            day, year = date_el[0], date_el[2]
            return datetime(int(year), month, int(day))
        else:
            year = int(datestr[:4])
            month = int(datestr[5:7])
            day = int(datestr[8:10])
            return datetime(year, month, day)

    @staticmethod
    def __ellipsis_str(_str):
        return _str if len(_str) <= 20 else _str[:20] + '...'

    @staticmethod
    def __to_unicode(_str):  # for managing different encodings
        try:
            return unicode(_str)
        except UnicodeDecodeError:
            return ''

    def destroy(self):
        self.ver_check.destroy()
        MainPageGui.destroy(self)
Пример #2
0
class UsersFrm(GameObject):

    def __init__(self, menu_props, yorg_srv):
        GameObject.__init__(self)
        self.eng.log('create users form')
        self.ver_check = VersionChecker()
        self.yorg_srv = yorg_srv
        self.room_name = None
        self.labels = []
        self.invited_users = []
        self.menu_props = menu_props
        lab_args = menu_props.label_args
        lab_args['scale'] = .046
        self.users_lab = Label(
            text=_('Current online users'), pos=(-.85, -.02),
            hpr=(0, 0, -90), parent=base.a2dTopRight,
            text_align=TextNode.A_right, **lab_args)
        self.frm = DirectScrolledFrame(
            frameSize=(-.02, .8, .45, 2.43),
            canvasSize=(-.02, .76, -.08, 3.8),
            scrollBarWidth=.036,
            verticalScroll_relief=FLAT,
            verticalScroll_frameColor=(.2, .2, .2, .4),
            verticalScroll_thumb_relief=FLAT,
            verticalScroll_thumb_frameColor=(.8, .8, .8, .6),
            verticalScroll_incButton_relief=FLAT,
            verticalScroll_incButton_frameColor=(.8, .8, .8, .6),
            verticalScroll_decButton_relief=FLAT,
            verticalScroll_decButton_frameColor=(.8, .8, .8, .6),
            horizontalScroll_relief=FLAT,
            frameColor=(.2, .2, .2, .5),
            pos=(-.82, 1, -2.44), parent=base.a2dTopRight)
        self.conn_lab = Label(
            text='', pos=(.38, 1.5), parent=self.frm,
            text_wordwrap=10, **lab_args)
        self.set_connection_label()
        self.in_match_room = None
        self.invited = False

    def show(self):
        self.frm.show()
        self.users_lab.show()

    def hide(self):
        self.frm.hide()
        self.users_lab.hide()

    def set_connection_label(self):
        lab_args = self.menu_props.label_args
        lab_args['scale'] = .046
        txt = ''
        if not self.ver_check.is_uptodate():
            txt = _("Your game isn't up-to-date, please update")
        elif not self.eng.client.is_server_up:
            txt = _("Yorg's server isn't running")
        elif not self.eng.client.authenticated: txt = _("You aren't logged in")
        (self.conn_lab.show if txt else self.conn_lab.hide)()
        self.conn_lab['text'] = txt

    def set_size(self, full=True):
        if full:
            self.frm.setPos(-.82, 1, -2.44)
            self.frm['frameSize'] = (-.02, .8, .45, 2.43)
        else:
            self.frm.setPos(-.82, 1, -1.97)
            self.frm['frameSize'] = (-.02, .8, .45, 1.96)

    @staticmethod
    def trunc(name, lgt):
        if len(name) > lgt: return name[:lgt] + '...'
        return name

    def on_users(self):
        self.set_connection_label()
        bare_users = [self.trunc(user.uid, 20)
                      for user in self.eng.client.sorted_users]
        for lab in self.labels[:]:
            _lab = lab.lab.lab['text'].replace('\1smaller\1', '').replace('\2', '')
            if _lab not in bare_users:
                if _lab not in self.eng.client.users:
                    lab.destroy()
                    self.labels.remove(lab)
        nusers = len(self.eng.client.sorted_users)
        invite_btn = len(self.invited_users) < 8
        invite_btn = invite_btn and not self.in_match_room and not self.invited
        top = .08 * nusers + .08
        self.frm['canvasSize'] = (-.02, .76, 0, top)
        label_users = [lab.lab.lab['text'] for lab in self.labels]
        clean = lambda n: n.replace('\1smaller\1', '').replace('\2', '')
        label_users = list(map(clean, label_users))
        for i, user in enumerate(self.eng.client.sorted_users):
            if self.trunc(user.uid, 20) not in label_users:
                if self.eng.client.myid != user.uid:
                    lab = UserFrmList(
                        user.uid,
                        user.is_supporter,
                        user.is_playing,
                        (0, 1, top - .08 - .08 * i),
                        self.frm.getCanvas(),
                        self.menu_props)
                else:
                    lab = UserFrmListMe(
                        user.uid,
                        user.is_supporter,
                        (0, 1, top - .08 - .08 * i),
                        self.frm.getCanvas(),
                        self.menu_props)
                self.labels += [lab]
                lab.attach(self.on_invite)
                lab.attach(self.on_friend)
                lab.attach(self.on_unfriend)
                lab.attach(self.on_add_chat)
        #for i, user in enumerate(self.eng.client.sorted_users):
        #    clean = lambda n: n.replace('\1smaller\1', '').replace('\2', '')
        #    lab = [lab for lab in self.labels
        #           if clean(lab.lab.lab['text']) == self.trunc(user.uid, 20)][0]
        #    enb_val = invite_btn and user.uid not in self.invited_users and not user.is_playing
        #    if hasattr(lab, 'invite_btn'):
        #        inv_btn = lab.invite_btn
        #        if enb_val: inv_btn.tooltip['text'] = _('invite the user to a match')
        #        elif len(self.invited_users) == 8: inv_btn.tooltip['text'] = _("you can't invite more players")
        #        elif self.in_match_room: inv_btn.tooltip['text'] = _("you're already in a match")
        #        elif user.uid in self.invited_users: inv_btn.tooltip['text'] = _("you've already invited this user")
        #        elif user.is_playing: inv_btn.tooltip['text'] = _("the user is already playing a match")
        #    lab.enable_invite_btn(enb_val)
        #    lab.frm.set_z(top - .08 - .08 * i)
        #    lab.lab.set_supporter(user.is_supporter)

    def on_invite(self, usr):
        self.notify('on_invite', usr)
        self.invited_users += [usr.uid]
        self.on_users()
        if not self.room_name:

            time_code = strftime('%y%m%d%H%M%S')
            self.room_name = self.eng.client.myid + time_code
            #self.eng.xmpp.client.plugin['xep_0045'].joinMUC(
            #    self.room_name, self.eng.xmpp.client.boundjid.bare,
            #    pfrom=self.eng.xmpp.client.boundjid.full)
            #cfg = self.eng.xmpp.client.plugin['xep_0045'].getRoomConfig(self.room_name)
            #values = cfg.get_values()
            #values['muc#roomconfig_publicroom'] = False
            #cfg.set_values(values)
            #self.eng.xmpp.client.plugin['xep_0045'].configureRoom(self.room_name, cfg)
            self.eng.client.register_rpc('join_room')
            self.eng.client.join_room(self.room_name)
            self.eng.log('created room ' + self.room_name)
            self.eng.client.is_server_active = True
            #for usr_name in [self.yorg_srv] + \
            #    [_usr.name_full for _usr in self.eng.xmpp.users if _usr.is_in_yorg]:
            #    self.eng.xmpp.client.send_message(
            #        mfrom=self.eng.xmpp.client.boundjid.full,
            #        mto=usr_name,
            #        mtype='ya2_yorg',
            #        msubject='is_playing',
            #        mbody='1')
        self.eng.client.register_rpc('invite')
        ret = self.eng.client.invite(usr.uid, self.room_name)
        #self.eng.xmpp.client.send_message(
        #    mfrom=self.eng.xmpp.client.boundjid.full,
        #    mto=usr.name_full,
        #    mtype='ya2_yorg',
        #    msubject='invite',
        #    mbody=self.room_name + '\n' + self.eng.server.public_addr + '\n' + self.eng.server.local_addr)
        if ret == 'ok':
            self.eng.log('invited ' + str(usr.uid))
            self.notify('on_add_groupchat', self.room_name, usr.uid)

    def on_declined(self, from_):
        self.eng.log('declined from ' + from_)
        self.invited_users.remove(from_)
        self.on_users()

    def on_add_chat(self, msg): self.notify('on_add_chat', msg)

    def on_logout(self):
        list(map(lambda lab: lab.destroy(), self.labels))
        self.labels = []

    def on_friend(self, usr_name):
        self.eng.log('send friend to ' + usr_name)
        self.eng.xmpp.client.send_presence_subscription(
            usr_name, ptype='subscribe',
            pfrom=self.eng.xmpp.client.boundjid.full)

    def on_unfriend(self, usr):
        self.eng.log('roster ' + str(self.eng.xmpp.client.client_roster))
        self.eng.xmpp.client.del_roster_item(usr)
        self.eng.log('roster ' + str(self.eng.xmpp.client.client_roster))

    def destroy(self):
        self.eng.log('destroyed usersfrm')
        self.frm = self.frm.destroy()
        GameObject.destroy(self)
Пример #3
0
class YorgMainPageGui(MainPageGui):
    def __init__(self, mediator, mainpage_props):
        self.__feed_type = ''
        self.__date_field = ''
        self.props = mainpage_props
        self.load_settings()
        self.conn_attempted = False
        if not self.eng.client.netw_thr or \
                not self.eng.client.netw_thr.is_running:
            self.eng.client.restart()
        self.ver_check = VersionChecker()
        MainPageGui.__init__(self, mediator, self.props.gameprops.menu_props)
        if self.ver_check.is_uptodate():
            options = self.props.opt_file
            user = options['settings']['login']['usr']
            password = options['settings']['login']['pwd']
            parser = argparse.ArgumentParser()
            parser.add_argument('--user')
            parser.add_argument('--pwd')
            parser.add_argument('--win_orig')
            parser.add_argument('--optfile')
            args = parser.parse_args(EngineLogic.cmd_line())
            if args.user and args.pwd:
                user = args.user
                password = args.pwd
            if user and password and self.eng.client.is_server_up:
                # if user:
                # if platform.startswith('linux'): set_keyring(Keyring())
                # pwd = get_password('ya2_rog', user)
                # if not pwd:
                pwd = password
                # set_password('ya2_rog', user, pwd)
                # self.eng.xmpp.start(user, pwd)
                #self.eng.xmpp.start(user, pwd, self.on_ok, self.on_ko, self.props.gameprops.xmpp_debug)
                self.eng.client.register_rpc('login')
                while not self.eng.client.netw_thr:
                    pass
                # wait for the thread
                ret_val = 'ok'
                if not self.eng.client.authenticated:
                    ret_val = self.eng.client.login(user, password)
                if ret_val in [
                        'invalid_nick', 'unregistered_nick', 'wrong_pwd'
                ]:
                    self.on_ko(ret_val)
                    #return self.on_ko(ret_val)
                taskMgr.doMethodLater(.1, lambda task: self.on_ok(), 'x')
                # otherwise the menu is not attached to the page yet

            if not (user and password):
                self.on_ko()

    def on_ok(self):
        self.eng.client.authenticated = True
        self.conn_attempted = True
        #self.eng.xmpp.send_connected()
        self.eng.client.init(self.props.opt_file['settings']['login']['usr'])
        self.notify('on_login')

    def on_ko(self, msg=None):  # unused msg
        self.conn_attempted = True

    def load_settings(self):
        sett = self.props.opt_file['settings']
        self.keys = sett['keys']
        self.lang = sett['lang']
        self.volume = sett['volume']
        self.fullscreen = sett['fullscreen']
        self.antialiasing = sett['antialiasing']
        self.cars_num = sett['cars_number']
        self.shaders = sett['shaders']
        self.camera = sett['camera']

    def build(self):
        sp_cb = lambda: self.notify('on_push_page', 'singleplayer',
                                    [self.props])
        mp_cb = lambda: self.notify('on_push_page', 'multiplayer',
                                    [self.props])
        supp_cb = lambda: self.eng.open_browser(self.props.support_url)
        cred_cb = lambda: self.notify('on_push_page', 'credits')
        menu_data = [('Single Player', _('Single Player'), sp_cb),
                     ('Multiplayer', _('Multiplayer'), mp_cb),
                     ('Options', _('Options'), self.on_options),
                     ('Support us', _('Support us'), supp_cb),
                     ('Credits', _('Credits'), cred_cb),
                     ('Quit', _('Quit'), lambda: self.notify('on_exit'))]
        widgets = [
            Btn(text='',
                pos=(0, .64 - i * .23),
                cmd=menu[2],
                tra_src=menu_data[i][0],
                tra_tra=menu_data[i][1],
                **self.props.gameprops.menu_props.btn_args)
            for i, menu in enumerate(menu_data)
        ]
        logo_img = Img(self.props.title_img,
                       scale=(.64, 1, .64 * (380.0 / 772)),
                       parent=base.a2dTopLeft,
                       pos=(.65, -.32))
        widgets += [logo_img]
        lab_args = self.props.gameprops.menu_props.label_args
        lab_args['scale'] = .12
        lab_args['text_fg'] = self.props.gameprops.menu_props.text_err_col
        wip_lab = Label(text='',
                        pos=(-.05, -1.58),
                        parent=base.a2dTopRight,
                        text_wordwrap=10,
                        text_align=TextNode.A_right,
                        tra_src='Note: the game is work-in-progress',
                        tra_tra=_('Note: the game is work-in-progress'),
                        **lab_args)
        self.widgets += [wip_lab]
        self.add_widgets(widgets)
        self.set_news()
        MainPageGui.build(self)
        if not self.ver_check.is_uptodate():
            self.widgets[2]['state'] = DISABLED

    def on_options(self):
        self.load_settings()
        option_props = OptionPageProps(self.keys, self.lang, self.volume,
                                       self.fullscreen, self.antialiasing,
                                       self.shaders, self.cars_num,
                                       self.camera, self.props.opt_file)
        self.notify('on_push_page', 'options', [option_props])

    def set_news(self):
        menu_props = self.props.gameprops.menu_props
        feed = urlopen(self.props.feed_url).read()
        items = etree.fromstring(feed).findall('channel/item')
        setlocale(LC_ALL, 'en_US.UTF-8')
        try:
            entries = [(datetime.strptime(entry.findtext('pubDate'),
                                          '%a, %d %b %Y %H:%M:%S %z'),
                        entry.findtext('title') or '') for entry in items]
        except TypeError:
            entries = []
        entries = list(reversed(sorted(entries,
                                       key=lambda entry: entry[0])))[:5]
        entries = [(datetime.strftime(entry[0],
                                      '%b %d'), self.__ellipsis_str(entry[1]))
                   for entry in entries]
        frm = Frame(frame_size=(0, 1.0, 0, .75),
                    frame_col=(.2, .2, .2, .5),
                    pos=(.05, .1),
                    parent=base.a2dBottomLeft)
        texts = [
            Text(_('Last news:'),
                 pos=(.55, .75),
                 scale=.055,
                 wordwrap=32,
                 parent='bottomleft',
                 fg=menu_props.text_normal_col,
                 font=menu_props.font,
                 tra_src='Last news:',
                 tra_tra=_('Last news:'))
        ]
        texts += [
            Text(': '.join(entries[i]),
                 pos=(.1, .65 - i * .1),
                 scale=.055,
                 wordwrap=32,
                 parent='bottomleft',
                 align='left',
                 fg=menu_props.text_normal_col,
                 font=menu_props.font) for i in range(min(5, len(entries)))
        ]
        btn_args = self.props.gameprops.menu_props.btn_args.copy()
        btn_args['scale'] = (.055, .055)
        show_btn = Btn(text=_('show'),
                       pos=(.55, .15),
                       cmd=self.eng.open_browser,
                       extra_args=[self.props.site_url],
                       parent=base.a2dBottomLeft,
                       tra_src='show',
                       tra_tra=_('show'),
                       **btn_args)
        self.add_widgets([frm] + texts + [show_btn])

    @staticmethod
    def __ellipsis_str(_str):
        return _str if len(_str) <= 20 else _str[:20] + '...'

    def destroy(self):
        self.ver_check.destroy()
        MainPageGui.destroy(self)
Пример #4
0
class OnlinePageGui(ThanksPageGui):
    def __init__(self, mediator, mp_props):
        self.props = mp_props
        self.ver_check = VersionChecker()
        self.conn_attempted = True
        ThanksPageGui.__init__(self, mediator, mp_props.gameprops.menu_props)

    def show(self):
        ThanksPageGui.show(self)
        self.build()

    def build(self):
        lmp_cb = lambda: self.notify('on_push_page', 'localmp', [self.props])
        menu_data = []
        top = .3
        if self.eng.client.is_active and self.eng.client.authenticated:
            menu_data = [('Play', _('Play'), self.on_play)]
            top = .5
        menu_data += [('Server problem', self.get_label(), self.on_loginout),
                      ('Register', _('Register'), self.on_register),
                      ('Reset password', _('Reset password'), self.on_reset)]
        widgets = [
            Btn(text=menu[0],
                pos=(0, top - i * .28),
                cmd=menu[2],
                tra_src=menu[0],
                tra_tra=menu[1],
                **self.props.gameprops.menu_props.btn_args)
            for i, menu in enumerate(menu_data)
        ]
        self.__loginout_btn = widgets[-3]
        self.add_widgets(widgets)
        ThanksPageGui.build(self)

    def on_logout(self):
        #self.eng.xmpp.disconnect()
        self.widgets[5].destroy()
        self.widgets.remove(self.widgets[5])
        self.eng.client.authenticated = False
        options = self.props.opt_file
        options['settings']['login']['usr'] = ''
        options['settings']['login']['pwd'] = ''
        options.store()
        self.__loginout_btn['text'] = self.get_label()
        self.notify('on_logout')

    def on_play(self):
        self.notify('on_push_page', 'onlineplay', [self.props])

    def on_login(self):
        self.notify('on_push_page', 'login', [self.props])

    def on_loginout(self):
        if not self.eng.client.is_server_up: return
        if self.eng.client.is_active and self.eng.client.authenticated:
            self.on_logout()
        elif self.conn_attempted:
            self.on_login()

    def get_label(self):
        if not self.eng.client.is_server_up:
            return _('Server problem')
        if not self.ver_check.is_uptodate():
            return _('Not up-to-date')
        if self.eng.client.is_active and self.eng.client.authenticated:
            return _('Log out') + \
                ' \1small\1(%s)\2' % self.props.opt_file['settings']['login']['usr']
        elif self.conn_attempted:
            return _('Log in') + ' \1small\1(' + _('multiplayer') + ')\2'
        #i18n: This is a caption of a button.
        return _('Connecting')

    def on_register(self):
        self.notify('on_push_page', 'register', [self.props])

    def on_reset(self):
        self.notify('on_push_page', 'reset', [self.props])
Пример #5
0
class UsersFrm(GameObject):
    def __init__(self, menu_args, yorg_srv):
        GameObject.__init__(self)
        self.eng.log('create users form')
        self.ver_check = VersionChecker()
        self.yorg_srv = yorg_srv
        self.room_name = None
        self.labels = []
        self.invited_users = []
        self.menu_args = menu_args
        lab_args = menu_args.label_args
        lab_args['scale'] = .046
        self.users_lab = DirectLabel(text=_('Current online users'),
                                     pos=(-.85, 1, -.02),
                                     hpr=(0, 0, -90),
                                     parent=base.a2dTopRight,
                                     text_align=TextNode.A_right,
                                     **lab_args)
        self.frm = DirectScrolledFrame(
            frameSize=(-.02, .8, .45, 2.43),
            canvasSize=(-.02, .76, -.08, 3.8),
            scrollBarWidth=.036,
            verticalScroll_relief=FLAT,
            verticalScroll_frameColor=(.2, .2, .2, .4),
            verticalScroll_thumb_relief=FLAT,
            verticalScroll_thumb_frameColor=(.8, .8, .8, .6),
            verticalScroll_incButton_relief=FLAT,
            verticalScroll_incButton_frameColor=(.8, .8, .8, .6),
            verticalScroll_decButton_relief=FLAT,
            verticalScroll_decButton_frameColor=(.8, .8, .8, .6),
            horizontalScroll_relief=FLAT,
            frameColor=(.2, .2, .2, .5),
            pos=(-.82, 1, -2.44),
            parent=base.a2dTopRight)
        self.conn_lab = DirectLabel(text='',
                                    pos=(.38, 1, 1.5),
                                    parent=self.frm,
                                    text_wordwrap=10,
                                    **lab_args)
        self.set_connection_label()
        self.in_match_room = None

    def show(self):
        self.frm.show()
        self.users_lab.show()

    def hide(self):
        self.frm.hide()
        self.users_lab.hide()

    def set_connection_label(self):
        lab_args = self.menu_args.label_args
        lab_args['scale'] = .046
        txt = ''
        if not self.ver_check.is_uptodate():
            txt = _("Your game isn't up-to-date, please update")
        elif not self.eng.xmpp.client:
            txt = _("You aren't logged in")
        elif not self.eng.xmpp.is_server_up:
            txt = _("Yorg's server isn't running")
        self.conn_lab['text'] = txt

    def set_size(self, full=True):
        if full:
            self.frm.setPos(-.82, 1, -2.44)
            self.frm['frameSize'] = (-.02, .8, .45, 2.43)
        else:
            self.frm.setPos(-.82, 1, -1.97)
            self.frm['frameSize'] = (-.02, .8, .45, 1.96)

    @staticmethod
    def trunc(name, lgt):
        if len(name) > lgt: return name[:lgt] + '...'
        return name

    def on_users(self):
        self.set_connection_label()
        bare_users = [
            self.trunc(user.name, 20) for user in self.eng.xmpp.users_nodup
        ]
        for lab in self.labels[:]:
            _lab = lab.lab.lab['text'].replace('\1smaller\1',
                                               '').replace('\2', '')
            if _lab not in bare_users:
                if _lab not in self.eng.xmpp.client.client_roster.keys():
                    lab.destroy()
                    self.labels.remove(lab)
        nusers = len(self.eng.xmpp.users_nodup)
        invite_btn = len(self.invited_users) < 8
        invite_btn = invite_btn and not self.in_match_room
        top = .08 * nusers + .08
        self.frm['canvasSize'] = (-.02, .76, 0, top)
        label_users = [lab.lab.lab['text'] for lab in self.labels]
        clean = lambda n: n.replace('\1smaller\1', '').replace('\2', '')
        label_users = map(clean, label_users)
        for i, user in enumerate(self.eng.xmpp.users_nodup):
            usr_inv = invite_btn and user.is_in_yorg
            if self.trunc(user.name, 20) not in label_users:
                if self.eng.xmpp.client.boundjid.bare != user.name:
                    lab = UserFrmList(self.trunc(user.name, 20), user,
                                      user.is_supporter, user.is_online,
                                      self.eng.xmpp.is_friend(user.name),
                                      user.is_in_yorg, user.is_playing,
                                      (0, 1, top - .08 - .08 * i),
                                      self.frm.getCanvas(), self.menu_args)
                else:
                    lab = UserFrmListMe(self.trunc(user.name, 20), user,
                                        user.is_supporter,
                                        (0, 1, top - .08 - .08 * i),
                                        self.frm.getCanvas(), self.menu_args)
                self.labels += [lab]
                lab.attach(self.on_invite)
                lab.attach(self.on_friend)
                lab.attach(self.on_unfriend)
                lab.attach(self.on_add_chat)
        for i, user in enumerate(self.eng.xmpp.users_nodup):
            clean = lambda n: n.replace('\1smaller\1', '').replace('\2', '')
            lab = [
                lab for lab in self.labels
                if clean(lab.lab.lab['text']) == self.trunc(user.name, 20)
            ][0]
            enb_val = usr_inv and user.name not in self.invited_users and user.is_in_yorg and not user.is_playing
            if hasattr(lab, 'invite_btn'):
                inv_btn = lab.invite_btn
                if enb_val:
                    inv_btn.tooltip['text'] = _('invite the user to a match')
                elif len(self.invited_users) == 8:
                    inv_btn.tooltip['text'] = _(
                        "you can't invite more players")
                elif self.in_match_room:
                    inv_btn.tooltip['text'] = _("you're already in a match")
                elif not user.is_in_yorg:
                    inv_btn.tooltip['text'] = _("the user isn't playing yorg")
                elif user.name in self.invited_users:
                    inv_btn.tooltip['text'] = _(
                        "you've already invited this user")
                elif user.is_playing:
                    inv_btn.tooltip['text'] = _(
                        "the user is already playing a match")
            lab.enable_invite_btn(enb_val)
            lab.frm.set_z(top - .08 - .08 * i)
            lab.lab.set_supporter(user.is_supporter)
            lab.lab.set_online(user.is_online)

    def on_invite(self, usr):
        self.invited_users += [usr.name]
        self.notify('on_invite', usr)
        self.on_users()
        if not self.room_name:
            jid = self.eng.xmpp.client.boundjid
            time_code = strftime('%y%m%d%H%M%S')
            srv = self.eng.xmpp.client.conf_srv
            self.room_name = 'yorg' + jid.user + time_code + '@' + srv
            self.eng.xmpp.client.plugin['xep_0045'].joinMUC(
                self.room_name,
                self.eng.xmpp.client.boundjid.bare,
                pfrom=self.eng.xmpp.client.boundjid.full)
            cfg = self.eng.xmpp.client.plugin['xep_0045'].getRoomConfig(
                self.room_name)
            values = cfg.get_values()
            values['muc#roomconfig_publicroom'] = False
            cfg.set_values(values)
            self.eng.xmpp.client.plugin['xep_0045'].configureRoom(
                self.room_name, cfg)
            self.eng.log('created room ' + self.room_name)
            for usr_name in [self.yorg_srv] + \
                [_usr.name_full for _usr in self.eng.xmpp.users if _usr.is_in_yorg]:
                self.eng.xmpp.client.send_message(
                    mfrom=self.eng.xmpp.client.boundjid.full,
                    mto=usr_name,
                    mtype='ya2_yorg',
                    msubject='is_playing',
                    mbody='1')
        public_addr = load(urlopen('http://httpbin.org/ip'))['origin']
        sock = socket(AF_INET, SOCK_DGRAM)
        try:
            sock.connect(('ya2.it', 8080))
            local_addr = sock.getsockname()[0]
        except gaierror:
            local_addr = ''
        self.eng.xmpp.client.send_message(
            mfrom=self.eng.xmpp.client.boundjid.full,
            mto=usr.name_full,
            mtype='ya2_yorg',
            msubject='invite',
            mbody=self.room_name + '\n' + public_addr + '\n' + local_addr)
        self.eng.log('invited ' + str(usr.name_full))
        self.notify('on_add_groupchat', self.room_name, usr.name)

    def on_declined(self, msg):
        self.eng.log('declined from ' + str(JID(msg['from']).bare))
        usr = str(JID(msg['from']).bare)
        self.invited_users.remove(usr)
        self.on_users()

    def on_add_chat(self, msg):
        self.notify('on_add_chat', msg)

    def on_logout(self):
        map(lambda lab: lab.destroy(), self.labels)
        self.labels = []

    def on_friend(self, usr_name):
        self.eng.log('send friend to ' + usr_name)
        self.eng.xmpp.client.send_presence_subscription(
            usr_name,
            ptype='subscribe',
            pfrom=self.eng.xmpp.client.boundjid.full)

    def on_unfriend(self, usr):
        self.eng.log('roster ' + str(self.eng.xmpp.client.client_roster))
        self.eng.xmpp.client.del_roster_item(usr)
        self.eng.log('roster ' + str(self.eng.xmpp.client.client_roster))

    def destroy(self):
        self.eng.log('destroyed usersfrm')
        self.frm = self.frm.destroy()
        GameObject.destroy(self)