-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgtkwrapper.d
1641 lines (1359 loc) · 51.4 KB
/
gtkwrapper.d
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
This file contains the GTK-specific parts of Plot2Kill and is publicly
imported by plot2kill.figure if compiled with GtkD.
Note: The functions that need GTK to be initialized for their use automatically
call gtk.Main.initCheck() to provide sane default initialization. This
is for convenience in programs that throw up a few simple plots and
otherwise don't have a GUI. If gtk.Main.init() is called before
calling any function in this module that requires GTK to be initialized,
the first call's settings take precedence and the calls from this
module have no effect.
Copyright (C) 2010-2011 David Simcha
License:
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
module plot2kill.gtkwrapper;
version(dfl) {
} else {
import plot2kill.util;
import plot2kill.guiagnosticbase;
import plot2kill.subplot;
import plot2kill.figure;
import plot2kill.plot;
alias std.string.CaseSensitive CaseSensitive;
static import std.file;
import gdk.Color, gdk.GC, gtk.Widget, gdk.Drawable, gtk.DrawingArea,
gtk.MainWindow, gtk.Main, gdk.Window, gtk.Container, gtk.Window,
gdk.Pixbuf, gdk.Pixmap, gtkc.all, gtk.FileChooserDialog, gtk.Dialog,
gtk.FileFilter, gobject.ObjectG, cairo.Context, cairo.FontFace,
gtkc.cairotypes, cairo.PdfSurface, cairo.SvgSurface,
cairo.PostScriptSurface, cairo.Surface, cairo.ImageSurface,
gtk.FileSelection, gtk.MessageDialog, gtk.Menu, gtk.MenuItem,
gtk.Entry, gtk.HBox, gtk.Label, gtk.FontSelectionDialog, gtk.RadioButton,
gtk.HSeparator, gtk.CheckButton, gtk.SeparatorMenuItem, gtkc.gtk;
// Default initialize GTK.
package void defaultInit() {
string[] args;
Main.initCheck(args);
}
/**GTK's implementation of a color object.*/
struct Color {
ubyte r;
ubyte g;
ubyte b;
}
/**Holds context for drawing lines.*/
struct Pen {
Color color;
double lineWidth;
}
/**Holds context for drawing rectangles.*/
struct Brush {
Color color;
}
///
struct Point {
///
int x;
///
int y;
}
///
struct Rect {
///
int x;
///
int y;
///
int width;
///
int height;
}
///
struct Size {
///
int width;
///
int height;
}
/**Holds font information.*/
alias cairo.FontFace.FontFace font;
/**Get a color in a GUI framework-agnostic way.*/
Color getColor(ubyte red, ubyte green, ubyte blue) {
return Color(red, green, blue);
}
/**Get a font in a GUI framework-agnostic way.*/
struct Font {
FontFace face;
string name;
double size;
}
Font getFont(string fontName, double size) {
auto slant = (fontName.indexOf("oblique", CaseSensitive.no) > -1) ?
cairo_font_slant_t.OBLIQUE : cairo_font_slant_t.NORMAL;
auto weight = (fontName.indexOf("bold", CaseSensitive.no) > -1) ?
cairo_font_weight_t.BOLD : cairo_font_weight_t.NORMAL;
return Font(
Context.toyFontFaceCreate(
fontName,
slant,
weight
), fontName, size
);
}
///
enum TextAlignment {
///
Left = 0,
///
Center = 1,
///
Right = 2
}
// This calls the relevant lib's method of cleaning up the given object, if
// any.
void doneWith(T)(T garbage) {
static if(is(T : gdk.GC.GC) || is(T : gdk.Pixmap.Pixmap) ||
is(T : gdk.Pixbuf.Pixbuf)) {
// Most things seem to manage themselves fine, but these objects
// leak like a seive.
garbage.unref();
// Since we're already in here be dragons territory, we may as well:
core.memory.GC.free(cast(void*) garbage);
} else static if(is(T : cairo.Context.Context) || is(T : cairo.Surface.Surface)) {
static if(is(T : cairo.Surface.Surface)) {
garbage.finish();
}
//garbage.destroy();
}
}
/**The base class for both FigureBase and Subplot. Holds common functionality
* like saving and text drawing.
*/
abstract class FigureBase : GuiAgnosticBase {
private:
enum ubyteMax = cast(double) ubyte.max;
// See drawLine() for an explanation of these variables.
PlotPoint[] prevLine;
Pen lastLinePen;
void saveImplPixmap
(string filename, string type, double width, double height) {
plot2kill.gtkwrapper.defaultInit();
int w = roundTo!int(width);
int h = roundTo!int(height);
auto pixmap = new Pixmap(null, w, h, 24);
scope(exit) doneWith(pixmap);
auto c = new Context(pixmap);
scope(exit) doneWith(c);
this.drawTo(c, PlotRect(0, 0, w, h));
auto pixbuf = new Pixbuf(pixmap, 0, 0, w, h);
scope(exit) doneWith(pixbuf);
int result = pixbuf.savev(filename, type, null, null);
enforce(result, "File not saved successfully.");
}
void saveImplSurface
(string filename, string type, double width, double height) {
Surface surf;
switch(type) {
case "pdf":
surf = PdfSurface.create(filename, width, height);
break;
case "eps":
surf = PostScriptSurface.create(filename, width, height);
break;
case "svg":
surf = SvgSurface.create(filename, width, height);
break;
case "png":
surf = ImageSurface.create(cairo_format_t.RGB24,
roundTo!int(width), roundTo!int(height));
break;
default:
enforce(0, "Invalid file format: " ~ type);
}
enforce(surf, "Couldn't save file because surface couldn't be created.");
auto context = Context.create(surf);
this.drawTo(context, PlotRect(0,0, width, height));
surf.flush();
if(type == "png") {
// So sue me for the cast.
auto result = (cast(ImageSurface) surf).writeToPng(filename);
enforce(result == cairo_status_t.SUCCESS, text(
"Unsuccessfully wrote png. Error: ", result));
}
// This should really be a scope(exit) but using scope(exit) instead
// of putting this line down here segfaults on Linux 64 for reasons
// I don't understand.
surf.finish();
}
void saveImplSvgz(string filename, double width, double height) {
// An svgz file is just an SVG that's been compressed with gzip.
static extern(C) cairo_status_t
writeFunc(void* gzVoid, ubyte* dataPtr, uint len) {
uchar[] data = dataPtr[0..len];
auto gz = cast(Gzip*) gzVoid;
gz.addData(data);
return cairo_status_t.SUCCESS;
}
auto gz = Gzip(filename);
scope(exit) gz.finish();
auto surf = SvgSurface.createForStream
(&writeFunc, cast(void*) &gz, width, height);
scope(exit) doneWith(surf);
auto context = Context.create(surf);
scope(exit) doneWith(context);
this.drawTo(context, PlotRect(0,0, width, height));
surf.flush();
}
void finishLine() {
if(!prevLine.length) return;
assert(prevLine.length > 1);
context.save();
scope(exit) context.restore();
context.newPath();
auto c = lastLinePen.color;
context.setSourceRgb(c.r / ubyteMax, c.g / ubyteMax, c.b / ubyteMax);
context.setLineWidth(lastLinePen.lineWidth);
// If we're joining lines, it's always on a LineGraph or something,
// where miter creates weird artifacts. Bevel looks best.
context.setLineJoin(cairo_line_join_t.BEVEL);
context.moveTo(prevLine.front.x + xOffset, prevLine.front.y + yOffset);
foreach(i; 1..prevLine.length) {
auto point = prevLine[i];
context.lineTo(point.x + xOffset, point.y + yOffset);
}
context.stroke();
prevLine.length = 0;
assumeSafeAppend(prevLine);
}
protected:
// Fonts tend to be different actual sizes on different GUI libs for a
// given nominal size. This adjusts for that factor when setting default
// fonts.
enum fontSizeAdjust = 0;
Context context;
public:
// These are undocumented FOR A REASON: They aren't part of the public
// API, but package is so broken it's not usable. All this stuff w/o
// ddoc should only be messed with if you're a developer of this lib,
// not if you want to use it as a black box.
final void drawLine
(Pen pen, double startX, double startY, double endX, double endY) {
/* HACK ALERT: The front end to this library is designed for each line
* to be drawn as a discrete unit, but for line joining purposes,
* lines need to be drawn in a single path in Cairo. Therefore,
* we save stuff here and only draw it when moving to a new continuous
* line.
*/
if(prevLine.length > 0) {
if(startX != prevLine.back.x || startY != prevLine.back.y
|| pen != lastLinePen) {
finishLine();
}
}
// This can change by calling finishLine(). Need to check it again
// instead of just using an else block.
if(prevLine.length == 0) {
prevLine ~= PlotPoint(startX, startY);
lastLinePen = pen;
}
prevLine ~= PlotPoint(endX, endY);
}
final void drawLine(Pen pen, PlotPoint start, PlotPoint end) {
this.drawLine(pen, start.x, start.y, end.x, end.y);
}
final void drawRectangle
(Pen pen, double x, double y, double width, double height) {
context.save();
scope(exit) context.restore();
context.newPath();
auto c = pen.color;
context.setSourceRgb(c.r / ubyteMax, c.g / ubyteMax, c.b / ubyteMax);
context.setLineWidth(pen.lineWidth);
context.rectangle(x + xOffset, y + yOffset, width, height);
context.stroke();
}
final void drawRectangle(Pen pen, Rect r) {
this.drawRectangle(pen, r.x, r.y, width, height);
}
final void fillRectangle
(Brush brush, double x, double y, double width, double height) {
context.save();
scope(exit) context.restore();
context.newPath();
auto c = brush.color;
enum ubyteMax = cast(double) ubyte.max;
context.setSourceRgb(c.r / ubyteMax, c.g / ubyteMax, c.b / ubyteMax);
context.rectangle(x + xOffset, y + yOffset, width, height);
context.fill();
}
final void fillRectangle(Brush brush, Rect r) {
this.fillRectangle(brush, r.x, r.y, r.width, r.height);
}
final void drawText(
string text,
Font font,
Color pointColor,
PlotRect rect,
TextAlignment alignment
) {
context.save();
scope(exit) context.restore();
context.newPath();
drawTextCurrentContext(text, font, pointColor, rect, alignment);
}
final void drawTextCurrentContext(
string text,
Font font,
Color pointColor,
PlotRect rect,
TextAlignment alignment
) {
alias rect r; // save typing
auto measurements = measureText(text, font);
// The height added by stuff below the baseline for letters like "g"
// and "y" throws off aligning text vertically. Use the height of
// "A", which is a tall letter with nothing below baseline, to
// figure out where to start writing.
immutable standardLetterHeight = measureText("A", font).height;
if(measurements.width > rect.width) {
alignment = TextAlignment.Left;
}
if(alignment == TextAlignment.Left) {
r = PlotRect(
r.x,
r.y + standardLetterHeight,
r.width,
r.height
);
} else if(alignment == TextAlignment.Center) {
r = PlotRect(
r.x + (r.width - measurements.width) / 2,
r.y + standardLetterHeight,
r.width, r.height
);
} else if(alignment == TextAlignment.Right) {
r = PlotRect(
r.x + (r.width - measurements.width),
r.y + standardLetterHeight,
r.width, r.height
);
} else {
assert(0);
}
//context.rectangle(r.x, r.y - measurements.height, r.width, r.height);
//context.clip();
context.setFontSize(font.size);
context.setFontFace(font.face);
alias pointColor c;
context.setSourceRgb(c.r / ubyteMax, c.g / ubyteMax, c.b / ubyteMax);
context.setLineWidth(0.5);
context.moveTo(r.x + xOffset, r.y + yOffset);
context.textPath(text);
context.fill();
}
final void drawText(
string text,
Font font,
Color pointColor,
PlotRect rect
) {
drawText(text, font, pointColor, rect, TextAlignment.Left);
}
final void drawRotatedText(
string text,
Font font,
Color pointColor,
PlotRect rect,
TextAlignment alignment
) {
context.save();
scope(exit) context.restore;
context.newPath();
alias rect r; // save typing
auto measurements = measureText(text, font);
// The height added by stuff below the baseline for letters like "g"
// and "y" throws off aligning text vertically. Use the height of
// "A", which is a tall letter with nothing below baseline, to
// figure out where to start writing.
immutable standardLetterHeight = measureText("A", font).height;
immutable slack = rect.height - measurements.width;
if(slack < 0) {
alignment = TextAlignment.Left;
}
if(alignment == TextAlignment.Left) {
r = PlotRect(
r.x + standardLetterHeight,
r.y + r.height,
r.width,
r.height
);
} else if(alignment == TextAlignment.Center) {
r = PlotRect(
r.x + standardLetterHeight,
r.y + r.height - slack / 2,
r.width, r.height
);
} else if(alignment == TextAlignment.Right) {
r = PlotRect(
r.x + standardLetterHeight,
r.y + r.height - slack,
r.width, r.height
);
} else {
assert(0);
}
//context.rectangle(r.x, r.y - measurements.height, r.width, r.height);
//context.clip();
context.setFontSize(font.size);
context.setFontFace(font.face);
alias pointColor c;
context.setSourceRgb(c.r / ubyteMax, c.g / ubyteMax, c.b / ubyteMax);
context.setLineWidth(0.5);
context.moveTo(r.x + xOffset, r.y + yOffset);
context.rotate(PI * 1.5);
context.textPath(text);
context.fill();
}
final void drawRotatedText(
string text,
Font font,
Color pointColor,
PlotRect rect
) {
drawRotatedText(text, font, pointColor, rect, TextAlignment.Left);
}
// BUGS: Ignores maxWidth.
final PlotSize measureText
(string text, Font font, double maxWidth, TextAlignment alignment) {
return measureText(text, font);
}
// BUGS: Ignores maxWidth.
final PlotSize measureText(string text, Font font, double maxWidth) {
return measureText(text, font);
}
final PlotSize measureText(string text, Font font) {
context.save();
scope(exit) context.restore();
context.setLineWidth(1);
context.setFontSize(font.size);
context.setFontFace(font.face);
cairo_text_extents_t ext;
context.textExtents(text, &ext);
return PlotSize(ext.width, ext.height);
}
// TODO: Add support for stuff other than solid brushes.
/*Get a brush in a GUI framework-agnostic way.*/
static Brush getBrush(Color color) {
return Brush(color);
}
/*Get a pen in a GUI framework-agnostic way.*/
static Pen getPen(Color color, double width = 1) {
return Pen(color, width);
}
void drawTo(Context context) {
drawTo(context, this.width, this.height);
}
void drawTo(Context context, double width, double height) {
return drawTo(context, PlotRect(0, 0, width, height));
}
// Allows drawing at an offset from the origin.
void drawTo(Context context, PlotRect whereToDraw) {
enforceSane(whereToDraw);
// Save the default class-level values, make the values passed in the
// class-level values, call drawImpl(), then restore the default values.
auto oldContext = this.context;
auto oldWidth = this._width;
auto oldHeight = this._height;
auto oldXoffset = this.xOffset;
auto oldYoffset = this.yOffset;
scope(exit) {
this.context = oldContext;
this._height = oldHeight;
this._width = oldWidth;
this.xOffset = oldXoffset;
this.yOffset = oldYoffset;
}
this.context = context;
this._width = whereToDraw.width;
this._height = whereToDraw.height;
this.xOffset = whereToDraw.x;
this.yOffset = whereToDraw.y;
drawImpl();
finishLine();
}
/**Saves this figure to a file. The file type can be one of either the
* raster formats .png, .jpg, .tiff, and .bmp, or the vector formats
* .pdf, .svg and .eps. The width and height parameters allow you to
* specify explicit width and height parameters for the image file. If
* width and height are left at their default values
* of 0, the default width and height of the subclass being saved will
* be used.
*
* Bugs: .jpg, .tiff and .bmp formats rely on Pixmap objects, meaning
* you can't save them to a file unless you have a screen and
* have called Main.init(), even though saving should have
* nothing to do with X or screens.
*/
void saveToFile
(string filename, string type, double width = 0, double height = 0) {
// User friendliness: Remove . if it was included, don't be case sens.
type = toLower(type);
if(!type.empty && type.front == '.') {
type.popFront();
}
if(type == "jpg") {
type = "jpeg";
}
if(width == 0 || height == 0) {
width = this.defaultWindowWidth;
height = this.defaultWindowHeight;
}
if(type == "eps" || type == "pdf" || type == "svg" || type == "png") {
return saveImplSurface(filename, type, width, height);
} else if(type == "svgz") {
return saveImplSvgz(filename, width, height);
} else {
enforce(type == "tiff" || type == "bmp" || type == "jpeg",
"Invalid format: " ~ type);
return saveImplPixmap(filename, type, width, height);
}
}
/**Convenience function that infers the type from the filename extenstion
* and defaults to .png if no valid file format extension is found.
*/
void saveToFile(string filename, double width = 0, double height = 0) {
auto type = toLower(extensionNoDot(filename));
try {
saveToFile(filename, type, width, height);
} catch {
// Default to png.
saveToFile(filename, "png", width, height);
}
}
/**Creates a Widget that will have this object drawn to it. This Widget
* can be displayed in a window.
*/
FigureWidget toWidget() {
defaultInit();
return new FigureWidget(this);
}
/**Draw and display the figure as a main form. This is useful in
* otherwise console-based apps that want to display a few plots.
* However, you can't have another main form up at the same time.
*/
void showAsMain() {
auto mw = new DefaultPlotWindow!(MainWindow)(this.toWidget);
Main.run();
}
/**Returns a default plot window with this figure in it.*/
gtk.Window.Window getDefaultWindow() {
return new DefaultPlotWindow!(gtk.Window.Window)(this.toWidget);
}
}
// Used for scatter plots. Efficiently draws a single character in a lot of
// places, centered on a point. ASSUMPTION: No drawing commands not related
// to drawing scatter plot points are issued between when initialize()
// and reset() are called.
package struct ScatterCharDrawer {
private:
string str;
PlotSize halfMeasurements;
Figure fig;
Font font;
float red, green, blue;
public:
this(dchar c, Font font, Color color, Figure fig) {
str = to!string(c);
this.fig = fig;
this.font = font;
red = color.r / cast(float) ubyte.max;
green = color.g / cast(float) ubyte.max;
blue = color.b / cast(float) ubyte.max;
auto measurements = fig.measureText(str, font);
halfMeasurements = PlotSize(measurements.width / 2,
measurements.height / 2);
}
void draw(PlotPoint where) {
with(fig) {
if(!insideAxes(where)) return;
context.moveTo(where.x + xOffset - halfMeasurements.width,
where.y + yOffset + halfMeasurements.height);
context.textPath(str);
context.fill();
}
}
// Initialize the Cairo context to the settings we need.
void initialize() {
with(fig) {
context.save();
// Set up a clip region.
context.moveTo(leftMargin + xOffset, topMargin + yOffset);
context.lineTo(leftMargin + xOffset,
fig.height - bottomMargin + yOffset);
context.lineTo(fig.width - rightMargin + xOffset,
fig.height - bottomMargin + yOffset);
context.lineTo(fig.width - rightMargin + xOffset,
topMargin + yOffset);
context.lineTo(leftMargin + xOffset, topMargin + yOffset);
context.clip();
context.setFontSize(font.size);
context.setFontFace(font.face);
context.setSourceRgb(red, green, blue);
context.setLineWidth(0.5);
}
}
// Restore the Cairo context to the old settings.
void restore() {
fig.context.restore();
}
}
/*
This class allows a legend symbol to be drawn in a small area. This really
needs to be refactored to separate the GUI wrapping code from FigureBase,
but I'm too lazy to do it for now.
*/
private class LegendSymbolDrawer : FigureBase {
Plot plot;
this(Plot plot) {
this._width = legendSymbolSize;
this._height = legendSymbolSize;
this.plot = plot;
}
override void drawImpl() {
try {
auto rect = Rect(0, 0, legendSymbolSize, legendSymbolSize);
auto prect = PlotRect(0, 0, legendSymbolSize, legendSymbolSize);
auto brush = getBrush(getColor(255, 255, 255));
scope(exit) doneWith(brush);
fillRectangle(brush, rect);
plot.drawLegendSymbol(this, prect);
} catch(Exception) {
// Legend not implemented for plot type. This is ok to ignore.
}
}
override int defaultWindowWidth() { return legendSymbolSize; }
override int defaultWindowHeight() { return legendSymbolSize; }
override int minWindowWidth() { return legendSymbolSize; }
override int minWindowHeight() { return legendSymbolSize; }
}
/**The default widget for displaying Figure and Subplot objects on screen.
* This class has no public constructor or static factory method because the
* proper way to instantiate this object is via the toWidget properties
* of FigureBase and Subplot.
*/
class FigureWidget : DrawingArea {
private:
FigureBase _figure;
package:
this(FigureBase fig) {
super();
this._figure = fig;
this.addOnExpose(&onDrawingExpose);
this.setSizeRequest(fig.minWindowWidth, fig.minWindowHeight);
}
bool onDrawingExpose(GdkEventExpose* event, Widget drawingArea) {
draw();
return true;
}
void draw(double w, double h) {
enforce(getParent() !is null, this.classinfo.name);
auto context = new Context(getWindow());
scope(exit) doneWith(context);
figure.drawTo(context, w, h);
}
public:
/**Get the underlying FigureBase object.*/
final FigureBase figure() @property {
return _figure;
}
/**If set as an addOnSizeAllocate callback, this will resize this control
* to the size of its parent window when the parent window is resized.
*/
void parentSizeChanged(GtkAllocation* alloc, Widget widget) {
if(this.getWidth != alloc.width || this.getHeight != alloc.height) {
this.setSizeRequest(alloc.width, alloc.height);
}
}
/**Draw the figure to the internal drawing area.*/
final void draw() {
draw(this.getWidth, this.getHeight);
}
}
// Convenience subclass of Dialog that has the entries for title, xlabel
// and ylabel available in a way that's actually easy to get to. Also
// encapsulates the building code.
private class LabelDialog : Dialog {
Entry titleEntry, xLabelEntry, yLabelEntry;
this(FigureWidget widget) {
super();
setTitle("Labels");
auto content = this.getContentArea();
auto fb = widget.figure;
auto sp = cast(Subplot) fb;
if(sp) {
auto zoomed = sp.zoomedFigure;
if(zoomed) fb = zoomed;
}
// For some reason GTK complains about null text. Fix it here.
static string fixNull(string s) {
return (s.length == 0) ? "\0" : s;
}
titleEntry = new Entry(
fixNull(fb.title())
);
xLabelEntry = new Entry(
fixNull(fb.xLabel())
);
yLabelEntry = new Entry(
fixNull(fb.yLabel())
);
titleEntry.setActivatesDefault(1);
xLabelEntry.setActivatesDefault(1);
yLabelEntry.setActivatesDefault(1);
auto titleBox = new HBox(0, 5);
titleBox.add(new Label("Title "));
titleBox.add(titleEntry);
auto xLabelBox = new HBox(0, 5);
xLabelBox.add(new Label("X Label"));
xLabelBox.add(xLabelEntry);
auto yLabelBox = new HBox(0, 5);
yLabelBox.add(new Label("Y Label"));
yLabelBox.add(yLabelEntry);
content.add(titleBox);
content.add(xLabelBox);
content.add(yLabelBox);
this.addButtons([StockID.OK, StockID.CANCEL],
[GtkResponseType.OK,
GtkResponseType.CANCEL]
);
this.setDefaultResponse(GtkResponseType.OK);
this.setResizable(0);
}
}
private class ZoomDialog : Dialog {
Entry topEntry, bottomEntry, leftEntry, rightEntry;
this(Figure fig) {
super();
setTitle("Zoom");
auto content = this.getContentArea();
topEntry = new Entry(to!string(fig.topMost));
bottomEntry = new Entry(to!string(fig.bottomMost));
leftEntry = new Entry(to!string(fig.leftMost));
rightEntry = new Entry(to!string(fig.rightMost));
topEntry.setActivatesDefault(1);
bottomEntry.setActivatesDefault(1);
leftEntry.setActivatesDefault(1);
rightEntry.setActivatesDefault(1);
auto topBox = new HBox(0, 5);
topBox.add(new Label("Y Max"));
topBox.add(topEntry);
auto bottomBox = new HBox(0, 5);
bottomBox.add(new Label("Y Min"));
bottomBox.add(bottomEntry);
auto leftBox = new HBox(0, 5);
leftBox.add(new Label("X Min"));
leftBox.add(leftEntry);
auto rightBox = new HBox(0, 5);
rightBox.add(new Label("X Max"));
rightBox.add(rightEntry);
content.add(leftBox);
content.add(rightBox);
content.add(bottomBox);
content.add(topBox);
this.addButtons([StockID.OK, StockID.CANCEL],
[GtkResponseType.OK,
GtkResponseType.CANCEL]
);
this.setDefaultResponse(GtkResponseType.OK);
this.addButtons(["Default"], [cast(GtkResponseType) 1]);
this.setResizable(0);
}
}
private class LegendDialog : Dialog {
Entry[] entries;
RadioButton topRadio, bottomRadio, leftRadio,rightRadio;
this(Figure fig) {
super();
setTitle("Legend");
auto content = this.getContentArea();
content.add(new Label("Position"));
auto posBox1 = new HBox(1, 5);
auto posBox2 = new HBox(1, 5);
topRadio = new RadioButton("Top");
bottomRadio = new RadioButton(topRadio, "Bottom");
leftRadio = new RadioButton(topRadio, "Left");
rightRadio = new RadioButton(topRadio, "Right");
final switch(fig.legendLocation()) {
case LegendLocation.left:
leftRadio.setActive(1);
break;
case LegendLocation.right:
rightRadio.setActive(1);
break;
case LegendLocation.top:
topRadio.setActive(1);
break;
case LegendLocation.bottom:
bottomRadio.setActive(1);
break;
}
posBox1.add(topRadio);
posBox1.add(bottomRadio);
posBox2.add(leftRadio);
posBox2.add(rightRadio);
content.add(posBox1);
content.add(posBox2);
content.add(new HSeparator);
foreach(plot; fig.plotData) if(plot.hasLegend()) {
auto symbolDrawer = new LegendSymbolDrawer(plot);
auto widget = new FigureWidget(symbolDrawer);
auto ltext = plot.legendText();
if(!ltext.length) ltext = "\0";
auto box = new HBox(0, 5);
box.add(widget);