-
Notifications
You must be signed in to change notification settings - Fork 62
/
notebook.cpp
1465 lines (1230 loc) · 43.9 KB
/
notebook.cpp
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
#include "notebook.h"
#include "notebook_clipboard.hpp"
#include "notebook_highlight.hpp"
#include "imagewidgets.h"
#include "notebook_widgets.hpp"
#include <unordered_set>
// #define _DEBUG_MOTION_
#ifdef _DEBUG_MOTION_
#define DMPRINTF(...) printf(__VA_ARGS__);
#else
#define DMPRINTF(...)
#endif
/* list of Gsv syntax highlighting classes that can be rendered as widgets */
std::unordered_map<std::string, std::function<Gtk::Widget *(CNotebook*, Gtk::TextBuffer::iterator, Gtk::TextBuffer::iterator)> >
CNotebook::widget_classes {
{ "checkbox", widgets::RenderCheckbox },
{ "image", widgets::RenderImage },
#if defined (HAVE_LASEM) || defined (HAVE_CLATEXMATH)
{ "latex", widgets::RenderLatex },
#endif
};
CNotebook::CNotebook()
{
last_device=NULL;
}
/* DIRTY HACK: If the layout changes a lot, sometimes GtkTextView will
* get events without it being valid (event race?). This can lead
* to crashes. Therefore, we'll manually check for layout validity
* at the beginning of events. */
extern "C" bool gtk_text_layout_is_valid(void*);
bool CNotebook::on_event(GdkEvent* e)
{
// never block key events, as this can gum up text entry
if(e->type == GDK_KEY_PRESS || e->type == GDK_KEY_RELEASE)
return false;
// but otherwise, do block if the layout is not valid
if(!gtk_text_layout_is_valid(*(void**)GTK_TEXT_VIEW(gobj())->priv)) {
//printf("event %d blocked\n", e->type);
return true;
}
return false;
}
void (*draw_layer_real)(GtkTextView *text_view, GtkTextViewLayer layer, cairo_t *cr);
void notebook_draw_layer(GtkTextView *text_view, GtkTextViewLayer layer, cairo_t *cr)
{
draw_layer_real(text_view,layer,cr);
if(layer == GTK_TEXT_VIEW_LAYER_BELOW) {
CNotebook *nb = (CNotebook*)g_object_get_data(G_OBJECT(text_view), "cppobj");
if(nb) nb->on_redraw_underlay(Cairo::RefPtr<Cairo::Context>(new Cairo::Context(cr,false)));
}
}
/* Initialise notebook widget, loading style files etc. from data_path. */
void CNotebook::Init(std::string data_path, bool use_highlight_proxy)
{
sbuffer = get_source_buffer();
/* load syntax highlighting scheme */
Glib::RefPtr<Gsv::StyleSchemeManager> styleman = Gsv::StyleSchemeManager::create();
styleman->set_search_path({data_path+"/sourceview/"});
Glib::RefPtr<Gsv::StyleScheme> the_scheme;
the_scheme = styleman->get_scheme("notekit");
sbuffer->set_style_scheme(the_scheme);
langman = Gsv::LanguageManager::create();
/* make our custom markdown definition override the system gtksourceview defaults,
* but retain access to them for other language defs */
std::vector<std::string> paths = langman->get_search_path();
paths.insert(paths.begin(),data_path+"/sourceview/");
if(use_highlight_proxy) paths.insert(paths.begin(),GetHighlightProxyDir());
langman->set_search_path(paths);
sbuffer->set_language(langman->get_language("markdown"));
/* register our serialisation formats */
sbuffer->register_serialize_format("text/notekit-markdown", sigc::bind( sigc::mem_fun(this,&CNotebook::on_serialize), false ));
sbuffer->register_deserialize_format("text/notekit-markdown",sigc::mem_fun(this,&CNotebook::on_deserialize));
sbuffer->register_serialize_format("text/plain", sigc::bind( sigc::mem_fun(this,&CNotebook::on_serialize), true ));
Glib::RefPtr<Gtk::TargetList> l = sbuffer->get_copy_target_list();
/* create drawing overlay */
add_child_in_window(overlay,Gtk::TEXT_WINDOW_WIDGET,0,0);
/* define actions that the toolbar will hook up to */
actions = Gio::SimpleActionGroup::create();
#define ACTION(name,param1,param2) actions->add_action(name, sigc::bind( sigc::mem_fun(this,&CNotebook::on_action), std::string(name), param1, param2 ) )
ACTION("cmode-text",NB_ACTION_CMODE,NB_MODE_TEXT);
ACTION("cmode-draw",NB_ACTION_CMODE,NB_MODE_DRAW);
ACTION("cmode-erase",NB_ACTION_CMODE,NB_MODE_ERASE);
ACTION("cmode-select",NB_ACTION_CMODE,NB_MODE_SELECT);
ACTION("stroke1",NB_ACTION_STROKE,1);
ACTION("stroke2",NB_ACTION_STROKE,2);
ACTION("stroke3",NB_ACTION_STROKE,3);
/* connect signals */
signal_size_allocate().connect(sigc::mem_fun(this,&CNotebook::on_allocate));
overlay.signal_draw().connect(sigc::mem_fun(this,&CNotebook::on_redraw_overlay));
signal_button_press_event().connect(sigc::mem_fun(this,&CNotebook::on_button_press),false);
signal_button_release_event().connect(sigc::mem_fun(this,&CNotebook::on_button_release),false);
signal_motion_notify_event().connect(sigc::mem_fun(this,&CNotebook::on_motion_notify),false);
sbuffer->signal_insert().connect(sigc::mem_fun(this,&CNotebook::on_insert),true);
sbuffer->signal_changed().connect(sigc::mem_fun(this,&CNotebook::on_changed),true);
sbuffer->signal_highlight_updated().connect(sigc::mem_fun(this,&CNotebook::on_highlight_updated),true);
sbuffer->property_cursor_position().signal_changed().connect(sigc::mem_fun(this,&CNotebook::on_move_cursor));
/* overwrite clipboard signals with our custom impls */
GtkTextViewClass *k = GTK_TEXT_VIEW_GET_CLASS(gobj());
k->copy_clipboard = notebook_copy_clipboard;
k->cut_clipboard = notebook_cut_clipboard;
k->paste_clipboard = notebook_paste_clipboard;
/* also overwrite layer drawing function */
draw_layer_real = k->draw_layer;
k->draw_layer = notebook_draw_layer;
/* save a pointer to the C++ object so we can call back from the clipboard functions */
g_object_set_data((GObject*)gobj(),"cppobj",this);
/* DIRTY HACK: GtkSourceView's cursor movement methods loop forever in the presence of invisible text sometimes */
GtkWidget *text_view = gtk_text_view_new();
GtkTextViewClass *plain = GTK_TEXT_VIEW_GET_CLASS(text_view);
k->extend_selection = plain->extend_selection;
k->move_cursor = plain->move_cursor;
gtk_widget_destroy(text_view);
//printf("%08lX %08lX",k->extend_selection,GTK_TEXT_VIEW_CLASS(&k->parent_class)->extend_selection);
//k->extend_selection = GTK_TEXT_VIEW_CLASS(&k->parent_class)->extend_selection;
//g_signal_connect(gobj(),"copy-clipboard",G_CALLBACK(notebook_copy_clipboard),NULL);
active_state=NB_STATE_NOTHING;
update_cursor=false;
attention_ewma=0.0;
/* load cursor. Why don't we actually do all the cursor handling here? */
pointer_cursor = Gdk::Cursor::create(Gdk::Display::get_default(),"default");
hand_cursor = Gdk::Cursor::create(Gdk::Display::get_default(),"pointer");
/* create tags for style aspects that the syntax highlighter doesn't handle */
tag_extra_space = sbuffer->create_tag();
tag_extra_space->property_pixels_below_lines().set_value(8);
tag_extra_space->property_pixels_above_lines().set_value(8);
tag_blockquote = sbuffer->create_tag();
tag_blockquote->property_left_margin().set_value(16);
tag_blockquote->property_indent().set_value(-16);
tag_blockquote->property_accumulative_margin().set_value(true);
tag_override_bg = sbuffer->create_tag(); // solid background of widget BG color, overriding underlay
tag_invisible = sbuffer->create_tag(); // foreground = widget BG color
tag_hidden = sbuffer->create_tag();
tag_hidden->property_invisible().set_value(true);
tag_mono = sbuffer->create_tag();
tag_mono->property_family().set_value("monospace");
tag_mono->property_scale().set_value(0.8);
tag_is_anchor=sbuffer->create_tag();
RecalculateColors();
signal_style_updated().connect(sigc::mem_fun(this, &CNotebook::RecalculateColors),true);
/* remember position for proximity widgets */
last_position=sbuffer->create_mark("last_position", sbuffer->begin(),true);
tag_proximity=sbuffer->create_tag();
//use for debug
//tag_proximity->property_background_rgba().set_value(Gdk::RGBA("rgb(255,128,128)"));
set_wrap_mode(Gtk::WRAP_WORD_CHAR);
}
// Calculate colors of tags not handled by the syntax highlighter.
// May be necessary in the event of theme changes.
void CNotebook::RecalculateColors()
{
Gdk::RGBA fg = get_style_context()->get_color();
Gdk::RGBA bg = get_style_context()->get_background_color();
Gdk::RGBA blended;
blended.set_rgba(0.75*fg.get_red()+0.25*bg.get_red(),
0.75*fg.get_green()+0.25*bg.get_green(),
0.75*fg.get_blue()+0.25*bg.get_blue(),
1.0);
tag_blockquote->property_foreground_rgba().set_value(blended);
tag_override_bg->property_background_rgba().set_value(bg);
tag_invisible->property_foreground_rgba().set_value(bg); //Gdk::RGBA("rgba(0,0,0,0)"));
}
void CNotebook::DisableProximityRendering()
{
sbuffer->set_language(langman->get_language("markdown-basic"));
Gtk::TextIter begin = sbuffer->begin(), end = sbuffer->end();
CleanUpSpan(begin,end);
}
void CNotebook::EnableProximityRendering()
{
sbuffer->set_language(langman->get_language("markdown"));
}
bool CNotebook::Find(Glib::ustring text, bool forward, bool skip)
{
Gtk::TextIter st, ed, ins, sel;
ins = sbuffer->get_iter_at_mark(sbuffer->get_insert());
sel = sbuffer->get_iter_at_mark(sbuffer->get_selection_bound());
bool found=false;
if( forward && !skip ) {
if(ins.forward_search(text,Gtk::TEXT_SEARCH_CASE_INSENSITIVE,st,ed)) found=true;
else if(sbuffer->begin().forward_search(text,Gtk::TEXT_SEARCH_CASE_INSENSITIVE,st,ed,ins)) found=true;
} else if(forward && skip) {
if(sel.forward_search(text,Gtk::TEXT_SEARCH_CASE_INSENSITIVE,st,ed)) found=true;
else if(sbuffer->begin().forward_search(text,Gtk::TEXT_SEARCH_CASE_INSENSITIVE,st,ed,sel)) found=true;
} else if(!forward) {
if(ins.backward_search(text,Gtk::TEXT_SEARCH_CASE_INSENSITIVE,st,ed)) found=true;
else if(sbuffer->begin().backward_search(text,Gtk::TEXT_SEARCH_CASE_INSENSITIVE,st,ed,ins)) found=true;
}
if(found) {
sbuffer->select_range(st,ed);
update_prox_to_cursor();
scroll_to(st, 0.1);
}
return found;
}
void CNotebook::SetCursor(Glib::RefPtr<Gdk::Cursor> c)
{
if(auto w=get_window(Gtk::TEXT_WINDOW_TEXT)) w->set_cursor(c);
}
void CNotebook::on_action(std::string name,int type,int param)
{
switch(type) {
case NB_ACTION_CMODE:
devicemodes[last_device]=param;
update_cursor=true;
break;
case NB_ACTION_STROKE:
stroke_width=param;
break;
}
}
void CNotebook::on_allocate(Gtk::Allocation &a)
{
//printf("alloc %d %d\n",a.get_width(),a.get_height());
overlay.size_allocate(a);
if(overlay.get_window()) {
/* if we don't do this, some mystery subset of signals gets eaten */
overlay.get_window()->set_pass_through(true);
// size changed; need to recreate Cairo surface
Cairo::RefPtr<Cairo::Surface> newptr = overlay.get_window()->create_similar_surface(Cairo::CONTENT_COLOR_ALPHA,a.get_width(),a.get_height());
overlay_ctx = Cairo::Context::create(newptr);
// copy old surface
if(overlay_image) {
overlay_ctx->save();
overlay_ctx->set_source(overlay_image,0,0);
overlay_ctx->rectangle(0,0,a.get_width(),a.get_height());
overlay_ctx->set_operator(Cairo::OPERATOR_SOURCE);
overlay_ctx->fill();
overlay_ctx->restore();
}
// replace surface
overlay_image = newptr;
}
}
void CStroke::Render(const Cairo::RefPtr<Cairo::Context> &ctx, float basex, float basey, int start_index)
{
ctx->translate(-basex,-basey);
ctx->set_source_rgba(r,g,b,a);
ctx->set_line_cap(Cairo::LINE_CAP_ROUND);
for(unsigned int i=start_index;i<xcoords.size();++i) {
ctx->move_to(xcoords[i-1],ycoords[i-1]);
ctx->line_to(xcoords[i],ycoords[i]);
ctx->set_line_width(pcoords[i-1]);
ctx->stroke();
}
ctx->translate(basex,basey);
}
void CStroke::RenderSelectionGlow(const Cairo::RefPtr<Cairo::Context> &ctx, float basex, float basey)
{
if(!selected.size()) return;
ctx->translate(-basex,-basey);
ctx->set_source_rgba(r,g,b,a);
ctx->set_line_cap(Cairo::LINE_CAP_ROUND);
for(unsigned int i=1;i<xcoords.size();++i) {
if(selected[i]) {
ctx->move_to(xcoords[i-1],ycoords[i-1]);
ctx->line_to(xcoords[i],ycoords[i]);
ctx->set_line_width(pcoords[i-1]+6);
ctx->stroke();
}
}
ctx->translate(basex,basey);
}
#include <gdk/gdkkeysyms.h>
bool CNotebook::on_key_press_event(GdkEventKey *k)
{
modifier_keys = k->state & (GDK_MODIFIER_MASK);
latest_keyval = k->keyval;
return Gsv::View::on_key_press_event(k);
}
void CNotebook::on_changed()
{
last_modified = g_get_real_time();
}
void CNotebook::on_insert(const Gtk::TextBuffer::iterator &iter,const Glib::ustring& str,int len)
{
if(str=="\n") {
if(modifier_keys & GDK_SHIFT_MASK) return;
if(!iter.ends_line()) return;
/* extract previous line's first word and indentation preceding it */
Gtk::TextBuffer::iterator start = iter; start.backward_line();
Gtk::TextBuffer::iterator end = start;
if(end.get_char()==' ' || end.get_char()=='\t') end.forward_find_char([] (char c) { return (c!=' ' && c!='\t') || c=='\n'; });
end.forward_find_char([] (char c) { return c==' ' || c=='\t' || c=='\n'; });
end.forward_char();
Glib::ustring str = sbuffer->get_text(start,end,true);
end.forward_char();
int num=0,pad=0,len=0;
//printf("word: %s\n",str.c_str());
/* count indentation spaces, then eat them */
sscanf(str.c_str()," %n",&pad);
str=str.substr(pad);
//printf("word: %s\n",str.c_str());
/* try to see if we have any valid markdown enumeration we could extend */
sscanf(str.c_str(),"%d.%*1[ \t]%n",&num,&len);
char buf[512];
if(len==str.length() && num>0) {
if(end >= iter) {
sbuffer->erase(start,iter);
return;
}
sprintf(buf,"%*s%d. ",pad,"",num+1);
sbuffer->insert(iter,buf);
} else if(str=="* ") {
if(end >= iter) {
sbuffer->erase(start,iter);
return;
}
sprintf(buf,"%*s* ",pad,"");
sbuffer->insert(iter,buf);
} else if(str=="- ") {
if(end >= iter) {
sbuffer->erase(start,iter);
return;
}
sprintf(buf,"%*s- ",pad,"");
sbuffer->insert(iter,buf);
} else if(str=="> ") {
if(end == iter) {
sbuffer->erase(start,iter);
return;
}
sprintf(buf,"%*s> ",pad,"");
sbuffer->insert(iter,buf);
}
}
/* TODO: we really should fix up the iterator, but this version of gtkmm erroneously sets iter to const */
}
/* redraw cairo overlay: active stroke, some special widgets, etc. */
bool CNotebook::on_redraw_overlay(const Cairo::RefPtr<Cairo::Context> &ctx)
{
/* it seems that this can theoretically be called before the first on_allocate;
* since we don't know our document view's size yet, we have no choice but to bail */
if(!overlay_image) {
return true;
}
//active.Render(ctx,bx,by);
ctx->set_source(overlay_image,0,0);
ctx->paint();
//ctx->rectangle(0,0,get_width(),get_height());
//ctx->fill();
/* draw selection rect, if there is any */
if(active_state == NB_MODE_SELECT) {
int bx, by;
window_to_buffer_coords(Gtk::TEXT_WINDOW_WIDGET,0,0,bx,by);
ctx->save();
ctx->set_line_width(2.0);
ctx->set_source_rgba(.627,.659,.75,1);
ctx->rectangle(sel_x0-bx,sel_y0-by,sel_x1-sel_x0,sel_y1-sel_y0);
ctx->set_dash(std::valarray<double>({2.0,2.0}),0.0);
ctx->stroke();
ctx->restore();
}
return true;
}
/* redraw widget background: lines, background of code blocks, etc. */
void CNotebook::on_redraw_underlay(const Cairo::RefPtr<Cairo::Context> &ctx)
{
/* redrawing logic may force us to paint some parts of the control before they enter
* the visible region, and we don't get another chance after they do */
double x1,y1,x2,y2;
ctx->get_clip_extents(x1,y1,x2,y2);
int x1b,y1b;
window_to_buffer_coords(Gtk::TEXT_WINDOW_WIDGET,x1,y1,x1b,y1b);
Gdk::Rectangle rect(x1b,y1b,x2-x1,y2-y1),vrect;
get_visible_rect(vrect);
rect.join(vrect);
/* draw horizontal rules */
Gsv::Buffer::iterator i, end;
get_iter_at_location(i,rect.get_x(),rect.get_y());
get_iter_at_location(end,rect.get_x()+rect.get_width(),rect.get_y()+rect.get_height());
do{
if(sbuffer->iter_has_context_class(i, "hline")) {
// TODO?: use computed colours from theme instead of hardcoded
int y, height;
get_line_yrange(i,y,height);
int linex0,liney0;
buffer_to_window_coords(Gtk::TEXT_WINDOW_WIDGET,0,y+height,linex0,liney0);
ctx->set_line_width(1.0);
ctx->set_source_rgba(.627,.659,.75,1);
ctx->move_to(linex0+margin_x,liney0-height/2);
ctx->line_to(linex0+rect.get_width()-margin_x,liney0-height/2);
ctx->stroke();
}
}while(sbuffer->iter_forward_to_context_class_toggle(i, "hline") && i<end);
/* draw code block background */
get_iter_at_location(i,rect.get_x(),rect.get_y());
get_iter_at_location(end,rect.get_x()+rect.get_width(),rect.get_y()+rect.get_height());
// we may have started inside a running code block. Try to find the first relevant end...
auto save_i=i;
sbuffer->iter_forward_to_context_class_toggle(i, "cbend");
if(i<sbuffer->end()) {
// ...and go back to the corresponding beginning, if possible
sbuffer->iter_backward_to_context_class_toggle(i, "cbstart");
sbuffer->iter_backward_to_context_class_toggle(i, "cbstart");
} else i=save_i;
do{
if(sbuffer->iter_has_context_class(i, "cbstart")) {
int y0, height0;
get_line_yrange(i,y0,height0);
int blockx0,blocky0;
buffer_to_window_coords(Gtk::TEXT_WINDOW_WIDGET,0,y0+height0,blockx0,blocky0);
// try to find end of code block
sbuffer->iter_forward_to_context_class_toggle(i, "cbend");
int y1, height1;
get_line_yrange(i,y1,height1);
int blockx1,blocky1;
buffer_to_window_coords(Gtk::TEXT_WINDOW_WIDGET,0,y1+height1,blockx1,blocky1);
/*ctx->set_source_rgba(.627,.659,.75,0.3);
ctx->rectangle(blockx0+margin_x-height0/2,blocky0-height0/2,rect.get_width()-margin_x*2+height0, blocky1-blocky0);
ctx->set_operator(Cairo::OPERATOR_OVER);
ctx->fill();*/
ctx->set_source_rgba(.627,.659,.75,1);
ctx->set_line_width(1.0);
ctx->rectangle(blockx0+margin_x-height0/2,blocky0-height0/2,rect.get_width()-margin_x*2+height0, blocky1-blocky0);
ctx->stroke();
// skip forward to the end of the code block end tag
sbuffer->iter_forward_to_context_class_toggle(i, "cbend");
}
// try jumping forward to the start of the next code block;
}while(sbuffer->iter_forward_to_context_class_toggle(i, "cbstart") && i<end);
}
void CNotebook::SetDocumentPath(std::string newpath)
{
document_path = newpath;
// todo?: rerender all image widgets.
// We can get away without doing that for now, since the document path will only be set before loading.
}
std::string CNotebook::DepositImage(GdkPixbuf *pixbuf)
{
guchar *buf = gdk_pixbuf_get_pixels(pixbuf);
/* walk through the pixbuf buffer, hashing the image pixels. */
/* this convoluted way is necessary because sometimes stride>3*width, and the padding bytes can contain random noise, breaking deduplication. */
int stride = gdk_pixbuf_get_rowstride(pixbuf);
int height = gdk_pixbuf_get_height(pixbuf);
int width = gdk_pixbuf_get_width(pixbuf);
GChecksum *cs = g_checksum_new(G_CHECKSUM_SHA1);
for(int y=0;y<height;++y)
g_checksum_update(cs,buf+y*stride,width);
const gchar *checksum = g_checksum_get_string(cs);
// gchar *checksum = g_compute_checksum_for_data(G_CHECKSUM_SHA1,buf,buf_length);
std::string filename = ".images/"+std::string(checksum,16)+".png";
// workaround for canonicalize_filename not being supported in glibmm<2.64
Glib::RefPtr<Gio::File> file = Glib::wrap(g_file_new_for_commandline_arg_and_cwd(filename.c_str(), document_path.c_str()));
std::string real_path = file->get_path();
Glib::RefPtr<Gio::File> f = Gio::File::create_for_path(document_path+"/.images");
try {
f->make_directory();
} catch(Gio::Error &e) {
// already exists
}
GError *err = NULL;
gdk_pixbuf_save(pixbuf,real_path.c_str(),"png",&err,NULL);
g_checksum_free(cs);
return "![]("+filename+") ";
}
void CNotebook::on_highlight_updated(Gtk::TextBuffer::iterator &start, Gtk::TextBuffer::iterator &end)
{
//printf("relight %d %d\n",start.get_offset(),end.get_offset());
std::pair<Glib::ustring,Glib::RefPtr<Gtk::TextTag> > extratags[]
= { {"extra-space", tag_extra_space},
{"blockquote-text", tag_blockquote},
{"invis", tag_invisible},
{"cbtag", tag_override_bg},
{"mono", tag_mono} };
for(auto &[cclass,ttag] : extratags) {
Gtk::TextBuffer::iterator i = start;
do {
Gtk::TextBuffer::iterator next = i;
if(!sbuffer->iter_forward_to_context_class_toggle(next, cclass)) next=end;
if(sbuffer->iter_has_context_class(i, cclass)) {
sbuffer->apply_tag(ttag, i, next);
} else {
sbuffer->remove_tag(ttag, i, next);
}
i=next;
} while(i<end);
}
/* TODO: this makes some widgets flicker when they shouldn't. */
/* We really shouldn't clean up a span unless it changed,
* but need to solve the *asdf*ghjk* middle * being part of
* both prox tags problem */
/* probably:
* (1) walk the whole region, clear prox tags that no longer
* are overlapped by an exactly matching prox context;
* (2) walk the whole region, instantiate all prox contexts
* that are not already overlapped by an exactly matching
* prox tag.
* This ignores the case that a prox region has been
* EXACTLY replaced by an incompatible one, but whatevs. */
CleanUpSpan(start,end);
Gtk::TextBuffer::iterator i = start;
do {
Gtk::TextBuffer::iterator next = i;
if(!sbuffer->iter_forward_to_context_class_toggle(next, "prox")) next=end;
if(sbuffer->iter_has_context_class(i, "prox")) {
if(!i.has_tag(tag_proximity)) {
/* initialise tag by leaving if necessary */
Gtk::TextIter old_iter = sbuffer->get_iter_at_mark(last_position);
if(old_iter.compare(i)<0 || old_iter.compare(next)>0) {
PushIter(start);
PushIter(end);
on_leave_region(i,next);
end=PopIter();
start=PopIter();
}
}
sbuffer->apply_tag(tag_proximity, i, next);
} else {
/* nothing to do \o/ */
}
i=next;
} while(i<end);
}
Glib::RefPtr<Gtk::TextMark> CNotebook::PushIter(Gtk::TextIter i)
{
iter_stack.push(sbuffer->create_mark(i,true));
return iter_stack.top();
}
Gtk::TextIter CNotebook::PopIter()
{
Glib::RefPtr<Gtk::TextMark> m = iter_stack.top();
iter_stack.pop();
Gtk::TextIter ret = sbuffer->get_iter_at_mark(m);
sbuffer->delete_mark(m);
return ret;
}
void CNotebook::DebugTags(Gtk::TextBuffer::iterator &start, Gtk::TextBuffer::iterator &end)
{
std::map<GtkTextTag*,char> known_tags;
std::map<GtkTextTag*,Glib::ustring> tag_names;
char lastid='A';
for(auto i=start;i<end;++i) {
std::string taglist;
std::vector<Glib::RefPtr<Gtk::TextTag> > tags = i.get_tags();
for(auto &t : tags) {
if(known_tags.count(t->gobj())) {
taglist += known_tags[t->gobj()];
} else {
taglist += lastid;
known_tags[t->gobj()] = lastid++;
tag_names[t->gobj()] = t->property_name().get_value();
}
}
printf("'%lc' %04X %s\n",i.get_char(),i.get_char(),taglist.c_str());
}
}
/* Queue creation of a new child anchor at the position indicated by the mark.
* The deferral may be necessary because insertion invalidates all iterators. */
void CNotebook::QueueChildAnchor(Glib::RefPtr<Gtk::TextMark> mstart)
{
auto s = Glib::IdleSource::create();
s->connect(sigc::slot<bool>( [mstart,this]() {
Gtk::TextIter start = sbuffer->get_iter_at_mark(mstart);
if(!start.get_child_anchor()) {
sbuffer->create_child_anchor(start);
}
/* We may have entered the region between the issuance of the original command
* and the IdleSource being processed, which would result in the second pass
* that is supposed to actually attach the widget not happening.
*
* To prevent this resulting in a displayed [X], start with the anchor hidden. */
start = sbuffer->get_iter_at_mark(mstart);
auto j = start; ++j;
sbuffer->apply_tag(tag_hidden,start,j);
sbuffer->apply_tag(tag_is_anchor,start,j);
sbuffer->delete_mark(mstart);
return false;
}));
s->attach();
}
void CNotebook::RenderToWidget(Glib::ustring wtype, Gtk::TextBuffer::iterator &start, Gtk::TextBuffer::iterator &end)
{
// Debug output if necessary
DMPRINTF("rtw %s: %d, %d \n",wtype.c_str(),start.get_line_offset(),end.get_line_offset());
#ifdef _DEBUG_MOTION_
Gtk::TextBuffer::iterator s1=start, e1=end;
s1.backward_line(); s1.forward_line();
e1.forward_line(); e1.backward_char();
DebugTags(s1,e1);
#endif
Glib::RefPtr<Gtk::TextBuffer::ChildAnchor> anch;
if(!(anch=start.get_child_anchor())) {
/* we haven't set up a child anchor yet, so we need to queue the creation of one */
Glib::RefPtr<Gtk::TextMark> mstart = sbuffer->create_mark(start,true);
/* once the anchor is created, syntax highlighting will recalculate, eventually
* calling this function again from the start */
QueueChildAnchor(mstart);
} else {
auto j = start; ++j;
sbuffer->remove_tag(tag_hidden,start,j);
Gtk::Widget *b = widget_classes[wtype](this, start, end);
Gtk::manage(b);
add_child_at_anchor(*b,anch);
b->show();
}
}
Glib::RefPtr<Gtk::TextTag> CNotebook::GetBaselineTag(int baseline)
{
if(!baseline_tags.count(baseline)) {
auto t = sbuffer->create_tag();
t->property_rise().set_value(-PANGO_SCALE*baseline);
baseline_tags[baseline]=t;
}
return baseline_tags[baseline];
}
void CNotebook::UnrenderWidgets(Gtk::TextBuffer::iterator &start, Gtk::TextBuffer::iterator &end)
{
if(start.get_child_anchor()) {
auto ws = start.get_child_anchor()->get_widgets();
for(Gtk::Widget *w : ws) {
delete w;
}
auto j = start; ++j;
sbuffer->apply_tag(tag_hidden,start,j);
/*PushIter(end);
Gtk::TextBuffer::iterator start_old = start;
++start;
start=sbuffer->erase(start_old,start);
end=PopIter();*/
}
}
/* Remove widget child anchors and proximity-related tags in span. */
void CNotebook::CleanUpSpan(Gtk::TextBuffer::iterator &start, Gtk::TextBuffer::iterator &end)
{
DMPRINTF("start cleaning %d %d\n",start.get_offset(),end.get_offset());
/* PASS 1: Clean any tag_proximity regions that disappeared. */
PushIter(start);
Gtk::TextBuffer::iterator i = start;
do {
Gtk::TextBuffer::iterator next = i;
if(!next.forward_to_tag_toggle(tag_proximity) || next>end) next=end;
Gtk::TextIter ic=next, nextc=i;
sbuffer->iter_backward_to_context_class_toggle(ic,"prox");
sbuffer->iter_forward_to_context_class_toggle(nextc,"prox");
if(i.has_tag(tag_proximity) && (ic!=i || nextc!=next)) {
DMPRINTF("clean old prox region %d %d\n",i.get_offset(),next.get_offset());
std::pair<Glib::ustring,Glib::RefPtr<Gtk::TextTag> > volatile_tags[]
= { {"invisible", tag_hidden} };
for(auto &[cclass,ttag] : volatile_tags) {
sbuffer->remove_tag(ttag, i, next);
}
sbuffer->remove_tag(tag_proximity,i,next);
if(i.get_child_anchor()) {
PushIter(end);
PushIter(next);
next=i;
++next;
start=sbuffer->erase(i,next);
next=PopIter();
end=PopIter();
}
}
i=next;
} while(i<end);
start=PopIter();
/* PASS 2: Clean any leftover internal child anchors from tag_proximity regions that got merged. */
PushIter(start);
i = start;
do {
Gtk::TextBuffer::iterator next = i;
if(!next.forward_to_tag_toggle(tag_is_anchor) || next>end) next=end;
Gtk::TextIter ic=next;
sbuffer->iter_backward_to_context_class_toggle(ic,"prox");
if(i.has_tag(tag_is_anchor) && (ic!=i)) {
DMPRINTF("clean straggler tag %d %d\n",i.get_offset(),next.get_offset());
if(i.get_child_anchor()) {
PushIter(end);
PushIter(next);
next=i;
++next;
start=sbuffer->erase(i,next);
next=PopIter();
end=PopIter();
}
}
i=next;
} while(i<end);
start=PopIter();
}
void CNotebook::on_enter_region(Gtk::TextBuffer::iterator &start, Gtk::TextBuffer::iterator &end)
{
DMPRINTF("enter region: %d %d\n",start.get_offset(),end.get_offset());
std::pair<Glib::ustring,Glib::RefPtr<Gtk::TextTag> > volatile_tags[]
= { {"invisible", tag_hidden} };
for(auto &[cclass,ttag] : volatile_tags) {
sbuffer->remove_tag(ttag, start, end);
}
for(auto &[s,f] : widget_classes) {
if(sbuffer->iter_has_context_class(start, s)) {
UnrenderWidgets(start,end);
}
}
}
void CNotebook::on_leave_region(Gtk::TextBuffer::iterator &start, Gtk::TextBuffer::iterator &end)
{
DMPRINTF("leave region: %d %d\n",start.get_offset(),end.get_offset());
std::pair<Glib::ustring,Glib::RefPtr<Gtk::TextTag> > volatile_tags[]
= { {"invisible", tag_hidden} };
for(auto &[cclass,ttag] : volatile_tags) {
Gtk::TextBuffer::iterator i = start;
do {
Gtk::TextBuffer::iterator next = i;
if(!sbuffer->iter_forward_to_context_class_toggle(next, cclass)) next=end;
if(sbuffer->iter_has_context_class(i, cclass)) {
sbuffer->apply_tag(ttag, i, next);
} else {
sbuffer->remove_tag(ttag, i, next);
}
i=next;
} while(i<end);
}
for(auto &[s,f] : widget_classes) {
if(sbuffer->iter_has_context_class(start, s)) {
UnrenderWidgets(start,end); // just in case
RenderToWidget(s,start,end);
}
}
}
bool GetTagExtents(Gtk::TextIter t, Glib::RefPtr<Gtk::TextTag> tag, Gtk::TextIter &left, Gtk::TextIter &right)
{
if(t.starts_tag(tag)) {
left=t;
t.forward_to_tag_toggle(tag);
right=t;
return true;
}
if(t.ends_tag(tag)) {
right=t;
t.backward_to_tag_toggle(tag);
left=t;
return true;
}
if(t.has_tag(tag)) {
left=t;
left.backward_to_tag_toggle(tag);
right=t;
right.forward_to_tag_toggle(tag);
return true;
}
return false;
}
void CNotebook::on_move_cursor()
{
/* selecting text is mostly frustrating if the text layout
* changes due to hiding/unhiding while doing it */
if(sbuffer->get_has_selection()) return;
update_prox_to_cursor();
}
void CNotebook::update_prox_to_cursor()
{
auto s = Glib::IdleSource::create();
s->connect(sigc::slot<bool>( [this]() {
Gtk::TextIter new_iter = sbuffer->get_iter_at_mark(sbuffer->get_insert());
Gtk::TextIter old_iter = sbuffer->get_iter_at_mark(last_position);
//printf("old: %d, new: %d\n", old_iter.get_offset(), new_iter.get_offset());
/*auto v = new_iter.get_marks();
printf("%d marks here: ",v.size());
for(auto &m : v) printf("%s ",m->get_name().c_str());
printf("\n");*/
Gtk::TextIter old_left, old_right, new_left, new_right;
bool old_valid = GetTagExtents(old_iter,tag_proximity,old_left,old_right);
bool new_valid = GetTagExtents(new_iter,tag_proximity,new_left,new_right);
bool from_right = new_valid && new_iter.compare(new_left)>0//old_iter.compare(new_iter)>0
&& (!latest_keyval || latest_keyval == GDK_KEY_Left ||
latest_keyval == GDK_KEY_Up || latest_keyval == GDK_KEY_Down);
Glib::RefPtr<Gtk::TextMark> move_to;
if(old_valid) {
if(new_valid) {
if(new_iter.compare(old_left)<0 || new_iter.compare(old_right)>0) {
if(from_right) {
if(new_iter.has_tag(tag_hidden)) {
new_iter.forward_to_tag_toggle(tag_hidden);
move_to = sbuffer->create_mark(new_iter,false);
}
}
/* moved into a different prox region. signal both. */
PushIter(new_left);
PushIter(new_right);
on_leave_region(old_left,old_right);
new_right=PopIter();
new_left=PopIter();
on_enter_region(new_left,new_right);
} else if(new_iter==old_iter) {
/* we may have deleted right into a prox region's boundary. signal to be safe. */
DMPRINTF("deletion enter\n");
on_enter_region(new_left,new_right);
}
/* otherwise, we stayed in the same one. no signals needed */
} else {
on_leave_region(old_left,old_right);
}
} else if(new_valid) {
if(from_right) {
if(new_iter.has_tag(tag_hidden)) {
new_iter.forward_to_tag_toggle(tag_hidden);
move_to = sbuffer->create_mark(new_iter,false);
}
}
on_enter_region(new_left,new_right);
}
if(move_to) {
//printf("move right: %d\n",latest_keyval);
Gtk::TextIter t = sbuffer->get_iter_at_mark(move_to);
Gtk::TextIter ins = sbuffer->get_iter_at_mark(sbuffer->get_insert());
Gtk::TextIter sb = sbuffer->get_iter_at_mark(sbuffer->get_mark("selection_bound"));
sbuffer->move_mark_by_name("insert",t);
if(sb==ins) sbuffer->move_mark_by_name("selection_bound",t);
sbuffer->delete_mark(move_to);
/*auto s = Glib::IdleSource::create();
s->connect(sigc::slot<bool>( [move_to,this]() {
Gtk::TextIter t = sbuffer->get_iter_at_mark(move_to);
Gtk::TextIter ins = sbuffer->get_iter_at_mark(sbuffer->get_insert());
Gtk::TextIter sb = sbuffer->get_iter_at_mark(sbuffer->get_mark("selection_bound"));
sbuffer->move_mark_by_name("insert",t);
if(sb==ins) sbuffer->move_mark_by_name("selection_bound",t);
sbuffer->delete_mark(move_to);
return false;
}));
s->attach();*/
}
sbuffer->move_mark(last_position, sbuffer->get_iter_at_mark(sbuffer->get_insert()));//new_iter);
return false;
}));
s->attach();
}
void CNotebook::Widget2Doc(double in_x, double in_y, double &out_x, double &out_y)
{
int bx, by;
window_to_buffer_coords(Gtk::TEXT_WINDOW_WIDGET,0,0,bx,by);
out_x = in_x+bx;
out_y = in_y+by;
}
bool CNotebook::on_button_press(GdkEventButton *e)
{
latest_keyval=0;
GdkDevice *d = gdk_event_get_source_device((GdkEvent*)e);
if(!devicemodes.count(d)) {
if(gdk_device_get_n_axes(d)>4) {
// assume it's a pen
devicemodes[d] = NB_MODE_DRAW;
} else {
devicemodes[d] = NB_MODE_TEXT;
}
}
switch(devicemodes[d]) {
case NB_MODE_TEXT: {
/* click link, unless we were holding CTRL */
if(!(e->state & GDK_CONTROL_MASK)) {
double x,y;
Widget2Doc(e->x,e->y,x,y);
if(IsLinkAt(x,y)) {
signal_link.emit(GetLinkAt(x,y));
return true;
}