On Sat, 10 May 2008, Søren Hauberg wrote:

Hi all,
 I'm using gtksourceviewmm as terminal-like widget, and I want to
redirect std::cout to this widget. Currently I'm doing something like
this in my constructor:

   std::ostringstream outs;
   std::cout.rdbuf (outs.rdbuf ());

Caveat: I don't know much about gtksourcemm but I do know something about STL streambufs.

If the above code works (its an interesting idea that I have not seen before), then my advice would be subclass your own streambuf. You'll need to overload the the sync and overflow members. These have slightly weird actions and (on first viewing) appear non trivial.

The advantage of this appreoach is that the source view will only be updated when 1) the buffer runs out, 2) the stream explicitly asks for it, usually via stream.sync() being called. This (correctly) puts the control of the updates in the hands of the user of the stream, rather than having to wait for timeouts.

Here is an (untested) example based on a streambuf I wrote for encoding
streams into base64,

class ogsbuf : public std::streambuf
{
public:
        const static int kZBufferSize = 2048;
        typedef unsigned char char_type;
        typedef int int_type;
        typedef std::streampos pos_type;
        typedef std::streamoff off_type;

        private:
                gtksourceviewmm *destination;
                unsigned char buffer[kZBufferSize];

        public:

        explicit ogsbuf(gtksourceviewmm *_destination) : 
destination(_destinination) {
                setp((char *)buffer, (char *)buffer + kZBufferSize);
        }

        ~ogsbuf() { sync(); }

protected:
        inline int sync()
        {
                // pbase() is an unsigned char * pointing to the data to be 
written to the destination
                // pptr() is an end pointer for the data.
                // pptr() - pbase() is the length of the data in the buffer
                destination->append(pbase(), pbase() - pptr());

                setp((char *)buffer, (char *)buffer + kZBufferSize);

                return 0;
        };

        inline int overflow(int ch = traits_type::eof())
        {
                int ret = sync();
                *pptr() = ch;
                pbump(1);
                return ret;
        };
};

Then do

ogsbuf  gsb(ptrToSourceView);
std::cout.rdbuf (gsb);


Charlie - Metropolis Data Consultants - 07976 028167 - 01223 763758
_______________________________________________
gtkmm-list mailing list
[email protected]
http://mail.gnome.org/mailman/listinfo/gtkmm-list

Reply via email to