Re: flow control question



On Wed, 22 Jul 2009, Chris Vine wrote:

On Tue, 21 Jul 2009 23:45:38 -0400 (EDT)
Allin Cottrell <cottrell wfu edu> wrote:
On Tue, 21 Jul 2009, Dov Grobgeld wrote:

Here are two programs that implement through the text viewer
widget what you are asking for:

   - The Python console in gimp
   - GemTcl - a tcl interpreter

The way I set up the interaction is to listen to both the
key-press-event and the insert-text events of the text-viewer.
The key-press-event signals to the insert-event handler that it
is supposed to enter eval mode... and the insert-event catches
this before the newline is inserted into the buffer, runs the
eval and inserts the result into the buffer[.]

Thanks for the references.  That is pretty much what I have been
doing up till now.  What I really wanted that was new, though, was
a loop of precisely the form

while (get_a_command()) {
  respond
}

You can't put a single threaded program in a blocking loop like this
if you are running an event based GUI such as GTK+ or Qt.

You either have to put your blocking loop in a separate thread (and
you must make sure that get_a_command() really does block or you will
have a tight loop using 100% of one of your CPU cores), or use
the event mechanism, which means connecting to a relevant GTK+/GObject
signal such as a key-press-event as suggested (which is in fact
dispatched by the glib main loop).

Well, this may be a horrible hack, but what I did is:

/* this is set to 1 by a callback attached to the Return key
   in a GtkTextView */
static int command_entered;

int get_a_command (void *ptr)
{
    while (!command_entered) {
        if (gtk_events_pending()) {
            gtk_main_iteration();
        }
        g_usleep(1000);
    }

    command_entered = 0;

    /* do stuff with ptr */

    /* pseudo-code */
    return (command is not "quit");
}

The g_usleep value of 1000 seems to work well: one check on
command_entered per millisecond puts little demand on the CPU but
doesn't slow down the GUI so you'd notice -- and the "console"
thing I'm describing is unlikely to be used much of the time
anyway.

Allin Cottrell



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]