File: grapher-grapher-cpp.html

package info (click to toggle)
qt-embedded 2.3.2-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 68,608 kB
  • ctags: 45,998
  • sloc: cpp: 276,654; ansic: 71,987; makefile: 29,074; sh: 12,305; yacc: 2,465; python: 1,863; perl: 481; lex: 480; xml: 68; lisp: 15
file content (548 lines) | stat: -rw-r--r-- 18,934 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>
Qt Toolkit - grapher/grapher.cpp example file
</title><style type="text/css"><!--
h3.fn,span.fn { margin-left: 1cm; text-indent: -1cm; }
a:link { color: #004faf; text-decoration: none }
a:visited { color: #672967; text-decoration: none }body { background: white; color: black; }
--></style>
</head><body bgcolor="#ffffff">

<table width="100%">
<tr><td><a href="index.html">
<img width="100" height="100" src="qtlogo.png"
alt="Home" border="0"><img width="100"
height="100" src="face.png" alt="Home" border="0">
</a><td valign=top><div align=right><img src="dochead.png" width="472" height="27"><br>
<a href="classes.html"><b>Classes</b></a>
-<a href="annotated.html">Annotated</a>
- <a href="hierarchy.html">Tree</a>
-<a href="functions.html">Functions</a>
-<a href="index.html">Home</a>
-<a href="topicals.html"><b>Structure</b></a>
</div>
</table>

<h1 align=center>Grapher Plugin</h1>
  <p>
  This example graphs data from a simple text file.  It
  demonstrates the use of the QNPInstance::writeReady()
  and QNPInstance::write() functions.
  <p>
  To build the example, you must first build the
  <a href=nsplugin.html>Qt Netscape Plugin Extension</a> library.
  Then type <tt>make</tt> in <tt>extensions/nsplugin/examples/grapher/</tt>
  and copy the resulting <tt>grapher.so</tt> or <tt>npgrapher.dll</tt>
  to the Plugins directory of your WWW browser.
  <p>
  <EMBED ALIGN=LEFT WIDTH=49% HEIGHT=300 SRC=graph.g1n
    graphstyle=pie fontfamily=times fontsize=18>
  <p>
  The text file it accepts as input has a title line, then
  a sequence of lines with a number, then a string.  The
  plugin displays a pie chart of the numbers, each segment
  labelled by the associated string.  The user can select
  a bar chart view of the same data by selecting from the
  menu that appears when they point at the plugin.
  <p>
  The HTML tag used to embed the graph is:
<small>
<pre>
  &lt;EMBED
    SRC=graph.g1n
    ALIGN=LEFT
    WIDTH=49% HEIGHT=300
    graphstyle=pie fontfamily=times
    fontsize=18&gt;
</pre>
</small>
  Note that some HTML arguments (which we have capitalized here)
  are interpreted by the browser, while others are used by the
  plugin.

<br clear>
With the simplicity and cross-platform nature of Qt-based plugins,
pages like <a href="http://www.netcraft.com/survey/">Netcraft's
Server Graphs</a> can be provided much more efficiently for both
the service provider and consumer.  Data need not be converted
to an image at the server.

<br clear>
<pre>#include "grapher.h"

Graph::Graph( GraphModel&amp; mdl ) :
    model(mdl),
    style(Bar),
    pieRotationTimer(0),
    pieRotation(0)
{
    // Create a menubar for the widget
    //
    menubar = new <a name="QMenuBar"></a><a href="qmenubar.html">QMenuBar</a>( this );
    stylemenu = new <a name="QPopupMenu"></a><a href="qpopupmenu.html">QPopupMenu</a>;
    stylemenu-&gt;setCheckable(TRUE);
    for ( Style s = Pie; styleName[s]; s = Style(s+1)) {
        stylemenu-&gt;insertItem(styleName[s], s+100);
    }
    connect(stylemenu, SIGNAL(activated(int)),
        this, SLOT(setStyleFromMenu(int)));
    setStyle(Pie);

    menubar-&gt;insertItem("Style", stylemenu);
    menubar-&gt;insertSeparator();

    <a href="qpopupmenu.html">QPopupMenu</a>* help = new <a href="qpopupmenu.html">QPopupMenu</a>;
    help-&gt;<a name="insertItem"></a><a href="qmenudata.html#0076cb">insertItem</a>( "About plugin...", this, SIGNAL(aboutPlugin()) );
    help-&gt;<a href="qmenudata.html#0076cb">insertItem</a>( "About data...", this, SIGNAL(aboutData()) );
    menubar-&gt;insertItem("Help", help);
}

Graph::~Graph()
{
}

void <a name="103"></a>Graph::setStyle(Style s)
{
    if (style != s) {
        if (pieRotationTimer)
            <a name="killTimer"></a><a href="qobject.html#46d1c6">killTimer</a>(pieRotationTimer);
        stylemenu-&gt;setItemChecked(100+style, FALSE);
        style = s;
        if ( style == Pie )
            pieRotationTimer = startTimer( 80 );
        else
            pieRotationTimer = 0;
        stylemenu-&gt;setItemChecked(100+style, TRUE);
        <a name="update"></a><a href="qwidget.html#f3f721">update</a>();
    }
}

void <a name="102"></a>Graph::timerEvent(<a name="QTimerEvent"></a><a href="qtimerevent.html">QTimerEvent</a>*)
{
    pieRotation = ( pieRotation + 6 ) % 360; 
    <a name="repaint"></a><a href="qwidget.html#d5cfc3">repaint</a>(false);    
}

void <a name="103"></a>Graph::setStyle(const char* stext)
{
    for ( Style s = Pie; styleName[s]; s = Style(s+1) ) {
        if ( qstricmp(stext,styleName[s])==0 ) {
            <a name="setStyle"></a><a href="#103">setStyle</a>(s);
            return;
        }
    }
}

void <a name="104"></a>Graph::enterInstance()
{    
    menubar-&gt;show();
}

void <a name="105"></a>Graph::leaveInstance()
{
    menubar-&gt;hide();
}

void <a name="106"></a>Graph::paintError(const char* e)
{
    <a name="QPainter"></a><a href="qpainter.html">QPainter</a> p(this);
    int w = width();
    p.<a name="drawText"></a><a href="qpainter.html#0f088f">drawText</a>(w/8, 0, w-w/4, <a name="height"></a><a href="qwidget.html#e3c588">height</a>(), AlignCenter|WordBreak, e);
}

void <a name="107"></a>Graph::paintBar(<a name="QPaintEvent"></a><a href="qpaintevent.html">QPaintEvent</a>* event)
{
    if ( model.colType(0) != GraphModel::Numeric ) {
        <a name="paintError"></a><a href="#106">paintError</a>("First column not numeric, cannot draw bar graph\n");
        return;
    }

    <a name="QList"></a><a href="qlist.html">QList</a>&lt;GraphModel::Datum&gt;&amp; data = model.graphData();

    double max = 0.0;

    for (GraphModel::Datum* rowdata = data.first();
        rowdata; rowdata = data.next())
    {
        if (rowdata[0].dbl &gt; max) max = rowdata[0].dbl;
    }

    const uint w = width();
    const uint h = height();

    <a href="qpainter.html">QPainter</a> p(this);

    p.<a name="setClipRect"></a><a href="qpainter.html#898839">setClipRect</a>(event-&gt;<a name="rect"></a><a href="qpaintevent.html#2d6e18">rect</a>());

    if ( w &gt; data.count() ) {
        // More pixels than data
        int x = 0;
        int i = 0;
        <a name="QFontMetrics"></a><a href="qfontmetrics.html">QFontMetrics</a> fm=fontMetrics();
        int fh = fm.<a name="height"></a><a href="qfontmetrics.html#341253">height</a>();

        for (GraphModel::Datum* rowdata = data.first();
            rowdata; rowdata = data.next())
        {
            <a name="QColor"></a><a href="qcolor.html">QColor</a> c;
            c.<a name="setHsv"></a><a href="qcolor.html#e47175">setHsv</a>( (i * 255)/data.count(), 255, 255 );// rainbow effect
            p.<a name="setBrush"></a><a href="qpainter.html#3e0cc8">setBrush</a>(c);
            int bw = (w-w/4-x)/(data.count()-i);
            int bh = int((h-h/4-1)*rowdata[0].dbl/max);
            p.<a name="drawRect"></a><a href="qpainter.html#4c0077">drawRect</a>( w/8+x, h-h/8-1-bh, bw, bh );

            // ### This causes a crash, so comment out for now      
            /*if (model.colType(1) == GraphModel::Label) {
                p.<a href="qpainter.html#0f088f">drawText</a>(w/8+x, h-h/8, bw, fh+h/8,
                    WordBreak|AlignTop|AlignHCenter,
                    *rowdata[1].str);
            }*/
            i++;
            x+=bw;
        }
    } else {
        // More data than pixels
        int x = 0;
        int i = 0;
        double av = 0.0;
        int n = 0;
        for (GraphModel::Datum* rowdata = data.first(); rowdata;
            rowdata = data.next())
        {
            int bx = i*w/data.count();

            if (bx &gt; x) {
                <a href="qcolor.html">QColor</a> c;
                c.<a href="qcolor.html#e47175">setHsv</a>( (x * 255)/w, 255, 255 );// rainbow effect
                p.<a name="setPen"></a><a href="qpainter.html#0183e4">setPen</a>(c);
                int bh = int(h*av/n/max);

                p.<a name="drawLine"></a><a href="qpainter.html#e3a489">drawLine</a>(x,h-1,x,h-bh);

                av = 0.0;
                n = 0;
                x = bx;
            }

            av += rowdata[0].dbl;
            n++;

            i++;
        }
    }
}

void <a name="108"></a>Graph::paintPie(<a href="qpaintevent.html">QPaintEvent</a>* event)
{
    if ( model.colType(0) != GraphModel::Numeric ) {
        <a href=#106>paintError</a>("First column not numeric, cannot draw pie graph\n");
        return;
    }

    <a href="qlist.html">QList</a>&lt;GraphModel::Datum&gt;&amp; data = model.graphData();

    double total = 0.0;

    GraphModel::Datum* rowdata;

    for (rowdata = data.first();
        rowdata; rowdata = data.next())
    {
        total += rowdata[0].dbl;
    }

    // Only use first column for pie chart
    if ( !total ) return;

    int apos = (pieRotation-90)*16;

    const int w = width();
    const int h = height();

    const int xd = w - w/5;
    const int yd = h - h/5;

    pm.resize(<a name="width"></a><a href="qwidget.html#2edab1">width</a>(),<a href="qwidget.html#e3c588">height</a>());
    pm.fill(<a name="backgroundColor"></a><a href="qwidget.html#d5be64">backgroundColor</a>());
    <a href="qpainter.html">QPainter</a> p(&amp;pm);
    p.<a name="setFont"></a><a href="qpainter.html#998df2">setFont</a>(<a name="font"></a><a href="qwidget.html#167922">font</a>());

    p.<a href="qpainter.html#898839">setClipRect</a>(event-&gt;<a href="qpaintevent.html#2d6e18">rect</a>());

    int i = 0;

    for (rowdata = data.first();
        rowdata; rowdata = data.next())
    {
        <a href="qcolor.html">QColor</a> c;

        c.<a href="qcolor.html#e47175">setHsv</a>( ( i * 255)/data.count(), 255, 255 );// rainbow effect
        p.<a href="qpainter.html#3e0cc8">setBrush</a>( c );                        // solid fill with color c

        int a = int(( rowdata[0].dbl * 360.0 ) / total * 16.0 + 0.5);
        p.<a name="drawPie"></a><a href="qpainter.html#3ca7a2">drawPie</a>( w/10, h/10, xd, yd, -apos, -a );
        apos += a;
        i++;
    }

    if (model.colType(1) == GraphModel::Label) {
        double apos = (pieRotation-90)*M_PI/180;

        for (rowdata = data.first();
            rowdata; rowdata = data.next())
        {
            double a = rowdata[0].dbl * 360 / total * M_PI / 180;
            int x = int(cos(apos+a/2)*w*5/16 + w/2 + 0.5);
            int y = int(sin(apos+a/2)*h*5/16 + h/2 + 0.5);

            // ### This causes a crash, so comment out for now
            /*p.<a href="qpainter.html#0f088f">drawText</a>(x-w/8, y-h/8, w/4, h/4,
                WordBreak|AlignCenter,
                *rowdata[1].str);*/
            apos += a;
        }
    }

    <a href="qpainter.html">QPainter</a> p2(this);
    p2.<a href="qpainter.html#898839">setClipRect</a>(event-&gt;<a href="qpaintevent.html#2d6e18">rect</a>());
    p2.<a name="drawPixmap"></a><a href="qpainter.html#c64b89">drawPixmap</a>(0,0,pm);
}

void <a name="109"></a>Graph::paintWait(<a href="qpaintevent.html">QPaintEvent</a>*)
{
    <a href="qpainter.html">QPainter</a> p(this);
    p.<a href="qpainter.html#0f088f">drawText</a>(<a name="rect"></a><a href="qwidget.html#75ae71">rect</a>(), AlignCenter, "Loading...");
}

void <a name="110"></a>Graph::paintEvent(<a href="qpaintevent.html">QPaintEvent</a>* event)
{    
    if (!model.nCols()) {
        <a name="paintWait"></a><a href="#109">paintWait</a>(event);
    } else {
        switch (style) {
          case Pie:
            <a name="paintPie"></a><a href="#108">paintPie</a>(event);
            break;
          case Bar:
            <a name="paintBar"></a><a href="#107">paintBar</a>(event);
            break;
        }
    }

}

void <a name="111"></a>Graph::setStyleFromMenu(int id)
{
    <a href=#103>setStyle</a>(Style(id-100));
}

const char* <a name="112"></a>Graph::styleName[] = { "Pie", "Bar", 0 };

Grapher::Grapher()
{
    data.setAutoDelete(TRUE);
    firstline = TRUE;
    ncols = 0;
    line.open(IO_WriteOnly|IO_Truncate);
}

Grapher::~Grapher()
{
}

<a href="qlist.html">QList</a>&lt;GraphModel::Datum&gt;&amp; <a name="<a name="93">"></a><a href="#93"><a name="93"></a>Grapher::graphData</a>()
{
    return data;
}

GraphModel::ColType <a name="94"></a>Grapher::colType(int col) const
{
    return coltype[col];
}

int <a name="95"></a>Grapher::nCols() const
{
    return ncols;
}

<a name="QNPWidget"></a><a href="qnpwidget.html">QNPWidget</a>* <a name="96"></a>Grapher::newWindow()
{
    // Create a Graph - our subclass of QNPWidget.
    Graph *graph = new Graph(*this);

    // Look at the arguments from the EMBED tag.
    //   GRAPHSTYLE chooses pie or bar
    //   FONTFAMILY and FONTSIZE choose the font
    //
    const char* style = arg("GRAPHSTYLE");
    if ( style ) graph-&gt;<a name="setStyle"></a><a href="qwidget.html#287f79">setStyle</a>(style);

    const char* fontfamily = arg("FONTFAMILY");
    const char* fontsize = arg("FONTSIZE");
    int ptsize = fontsize ? atoi(fontsize) : graph-&gt;<a href="qwidget.html#167922">font</a>().pointSize();
    if (fontfamily) graph-&gt;<a name="setFont"></a><a href="qwidget.html#c52788">setFont</a>(<a name="QFont"></a><a href="qfont.html">QFont</a>(fontfamily, ptsize));

    <a name="connect"></a><a href="qobject.html#7f8e37">connect</a>(graph, SIGNAL(<a name="aboutPlugin"></a><a href="#99">aboutPlugin</a>()), this, SLOT(<a href=#99>aboutPlugin</a>()));
    <a href="qobject.html#7f8e37">connect</a>(graph, SIGNAL(<a name="aboutData"></a><a href="#100">aboutData</a>()), this, SLOT(<a href=#100>aboutData</a>()));

    return graph;
}

void <a name="97"></a>Grapher::consumeLine()
{
    line.close();
    line.open(IO_ReadOnly);

    <a name="QTextStream"></a><a href="qtextstream.html">QTextStream</a> ts( &amp;line );

    if (firstline) {
        firstline = FALSE;
        ncols=0;
        <a href="qlist.html">QList</a>&lt;ColType&gt; typelist;
        typelist.<a name="setAutoDelete"></a><a href="qcollection.html#a8ef9f">setAutoDelete</a>(TRUE);
        do {
            <a name="QString"></a><a href="qstring.html">QString</a> typestr;
            ts &gt;&gt; typestr &gt;&gt; ws;
            ColType* t = 0;
            if ( typestr == "num" ) {
                t = new ColType(Numeric);
            } else if ( typestr == "label" ) {
                t = new ColType(Label);
            }
            if (t) typelist.<a name="append"></a><a href="qlist.html#c5746a">append</a>(t);
        } while (!ts.<a name="eof"></a><a href="qtextstream.html#bb145b">eof</a>());
        coltype = new ColType[ncols];
        for (ColType* t = typelist.<a name="first"></a><a href="qlist.html#e625f9">first</a>(); t; t = typelist.<a name="next"></a><a href="qlist.html#f95ddd">next</a>()) {
            coltype[ncols++] = *t;
        }
    } else {
        int col=0;
        Datum *rowdata = new Datum[ncols];
        while ( col &lt; ncols &amp;&amp; !ts.<a href="qtextstream.html#bb145b">eof</a>() ) {
            switch (coltype[col]) {
              case Numeric: {
                double value;
                ts &gt;&gt; value &gt;&gt; ws;
                rowdata[col].dbl = value;
                break;
              }
              case Label: {
                <a href="qstring.html">QString</a>* value = new <a href="qstring.html">QString</a>;
                ts &gt;&gt; *value &gt;&gt; ws;
                rowdata[col].str = value;
                break;
              }
            }
            col++;
        }

        data.append(rowdata);
    }

    line.close();
    line.open(IO_WriteOnly|IO_Truncate);
}

int <a name="98"></a>Grapher::write(<a name="QNPStream"></a><a href="qnpstream.html">QNPStream</a>* /*str*/, int /*offset*/, int len, void* buffer)
{
    // The browser calls this function when data is available on one
    // of the streams the plugin has requested.  Since we are only
    // processing one stream - the URL in the SRC argument of the EMBED
    // tag, we assume the QNPStream is that one.  Also, since we do not
    // override QNPInstance::writeReady(), we must accepts ALL the data
    // that is sent to this function.
    //
    char* txt = (char*)buffer;
    for (int i=0; i&lt;len; i++) {
        char ch = txt[i];
        switch ( ch ) {
          case '\n':
            <a name="consumeLine"></a><a href="#97">consumeLine</a>();
            break;
          case '\r': // ignore;
            break;
          default:
            line.putch(ch);
        }
    }

    if ( widget() ) {
        <a name="widget"></a><a href="qnpinstance.html#9ac952">widget</a>()-&gt;update();
    }

    return len;
}

void <a name="99"></a>Grapher::aboutPlugin()
{
    <a name="getURL"></a><a href="qnpinstance.html#d57f95">getURL</a>( "http://www.trolltech.com/nsplugin/", "_blank" );
}

void <a name="100"></a>Grapher::aboutData()
{
    const char* page = arg("DATAPAGE");
    if (page)
        <a href="qnpinstance.html#d57f95">getURL</a>( page, "_blank" );
    else
        <a name="QMessageBox::message"></a><a href="qmessagebox.html#6f1d2d">QMessageBox::message</a>("Help", "No help for this data");
}

//
// GrapherPlugin is the start of everything.  It is a QNPlugin subclass,
// and it is responsible for describing the plugin to the browser, and
// creating instances of the plugin when it appears in web page.
//

class GrapherPlugin : public QNPlugin {
public:
    GrapherPlugin()
    {
    }

    <a name="QNPInstance"></a><a href="qnpinstance.html">QNPInstance</a>* newInstance()
    {
        // Make a new Grapher, our subclass of QNPInstance.
        return new Grapher;
    }

    const char* getMIMEDescription() const
    {
        // Describe the MIME types which this plugin can
        // process.  Just the concocted "application/x-graphable"
        // type, with the "g1n" filename extension.
        //
        return "application/x-graphable:g1n:Graphable ASCII numeric data";
    }

    const char * getPluginNameString() const
    {
        // The name of the plugin.  This is the title string used in
        // the "About Plugins" page of the browser.
        //
        return "Qt-based Graph Plugin";
    }

    const char * getPluginDescriptionString() const
    {
        // A longer description of the plugin.
        //
        return "A Qt-based LiveConnected plug-in that graphs numeric data";
    }

};

//
// Finally, we provide the implementation of QNPlugin::create(), to
// provide our subclass of QNPlugin.
//

<a name="QNPlugin"></a><a href="qnplugin.html">QNPlugin</a>* QNPlugin::create()
{
    return new GrapherPlugin;
}
</pre>
<p><address><hr><div align="center">
<table width="100%" cellspacing="0" border="0"><tr>
<td>Copyright  2001 Trolltech<td><a href="http://www.trolltech.com/trademarks.html">Trademarks</a>
<td align="right"><div align="right">Qt version 2.3.2</div>
</table></div></address></body></html>