class Entry(DirectObject): def __init__(self, placeholder, pos, on_enter, focus=False, sort_order=0): """ Object of a simple entry field @param placeholder: text to appear in textbox automatically @type placeholder: string @param pos: where to place the textbox @type pos: (float, float, float) @param on_enter: function to call upon them submitting a response @type on_enter: function @param focus: Should the entry auto-focus? @type focus: bool @param sort_order: Where should Entry display? (Alert is at 1000) @type sort_order: int """ DirectObject.__init__(self) self.accept('mouse1', self.click_out) self.placeholder = placeholder self.on_enter = on_enter self.entry = DirectEntry(initialText=self.placeholder, scale=0.05, focus=focus, focusOutCommand=self.focus_out, focusInCommand=self.focus_in, pos=pos, sortOrder=sort_order) def focus_out(self): if self.entry.get() == "": self.entry.enterText(self.placeholder) else: # they typed Something. # TODO validate self.on_enter(self.entry.get()) def focus_in(self): self.entry.set("") def click_out(self): self.entry.setFocus() def destroy(self): self.entry.destroy() self.ignoreAll()
class panda3dIOClass( DirectObject.DirectObject ): # set gui key to None if you want to call toggleConsole from outside this class gui_key = CONSOLE_TOGGLE_KEY autocomplete_key = CONSOLE_AUTOCOMPLETE_KEY autohelp_key = CONSOLE_AUTOHELP_KEY scroll_up_repeat_key = CONSOLE_SCROLL_UP_KEY + "-repeat" scroll_down_repeat_key = CONSOLE_SCROLL_DOWN_KEY + "-repeat" # change size of text and number of characters on one line # scale of frame ( must be small (0.0x) scale = PANDA3D_CONSOLE_SCALE # to define a special font, if loading fails the default font is used (without warning) font = PANDA3D_CONSOLE_FONT fontWidth = PANDA3D_CONSOLE_FONT_WIDTH # frame position and size (vertical & horizontal) h_pos = PANDA3D_CONSOLE_HORIZONTAL_POS h_size = PANDA3D_CONSOLE_HORIZONTAL_SIZE # v_size + v_pos should not exceed 2.0, else parts of the interface will not be visible # space above the frame ( must be below 2.0, best between 0.0 and 1.0 ) v_pos = PANDA3D_CONSOLE_VERTICAL_POS # vertical size of the frame ( must be at max 2.0, best between 0.5 and 2.0 ) v_size = PANDA3D_CONSOLE_VERTICAL_SIZE linelength = int((h_size/scale - 5) / fontWidth) print "max number of characters on a length:", linelength numlines = int(v_size/scale - 5) defaultTextColor = (0.0,0.0,0.0,1.0) autoCompleteColor = (0.9,0.9,0.9,1.0) def __init__( self, parent ): self.parent = parent # line wrapper self.linewrap = textwrap.TextWrapper() self.linewrap.width = self.linelength # calculate window size left = (self.h_pos) / self.scale right = (self.h_pos + self.h_size) / self.scale bottom = (self.v_pos) / self.scale top = (self.v_pos + self.v_size) /self.scale # panda3d interface self.consoleFrame = DirectFrame ( relief = DGG.GROOVE , frameColor = (200, 200, 200, 0.5) , scale=self.scale , frameSize = (0, self.h_size / self.scale, 0, self.v_size / self.scale) ) self.windowEvent( base.win ) # try to load the defined font try: fixedWidthFont = loader.loadFont(self.font) except: print "pandaInteractiveConsole.py :: could not load the defined font %s" % str(self.font) fixedWidthFont = DGG.getDefaultFont() # if font is not valid use default font if not fixedWidthFont.isValid(): if self.font is None: print "pandaInteractiveConsole.py :: could not load the defined font %s" % str(self.font) fixedWidthFont = DGG.getDefaultFont() # text entry line self.consoleEntry = DirectEntry ( self.consoleFrame , text = "" , command = self.onEnterPress , width = self.h_size/self.scale - 2 , pos = (1, 0, 1.5) , initialText = "" , numLines = 1 , focus = 1 , entryFont = fixedWidthFont) # output lines self.consoleOutputList = list() for i in xrange( self.numlines ): label = OnscreenText( parent = self.consoleFrame , text = "" , pos = (1, -i+3+self.numlines) , align=TextNode.ALeft , mayChange=1 , scale=1.0 , fg = self.defaultTextColor ) label.setFont( fixedWidthFont ) self.consoleOutputList.append( label ) # list of the last commands of the user self.userCommandList = list() self.userCommandListLength = 100 for i in xrange(self.userCommandListLength): self.userCommandList.append('') self.userCommandPos = 0 # buffer for data self.textBuffer = list() self.textBufferLength = 1000 for i in xrange(self.textBufferLength): self.textBuffer.append(['', DEFAULT_COLOR]) self.textBufferPos = self.textBufferLength-self.numlines # toggle the window at least once to activate the events self.toggleConsole() self.toggleConsole() # call the help-command on start self.onEnterPress("help") # write a string to the panda3d console def write( self, printString, color=defaultTextColor ): # remove not printable characters (which can be input by console input) printString = re.sub( r'[^%s]' % re.escape(string.printable[:95]), "", printString) splitLines = self.linewrap.wrap(printString) for line in splitLines: self.textBuffer.append( [line, color] ) self.textBuffer.pop(0) self.updateOutput() def updateOutput( self ): for lineNumber in xrange(self.numlines): lineText, color = self.textBuffer[lineNumber + self.textBufferPos] self.consoleOutputList[lineNumber].setText( lineText ) self.consoleOutputList[lineNumber]['fg'] = color # toggle the gui console def toggleConsole( self ): self.consoleFrame.toggleVis() hidden = self.consoleFrame.isHidden() self.consoleEntry['focus'] != hidden if hidden: self.ignoreAll() self.accept( self.gui_key, self.toggleConsole ) #playerController.enableInput() #unpause("v") else: self.ignoreAll() #playerController.disableInput() #pause("v") self.accept( CONSOLE_SCROLL_UP_KEY, self.scroll, [-5] ) self.accept( self.scroll_up_repeat_key, self.scroll, [-5] ) self.accept( CONSOLE_SCROLL_DOWN_KEY, self.scroll, [5] ) self.accept( self.scroll_down_repeat_key, self.scroll, [5] ) self.accept( 'window-event', self.windowEvent) self.accept( CONSOLE_PREVIOUS_COMMAND_KEY , self.scrollCmd, [ 1] ) self.accept( CONSOLE_NEXT_COMMAND_KEY, self.scrollCmd, [-1] ) self.accept( self.gui_key, self.toggleConsole ) #self.accept( self.autocomplete_key, self.autocomplete ) #self.accept( self.autohelp_key, self.autohelp ) # accept v, c and x, where c & x copy's the whole console text #messenger.toggleVerbose() #for osx use ('meta') if sys.platform == 'darwin': self.accept( 'meta', self.unfocus ) self.accept( 'meta-up', self.focus ) self.accept( 'meta-c', self.copy ) self.accept( 'meta-x', self.cut ) self.accept( 'meta-v', self.paste ) #for windows use ('control') if sys.platform == 'win32' or sys.platform == 'linux2': self.accept( 'control', self.unfocus ) self.accept( 'control-up', self.focus ) self.accept( 'control-c', self.copy ) self.accept( 'control-x', self.cut ) self.accept( 'control-v', self.paste ) # def autohelp( self ): # currentText = self.consoleEntry.get() # currentPos = self.consoleEntry.guiItem.getCursorPosition() # self.parent.autohelp( currentText, currentPos ) def focus( self ): self.consoleEntry['focus'] = 1 def unfocus( self ): self.consoleEntry['focus'] = 0 def copy( self ): copy = self.consoleEntry.get() clipboard.setText( copy ) def paste( self ): oldCursorPos = self.consoleEntry.guiItem.getCursorPosition() clipboardText = clipboard.getText() # compose new text line oldText = self.consoleEntry.get() newText = oldText[0:oldCursorPos] + clipboardText + oldText[oldCursorPos:] clipboardTextLines = newText.split(os.linesep) for i in xrange( len(clipboardTextLines)-1 ): currentLine = clipboardTextLines[i] # we only want printable characters currentLine = re.sub( r'[^' + re.escape(string.printable[:95]) + ']', "", currentLine) # set new text and position self.consoleEntry.set( currentLine ) self.onEnterPress( currentLine ) currentLine = clipboardTextLines[-1] currentLine = re.sub( r'[^' + re.escape(string.printable[:95]) + ']', "", currentLine) self.consoleEntry.set( currentLine ) self.consoleEntry.setCursorPosition( len(self.consoleEntry.get()) ) self.focus() def cut( self ): clipboard.setText( self.consoleEntry.get() ) self.consoleEntry.enterText('') self.focus() def scroll( self, step ): self.textBufferPos += step self.textBufferPos = min( self.textBufferLength-self.numlines, max( 0, self.textBufferPos ) ) self.updateOutput() def scrollCmd( self, step ): oldCmdPos = self.userCommandPos self.userCommandPos += step self.userCommandPos = min( self.userCommandListLength-1, max( 0, self.userCommandPos ) ) self.userCommandList[oldCmdPos] = self.consoleEntry.get() newCmd = self.userCommandList[self.userCommandPos] self.consoleEntry.set( newCmd ) self.consoleEntry.setCursorPosition( len(newCmd) ) def onEnterPress( self, textEntered ): # set to last message self.textBufferPos = self.textBufferLength-self.numlines # clear line self.consoleEntry.enterText('') self.focus() # add text entered to user command list & remove oldest entry self.userCommandList.insert( 1, textEntered ) self.userCommandList[0] = '' self.userCommandList.pop( -1 ) self.userCommandPos = 0 # call the interpreter to handle the input interpreter = cliClass() result = interpreter.interpreter(textEntered) # write the entered text to the output self.write(textEntered, (0.0, 0.0, 1, 1)) print textEntered # write each line seperately to the output for line in result.split('\n'): line = " " + line self.write(line, (0, 0, 0, 1)) print line def windowEvent( self, window ): """ This is a special callback. It is called when the panda window is modified. """ wp = window.getProperties() width = wp.getXSize() / float(wp.getYSize()) height = wp.getYSize() / float(wp.getXSize()) if width > height: height = 1.0 else: width = 1.0 # aligned to center consolePos = Vec3(-self.h_size/2, 0, -self.v_size/2) # aligned to left bottom #consolePos = Vec3(-width+self.h_pos, 0, -height+self.v_pos) # aligned to right top #consolePos = Vec3(width-self.h_size, 0, height-self.v_size) # set position self.consoleFrame.setPos( consolePos )
class DeveloperConsole(InteractiveInterpreter, DirectObject): """The name says it all.""" def __init__(self): sys.stdout = PseudoFile(self.writeOut) sys.stderr = PseudoFile(self.writeErr) tpErr = TextProperties() tpErr.setTextColor(1, 0.5, 0.5, 1) TextPropertiesManager.getGlobalPtr().setProperties("err", tpErr) #font = loader.loadFont("cmss12") self.frame = DirectFrame(parent = base.a2dTopCenter, text_align = TextNode.ALeft, text_pos = (-base.getAspectRatio() + TEXT_MARGIN[0], TEXT_MARGIN[1]), text_scale = 0.05, text_fg = (1, 1, 1, 1), frameSize = (-2.0, 2.0, -0.5, 0.0), frameColor = (0, 0, 0, 0.5), text = '')#, text_font = font) self.entry = DirectEntry(parent = base.a2dTopLeft, command = self.command, scale = 0.05, width = 1000.0, pos = (-0.02, 0, -0.48), relief = None, text_pos = (1.5, 0, 0), text_fg = (1, 1, 0.5, 1), rolloverSound = None, clickSound = None)#, text_font = font) self.otext = OnscreenText(parent = self.entry, scale = 1, align = TextNode.ALeft, pos = (1, 0, 0), fg = (1, 1, 0.5, 1), text = ':')#, font = font) self.lines = [''] * 9 self.commands = [] # All previously sent commands self.cscroll = None # Index of currently navigated command, None if current self.command = '' # Currently entered command self.block = '' # Temporarily stores a block of commands self.hide() self.initialized = False def prevCommand(self): if self.hidden: return if len(self.commands) == 0: return if self.cscroll == None: self.cscroll = len(self.commands) self.command = self.entry.get() elif self.cscroll <= 0: return else: self.commands[self.cscroll] = self.entry.get() self.cscroll -= 1 self.entry.set(self.commands[self.cscroll]) self.entry.setCursorPosition(len(self.commands[self.cscroll])) def nextCommand(self): if self.hidden: return if len(self.commands) == 0: return if self.cscroll == None: return self.commands[self.cscroll] = self.entry.get() self.cscroll += 1 if self.cscroll >= len(self.commands): self.cscroll = None self.entry.set(self.command) self.entry.setCursorPosition(len(self.command)) else: self.entry.set(self.commands[self.cscroll]) self.entry.setCursorPosition(len(self.commands[self.cscroll])) def writeOut(self, line, copy = True): if copy: sys.__stdout__.write(line) lines = line.split('\n') firstline = lines.pop(0) self.lines[-1] += firstline self.lines += lines self.frame['text'] = '\n'.join(self.lines[-9:]) def writeErr(self, line, copy = True): if copy: sys.__stderr__.write(line) line = '\1err\1%s\2' % line lines = line.split('\n') firstline = lines.pop(0) self.lines[-1] += firstline self.lines += lines self.frame['text'] = '\n'.join(self.lines[-9:]) def command(self, text): if not self.hidden: self.cscroll = None self.command = '' self.entry.set('') self.entry['focus'] = True self.writeOut(self.otext['text'] + ' ' + text + '\n', False) if text != '' and (len(self.commands) == 0 or self.commands[-1] != text): self.commands.append(text) # Insert plugins into the local namespace locals = __main__.__dict__ #locals['manager'] = self.manager #for plugin in self.manager.named.keys(): # locals[plugin] = self.manager.named[plugin] locals['panda3d'] = panda3d # Run it and print the output. if not self.initialized: InteractiveInterpreter.__init__(self, locals = locals) self.initialized = True try: if self.runsource(self.block + '\n' + text) and text != '': self.otext['text'] = '.' self.block += '\n' + text else: self.otext['text'] = ':' self.block = '' except Exception: # Not just "except", it will also catch SystemExit # Whoops! Print out a traceback. self.writeErr(traceback.format_exc()) def toggle(self): if self.hidden: self.show() else: self.hide() def show(self): self.accept('arrow_up', self.prevCommand) self.accept('arrow_up-repeat', self.prevCommand) self.accept('arrow_down', self.nextCommand) self.accept('arrow_down-repeat', self.nextCommand) self.hidden = False self.entry['focus'] = True self.frame.show() self.entry.show() self.otext.show() def hide(self): self.ignoreAll() self.hidden = True self.entry['focus'] = False self.frame.hide() self.entry.hide() self.otext.hide() def destroy(self): sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ self.ignoreAll() self.frame.destroy() self.entry.destroy() self.otext.destroy()
class DeveloperConsole(InteractiveInterpreter, DirectObject): """The name says it all.""" def __init__(self, manager, xml): sys.stdout = PseudoFile(self.writeOut) sys.stderr = PseudoFile(self.writeErr) tpErr = TextProperties() tpErr.setTextColor(1, 0.5, 0.5, 1) TextPropertiesManager.getGlobalPtr().setProperties("err", tpErr) self.manager = manager font = loader.loadFont("cmss12") self.frame = DirectFrame(parent=base.a2dTopCenter, text_align=TextNode.ALeft, text_pos=(-base.getAspectRatio() + TEXT_MARGIN[0], TEXT_MARGIN[1]), text_scale=0.05, text_fg=(1, 1, 1, 1), frameSize=(-2.0, 2.0, -0.5, 0.0), frameColor=(0, 0, 0, 0.5), text='', text_font=font) self.entry = DirectEntry(parent=base.a2dTopLeft, command=self.command, scale=0.05, width=1000.0, pos=(-0.02, 0, -0.48), relief=None, text_pos=(1.5, 0, 0), text_fg=(1, 1, 0.5, 1), rolloverSound=None, clickSound=None, text_font=font) self.otext = OnscreenText(parent=self.entry, scale=1, align=TextNode.ALeft, pos=(1, 0, 0), fg=(1, 1, 0.5, 1), text=':', font=font) self.lines = [''] * 9 self.commands = [] # All previously sent commands self.cscroll = None # Index of currently navigated command, None if current self.command = '' # Currently entered command self.block = '' # Temporarily stores a block of commands self.hide() self.initialized = False def prevCommand(self): if self.hidden: return if len(self.commands) == 0: return if self.cscroll == None: self.cscroll = len(self.commands) self.command = self.entry.get() elif self.cscroll <= 0: return else: self.commands[self.cscroll] = self.entry.get() self.cscroll -= 1 self.entry.set(self.commands[self.cscroll]) self.entry.setCursorPosition(len(self.commands[self.cscroll])) def nextCommand(self): if self.hidden: return if len(self.commands) == 0: return if self.cscroll == None: return self.commands[self.cscroll] = self.entry.get() self.cscroll += 1 if self.cscroll >= len(self.commands): self.cscroll = None self.entry.set(self.command) self.entry.setCursorPosition(len(self.command)) else: self.entry.set(self.commands[self.cscroll]) self.entry.setCursorPosition(len(self.commands[self.cscroll])) def writeOut(self, line, copy=True): if copy: sys.__stdout__.write(line) lines = line.split('\n') firstline = lines.pop(0) self.lines[-1] += firstline self.lines += lines self.frame['text'] = '\n'.join(self.lines[-9:]) def writeErr(self, line, copy=True): if copy: sys.__stderr__.write(line) line = '\1err\1%s\2' % line lines = line.split('\n') firstline = lines.pop(0) self.lines[-1] += firstline self.lines += lines self.frame['text'] = '\n'.join(self.lines[-9:]) def command(self, text): if not self.hidden: self.cscroll = None self.command = '' self.entry.set('') self.entry['focus'] = True self.writeOut(self.otext['text'] + ' ' + text + '\n', False) if text != '' and (len(self.commands) == 0 or self.commands[-1] != text): self.commands.append(text) # Insert plugins into the local namespace locals = __main__.__dict__ locals['manager'] = self.manager for plugin in self.manager.named.keys(): locals[plugin] = self.manager.named[plugin] locals['panda3d'] = panda3d # Run it and print the output. if not self.initialized: InteractiveInterpreter.__init__(self, locals=locals) self.initialized = True try: if self.runsource(self.block + '\n' + text) and text != '': self.otext['text'] = '.' self.block += '\n' + text else: self.otext['text'] = ':' self.block = '' except Exception: # Not just "except", it will also catch SystemExit # Whoops! Print out a traceback. self.writeErr(traceback.format_exc()) def toggle(self): if self.hidden: self.show() else: self.hide() def show(self): self.accept('arrow_up', self.prevCommand) self.accept('arrow_up-repeat', self.prevCommand) self.accept('arrow_down', self.nextCommand) self.accept('arrow_down-repeat', self.nextCommand) self.hidden = False self.entry['focus'] = True self.frame.show() self.entry.show() self.otext.show() def hide(self): self.ignoreAll() self.hidden = True self.entry['focus'] = False self.frame.hide() self.entry.hide() self.otext.hide() def destroy(self): sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ self.ignoreAll() self.frame.destroy() self.entry.destroy() self.otext.destroy()
class DeveloperConsole(InteractiveInterpreter, DirectObject): def __init__(self): sys.stdout = PseudoFile(self.write_out) sys.stderr = PseudoFile(self.write_err) tp_err = TextProperties() tp_err.setTextColor(1, 0.5, 0.5, 1) TextPropertiesManager.getGlobalPtr().setProperties('err', tp_err) font = loader.loadFont('cmss12') self.frame = DirectFrame(parent=base.a2dTopCenter, text_align=TextNode.ALeft, text_pos=(base.a2dLeft + TEXT_MARGIN[0], TEXT_MARGIN[1]), text_scale=0.05, text_fg=(1, 1, 1, 1), frameSize=(-2.0, 2.0, -1, 0.0), frameColor=(0, 0, 0, 0.5), text='', text_font=font, sortOrder=4) self.entry = DirectEntry(parent=base.a2dTopLeft, command=self.command, scale=0.05, width=1000.0, pos=(-0.02, 0, -0.98), relief=None, text_pos=(1.5, 0, 0), text_fg=(1, 1, 0.5, 1), rolloverSound=None, clickSound=None, text_font=font) self.otext = OnscreenText(parent=self.entry, scale=1, align=TextNode.ALeft, pos=(1, 0, 0), fg=(1, 1, 0.5, 1), text=':', font=font) self.lines = [''] * 19 self.commands = [] # All previously sent commands self.cscroll = None # Index of currently navigated command, None if current self.command = '' # Currently entered command self.block = '' # Temporarily stores a block of commands self.hide() self.initialized = False def prev_command(self): if self.hidden: return if len(self.commands) == 0: return if self.cscroll is None: self.cscroll = len(self.commands) self.command = self.entry.get() elif self.cscroll <= 0: return else: self.commands[self.cscroll] = self.entry.get() self.cscroll -= 1 self.entry.set(self.commands[self.cscroll]) self.entry.setCursorPosition(len(self.commands[self.cscroll])) def next_command(self): if self.hidden: return if len(self.commands) == 0: return if self.cscroll is None: return self.commands[self.cscroll] = self.entry.get() self.cscroll += 1 if self.cscroll >= len(self.commands): self.cscroll = None self.entry.set(self.command) self.entry.setCursorPosition(len(self.command)) else: self.entry.set(self.commands[self.cscroll]) self.entry.setCursorPosition(len(self.commands[self.cscroll])) def write_out(self, line, copy=True): if copy: sys.__stdout__.write(line) lines = line.split('\n') firstline = lines.pop(0) self.lines[-1] += firstline self.lines += lines self.frame['text'] = '\n'.join(self.lines[-19:]) def write_err(self, line, copy=True): if copy: sys.__stderr__.write(line) line = '\1err\1%s\2' % line lines = line.split('\n') firstline = lines.pop(0) self.lines[-1] += firstline self.lines += lines self.frame['text'] = '\n'.join(self.lines[-19:]) def command(self, text): if self.hidden: return self.cscroll = None self.command = '' self.entry.set('') self.entry['focus'] = True self.write_out(self.otext['text'] + ' ' + text + '\n', False) if text != '' and (len(self.commands) == 0 or self.commands[-1] != text): self.commands.append(text) if not self.initialized: InteractiveInterpreter.__init__(self) self.initialized = True try: if self.runsource(self.block + '\n' + text) and text != '': self.otext['text'] = '.' self.block += '\n' + text else: self.otext['text'] = ':' self.block = '' except Exception: self.write_err(traceback.format_exc()) def toggle(self): if self.hidden: self.show() else: self.hide() def show(self): self.accept('arrow_up', self.prev_command) self.accept('arrow_up-repeat', self.prev_command) self.accept('arrow_down', self.next_command) self.accept('arrow_down-repeat', self.next_command) self.hidden = False self.entry['focus'] = True self.frame.show() self.entry.show() self.otext.show() def hide(self): self.ignoreAll() self.hidden = True self.entry['focus'] = False self.entry.set(self.entry.get()[:-1]) self.frame.hide() self.entry.hide() self.otext.hide() def destroy(self): sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ self.ignoreAll() self.frame.destroy() self.entry.destroy() self.otext.destroy()
class FrameAutenticacao(object): ''' FrameAutenticacao ''' def __init__(self, parent=None, **kw): self.__qtd_conexao = 0 self.__frmAuth = DirectFrame(frameColor=(0, 0, 0, .3), frameSize=(-.5, .5, 0, 0.45), pos=(0, 0, -.1), enableEdit=1) self.__lblLogin = DirectLabel(text="Login: "******"Senha: ", scale=0.05, pos=(-0.3, 0, 0.2), frameColor=(0, 0, 0, 0), text_fg=(1, 1, 1, 1)) self.__etySenha = DirectEntry( scale=0.05, width=12, pos=(-.2, 0, 0.2), cursorKeys=1, obscured=1, focusInCommand=self.__command_clear_senha) self.__btnEntrar = DirectButton(frameColor=(0, 0, 0, 1), text="Entrar", scale=0.06, pos=(0.3, 0, 0.1), text_fg=(1, 1, 1, 1), rolloverSound=None, clickSound=None, command=self.__command_entrar) self.__lblLogin.reparentTo(self.__frmAuth) self.__etyLogin.reparentTo(self.__frmAuth) self.__lblSenha.reparentTo(self.__frmAuth) self.__etySenha.reparentTo(self.__frmAuth) self.__btnEntrar.reparentTo(self.__frmAuth) self.__etyLogin.set("viner") self.__etySenha.set("viner") def __command_clear_senha(self): self.__etySenha.set("") def __command_entrar(self, txt=None): login = self.__etyLogin.get() senha = self.__etySenha.get() valido = True if login == "": addMensagem("O campo Login e obrigatorio !", COR_BRANCO) valido = False if senha == "": addMensagem("O campo Senha e obrigatorio !", COR_BRANCO) valido = False if valido: self.__btnEntrar["state"] = DGG.DISABLED taskMgr.add(self.__task_conectar_servidor, 'ConectarServidor', extraArgs=[login, senha], appendTask=True) #inicia_nova_thread(1, 0, "Conectar Servidor", self.__conectar_servidor, login, senha) def __task_conectar_servidor(self, login, senha, task): if self.__qtd_conexao < TENTATIVAS: if vinerOnline.flg_conectado == vinerOnline.ERROLOGIN: vinerOnline.flg_conectado = vinerOnline.DESCONECT self.__btnEntrar["state"] = DGG.NORMAL self.__qtd_conexao = 0 addMensagem('Login ou senha invalido', COR_VERMELHO) self.__etyLogin.setFocus() elif vinerOnline.flg_conectado == vinerOnline.CONECTADO: #addMensagem("Conectado 12 !!!") #self.destroy() pass else: vinerOnline.conectar_servidor(login, senha) self.__qtd_conexao += 1 taskMgr.doMethodLater(INTERVALO_TENTATIVAS, self.__task_conectar_servidor, 'ConectarServidorLater', extraArgs=[login, senha], appendTask=True) msg = "Tentativa %s/5 - Conectando..." % (self.__qtd_conexao) addMensagem(msg, COR_BRANCO) else: vinerOnline.flg_conectado = vinerOnline.DESCONECT self.__btnEntrar["state"] = DGG.NORMAL self.__qtd_conexao = 0 addMensagem("Servidor nao encontrado", COR_VERMELHO) return task.done def destroy(self): self.__frmAuth.destroy() del self.__lblLogin del self.__etyLogin del self.__lblSenha del self.__etySenha del self.__btnEntrar del self.__frmAuth
class Pregame(): def __init__(self, showbase): self.showbase = showbase self.ready = False self.background = DirectFrame( frameSize=(-1, 1, -1, 1), frameTexture='media/gui/mainmenu/menu.png', parent=self.showbase.render2d, ) self.title = OnscreenText(text='Lobby!', fg=(1, 1, 1, 1), parent=self.background, pos=(-0.6, 0.1), scale=0.06) self.buttons = [] controlButtons = Vec3(-0.60, 0, -0.79) # Toggle ready p = controlButtons + Vec3(-0.25, 0, 0) self.toggleReadyButton = DirectButton( text='Ready/Unready', pos=p, scale=0.048, relief=DGG.GROOVE, command=self.toggleReady, ) self.buttons.append(self.toggleReadyButton) # Disconnect p = controlButtons + Vec3(0.0, 0.0, 0.0) self.disconnectButton = DirectButton( text='Disconnect', pos=p, scale=0.048, relief=DGG.GROOVE, command=self.disconnect, ) self.buttons.append(self.disconnectButton) # Send message p = controlButtons + Vec3(0.25, 0.0, 0.0) self.sendMessageButton = DirectButton( text='Send Message', pos=p, scale=0.048, relief=DGG.GROOVE, command=self.sendMessage, extraArgs=[''], ) self.buttons.append(self.sendMessageButton) # Message input self.message = DirectEntry( command=self.sendMessage, focusInCommand=self.clearText, frameSize=(-3, 3, -.5, 1), initialText='', parent=self.buttons[2], pos=(0, -0.6, -1.5), text_align=TextNode.ACenter, ) self.showbase.gameData = GameData() self.showbase.users = [] self.hide() def clearText(self): self.message.set('') def reset(self): self.messages = [] self.showbase.users = [] def updateLobby(self, task): temp = self.showbase.client.getData() for package in temp: if len(package) == 2: print 'Received: ', str(package) if package[0] == 'chat': if len(package[1]) == 2: self.messages.append(package[1]) print self.messages elif package[0] == 'client': self.showbase.users.append(User(package[1])) for user in self.showbase.users: print user.name, user.ready print 'all users' elif package[0] == 'ready': for user in self.showbase.users: if user.name == package[1][0]: user.ready = package[1][1] for user in self.showbase.users: print user.name, user.ready print 'all users' elif package[0] == 'disconnect': for user in self.showbase.users: if user.name == package[1]: self.showbase.users.remove(user) for user in self.showbase.users: print user.name, user.ready print 'all users' elif package[0] == 'gamedata': self.showbase.gameData.unpackageData(package[1]) elif package[0] == 'state': print 'state: ', package[1] if package[1] == 'preround': self.showbase.startRound() return task.done return task.again def toggleReady(self): self.ready = not self.ready self.showbase.client.sendData(('ready', self.ready)) def disconnect(self): self.showbase.client.sendData(('disconnect', 'disconnect')) self.showbase.authCon = self.showbase.client self.showbase.returnToMenu() def sendMessage(self, message): if message == '': message = self.message.get() if message != '': self.showbase.client.sendData(('chat', message)) self.message.set('') def hide(self): self.background.hide() self.message.hide() for b in self.buttons: b.hide() self.showbase.taskMgr.remove('Update Lobby') def show(self): self.background.show() self.message.show() for b in self.buttons: b.show() # Add the game loop procedure to the task manager. self.showbase.taskMgr.add(self.updateLobby, 'Update Lobby')
class Pregame(): def __init__(self, showbase): self.showbase = showbase self.ready = False self.background = DirectFrame( frameSize = (-1, 1, -1, 1), frameTexture = 'media/gui/mainmenu/menu.png', parent = self.showbase.render2d, ) self.title = OnscreenText( text = 'Lobby!', fg = (1, 1, 1, 1), parent = self.background, pos = (-0.6, 0.1), scale = 0.06 ) self.buttons = [] controlButtons = Vec3(-0.60, 0, -0.79) # Toggle ready p = controlButtons + Vec3(-0.25, 0, 0) self.toggleReadyButton = DirectButton( text = 'Ready/Unready', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.toggleReady, ) self.buttons.append(self.toggleReadyButton) # Disconnect p = controlButtons + Vec3(0.0, 0.0, 0.0) self.disconnectButton = DirectButton( text = 'Disconnect', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.disconnect, ) self.buttons.append(self.disconnectButton) # Send message p = controlButtons + Vec3(0.25, 0.0, 0.0) self.sendMessageButton = DirectButton( text = 'Send Message', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.sendMessage, extraArgs = [''], ) self.buttons.append(self.sendMessageButton) # Message input self.message = DirectEntry( command = self.sendMessage, focusInCommand = self.clearText, frameSize = (-3, 3, -.5, 1), initialText = '', parent = self.buttons[2], pos = (0, -0.6, -1.5), text_align = TextNode.ACenter, ) self.showbase.gameData = GameData() self.showbase.users = [] self.hide() def clearText(self): self.message.set('') def reset(self): self.messages = [] self.showbase.users = [] def updateLobby(self, task): temp = self.showbase.client.getData() for package in temp: if len(package) == 2: print 'Received: ', str(package) if package[0] == 'chat': if len(package[1]) == 2: self.messages.append(package[1]) print self.messages elif package[0] == 'client': self.showbase.users.append(User(package[1])) for user in self.showbase.users: print user.name, user.ready print 'all users' elif package[0] == 'ready': for user in self.showbase.users: if user.name == package[1][0]: user.ready = package[1][1] for user in self.showbase.users: print user.name, user.ready print 'all users' elif package[0] == 'disconnect': for user in self.showbase.users: if user.name == package[1]: self.showbase.users.remove(user) for user in self.showbase.users: print user.name, user.ready print 'all users' elif package[0] == 'gamedata': self.showbase.gameData.unpackageData(package[1]) elif package[0] == 'state': print 'state: ', package[1] if package[1] == 'preround': self.showbase.startRound() return task.done return task.again def toggleReady(self): self.ready = not self.ready self.showbase.client.sendData(('ready', self.ready)) def disconnect(self): self.showbase.client.sendData(('disconnect', 'disconnect')) self.showbase.authCon = self.showbase.client self.showbase.returnToMenu() def sendMessage(self, message): if message == '': message = self.message.get() if message != '': self.showbase.client.sendData(('chat', message)) self.message.set('') def hide(self): self.background.hide() self.message.hide() for b in self.buttons: b.hide() self.showbase.taskMgr.remove('Update Lobby') def show(self): self.background.show() self.message.show() for b in self.buttons: b.show() # Add the game loop procedure to the task manager. self.showbase.taskMgr.add(self.updateLobby, 'Update Lobby')
class ConsoleWindow(DirectObject.DirectObject): console_output = None gui_key = PANDA3D_CONSOLE_TOGGLE_KEY autocomplete_key = PANDA3D_CONSOLE_AUTOCOMPLETE_KEY autohelp_key = PANDA3D_CONSOLE_AUTOHELP_KEY # change size of text and number of characters on one line # scale of frame (must be small (0.0x) scale = PANDA3D_CONSOLE_SCALE # to define a special font, if loading fails the default font is used # (without warning) font = PANDA3D_CONSOLE_FONT fontWidth = PANDA3D_CONSOLE_FONT_WIDTH # frame position and size (vertical & horizontal) h_pos = PANDA3D_CONSOLE_HORIZONTAL_POS h_size = PANDA3D_CONSOLE_HORIZONTAL_SIZE # v_size + v_pos should not exceed 2.0, else parts of the interface # will not be visible # space above the frame (must be below 2.0, best between 0.0 and 1.0) v_pos = PANDA3D_CONSOLE_VERTICAL_POS # vertical size of the frame (must be at max 2.0, best between 0.5 and 2.0) v_size = PANDA3D_CONSOLE_VERTICAL_SIZE linelength = int((h_size / scale - 5) / fontWidth) textBuffer = list() MAX_BUFFER_LINES = 5000 commandPos = 0 _iconsole = None _commandBuffer = '' logger.debug("max number of characters on a length:", linelength) numlines = int(v_size / scale - 5) defaultTextColor = (0.0, 0.0, 0.0, 1.0) autoCompleteColor = (0.9, 0.9, 0.9, 1.0) consoleFrame = None commandList = [] maxCommandHistory = 10000 textBufferPos = -1 clipboardTextLines = None clipboardTextRaw = None def __init__(self, parent): global base if not logger.isEnabledFor(logging.DEBUG): global CONSOLE_MESSAGE CONSOLE_MESSAGE = ''' ----------------- Ship's Interface version 3.0.9_749 ------------------- Direct Ship Interface Enabled. Please use caution. Irresponsible use of this console may result in the ship's AI refusing access to this interface. type 'help' for basic commands. -------------------------------------------------------------------------''' # change up from parent/IC self.parent = parent localenv = globals() localenv['gameroot'] = self.parent self._iconsole = customConsoleClass(localsEnv=localenv) # line wrapper self.linewrap = textwrap.TextWrapper() self.linewrap.width = self.linelength # calculate window size # left = (self.h_pos) / self.scale # right = (self.h_pos + self.h_size) / self.scale # bottom = (self.v_pos) / self.scale # top = (self.v_pos + self.v_size) /self.scale # panda3d interface self.consoleFrame = DirectFrame(relief=DGG.GROOVE, frameColor=(200, 200, 200, 0.5), scale=self.scale, frameSize=(0, self.h_size / self.scale, 0, self.v_size / self.scale)) self.windowEvent(base.win) fixedWidthFont = None try: # try to load the defined font fixedWidthFont = parent.loader.loadFont(self.font) except Exception: traceback.print_exc() # if font is not valid use default font logger.warn('could not load the defined font %s" % str(self.font') fixedWidthFont = DGG.getDefaultFont() # text lines self._visibleLines = list( OnscreenText(parent=self.consoleFrame, text="", pos=(1, -i + 3 + self.numlines), align=TextNode.ALeft, mayChange=1, scale=1.0, fg=self.defaultTextColor) for i in range(self.numlines)) map(lambda x: x.setFont(fixedWidthFont), self._visibleLines) # text entry line self.consoleEntry = DirectEntry(self.consoleFrame, text="", command=self.submitTrigger, width=self.h_size / self.scale - 2, pos=(1, 0, 1.5), initialText="", numLines=1, focus=1, entryFont=fixedWidthFont) # self.console_output = ConsoleOutput(testme=True) self.echo(CONSOLE_MESSAGE) self.clipboard = pyperclip def windowEvent(self, window): """ This is a special callback. It is called when the panda window is modified. """ wp = window.getProperties() width = wp.getXSize() / float(wp.getYSize()) height = wp.getYSize() / float(wp.getXSize()) if width > height: height = 1.0 else: width = 1.0 # aligned to center consolePos = Vec3(-self.h_size / 2, 0, -self.v_size / 2) # aligned to left bottom # consolePos = Vec3(-width+self.h_pos, 0, -height+self.v_pos) # aligned to right top # consolePos = Vec3(width-self.h_size, 0, height-self.v_size) # set position self.consoleFrame.setPos(consolePos) def submitTrigger(self, cmdtext): # set to last message # clear line self.consoleEntry.enterText('') self.focus() # add text entered to user command list & remove oldest entry self.commandList.append(cmdtext) self.commandPos += 1 self._commandBuffer = '' logger.debug('CP {}'.format(self.commandPos)) # push to interp for text, pre, color in self._iconsole.push(cmdtext): self.echo(text, pre, color) # set up console controls def mapControls(self): hidden = self.consoleFrame.isHidden() self.consoleEntry['focus'] != hidden if hidden: self.ignoreAll() else: self.accept('page_up', self.scroll, [-5]) self.accept('page_up-repeat', self.scroll, [-5]) self.accept('page_down', self.scroll, [5]) self.accept('page_down-repeat', self.scroll, [5]) self.accept('window-event', self.windowEvent) self.accept('arrow_up', self.scrollCmd, [-1]) self.accept('arrow_down', self.scrollCmd, [1]) self.accept(self.gui_key, self.toggleConsole) self.accept('escape', self.toggleConsole) self.accept(self.autocomplete_key, self.autocomplete) self.accept(self.autohelp_key, self.autohelp) # accept v, c and x, where c & x copy's the whole console text # messenger.toggleVerbose() # for osx use ('meta') if sys.platform == 'darwin': self.accept('meta', self.unfocus) self.accept('meta-up', self.focus) self.accept('meta-c', self.copy) self.accept('meta-x', self.cut) self.accept('meta-v', self.paste) # for windows use ('control') if sys.platform == 'win32' or sys.platform == 'linux2': self.accept('control', self.unfocus) self.accept('control-up', self.focus) self.accept('control-c', self.copy) self.accept('control-x', self.cut) self.accept('control-v', self.paste) # toggle the gui console def toggleConsole(self, hide=False): if hide: self.consoleFrame.hide() self.ignoreAll() # express hide, don't call setControls() return if self.consoleFrame.is_hidden(): self.consoleFrame.show() self.parent.setControls(self) else: self.consoleFrame.hide() self.ignoreAll() self.parent.setControls() def scroll(self, step): newpos = self.textBufferPos + step if newpos < 0 or newpos >= len(self.textBuffer): # no... no... I no think so return self.textBufferPos = newpos self.redrawConsole() def redrawConsole(self): windowstart = max(self.textBufferPos - len(self._visibleLines) + 1, 0) windowend = min( len(self._visibleLines) + windowstart, len(self.textBuffer)) logger.debug('windowS: {} WindowE: {}'.format(windowstart, windowend)) for lineNumber, (lineText, color) in \ enumerate(self.textBuffer[ windowstart: windowend]): logger.debug("LN {}, LEN {}".format(lineNumber, len(self.textBuffer))) self._visibleLines[lineNumber].setText(lineText) self._visibleLines[lineNumber]['fg'] = color def scrollCmd(self, step): if not self.commandList: # 0 or null - nothing to scroll return # should we update a temp buffer? if self.commandPos == len(self.commandList): if step > 0: self.consoleEntry.set(self._commandBuffer) return else: tmp = self.consoleEntry.get() if self.commandList[-1] != tmp: self._commandBuffer = tmp self.commandPos += step if self.commandPos >= len(self.commandList): self.commandPos = len(self.commandList) - 1 self.consoleEntry.set(self._commandBuffer) self.consoleEntry.setCursorPosition( len(self.commandList[self.commandPos])) elif self.commandPos < 0: self.commandPos = -1 # No need to change anything, can't go past the beginning return # finally, just set it self.consoleEntry.set(self.commandList[self.commandPos]) self.consoleEntry.setCursorPosition( len(self.commandList[self.commandPos])) def autocomplete(self): currentText = self.consoleEntry.get() currentPos = self.consoleEntry.guiItem.getCursorPosition() newText = self._iconsole.autocomplete(currentText, currentPos) if newText[-1] and newText[-1] != currentText: self.consoleEntry.set(newText[-1]) self.consoleEntry.setCursorPosition(len(newText)) def autohelp(self): currentText = self.consoleEntry.get() currentPos = self.consoleEntry.guiItem.getCursorPosition() self.parent.autohelp(currentText, currentPos) def unfocus(self): self.consoleEntry['focus'] = 0 def focus(self): self.consoleEntry['focus'] = 1 def copy(self): copy = self.consoleEntry.get() pyperclip.copy(copy) def paste(self): oldCursorPos = self.consoleEntry.guiItem.getCursorPosition() self.clipboardTextRaw = pyperclip.paste() # compose new text line oldText = self.consoleEntry.get() newText = oldText[0:oldCursorPos] + self.clipboardTextRaw + oldText[ oldCursorPos:] self.clipboardTextLines = newText.split(os.linesep) for i in range(len(self.clipboardTextLines) - 1): currentLine = self.clipboardTextLines[i] # we only want printable characters currentLine = re.sub( r'[^' + re.escape(string.printable[:95]) + ']', "", currentLine) # set new text and position self.consoleEntry.set(currentLine) self.submitTrigger(currentLine) currentLine = self.clipboardTextLines[-1] currentLine = re.sub(r'[^' + re.escape(string.printable[:95]) + ']', "", currentLine) self.consoleEntry.set(currentLine) self.consoleEntry.setCursorPosition(len(self.consoleEntry.get())) self.focus() def cut(self): pyperclip.copy(self.consoleEntry.get()) self.consoleEntry.enterText('') self.focus() def echo(self, output, pre='*', color=defaultTextColor): if logger.isEnabledFor(logging.DEBUG): logger.debug('output: {}'.format(pprint.pformat(output))) for line in output.split('\n'): fmtline = "{}{}".format(pre, line) logger.debug(fmtline) if len(line) > 0: self.write_to_panel(fmtline, color) def write_to_panel(self, output, color=defaultTextColor): # remove not printable characters (which can be input by console input) output = re.sub(r'[^%s]' % re.escape(string.printable[:95]), "", output) logger.debug('write_to_panel: output="{}"'.format(output)) splitLines = self.linewrap.wrap(output) logger.debug('write_to_panel: splitLines="{}"'.format(splitLines)) for line in splitLines: self.textBuffer.append([line, color]) if len(self.textBuffer) > self.MAX_BUFFER_LINES: self.textBuffer.pop(0) else: self.textBufferPos += 1 self.redrawConsole()
class NamePicker(): """ A UI element that lets the players pick their name. Also has a confirmation element to the right of the entry box. """ def __init__(self, classSelectionMenu): self._classSelectionMenu = classSelectionMenu self._nameEntry = None self._confirmButton = None self._rootFrame = None self._font = loader.loadFont(PIERCEROMAN_FONT) self._draw() def _draw(self): winWidth = base.getAspectRatio() * 2 winHeight = 2 # Draw container: frameHeight = winHeight * NPKR_HEIGHT_PERCENTAGE frameWidth = winWidth * NPKR_WIDTH_PERCENTAGE cFCenterY = -winHeight / 2 + frameHeight / 2 self._rootFrame = DirectFrame( pos=(0, 0, cFCenterY), frameSize=(-frameWidth / 2, frameWidth / 2, -frameHeight / 2, frameHeight / 2), frameTexture=IMG_GRADIENT_1) self._rootFrame.setTransparency(TransparencyAttrib.MAlpha) # Draw Name Entry: entryWidth = self._rootFrame.getWidth() * NPKR_ENTRY_WIDTH_PERCENTAGE entryHeight = self._rootFrame.getHeight() entryCX = -(self._rootFrame.getWidth() - entryWidth) / 2 self._nameEntry = DirectEntry( parent=self._rootFrame, pos=(entryCX, 0, 0), frameSize=(-entryWidth / 2, entryWidth / 2, -entryHeight / 2, entryHeight / 2), frameColor=(0.25, 0.25, 0.25, 1), text_align=TextNode.ACenter, text_font=self._font, text_scale=NPKR_ENTRY_FONT_SIZE, text_pos=NPKR_ENTRY_FONT_OFFSET, initialText=NPKR_ENTRY_INITIAL_TEXT, numLines=1, focusOutCommand=self._syncName, focusInCommand=self._checkPlaceholderText, command=self._syncName, frameTexture=UI_WINDOW) # Draw Confirm Button: confirmWidth = self._rootFrame.getWidth()\ * (1-NPKR_ENTRY_WIDTH_PERCENTAGE) confirmHeight = self._rootFrame.getHeight() confirmCX = (self._rootFrame.getWidth() - confirmWidth) / 2 self._confirmButton = DirectButton( parent=self._rootFrame, pos=(confirmCX, 0, 0), frameSize=(-confirmWidth / 2, confirmWidth / 2, -confirmHeight / 2, confirmHeight / 2), command=self._onConfirmPressed, text_font=self._font, text_scale=NPKR_BUTTON_FONT_SIZE, text_pos=NPKR_BUTTON_FONT_OFFSET, text="Create Character", borderWidth=NPKR_BUTTON_BORDER_WIDTH) def getName(self): return str(self._nameEntry.get()) def _onConfirmPressed(self): """ Reroutes this input to the parent ClassSelectionMenu """ self._classSelectionMenu.createCharacter() def _checkPlaceholderText(self): """ Makes the nameEntry behave more like a real name entry by removing the placeholder text when the player begins to interact. """ # If the text entered is the placeholder text, simply remove it: if self._nameEntry.get() == NPKR_ENTRY_INITIAL_TEXT: self._nameEntry.set("") def _syncName(self, extraArgs=None): """ Syncs name with this game's host/client manager """ self._classSelectionMenu.syncInfo(cName=self.getName()) def close(self): self._rootFrame.destroy() # Destroy ui del self # Destroy this instance
class Login(): def __init__(self, showbase): self.showbase = showbase self.background = DirectFrame( frameSize=(-1, 1, -1, 1), frameTexture='media/gui/login/bg.png', parent=self.showbase.render2d, ) ### CONFIG LOADER ### config = ConfigParser.RawConfigParser() config.read('master.cfg') self.LOGIN_IP = config.get('MASTER SERVER CONNECTION', 'masterIp') self.LOGIN_PORT = config.getint('MASTER SERVER CONNECTION', 'masterPort') config = ConfigParser.RawConfigParser() config.read('client.cfg') self.storeUsername = config.getint('USERDATA', 'storeUsername') if self.storeUsername == 1: self.username = config.get('USERDATA', 'username') else: self.username = '' self.storePassword = config.getint('USERDATA', 'storePassword') if self.storePassword == 1: self.password = config.get('USERDATA', 'password') else: self.password = '' ### CONFIG END ### self.loginScreen("Press 'Enter' to login") # draws the login screen self.usernameBox['focus'] = 1 # sets the cursor to the username field by default self.showbase.accept('tab', self.cycleLoginBox) self.showbase.accept('shift-tab', self.cycleLoginBox) # enables the user to cycle through the text fields with the tab key # this is a standard feature on most login forms self.showbase.accept('enter', self.attemptLogin) # submits the login form, or you can just click the Login button # checking variable to stop multiple presses of the button spawn multiple tasks self.requestAttempt = False self.showbase.authCon = Client(self.showbase, self.LOGIN_IP, self.LOGIN_PORT, compress=True) if not self.showbase.authCon.getConnected(): self.updateStatus( "Could not connect to the Login server\nOFFLINE MODE") self.showbase.online = False def updateConfig(self): config = ConfigParser.RawConfigParser() config.read('client.cfg') config.set('USERDATA', 'storeUsername', self.usernameStoreBox["indicatorValue"]) config.set('USERDATA', 'storePassword', self.passwordStoreBox["indicatorValue"]) if self.usernameStoreBox["indicatorValue"] == 1: config.set('USERDATA', 'username', self.usernameBox.get()) if self.passwordStoreBox["indicatorValue"] == 1: config.set('USERDATA', 'password', self.passwordBox.get()) with open('client.cfg', 'wb') as configfile: config.write(configfile) def loginScreen(self, statusText): # creates a basic login screen that asks for a username/password boxloc = Vec3(0.0, 0.0, 0.0) # all items in the login form will have a position relative to this # this makes it easier to shift the entire form around once we have # some graphics to display with it without having to change the # positioning of every form element # p is the position of the form element relative to the boxloc # coordinates set above it is changed for every form element p = boxloc + Vec3(-0.22, 0.09, 0.0) self.usernameText = OnscreenText(text="Username:"******"Username: "******"", pos=p, scale=.04, initialText=self.username, numLines=1) # Username textbox where you type in your username p = boxloc + Vec3(0.4, 0.0, 0.09) self.usernameStoreBox = DirectCheckButton( text="Save Username?", pos=p, scale=.04, indicatorValue=self.storeUsername) # Toggle to save/not save your username p = boxloc + Vec3(-0.22, 0.0, 0.0) self.passwordText = OnscreenText(text="Password:"******"Password: "******"", pos=p, scale=.04, initialText=self.password, numLines=1, obscured=1) # Password textbox where you type in your password # Note - obscured = 1 denotes that all text entered will be replaced # with a * like a standard password box p = boxloc + Vec3(0.4, 0.0, 0.0) self.passwordStoreBox = DirectCheckButton( text="Save Password?", pos=p, scale=.04, indicatorValue=self.storePassword) # Toggle to save/not save your username p = boxloc + Vec3(0, 0, -0.090) self.loginButton = DirectButton(text="Login", pos=p, scale=0.048, relief=DGG.GROOVE, command=self.attemptLogin) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0.95, 0, -0.9) self.createAccButton = DirectButton(text="Create Account", scale=0.050, pos=p, relief=DGG.GROOVE, command=self.attemptCreateAccount) # Made a quick button for adding accounts. Its fugly p = boxloc + Vec3(1.20, 0, -0.9) self.quitButton = DirectButton(text="Quit", pos=p, scale=0.048, relief=DGG.GROOVE, command=self.showbase.quit) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0, -0.4, 0) self.statusText = OnscreenText(text=statusText, pos=p, scale=0.043, fg=(1, 0.5, 0, 1), align=TextNode.ACenter) # A simple text object that you can display an error/status messages # to the user def updateStatus(self, statusText): self.statusText.setText(statusText) # all this does is change the status text. def checkBoxes(self): # checks to make sure the user inputed a username and password: # if they didn't it will spit out an error message self.updateStatus("") if self.usernameBox.get() == "": if self.passwordBox.get() == "": self.updateStatus( "You must enter a username and password before logging in." ) else: self.updateStatus("You must specify a username") self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 return False elif self.passwordBox.get() == "": self.updateStatus("You must enter a password") self.usernameBox['focus'] = 0 self.passwordBox['focus'] = 1 return False # if both boxes are filled then return True return True def attemptLogin(self): if self.checkBoxes(): self.showbase.username = self.usernameBox.get() self.updateStatus("Attempting to login...") self.request(self.usernameBox.get(), self.passwordBox.get(), 'client') def attemptCreateAccount(self): if self.checkBoxes(): self.updateStatus("Attempting to create account and login...") self.request(self.usernameBox.get(), self.passwordBox.get(), 'create') def request(self, username, password, request): if not self.requestAttempt: # attempt to connect again if it failed on startup if self.showbase.authCon.getConnected(): self.requestAttempt = True self.loginButton["state"] = DGG.DISABLED self.createAccButton["state"] = DGG.DISABLED self.showbase.authCon.sendData((request, (username, password))) self.showbase.username = username self.showbase.online = True self.showbase.taskMgr.doMethodLater(0.2, self.responseReader, 'Update Login') else: # client not connected to login/auth server so display message self.updateStatus("Offline Mode") self.showbase.username = username self.showbase.online = False self.updateConfig() self.showbase.startMainmenu() def responseReader(self, task): if task.time > 2.5: self.loginButton["state"] = DGG.NORMAL self.createAccButton["state"] = DGG.NORMAL self.updateStatus("Timeout from Login server") return task.done else: temp = self.showbase.authCon.getData() for package in temp: if len(package) == 2: print "Received: " + str(package) print "Connected to login server" if package[0] == 'loginFailed': print "Login failed: ", package[1] if package[1] == 'username': self.updateStatus("Username Doesnt Exist") self.passwordBox.set("") self.usernameBox.set("") self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 elif package[1] == 'password': self.updateStatus("Password Incorrect") self.passwordBox.set("") self.usernameBox['focus'] = 0 self.passwordBox['focus'] = 1 elif package[1] == 'logged': self.updateStatus("Username already logged in") self.requestAttempt = False self.loginButton["state"] = DGG.NORMAL self.createAccButton["state"] = DGG.NORMAL return task.done elif package[0] == 'loginValid': print "Login valid: ", package[1] self.updateStatus(package[1]) self.updateConfig() self.showbase.startMainmenu() return task.done elif package[0] == 'createFailed': print "Create failed: ", package[1] if package[1] == 'exists': self.updateStatus("Username Already Exists") self.passwordBox.set("") self.usernameBox.set("") self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 self.requestAttempt = False self.loginButton["state"] = DGG.NORMAL self.createAccButton["state"] = DGG.NORMAL return task.done elif package[0] == 'createSuccess': print "Create success", package[1] self.updateStatus("Account Created Successfully") self.requestAttempt = False self.attemptLogin() return task.done return task.cont def cycleLoginBox(self): # function is triggered by the tab key so you can cycle between # the two input fields like on most login screens if self.passwordBox['focus'] == 1: self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 elif self.usernameBox['focus'] == 1: self.usernameBox['focus'] = 0 self.passwordBox['focus'] = 1 # IMPORTANT: When you change the focus to one of the text boxes, # you have to unset the focus on the other textbox. If you do not # do this Panda seems to get confused. def hide(self): self.background.destroy() self.usernameText.destroy() self.usernameBox.destroy() self.usernameStoreBox.destroy() self.passwordText.destroy() self.passwordBox.destroy() self.passwordStoreBox.destroy() self.loginButton.destroy() self.quitButton.destroy() self.createAccButton.destroy() self.statusText.destroy() self.showbase.ignore('tab') self.showbase.ignore('shift-tab') self.showbase.ignore('enter')
class panda3dIOClass(DirectObject.DirectObject): # set gui key to None if you want to call toggleConsole from outside this class gui_key = PANDA3D_CONSOLE_TOGGLE_KEY autocomplete_key = PANDA3D_CONSOLE_AUTOCOMPLETE_KEY autohelp_key = PANDA3d_CONSOLE_AUTOHELP_KEY # change size of text and number of characters on one line # scale of frame ( must be small (0.0x) scale = PANDA3D_CONSOLE_SCALE # to define a special font, if loading fails the default font is used (without warning) font = PANDA3D_CONSOLE_FONT fontWidth = PANDA3D_CONSOLE_FONT_WIDTH # frame position and size (vertical & horizontal) h_pos = PANDA3D_CONSOLE_HORIZONTAL_POS h_size = PANDA3D_CONSOLE_HORIZONTAL_SIZE # v_size + v_pos should not exceed 2.0, else parts of the interface will not be visible # space above the frame ( must be below 2.0, best between 0.0 and 1.0 ) v_pos = PANDA3D_CONSOLE_VERTICAL_POS # vertical size of the frame ( must be at max 2.0, best between 0.5 and 2.0 ) v_size = PANDA3D_CONSOLE_VERTICAL_SIZE linelength = int((h_size / scale - 5) / fontWidth) print "max number of characters on a length:", linelength numlines = int(v_size / scale - 5) defaultTextColor = (0.0, 0.0, 0.0, 1.0) autoCompleteColor = (0.9, 0.9, 0.9, 1.0) def __init__(self, parent): self.parent = parent # line wrapper self.linewrap = textwrap.TextWrapper() self.linewrap.width = self.linelength # calculate window size left = (self.h_pos) / self.scale right = (self.h_pos + self.h_size) / self.scale bottom = (self.v_pos) / self.scale top = (self.v_pos + self.v_size) / self.scale # panda3d interface self.consoleFrame = DirectFrame( relief=DGG.GROOVE, frameColor=(200, 200, 200, 0.5), scale=self.scale, frameSize=(0, self.h_size / self.scale, 0, self.v_size / self.scale), ) self.windowEvent(base.win) # try to load the defined font fixedWidthFont = loader.loadFont(self.font) # if font is not valid use default font if not fixedWidthFont.isValid(): if self.font is None: print "pandaInteractiveConsole.py :: could not load the defined font %s" % str(self.font) fixedWidthFont = DGG.getDefaultFont() # text entry line self.consoleEntry = DirectEntry( self.consoleFrame, text="", command=self.onEnterPress, width=self.h_size / self.scale - 2, pos=(1, 0, 1.5), initialText="", numLines=1, focus=1, entryFont=fixedWidthFont, ) # output lines self.consoleOutputList = list() for i in xrange(self.numlines): label = OnscreenText( parent=self.consoleFrame, text="", pos=(1, -i + 3 + self.numlines), align=TextNode.ALeft, mayChange=1, scale=1.0, fg=self.defaultTextColor, ) label.setFont(fixedWidthFont) self.consoleOutputList.append(label) # list of the last commands of the user self.userCommandList = list() self.userCommandListLength = 100 for i in xrange(self.userCommandListLength): self.userCommandList.append("") self.userCommandPos = 0 # buffer for data self.textBuffer = list() self.textBufferLength = 1000 for i in xrange(self.textBufferLength): self.textBuffer.append(["", DEFAULT_COLOR]) self.textBufferPos = self.textBufferLength - self.numlines # toggle the window at least once to activate the events self.toggleConsole() self.toggleConsole() self.help() def help(self): # output some info text about this module infoTxt = """ ------ Panda3dConsole ------ - press F10 to toggle it on/off - use the usual copy, cut & paste keys - page_up : scrolls up - page_down : scrolls down - arrow_up : previous command - arrow_down : next command - BUGS : if you paste a to long text, the entry blocks FIX : use cut to remove the whole line""" # for line in infoTxt.split('\n'): # self.write( line, color=DEFAULT_COLOR ) return infoTxt # write a string to the panda3d console def write(self, printString, color=defaultTextColor): # remove not printable characters (which can be input by console input) printString = re.sub(r"[^%s]" % re.escape(string.printable[:95]), "", printString) splitLines = self.linewrap.wrap(printString) for line in splitLines: self.textBuffer.append([line, color]) self.textBuffer.pop(0) self.updateOutput() def updateOutput(self): for lineNumber in xrange(self.numlines): lineText, color = self.textBuffer[lineNumber + self.textBufferPos] self.consoleOutputList[lineNumber].setText(lineText) self.consoleOutputList[lineNumber]["fg"] = color # toggle the gui console def toggleConsole(self): self.consoleFrame.toggleVis() hidden = self.consoleFrame.isHidden() self.consoleEntry["focus"] != hidden if hidden: self.ignoreAll() self.accept(self.gui_key, self.toggleConsole) else: self.ignoreAll() self.accept("page_up", self.scroll, [-5]) self.accept("page_up-repeat", self.scroll, [-5]) self.accept("page_down", self.scroll, [5]) self.accept("page_down-repeat", self.scroll, [5]) self.accept("window-event", self.windowEvent) self.accept("arrow_up", self.scrollCmd, [1]) self.accept("arrow_down", self.scrollCmd, [-1]) self.accept(self.gui_key, self.toggleConsole) self.accept(self.autocomplete_key, self.autocomplete) self.accept(self.autohelp_key, self.autohelp) # accept v, c and x, where c & x copy's the whole console text # messenger.toggleVerbose() # for osx use ('meta') if sys.platform == "darwin": self.accept("meta", self.unfocus) self.accept("meta-up", self.focus) self.accept("meta-c", self.copy) self.accept("meta-x", self.cut) self.accept("meta-v", self.paste) # for windows use ('control') if sys.platform == "win32" or sys.platform == "linux2": self.accept("control", self.unfocus) self.accept("control-up", self.focus) self.accept("control-c", self.copy) self.accept("control-x", self.cut) self.accept("control-v", self.paste) def autocomplete(self): currentText = self.consoleEntry.get() currentPos = self.consoleEntry.guiItem.getCursorPosition() newText = self.parent.autocomplete(currentText, currentPos) if newText != currentText: self.consoleEntry.set(newText) self.consoleEntry.setCursorPosition(len(newText)) def autohelp(self): currentText = self.consoleEntry.get() currentPos = self.consoleEntry.guiItem.getCursorPosition() self.parent.autohelp(currentText, currentPos) def focus(self): self.consoleEntry["focus"] = 1 def unfocus(self): self.consoleEntry["focus"] = 0 def copy(self): copy = self.consoleEntry.get() clipboard.setText(copy) def paste(self): oldCursorPos = self.consoleEntry.guiItem.getCursorPosition() clipboardText = clipboard.getText() # compose new text line oldText = self.consoleEntry.get() newText = oldText[0:oldCursorPos] + clipboardText + oldText[oldCursorPos:] clipboardTextLines = newText.split(os.linesep) for i in xrange(len(clipboardTextLines) - 1): currentLine = clipboardTextLines[i] # we only want printable characters currentLine = re.sub(r"[^" + re.escape(string.printable[:95]) + "]", "", currentLine) # set new text and position self.consoleEntry.set(currentLine) self.onEnterPress(currentLine) currentLine = clipboardTextLines[-1] currentLine = re.sub(r"[^" + re.escape(string.printable[:95]) + "]", "", currentLine) self.consoleEntry.set(currentLine) self.consoleEntry.setCursorPosition(len(self.consoleEntry.get())) self.focus() def cut(self): clipboard.setText(self.consoleEntry.get()) self.consoleEntry.enterText("") self.focus() def scroll(self, step): self.textBufferPos += step self.textBufferPos = min(self.textBufferLength - self.numlines, max(0, self.textBufferPos)) self.updateOutput() def scrollCmd(self, step): oldCmdPos = self.userCommandPos self.userCommandPos += step self.userCommandPos = min(self.userCommandListLength - 1, max(0, self.userCommandPos)) self.userCommandList[oldCmdPos] = self.consoleEntry.get() newCmd = self.userCommandList[self.userCommandPos] self.consoleEntry.set(newCmd) self.consoleEntry.setCursorPosition(len(newCmd)) def onEnterPress(self, textEntered): # set to last message self.textBufferPos = self.textBufferLength - self.numlines # clear line self.consoleEntry.enterText("") self.focus() # add text entered to user command list & remove oldest entry self.userCommandList.insert(1, textEntered) self.userCommandList[0] = "" self.userCommandList.pop(-1) self.userCommandPos = 0 # call our parent self.parent.push(textEntered) def windowEvent(self, window): """ This is a special callback. It is called when the panda window is modified. """ wp = window.getProperties() width = wp.getXSize() / float(wp.getYSize()) height = wp.getYSize() / float(wp.getXSize()) if width > height: height = 1.0 else: width = 1.0 # aligned to center consolePos = Vec3(-self.h_size / 2, 0, -self.v_size / 2) # aligned to left bottom # consolePos = Vec3(-width+self.h_pos, 0, -height+self.v_pos) # aligned to right top # consolePos = Vec3(width-self.h_size, 0, height-self.v_size) # set position self.consoleFrame.setPos(consolePos)
class Login(): def __init__(self, showbase): self.showbase = showbase self.background = DirectFrame( frameSize = (-1, 1, -1, 1), frameTexture = 'media/gui/login/bg.png', parent = self.showbase.render2d, ) ### CONFIG LOADER ### config = ConfigParser.RawConfigParser() config.read('master.cfg') self.LOGIN_IP = config.get('MASTER SERVER CONNECTION', 'masterIp') self.LOGIN_PORT = config.getint('MASTER SERVER CONNECTION', 'masterPort') config = ConfigParser.RawConfigParser() config.read('client.cfg') self.storeUsername = config.getint('USERDATA', 'storeUsername') if self.storeUsername == 1: self.username = config.get('USERDATA', 'username') else: self.username = '' self.storePassword = config.getint('USERDATA', 'storePassword') if self.storePassword == 1: self.password = config.get('USERDATA', 'password') else: self.password = '' ### CONFIG END ### self.loginScreen("Press 'Enter' to login") # draws the login screen self.usernameBox['focus'] = 1 # sets the cursor to the username field by default self.showbase.accept('tab', self.cycleLoginBox) self.showbase.accept('shift-tab', self.cycleLoginBox) # enables the user to cycle through the text fields with the tab key # this is a standard feature on most login forms self.showbase.accept('enter', self.attemptLogin) # submits the login form, or you can just click the Login button # checking variable to stop multiple presses of the button spawn multiple tasks self.requestAttempt = False self.showbase.authCon = Client(self.showbase, self.LOGIN_IP, self.LOGIN_PORT, compress = True) if not self.showbase.authCon.getConnected(): self.updateStatus("Could not connect to the Login server\nOFFLINE MODE") self.showbase.online = False def updateConfig(self): config = ConfigParser.RawConfigParser() config.read('client.cfg') config.set('USERDATA', 'storeUsername', self.usernameStoreBox["indicatorValue"]) config.set('USERDATA', 'storePassword', self.passwordStoreBox["indicatorValue"]) if self.usernameStoreBox["indicatorValue"] == 1: config.set('USERDATA', 'username', self.usernameBox.get()) if self.passwordStoreBox["indicatorValue"] == 1: config.set('USERDATA', 'password', self.passwordBox.get()) with open('client.cfg', 'wb') as configfile: config.write(configfile) def loginScreen(self, statusText): # creates a basic login screen that asks for a username/password boxloc = Vec3(0.0, 0.0, 0.0) # all items in the login form will have a position relative to this # this makes it easier to shift the entire form around once we have # some graphics to display with it without having to change the # positioning of every form element # p is the position of the form element relative to the boxloc # coordinates set above it is changed for every form element p = boxloc + Vec3(-0.22, 0.09, 0.0) self.usernameText = OnscreenText(text = "Username:"******"Username: "******"", pos = p, scale=.04, initialText = self.username, numLines = 1) # Username textbox where you type in your username p = boxloc + Vec3(0.4, 0.0, 0.09) self.usernameStoreBox = DirectCheckButton(text = "Save Username?", pos = p, scale = .04, indicatorValue = self.storeUsername) # Toggle to save/not save your username p = boxloc + Vec3(-0.22, 0.0, 0.0) self.passwordText = OnscreenText(text = "Password:"******"Password: "******"", pos = p, scale = .04, initialText = self.password, numLines = 1, obscured = 1) # Password textbox where you type in your password # Note - obscured = 1 denotes that all text entered will be replaced # with a * like a standard password box p = boxloc + Vec3(0.4, 0.0, 0.0) self.passwordStoreBox = DirectCheckButton(text = "Save Password?", pos = p, scale = .04, indicatorValue = self.storePassword) # Toggle to save/not save your username p = boxloc + Vec3(0, 0, -0.090) self.loginButton = DirectButton(text = "Login", pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.attemptLogin) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0.95, 0, -0.9) self.createAccButton = DirectButton(text = "Create Account", scale = 0.050, pos = p, relief = DGG.GROOVE, command = self.attemptCreateAccount) # Made a quick button for adding accounts. Its fugly p = boxloc + Vec3(1.20, 0, -0.9) self.quitButton = DirectButton(text = "Quit", pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.showbase.quit) # The 'Quit' button that will trigger the Quit function # when clicked p = boxloc + Vec3(0, -0.4, 0) self.statusText = OnscreenText(text = statusText, pos = p, scale = 0.043, fg = (1, 0.5, 0, 1), align = TextNode.ACenter) # A simple text object that you can display an error/status messages # to the user def updateStatus(self, statusText): self.statusText.setText(statusText) # all this does is change the status text. def checkBoxes(self): # checks to make sure the user inputed a username and password: # if they didn't it will spit out an error message self.updateStatus("") if self.usernameBox.get() == "": if self.passwordBox.get() == "": self.updateStatus("You must enter a username and password before logging in.") else: self.updateStatus("You must specify a username") self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 return False elif self.passwordBox.get() == "": self.updateStatus("You must enter a password") self.usernameBox['focus'] = 0 self.passwordBox['focus'] = 1 return False # if both boxes are filled then return True return True def attemptLogin(self): if self.checkBoxes(): self.showbase.username = self.usernameBox.get() self.updateStatus("Attempting to login...") self.request(self.usernameBox.get(), self.passwordBox.get(), 'client') def attemptCreateAccount(self): if self.checkBoxes(): self.updateStatus("Attempting to create account and login...") self.request(self.usernameBox.get(), self.passwordBox.get(), 'create') def request(self, username, password, request): if not self.requestAttempt: # attempt to connect again if it failed on startup if self.showbase.authCon.getConnected(): self.requestAttempt = True self.loginButton["state"] = DGG.DISABLED self.createAccButton["state"] = DGG.DISABLED self.showbase.authCon.sendData((request, (username, password))) self.showbase.username = username self.showbase.online = True self.showbase.taskMgr.doMethodLater(0.2, self.responseReader, 'Update Login') else: # client not connected to login/auth server so display message self.updateStatus("Offline Mode") self.showbase.username = username self.showbase.online = False self.updateConfig() self.showbase.startMainmenu() def responseReader(self, task): if task.time > 2.5: self.loginButton["state"] = DGG.NORMAL self.createAccButton["state"] = DGG.NORMAL self.updateStatus("Timeout from Login server") return task.done else: temp = self.showbase.authCon.getData() for package in temp: if len(package) == 2: print "Received: " + str(package) print "Connected to login server" if package[0] == 'loginFailed': print "Login failed: ", package[1] if package[1] == 'username': self.updateStatus("Username Doesnt Exist") self.passwordBox.set("") self.usernameBox.set("") self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 elif package[1] == 'password': self.updateStatus("Password Incorrect") self.passwordBox.set("") self.usernameBox['focus'] = 0 self.passwordBox['focus'] = 1 elif package[1] == 'logged': self.updateStatus("Username already logged in") self.requestAttempt = False self.loginButton["state"] = DGG.NORMAL self.createAccButton["state"] = DGG.NORMAL return task.done elif package[0] == 'loginValid': print "Login valid: ", package[1] self.updateStatus(package[1]) self.updateConfig() self.showbase.startMainmenu() return task.done elif package[0] == 'createFailed': print "Create failed: ", package[1] if package[1] == 'exists': self.updateStatus("Username Already Exists") self.passwordBox.set("") self.usernameBox.set("") self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 self.requestAttempt = False self.loginButton["state"] = DGG.NORMAL self.createAccButton["state"] = DGG.NORMAL return task.done elif package[0] == 'createSuccess': print "Create success", package[1] self.updateStatus("Account Created Successfully") self.requestAttempt = False self.attemptLogin() return task.done return task.cont def cycleLoginBox(self): # function is triggered by the tab key so you can cycle between # the two input fields like on most login screens if self.passwordBox['focus'] == 1: self.passwordBox['focus'] = 0 self.usernameBox['focus'] = 1 elif self.usernameBox['focus'] == 1: self.usernameBox['focus'] = 0 self.passwordBox['focus'] = 1 # IMPORTANT: When you change the focus to one of the text boxes, # you have to unset the focus on the other textbox. If you do not # do this Panda seems to get confused. def hide(self): self.background.destroy() self.usernameText.destroy() self.usernameBox.destroy() self.usernameStoreBox.destroy() self.passwordText.destroy() self.passwordBox.destroy() self.passwordStoreBox.destroy() self.loginButton.destroy() self.quitButton.destroy() self.createAccButton.destroy() self.statusText.destroy() self.showbase.ignore('tab') self.showbase.ignore('shift-tab') self.showbase.ignore('enter')
class FrameAutenticacao(object): ''' FrameAutenticacao ''' def __init__(self, parent = None, **kw): self.__qtd_conexao = 0 self.__frmAuth = DirectFrame( frameColor = (0,0,0,.3), frameSize = (-.5,.5,0,0.45), pos = (0,0,-.1), enableEdit = 1 ) self.__lblLogin = DirectLabel( text = "Login: "******"Senha: ", scale = 0.05, pos = (-0.3, 0, 0.2), frameColor = (0,0,0,0), text_fg = (1,1,1,1) ) self.__etySenha = DirectEntry( scale = 0.05, width = 12, pos = (-.2, 0, 0.2), cursorKeys = 1, obscured = 1, focusInCommand = self.__command_clear_senha) self.__btnEntrar = DirectButton( frameColor = (0,0,0,1), text = "Entrar", scale = 0.06, pos = (0.3, 0, 0.1), text_fg = (1,1,1,1), rolloverSound = None, clickSound = None, command = self.__command_entrar) self.__lblLogin.reparentTo(self.__frmAuth) self.__etyLogin.reparentTo(self.__frmAuth) self.__lblSenha.reparentTo(self.__frmAuth) self.__etySenha.reparentTo(self.__frmAuth) self.__btnEntrar.reparentTo(self.__frmAuth) self.__etyLogin.set("viner") self.__etySenha.set("viner") def __command_clear_senha(self): self.__etySenha.set("") def __command_entrar(self, txt = None): login = self.__etyLogin.get() senha = self.__etySenha.get() valido = True if login == "": addMensagem("O campo Login e obrigatorio !", COR_BRANCO) valido = False if senha == "": addMensagem("O campo Senha e obrigatorio !", COR_BRANCO) valido = False if valido: self.__btnEntrar["state"] = DGG.DISABLED taskMgr.add( self.__task_conectar_servidor, 'ConectarServidor', extraArgs=[login,senha], appendTask=True) #inicia_nova_thread(1, 0, "Conectar Servidor", self.__conectar_servidor, login, senha) def __task_conectar_servidor(self, login, senha, task): if self.__qtd_conexao < TENTATIVAS: if vinerOnline.flg_conectado == vinerOnline.ERROLOGIN: vinerOnline.flg_conectado = vinerOnline.DESCONECT self.__btnEntrar["state"] = DGG.NORMAL self.__qtd_conexao = 0 addMensagem('Login ou senha invalido', COR_VERMELHO) self.__etyLogin.setFocus() elif vinerOnline.flg_conectado == vinerOnline.CONECTADO: #addMensagem("Conectado 12 !!!") #self.destroy() pass else: vinerOnline.conectar_servidor(login, senha) self.__qtd_conexao += 1 taskMgr.doMethodLater( INTERVALO_TENTATIVAS, self.__task_conectar_servidor, 'ConectarServidorLater', extraArgs = [login,senha], appendTask = True) msg = "Tentativa %s/5 - Conectando..." % (self.__qtd_conexao) addMensagem(msg, COR_BRANCO) else: vinerOnline.flg_conectado = vinerOnline.DESCONECT self.__btnEntrar["state"] = DGG.NORMAL self.__qtd_conexao = 0 addMensagem("Servidor nao encontrado", COR_VERMELHO) return task.done def destroy(self): self.__frmAuth.destroy() del self.__lblLogin del self.__etyLogin del self.__lblSenha del self.__etySenha del self.__btnEntrar del self.__frmAuth
class EntyButtonFrame(object): def __init__(self, parent=None, scale=.05, limitText=100, frameSize=(0, 1.3, 0.11, .2), pos=(0, 0, .1)): self.__show = True self.frmMsg = DirectFrame(parent=parent, frameColor=(0, 0, 0, .5), frameSize=frameSize, pos=pos, enableEdit=1) self.etyMsg = DirectEntry(frameColor=(1, 1, 1, .5), scale=scale, width=22, numLines=1, pos=(.02, 0, .14), cursorKeys=1, focus=1, command=self.__command_enviar_msg, focusInCommand=self.__command_clear_msg) self.btnMsgr = DirectButton(frameColor=(0, 0, 0, 1), text="Enviar", scale=scale, pos=(1.21, 0, .14), text_fg=(1, 1, 1, 1), rolloverSound=None, clickSound=None, command=self.__command_enviar_msg) self.etyMsg.reparentTo(self.frmMsg) self.btnMsgr.reparentTo(self.frmMsg) self.hide() def hide(self): self.frmMsg.hide() self.__show = False def show(self): self.frmMsg.show() self.__show = True self.etyMsg.setFocus() def isShowing(self): return self.__show def __command_clear_msg(self): self.etyMsg.set("") def __command_enviar_msg(self, txt=None): msg = self.etyMsg.get() if msg != "": vinerOnline.envia_pacote_server(0, ACAO_SERVER_falar, [msg]) self.__command_clear_msg() self.etyMsg.setFocus() return False