Link to home
Start Free TrialLog in
Avatar of Tabris42
Tabris42Flag for United States of America

asked on

Python and Curses, mangled mess

Hi,
I'm fairly new to Python and completely confused when it comes to Curses. Perhaps an expert here can lend me a helping hand as I'm having a heck of a time trying to get any reason out of Curses.. the documentation for it is vague and not very helpful to me anymore, I can only ever seem to get the same couple of guides a million times on Google, so if anyone has any good tutorials or examples of this python socket curses client, that'd be nice too.

I am making a 3rd party client for a game. This game is typically graphical, however this client will be text only. I need a big huge window for a chat buffer and an input box below it for inputting text. The game is pretty much just a chat program, so the buffer will be filled with lots of "He says: Hi" and "She says: Bye".

My code so far is below... I was so frustrated I got rid of the bottom input box and just made it all the same.. I guess my main questions would be:
1. How can I add "scrolling", such that text does not get overwritten in the same spot in the output window all the time. I want each new line to be at the bottom and all lines before it to move up.
2. Please please please show me how to seperate the text input window from the output text window.
3. Any other hints or help would be appreciated!


from socket import *
import thread
import curses
import traceback

win = curses.initscr()
curses.cbreak()
win.keypad(1)
curses.echo()
max_y, max_x = win.getmaxyx()
begin_x = 1 ; begin_y = 1
win = curses.newwin(max_y-1, max_x-1, begin_y, begin_x)
win.border()
win.refresh()
fsocket = socket(AF_INET, SOCK_STREAM)
ADDR = ('blah.blahblah.com', 80)
fsocket.connect(ADDR)
fsocket.send("connect Username password\n")
def readdata():
        while 1:
                data = fsocket.recv(1024)
                try:
                        win.addstr(data)
                        win.refresh()
                except:
                        data = ""
thread.start_new_thread(readdata,tuple())
while 1:
        data = win.getstr(0,0)
        fsocket.send(data + "\n")
        win.refresh()
Avatar of pepr
pepr

Curses were designed in the middle age of computers. The main goal is to move the cursor to line Y and position X on the screen, type a character here (possibly some special character) and set the colour of the text or of the background on that position (simplified). It was clear at that time that each character occupies box of exactly same size. You could not change the font size nor the font face. You often could not change the number of lines and the number of charactes on the line.

In my opinion, you do not want to use curses for your purpose if you use _also_ another graphical window. You should focus on creating a normal GUI window using Tkinter, wxPython, wax or some similar framework. I would recommend the wxPython + wax. Then create a window with one big TextBox for collected texts and one smaller below for entering text.

Have a look at wax primer (http://zephyrfalcon.org/labs/wax_primer.html) that in steps shows how to write a simple text editor on 70 lines of code. After understanding that, you will be able to write you chat-like window. Inside TextBox, you can use various fonts, colors, etc.

For wax, you have to download and install wxPython and the wax. But it is pretty easy.
See also another page related to wax http://zephyrfalcon.org/labs/wax.html
There is also the project on SourceForge http://sourceforge.net/projects/waxgui

You can try the following quick hack -- two windows that you can type in, but no added functionality (just to start):

from wax import *

FIXED_FONT = ('Courier New', 10)

class MainFrame(Frame):

    def Body(self):

        vPanel = Panel(self, direction='vertical')

        self.bigTextBox = TextBox(vPanel, multiline=True, wrap=False)
        self.bigTextBox.SetFont(FIXED_FONT)
        self.bigTextBox.SetSize((600,400))
        vPanel.AddComponent(self.bigTextBox, expand='both')

        self.smallTextBox = TextBox(vPanel, multiline=True, wrap=True)
        self.smallTextBox.SetFont(FIXED_FONT)
        self.bigTextBox.SetSize((600,50))
        vPanel.AddComponent(self.smallTextBox, expand='h')

        vPanel.Pack()
   
        self.AddComponent(vPanel, expand='both')
        self.Pack()

app = Application(MainFrame, title='My title')
app.Run()
Avatar of Tabris42

ASKER

That's nifty and something I may use another time but for this specific application I need to run from a terminal (like through PuTTy).. this is why I need curses (or something like it), to be able to seperate input from output while still using the command line interface..
Frankly, I have never programmed using curses. I guess that you have looked at the curses module standard documentation and found also the URL for "Curses Programming with Python" http://www.amk.ca/python/howto/curses/curses.html. It would probably be better to ask in Unix Prog. or Linux Prog. channel, because curses are probably used mainly on unixes.

The following documets also seems to be interesting. (They deal with ncurses, but as far as I know it is a superset of the older curses which is already implemented in the Python curses module.)

http://dickey.his.com/ncurses/ncurses-intro.html
http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/

Good luck
Hi, I have written a small class which may be of use to you, I hope it helps.

#! /usr/bin/python
           
import curses, os, sys
           
class Start:
    def __init__(self):
        curses.wrapper(self.doDialog)
        self.endCurses()
        if self.next == "y": self.doProcess()
           
    def doDialog(self, event=None):
        win = self.createWindow(10, 2, 60, 15)    # x, y, w, h
        win.box()
        win.addstr(1, 24, "Primary Setup", curses.A_REVERSE)
        win.addstr(3, 1, "New Installation (y/n):")
        win.addstr(4, 1, "Date and Time (MMDDHHMM):")
        win.addstr(13, 1, "Continue (y/n):")
        self.new = self.inputString(win, 3, 30, 1, ("in", (chr(27), "y", "n")))
        if self.new == chr(27):
            self.endCurses()
            sys.exit()
        self.date  = self.inputString(win, 4, 30, 8, ("notblank",))
        self.next = self.inputString(win, 13, 30, 1, ("in", ("y", "n")))
        win.refresh()
       
    def createWindow(self, x, y, w, h):
        return curses.newwin(h, w, y, x)
       
    def createBox(self, scr, x, y, w, h):
        scr.addch(y, x, curses.ACS_ULCORNER)
        scr.addch(y, (x + w - 1), curses.ACS_URCORNER)
        scr.addch((y + h - 1), x, curses.ACS_LLCORNER)
        scr.addch((y + h - 1), (x + w - 1), curses.ACS_LRCORNER)
        scr.vline((y + 1), x, curses.ACS_VLINE, (h - 2))
        scr.hline(y, (x + 1), curses.ACS_HLINE, (w - 2))
        scr.vline((y + 1), (x + w - 1), curses.ACS_VLINE, (h - 2))
        scr.hline((y + h - 1), (x + 1), curses.ACS_HLINE, (w - 2))
        scr.refresh()

    def inputChar(self, w, y, x, l=1):
        curses.echo()
        c = ""
        for x in range(x, (x+l)):
            i = w.getch(y, x)
            if i == 10: break
            c += chr(i)
        curses.noecho()
        return c

    def inputString(self, w, y, x, l, verify=None):
        def doInput(w, y, x, l, verify):
            curses.echo()
            c = w.getstr(y, x, l)
            curses.noecho()
            if not verify: return c
            if verify[0] == "notblank" and c: return c
            if verify[0] == "in" and c in verify[1]: return c
            if verify[0] == "dir" and os.path.isdir(c): return c
        c = None
        while c == None: c = doInput(w, y, x, l, verify)
        return c

    def endCurses(self):
        curses.nocbreak()
        ##self.stdscr.keypad(0)
        curses.echo()
        curses.endwin()

    def doProcess(self):
        # Do whatever you want with the input
        pass

if __name__ == "__main__":
    Start()

ASKER CERTIFIED SOLUTION
Avatar of RichieHindle
RichieHindle

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That is exactly the kind of thing I'm looking for. Thanks a lot!