summaryrefslogtreecommitdiffstats
path: root/src/bltGraph.C
blob: dcc39a5bad4b454c154d3e2fad96cbbfddaab6b8 (plain)
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
/*
 * Smithsonian Astrophysical Observatory, Cambridge, MA, USA
 * This code has been modified under the terms listed below and is made
 * available under the same terms.
 */

/*
 *	Copyright 1991-2004 George A Howlett.
 *
 *	Permission is hereby granted, free of charge, to any person obtaining
 *	a copy of this software and associated documentation files (the
 *	"Software"), to deal in the Software without restriction, including
 *	without limitation the rights to use, copy, modify, merge, publish,
 *	distribute, sublicense, and/or sell copies of the Software, and to
 *	permit persons to whom the Software is furnished to do so, subject to
 *	the following conditions:
 *
 *	The above copyright notice and this permission notice shall be
 *	included in all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *	LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *	OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *	WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

extern "C" {
#include "bltInt.h"
#include "bltGraph.h"
}

#include "bltGraphOp.h"

#include "bltGrAxis.h"
#include "bltGrAxisOp.h"
#include "bltGrXAxisOp.h"
#include "bltGrPen.h"
#include "bltGrPenOp.h"
#include "bltGrElem.h"
#include "bltGrElemOp.h"
#include "bltGrMarker.h"
#include "bltGrMarkerOp.h"
#include "bltGrLegd.h"
#include "bltGrLegdOp.h"
#include "bltGrHairs.h"
#include "bltGrHairsOp.h"
#include "bltGrDef.h"

using namespace Blt;

#define MARKER_ABOVE	0
#define MARKER_UNDER	1

extern int Blt_CreatePageSetup(Graph* graphPtr);
extern void Blt_DestroyPageSetup(Graph* graphPtr);
extern void Blt_LayoutGraph(Graph* graphPtr);

static Blt_BindPickProc PickEntry;

static void AdjustAxisPointers(Graph* graphPtr);
static void UpdateMarginTraces(Graph* graphPtr);

// OptionSpecs

static const char* barmodeObjOption[] = 
  {"normal", "stacked", "aligned", "overlap", NULL};
const char* searchModeObjOption[] = {"points", "traces", "auto", NULL};
const char* searchAlongObjOption[] = {"x", "y", "both", NULL};

static Tk_OptionSpec optionSpecs[] = {
  {TK_OPTION_DOUBLE, "-aspect", "aspect", "Aspect", 
   "0", -1, Tk_Offset(GraphOptions, aspect), 
   0, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_BORDER, "-background", "background", "Background",
   STD_NORMAL_BACKGROUND, -1, Tk_Offset(GraphOptions, normalBg), 
   0, NULL, CACHE_DIRTY},
  {TK_OPTION_STRING_TABLE, "-barmode", "barMode", "BarMode", 
   "normal", -1, Tk_Offset(GraphOptions, barMode), 
   0, &barmodeObjOption, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_DOUBLE, "-barwidth", "barWidth", "BarWidth", 
   ".9", -1, Tk_Offset(GraphOptions, barWidth), 
   0, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_DOUBLE, "-baseline", "baseline", "Baseline", 
   "0", -1, Tk_Offset(GraphOptions, baseline), 0, NULL, 0},
  {TK_OPTION_SYNONYM, "-bd", NULL, NULL, NULL, -1, 0, 0, "-borderwidth", 0},
  {TK_OPTION_SYNONYM, "-bg", NULL, NULL, NULL, -1, 0, 0, "-background", 0},
  {TK_OPTION_SYNONYM, "-bm", NULL, NULL, NULL, -1, 0, 0, "-bottommargin", 0},
  {TK_OPTION_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
   STD_BORDERWIDTH, -1, Tk_Offset(GraphOptions, borderWidth), 0, NULL, 
   RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_PIXELS, "-bottommargin", "bottomMargin", "BottomMargin",
   "0", -1, Tk_Offset(GraphOptions, bottomMargin.reqSize), 0, NULL, 
   RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_STRING, "-bottomvariable", "bottomVariable", "BottomVariable",
   NULL, -1, Tk_Offset(GraphOptions, bottomMargin.varName), 
   TK_OPTION_NULL_OK, NULL, 0},
  {TK_OPTION_BOOLEAN, "-bufferelements", "bufferElements", "BufferElements",
   "yes", -1, Tk_Offset(GraphOptions, backingStore), 0, NULL, 0},
  {TK_OPTION_BOOLEAN, "-buffergraph", "bufferGraph", "BufferGraph",
   "yes", -1, Tk_Offset(GraphOptions, doubleBuffer), 0, NULL, 0},
  {TK_OPTION_CURSOR, "-cursor", "cursor", "Cursor", 
   "crosshair", -1, Tk_Offset(GraphOptions, cursor), 
   TK_OPTION_NULL_OK, NULL, 0},
  {TK_OPTION_SYNONYM, "-fg", NULL, NULL, NULL, -1, 0, 0, "-foreground", 0},
  {TK_OPTION_FONT, "-font", "font", "Font", 
   STD_FONT_MEDIUM, -1, Tk_Offset(GraphOptions, titleTextStyle.font), 0, NULL, 
   RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_COLOR, "-foreground", "foreground", "Foreground",
   STD_NORMAL_FOREGROUND, -1, Tk_Offset(GraphOptions, titleTextStyle.color), 
   0, NULL, 
   CACHE_DIRTY},
  {TK_OPTION_SYNONYM, "-halo", NULL, NULL, NULL, -1, 0, 0, "-searchhalo", 0},
  {TK_OPTION_PIXELS, "-height", "height", "Height", 
   "4i", -1, Tk_Offset(GraphOptions, reqHeight), 
   0, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_COLOR, "-highlightbackground", "highlightBackground",
   "HighlightBackground", 
   STD_NORMAL_BACKGROUND, -1, Tk_Offset(GraphOptions, highlightBgColor), 
   0, NULL, 
   CACHE_DIRTY},
  {TK_OPTION_COLOR, "-highlightcolor", "highlightColor", "HighlightColor",
   STD_NORMAL_FOREGROUND, -1, Tk_Offset(GraphOptions, highlightColor), 
   0, NULL, 0},
  {TK_OPTION_PIXELS, "-highlightthickness", "highlightThickness",
   "HighlightThickness", 
   "2", -1, Tk_Offset(GraphOptions, highlightWidth), 0, NULL, 0},
  {TK_OPTION_BOOLEAN, "-invertxy", "invertXY", "InvertXY", 
   "no", -1, Tk_Offset(GraphOptions, inverted), 0, NULL, 
   RESET_WORLD | CACHE_DIRTY | RESET_AXES},
  {TK_OPTION_JUSTIFY, "-justify", "justify", "Justify", 
   "center", -1, Tk_Offset(GraphOptions, titleTextStyle.justify), 0, NULL, 0},
  {TK_OPTION_PIXELS, "-leftmargin", "leftMargin", "Margin", 
   "0", -1, Tk_Offset(GraphOptions, leftMargin.reqSize), 0, NULL, 
   RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_STRING, "-leftvariable", "leftVariable", "LeftVariable",
   NULL, -1, Tk_Offset(GraphOptions, leftMargin.varName), 
   TK_OPTION_NULL_OK, NULL, 0},
  {TK_OPTION_SYNONYM, "-lm", NULL, NULL, NULL, -1, 0, 0, "-leftmargin", 0},
  {TK_OPTION_BORDER, "-plotbackground", "plotbackground", "PlotBackground",
   STD_NORMAL_BACKGROUND, -1, Tk_Offset(GraphOptions, plotBg), 0, NULL,
   RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_PIXELS, "-plotborderwidth", "plotBorderWidth", "PlotBorderWidth",
   STD_BORDERWIDTH, -1, Tk_Offset(GraphOptions, plotBW), 0, NULL, 
   RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_PIXELS, "-plotpadx", "plotPadX", "PlotPad", 
   "0", -1, Tk_Offset(GraphOptions, xPad), 0, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_PIXELS, "-plotpady", "plotPadY", "PlotPad", 
   "0", -1, Tk_Offset(GraphOptions, yPad), 0, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_RELIEF, "-plotrelief", "plotRelief", "Relief", 
   "flat", -1, Tk_Offset(GraphOptions, plotRelief), 0, NULL, 
   RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_RELIEF, "-relief", "relief", "Relief", 
   "flat", -1, Tk_Offset(GraphOptions, relief), 0, NULL, 0},
  {TK_OPTION_PIXELS, "-rightmargin", "rightMargin", "Margin", 
   "0", -1, Tk_Offset(GraphOptions, rightMargin.reqSize), 0, NULL, 
   RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_STRING, "-rightvariable", "rightVariable", "RightVariable",
   NULL, -1, Tk_Offset(GraphOptions, rightMargin.varName), 
   TK_OPTION_NULL_OK, NULL, 0},
  {TK_OPTION_SYNONYM, "-rm", NULL, NULL, NULL, -1, 0, 0, "-rightmargin", 0},
  {TK_OPTION_PIXELS, "-searchhalo", "searchhalo", "SearchHalo", 
   "2m", -1, Tk_Offset(GraphOptions, search.halo), 0, NULL, 0},
  {TK_OPTION_STRING_TABLE, "-searchmode", "searchMode", "SearchMode",
   "points", -1, Tk_Offset(GraphOptions, search.mode), 
   0, &searchModeObjOption, 0}, 
  {TK_OPTION_STRING_TABLE, "-searchalong", "searchAlong", "SearchAlong",
   "both", -1, Tk_Offset(GraphOptions, search.along), 
   0, &searchAlongObjOption, 0},
  {TK_OPTION_BOOLEAN, "-stackaxes", "stackAxes", "StackAxes", 
   "no", -1, Tk_Offset(GraphOptions, stackAxes), 0, NULL, 0},
  {TK_OPTION_STRING, "-takefocus", "takeFocus", "TakeFocus",
   NULL, -1, Tk_Offset(GraphOptions, takeFocus), TK_OPTION_NULL_OK, NULL, 0},
  {TK_OPTION_STRING, "-title", "title", "Title", 
   NULL, -1, Tk_Offset(GraphOptions, title), 
   TK_OPTION_NULL_OK, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_SYNONYM, "-tm", NULL, NULL, NULL, -1, 0, 0, "-topmargin", 0},
  {TK_OPTION_PIXELS, "-topmargin", "topMargin", "TopMargin", 
   "0", -1, Tk_Offset(GraphOptions, topMargin.reqSize), 
   0, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_STRING, "-topvariable", "topVariable", "TopVariable",
   NULL, -1, Tk_Offset(GraphOptions, topMargin.varName), 
   TK_OPTION_NULL_OK, NULL, 0},
  {TK_OPTION_PIXELS, "-width", "width", "Width", 
   "5i", -1, Tk_Offset(GraphOptions, reqWidth), 
   0, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_PIXELS, "-plotwidth", "plotWidth", "PlotWidth", 
   "0", -1, Tk_Offset(GraphOptions, reqPlotWidth), 
   0, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_PIXELS, "-plotheight", "plotHeight", "PlotHeight", 
   "0", -1, Tk_Offset(GraphOptions, reqPlotHeight), 
   0, NULL, RESET_WORLD | CACHE_DIRTY},
  {TK_OPTION_END, NULL, NULL, NULL, NULL, -1, 0, 0, NULL, 0}
};

// Create

Graph::Graph(ClientData clientData, Tcl_Interp* interp, 
	     int objc, Tcl_Obj* const objv[], ClassId classId)
{
  valid_ =1;
  interp_ = interp;
  tkwin_ = Tk_CreateWindowFromPath(interp_, Tk_MainWindow(interp_), 
				  Tcl_GetString(objv[1]), NULL);
  if (!tkwin_) {
    valid_ =0;
    return;
  }
  display_ = Tk_Display(tkwin_);
  ((TkWindow*)tkwin_)->instanceData = this;

  cmdToken_ = Tcl_CreateObjCommand(interp_, Tk_PathName(tkwin_),
				   GraphInstCmdProc, this,
				   GraphInstCmdDeleteProc);
  optionTable_ = Tk_CreateOptionTable(interp_, optionSpecs);
  ops_ = (GraphOptions*)calloc(1, sizeof(GraphOptions));
  GraphOptions* ops = (GraphOptions*)ops_;

  switch (classId) {
  case CID_ELEM_LINE:
    Tk_SetClass(tkwin_, "Graph");
    break;
  case CID_ELEM_BAR:
    Tk_SetClass(tkwin_, "Barchart");
    break;
  default:
    break;
  }

  classId_ = classId;
  flags = MAP_WORLD | REDRAW_WORLD;
  nextMarkerId_ = 1;

  legend_ = new Legend(this);
  crosshairs_ = new Crosshairs(this);

  inset_ =0;
  titleX_ =0;
  titleY_ =0;
  titleWidth_ =0;
  titleHeight_ =0;
  width_ =0;
  height_ =0;
  left_ =0;
  right_ =0;
  top_ =0;
  bottom_ =0;
  focusPtr_ =NULL;
  halo_ =0;
  drawGC_ =NULL;
  vRange_ =0;
  hRange_ =0;
  vOffset_ =0;
  hOffset_ =0;
  vScale_ =0;
  hScale_ =0;
  cache_ =None;
  cacheWidth_ =0;
  cacheHeight_ =0;

  barGroups_ =NULL;
  nBarGroups_ =0;
  maxBarSetSize_ =0;

  ops->bottomMargin.site = MARGIN_BOTTOM;
  ops->leftMargin.site = MARGIN_LEFT;
  ops->topMargin.site = MARGIN_TOP;
  ops->rightMargin.site = MARGIN_RIGHT;

  Blt_Ts_InitStyle(ops->titleTextStyle);
  ops->titleTextStyle.anchor = TK_ANCHOR_N;

  Tcl_InitHashTable(&axes_.table, TCL_STRING_KEYS);
  Tcl_InitHashTable(&axes_.tagTable, TCL_STRING_KEYS);
  Tcl_InitHashTable(&elements_.table, TCL_STRING_KEYS);
  Tcl_InitHashTable(&elements_.tagTable, TCL_STRING_KEYS);
  Tcl_InitHashTable(&markers_.table, TCL_STRING_KEYS);
  Tcl_InitHashTable(&markers_.tagTable, TCL_STRING_KEYS);
  Tcl_InitHashTable(&penTable_, TCL_STRING_KEYS);
  Tcl_InitHashTable(&setTable_, sizeof(BarSetKey) / sizeof(int));
  axes_.displayList = Blt_Chain_Create();
  elements_.displayList = Blt_Chain_Create();
  markers_.displayList = Blt_Chain_Create();
  bindTable_ = Blt_CreateBindingTable(interp_, tkwin_, this, 
				      PickEntry, Blt_GraphTags);

  if (Blt_CreatePen(this, interp_, "activeLine", CID_ELEM_LINE, 0, NULL) != 
      TCL_OK) {
    valid_ =0;
    return;
  }
  if (Blt_CreatePen(this, interp_, "activeBar", CID_ELEM_BAR, 0, NULL) != 
      TCL_OK) {
    valid_ =0;
    return;
  }
  if (Blt_CreateAxes(this) != TCL_OK) {
    valid_ =0;
    return;
  }
  if (Blt_CreatePageSetup(this) != TCL_OK) {
    valid_ =0;
    return;
  }

  // Keep a hold of the associated tkwin until we destroy the graph,
  // otherwise Tk might free it while we still need it.
  Tcl_Preserve(tkwin_);

  Tk_CreateEventHandler(tkwin_, 
			ExposureMask|StructureNotifyMask|FocusChangeMask,
			GraphEventProc, this);

  if ((Tk_InitOptions(interp_, (char*)ops_, optionTable_, tkwin_) != TCL_OK) || (GraphObjConfigure(interp_, this, objc-2, objv+2) != TCL_OK)) {
    valid_ =0;
    return;
  }

  AdjustAxisPointers(this);

  Tcl_SetStringObj(Tcl_GetObjResult(interp_), Tk_PathName(tkwin_), -1);
}

Graph::~Graph()
{
  GraphOptions* ops = (GraphOptions*)ops_;

  Blt::DestroyMarkers(this);
  Blt_DestroyElements(this);  // must come before legend and others

  if (crosshairs_)
    delete crosshairs_;
  if (legend_)
    delete legend_;

  Blt_DestroyAxes(this);
  Blt_DestroyPens(this);
  Blt_DestroyPageSetup(this);
  Blt_DestroyBarSets(this);

  if (bindTable_)
    Blt_DestroyBindingTable(bindTable_);

  if (drawGC_)
    Tk_FreeGC(display_, drawGC_);

  Blt_Ts_FreeStyle(display_, &ops->titleTextStyle);
  if (cache_ != None)
    Tk_FreePixmap(display_, cache_);

  Tk_FreeConfigOptions((char*)ops_, optionTable_, tkwin_);
  Tcl_Release(tkwin_);
  tkwin_ = NULL;

  if (ops_)
    free (ops_);
}

void Graph::configure()	
{
  GraphOptions* ops = (GraphOptions*)ops_;

  // Don't allow negative bar widths. Reset to an arbitrary value (0.1)
  if (ops->barWidth <= 0.0f)
    ops->barWidth = 0.8f;

  inset_ = ops->borderWidth + ops->highlightWidth;
  if ((ops->reqHeight != Tk_ReqHeight(tkwin_)) ||
      (ops->reqWidth != Tk_ReqWidth(tkwin_)))
    Tk_GeometryRequest(tkwin_, ops->reqWidth, ops->reqHeight);

  Tk_SetInternalBorder(tkwin_, ops->borderWidth);
  XColor* colorPtr = Tk_3DBorderColor(ops->normalBg);

  titleWidth_ =0;
  titleHeight_ =0;
  if (ops->title != NULL) {
    unsigned int w, h;
    Blt_Ts_GetExtents(&ops->titleTextStyle, ops->title, &w, &h);
    titleHeight_ = h;
  }

  // Create GCs for interior and exterior regions, and a background GC for
  // clearing the margins with XFillRectangle
  // Margin
  XGCValues gcValues;
  gcValues.foreground = ops->titleTextStyle.color->pixel;
  gcValues.background = colorPtr->pixel;
  unsigned long gcMask = (GCForeground | GCBackground);
  GC newGC = Tk_GetGC(tkwin_, gcMask, &gcValues);
  if (drawGC_ != NULL)
    Tk_FreeGC(display_, drawGC_);
  drawGC_ = newGC;

  // If the -inverted option changed, we need to readjust the pointers
  // to the axes and recompute the their scales.
  if (flags & RESET_AXES)
    AdjustAxisPointers(this);

  // Free the pixmap if we're not buffering the display of elements anymore.
  if ((!ops->backingStore) && (cache_ != None)) {
    Tk_FreePixmap(display_, cache_);
    cache_ = None;
  }
}

void Graph::display()
{
  GraphOptions* ops = (GraphOptions*)ops_;

  flags &= ~REDRAW_PENDING;
  if ((flags & GRAPH_DELETED) || !Tk_IsMapped(tkwin_))
    return;

  if ((Tk_Width(tkwin_) <= 1) || (Tk_Height(tkwin_) <= 1)) {
    /* Don't bother computing the layout until the size of the window is
     * something reasonable. */
    return;
  }
  width_ = Tk_Width(tkwin_);
  height_ = Tk_Height(tkwin_);
  map();

  if (!Tk_IsMapped(tkwin_)) {
    /* The graph's window isn't displayed, so don't bother drawing
     * anything.  By getting this far, we've at least computed the
     * coordinates of the graph's new layout.  */
    return;
  }
  /* Create a pixmap the size of the window for double buffering. */
  Pixmap drawable;
  if (ops->doubleBuffer)
    drawable = Tk_GetPixmap(display_, Tk_WindowId(tkwin_), 
			    width_, height_, Tk_Depth(tkwin_));
  else
    drawable = Tk_WindowId(tkwin_);

  if (ops->backingStore) {
    if ((cache_ == None) || 
	(cacheWidth_ != width_) ||
	(cacheHeight_ != height_)) {
      if (cache_ != None)
	Tk_FreePixmap(display_, cache_);

      cache_ = Tk_GetPixmap(display_, 
				     Tk_WindowId(tkwin_), 
				     width_, height_, 
				     Tk_Depth(tkwin_));
      cacheWidth_  = width_;
      cacheHeight_ = height_;
      flags |= CACHE_DIRTY;
    }
  }
  if (ops->backingStore) {
    if (flags & CACHE_DIRTY) {
      drawPlot(cache_);
      flags &= ~CACHE_DIRTY;
    }

    // Copy the pixmap to the one used for drawing the entire graph
    XCopyArea(display_, cache_, drawable, drawGC_, 0, 0, Tk_Width(tkwin_),
	      Tk_Height(tkwin_), 0, 0);
  }
  else
    drawPlot(drawable);

  // Draw markers above elements
  Blt::DrawMarkers(this, drawable, MARKER_ABOVE);
  Blt_DrawActiveElements(this, drawable);

  // Don't draw legend in the plot area.
  if (legend_->isRaised()) {
    switch (legend_->position()) {
    case Legend::PLOT:
    case Legend::XY:
      legend_->draw(drawable);
      break;
    default:
      break;
    }
  }

  // Draw 3D border just inside of the focus highlight ring
  if ((ops->borderWidth > 0) && (ops->relief != TK_RELIEF_FLAT))
    Tk_Draw3DRectangle(tkwin_, drawable, ops->normalBg, 
		       ops->highlightWidth, ops->highlightWidth, 
		       width_ - 2*ops->highlightWidth, 
		       height_ - 2*ops->highlightWidth, 
		       ops->borderWidth, ops->relief);

  // Draw focus highlight ring
  if ((ops->highlightWidth > 0) && (flags & FOCUS)) {
    GC gc = Tk_GCForColor(ops->highlightColor, drawable);
    Tk_DrawFocusHighlight(tkwin_, gc, ops->highlightWidth,
			  drawable);
  }

  // Disable crosshairs before redisplaying to the screen
  Blt_DisableCrosshairs(this);
  XCopyArea(display_, drawable, Tk_WindowId(tkwin_),
	    drawGC_, 0, 0, width_, height_, 0, 0);
  Blt_EnableCrosshairs(this);
  if (ops->doubleBuffer)
    Tk_FreePixmap(display_, drawable);

  flags &= ~MAP_WORLD;
  flags &= ~REDRAW_WORLD;
  UpdateMarginTraces(this);
}

void Graph::map()
{
  if (flags & RESET_AXES) {
    Blt_ResetAxes(this);
  }
  if (flags & LAYOUT_NEEDED) {
    Blt_LayoutGraph(this);
    flags &= ~LAYOUT_NEEDED;
  }

  if ((vRange_ > 1) && (hRange_ > 1)) {
    if (flags & MAP_WORLD)
      Blt_MapAxes(this);

    Blt_MapElements(this);
    Blt::MapMarkers(this);
    flags &= ~(MAP_ALL);
  }
}

void Graph::drawPlot(Drawable drawable)
{
  GraphOptions* ops = (GraphOptions*)ops_;
  drawMargins(drawable);

  // Draw the background of the plotting area with 3D border
  Tk_Fill3DRectangle(tkwin_, drawable, ops->plotBg,
		     left_ - ops->plotBW, 
		     top_ - ops->plotBW, 
		     right_ - left_ + 1 + 2*ops->plotBW,
		     bottom_ - top_  + 1 + 2*ops->plotBW, 
		     ops->plotBW, ops->plotRelief);
  
  // Draw the elements, markers, legend, and axis limits
  Blt_DrawAxes(this, drawable);
  Blt_DrawGrids(this, drawable);
  Blt::DrawMarkers(this, drawable, MARKER_UNDER);

  if (!legend_->isRaised()) {
    switch (legend_->position()) {
    case Legend::PLOT:
    case Legend::XY:
      legend_->draw(drawable);
      break;
    default:
      break;
    }
  }

  Blt_DrawAxisLimits(this, drawable);
  Blt_DrawElements(this, drawable);
}

/*
 *---------------------------------------------------------------------------
 *
 * DrawMargins --
 *
 * 	Draws the exterior region of the graph (axes, ticks, titles, etc) 
 * 	onto a pixmap. The interior region is defined by the given rectangle
 * 	structure.
 *
 *	---------------------------------
 *      |                               |
 *      |           rectArr[0]          |
 *      |                               |
 *	---------------------------------
 *      |     |top           right|     |
 *      |     |                   |     |
 *      |     |                   |     |
 *      | [1] |                   | [2] |
 *      |     |                   |     |
 *      |     |                   |     |
 *      |     |                   |     |
 *      |     |                   |     |
 *      |     |                   |     |
 *      |     |left         bottom|     |
 *	---------------------------------
 *      |                               |
 *      |          rectArr[3]           |
 *      |                               |
 *	---------------------------------
 *
 *		X coordinate axis
 *		Y coordinate axis
 *		legend
 *		interior border
 *		exterior border
 *		titles (X and Y axis, graph)
 *
 * Returns:
 *	None.
 *
 * Side Effects:
 *	Exterior of graph is displayed in its window.
 *
 *---------------------------------------------------------------------------
 */
void Graph::drawMargins(Drawable drawable)
{
  GraphOptions* ops = (GraphOptions*)ops_;
  XRectangle rects[4];

  /*
   * Draw the four outer rectangles which encompass the plotting
   * surface. This clears the surrounding area and clips the plot.
   */
  rects[0].x = rects[0].y = rects[3].x = rects[1].x = 0;
  rects[0].width = rects[3].width = (short int)width_;
  rects[0].height = (short int)top_;
  rects[3].y = bottom_;
  rects[3].height = height_ - bottom_;
  rects[2].y = rects[1].y = top_;
  rects[1].width = left_;
  rects[2].height = rects[1].height = bottom_ - top_;
  rects[2].x = right_;
  rects[2].width = width_ - right_;

  Tk_Fill3DRectangle(tkwin_, drawable, ops->normalBg, 
		     rects[0].x, rects[0].y, rects[0].width, rects[0].height, 
		     0, TK_RELIEF_FLAT);
  Tk_Fill3DRectangle(tkwin_, drawable, ops->normalBg, 
		     rects[1].x, rects[1].y, rects[1].width, rects[1].height, 
		     0, TK_RELIEF_FLAT);
  Tk_Fill3DRectangle(tkwin_, drawable, ops->normalBg, 
		     rects[2].x, rects[2].y, rects[2].width, rects[2].height, 
		     0, TK_RELIEF_FLAT);
  Tk_Fill3DRectangle(tkwin_, drawable, ops->normalBg, 
		     rects[3].x, rects[3].y, rects[3].width, rects[3].height, 
		     0, TK_RELIEF_FLAT);

  /* Draw 3D border around the plotting area */

  if (ops->plotBW > 0) {
    int x, y, w, h;

    x = left_ - ops->plotBW;
    y = top_ - ops->plotBW;
    w = (right_ - left_) + (2*ops->plotBW);
    h = (bottom_ - top_) + (2*ops->plotBW);
    Tk_Draw3DRectangle(tkwin_, drawable, ops->normalBg, 
		       x, y, w, h, ops->plotBW, ops->plotRelief);
  }
  
  switch (legend_->position()) {
  case Legend::TOP:
  case Legend::BOTTOM:
  case Legend::RIGHT:
  case Legend::LEFT:
    legend_->draw(drawable);
    break;
  default:
    break;
  }

  if (ops->title != NULL)
    Blt_DrawText(tkwin_, drawable, ops->title,
		 &ops->titleTextStyle, titleX_, titleY_);

  Blt_DrawAxes(this, drawable);
  flags &= ~DRAW_MARGINS;
}

void Graph::eventuallyRedraw() 
{
  if ((flags & GRAPH_DELETED) || !Tk_IsMapped(tkwin_))
    return;

  if (!(flags & REDRAW_PENDING)) {
    flags |= REDRAW_PENDING;
    Tcl_DoWhenIdle(DisplayGraph, this);
  }
}

static void AdjustAxisPointers(Graph* graphPtr) 
{
  GraphOptions* ops = (GraphOptions*)graphPtr->ops_;
  if (ops->inverted) {
    ops->leftMargin.axes   = graphPtr->axisChain_[0];
    ops->bottomMargin.axes = graphPtr->axisChain_[1];
    ops->rightMargin.axes  = graphPtr->axisChain_[2];
    ops->topMargin.axes    = graphPtr->axisChain_[3];
  }
  else {
    ops->leftMargin.axes   = graphPtr->axisChain_[1];
    ops->bottomMargin.axes = graphPtr->axisChain_[0];
    ops->rightMargin.axes  = graphPtr->axisChain_[3];
    ops->topMargin.axes    = graphPtr->axisChain_[2];
  }
}

// Support

static void UpdateMarginTraces(Graph* graphPtr)
{
  GraphOptions* ops = (GraphOptions*)graphPtr->ops_;
  Margin* marginPtr;
  Margin* endPtr;

  for (marginPtr = ops->margins, endPtr = marginPtr + 4; 
       marginPtr < endPtr; marginPtr++) {
    if (marginPtr->varName != NULL) { /* Trigger variable traces */
      int size;

      if ((marginPtr->site == MARGIN_LEFT) || 
	  (marginPtr->site == MARGIN_RIGHT)) {
	size = marginPtr->width;
      } else {
	size = marginPtr->height;
      }
      Tcl_SetVar(graphPtr->interp_, marginPtr->varName, Blt_Itoa(size), 
		 TCL_GLOBAL_ONLY);
    }
  }
}

/*
 *---------------------------------------------------------------------------
 * Generates a bounding box representing the plotting area of the
 * graph. This data structure is used to clip the points and line
 * segments of the line element.
 * The clip region is the plotting area plus such arbitrary extra space.
 * The reason we clip with a bounding box larger than the plot area is so
 * that symbols will be drawn even if their center point isn't in the
 * plotting area.
 *---------------------------------------------------------------------------
 */

void Blt_GraphExtents(Graph* graphPtr, Region2d *regionPtr)
{
  GraphOptions* ops = (GraphOptions*)graphPtr->ops_;
  regionPtr->left = (double)(graphPtr->hOffset_ - ops->xPad);
  regionPtr->top = (double)(graphPtr->vOffset_ - ops->yPad);
  regionPtr->right = (double)(graphPtr->hOffset_ + graphPtr->hRange_ + 
			      ops->xPad);
  regionPtr->bottom = (double)(graphPtr->vOffset_ + graphPtr->vRange_ + 
			       ops->yPad);
}

void Blt_ReconfigureGraph(Graph* graphPtr)	
{
  graphPtr->configure();
  graphPtr->legend_->configure();
  //  Blt_ConfigureElements(graphPtr);
  Blt_ConfigureAxes(graphPtr);
  Blt::ConfigureMarkers(graphPtr);
}

void Blt_GraphTags(Blt_BindTable table, ClientData object, ClientData context,
		   Blt_List list)
{
  Graph* graphPtr = (Graph*)Blt_GetBindingData(table);
  ClassId classId = (ClassId)(long(context));

  switch (classId) {
  case CID_ELEM_BAR:		
  case CID_ELEM_LINE: 
    {
      Element* elemPtr = (Element*)object;
      ElementOptions* ops = (ElementOptions*)elemPtr->ops();
      MakeTagProc* tagProc = Blt_MakeElementTag;
      Blt_List_Append(list, (const char*)(*tagProc)(graphPtr, elemPtr->name()), 0);
      Blt_List_Append(list, (const char*)(*tagProc)(graphPtr, elemPtr->className()), 0);
      if (ops->tags)
	for (const char** p = ops->tags; *p != NULL; p++)
	  Blt_List_Append(list, (const char*)(*tagProc)(graphPtr, *p), 0);
    }
    break;
  case CID_AXIS_X:
  case CID_AXIS_Y:
    {
      Axis* axisPtr = (Axis*)object;
      AxisOptions* ops = (AxisOptions*)axisPtr->ops();
      MakeTagProc* tagProc = Blt_MakeAxisTag;
      Blt_List_Append(list, (const char*)(*tagProc)(graphPtr, axisPtr->name()), 0);
      Blt_List_Append(list, (const char*)(*tagProc)(graphPtr, axisPtr->className()), 0);
      if (ops->tags)
	for (const char** p = ops->tags; *p != NULL; p++)
	  Blt_List_Append(list, (const char*)(*tagProc)(graphPtr, *p), 0);
    }
    break;
  case CID_MARKER_BITMAP:
  case CID_MARKER_LINE:
  case CID_MARKER_POLYGON:
  case CID_MARKER_TEXT:
  case CID_MARKER_WINDOW:
    {
      Marker* markerPtr = (Marker*)object;
      MarkerOptions* ops = (MarkerOptions*)markerPtr->ops();
      MakeTagProc* tagProc = Blt::MakeMarkerTag;
      Blt_List_Append(list, (const char*)(*tagProc)(graphPtr, markerPtr->name()), 0);
      Blt_List_Append(list, (const char*)(*tagProc)(graphPtr, markerPtr->className()), 0);
      if (ops->tags)
	for (const char** p = ops->tags; *p != NULL; p++)
	  Blt_List_Append(list, (const char*)(*tagProc)(graphPtr, *p), 0);

    }
    break;
  default:
    break;
  }
}

// Find the closest point from the set of displayed elements, searching
// the display list from back to front.  That way, if the points from
// two different elements overlay each other exactly, the one that's on
// top (visible) is picked.
static ClientData PickEntry(ClientData clientData, int x, int y, 
			    ClientData* contextPtr)
{
  Graph* graphPtr = (Graph*)clientData;
  GraphOptions* ops = (GraphOptions*)graphPtr->ops_;

  if (graphPtr->flags & MAP_ALL) {
    *contextPtr = (ClientData)NULL;
    return NULL;
  }

  Region2d exts;
  Blt_GraphExtents(graphPtr, &exts);

  // Sample coordinate is in one of the graph margins. Can only pick an axis.
  if ((x >= exts.right) || (x < exts.left) || 
      (y >= exts.bottom) || (y < exts.top)) {
    Axis* axisPtr = Blt_NearestAxis(graphPtr, x, y);
    if (axisPtr) {
      *contextPtr = (ClientData)axisPtr->classId();
      return axisPtr;
    }
  }

  // From top-to-bottom check:
  // 1. markers drawn on top (-under false).
  // 2. elements using its display list back to front.
  // 3. markers drawn under element (-under true).
  Marker* markerPtr = (Marker*)Blt::NearestMarker(graphPtr, x, y, 0);
  if (markerPtr) {
    *contextPtr = (ClientData)markerPtr->classId();
    return markerPtr;
  }

  ClosestSearch* searchPtr = &ops->search;
  searchPtr->index = -1;
  searchPtr->x = x;
  searchPtr->y = y;
  searchPtr->dist = (double)(searchPtr->halo + 1);
	
  Blt_ChainLink link;
  Element* elemPtr;
  for (link = Blt_Chain_LastLink(graphPtr->elements_.displayList);
       link != NULL; link = Blt_Chain_PrevLink(link)) {
    elemPtr = (Element*)Blt_Chain_GetValue(link);
    if (elemPtr->hide() || (elemPtr->flags & MAP_ITEM))
      continue;

    elemPtr->closest();
  }
  // Found an element within the minimum halo distance.
  if (searchPtr->dist <= (double)searchPtr->halo) {
    *contextPtr = (ClientData)elemPtr->classId();
    return searchPtr->elemPtr;
  }

  markerPtr = (Marker*)Blt::NearestMarker(graphPtr, x, y, 1);
  if (markerPtr) {
    *contextPtr = (ClientData)markerPtr->classId();
    return markerPtr;
  }

  *contextPtr = (ClientData)NULL;
  return NULL;
}