/
gcb-plugin.c
1750 lines (1480 loc) · 52.8 KB
/
gcb-plugin.c
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
/*
*
* Copyright (C) 2014 Colomban Wendling <ban@herbesfolles.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include <string.h>
#include <glib.h>
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <gtk/gtk.h>
#include <git2.h>
#include <geanyplugin.h>
#include <geany.h>
#include <document.h>
#ifdef LIBGIT2_VER_MINOR
# define CHECK_LIBGIT2_VERSION(MAJOR, MINOR) \
((LIBGIT2_VER_MAJOR == (MAJOR) && LIBGIT2_VER_MINOR >= (MINOR)) || \
LIBGIT2_VER_MAJOR > (MAJOR))
#else /* ! defined(LIBGIT2_VER_MINOR) */
# define CHECK_LIBGIT2_VERSION(MAJOR, MINOR) 0
#endif
#if ! CHECK_LIBGIT2_VERSION(0, 22)
# define git_libgit2_init git_threads_init
# define git_libgit2_shutdown git_threads_shutdown
#endif
#if ! CHECK_LIBGIT2_VERSION(0, 23)
/* 0.23 added @p binary_cb */
# define git_diff_buffers(old_buffer, old_len, old_as_path, \
new_buffer, new_len, new_as_path, options, \
file_cb, binary_cb, hunk_cb, line_cb, payload) \
git_diff_buffers (old_buffer, old_len, old_as_path, \
new_buffer, new_len, new_as_path, options, \
file_cb, hunk_cb, line_cb, payload)
#endif
#if ! CHECK_LIBGIT2_VERSION(0, 28)
# define git_buf_dispose git_buf_free
# define git_error_last giterr_last
#endif
#if ! CHECK_LIBGIT2_VERSION(0, 99)
# define git_diff_options_init git_diff_init_options
#endif
GeanyPlugin *geany_plugin;
GeanyData *geany_data;
PLUGIN_VERSION_CHECK(224)
PLUGIN_SET_TRANSLATABLE_INFO (
LOCALEDIR, GETTEXT_PACKAGE,
_("Git Change Bar"),
_("Highlights uncommitted changes in files tracked with Git"),
"0.1",
"Colomban Wendling <ban@herbesfolles.org>"
)
/* g_async_queue_push() doesn't allow for NULL data, so use a non-NULL fake
* data that we know cannot ever be a valid job */
#define QUIT_THREAD_JOB ((AsyncBlobContentsJob *) (&G_queue))
#define RESOURCES_ALLOCATED_QTAG \
(g_quark_from_string (PLUGIN"/git-resources-allocated"))
#define UNDO_LINE_QTAG \
(g_quark_from_string (PLUGIN"/git-undo-line"))
#define DOC_ID_QTAG \
(g_quark_from_string (PLUGIN"/git-doc-id"))
#define REMOVED_MARKER_POS(pos) \
((pos) == 0 ? 0 : (pos) - 1)
enum {
MARKER_LINE_ADDED,
MARKER_LINE_CHANGED,
MARKER_LINE_REMOVED,
MARKER_COUNT
};
enum {
KB_GOTO_PREV_HUNK,
KB_GOTO_NEXT_HUNK,
KB_UNDO_HUNK,
KB_COUNT
};
typedef void (*BlobContentsReadyFunc) (const gchar *path,
git_buf *buf,
gpointer data);
typedef struct AsyncBlobContentsJob AsyncBlobContentsJob;
struct AsyncBlobContentsJob {
gboolean force;
guint tag;
gchar *path;
git_buf buf;
BlobContentsReadyFunc callback;
gpointer user_data;
};
typedef struct TooltipHunkData TooltipHunkData;
struct TooltipHunkData {
gint line;
gboolean found;
GeanyDocument *doc;
const git_buf *buf;
GtkTooltip *tooltip;
};
#define TOOLTIP_HUNK_DATA_INIT(line, doc, buf, tooltip) \
{ line, FALSE, doc, buf, tooltip }
typedef struct GotoNextHunkData GotoNextHunkData;
struct GotoNextHunkData {
guint kb;
guint doc_id;
gint line;
gint next_line;
};
typedef struct UndoHunkData UndoHunkData;
struct UndoHunkData {
guint doc_id;
gint line;
gboolean found;
gint old_start;
gint old_lines;
gint new_start;
gint new_lines;
};
static void on_git_repo_changed (GFileMonitor *monitor,
GFile *file,
GFile *other_file,
GFileMonitorEvent event_type,
gpointer force);
static gboolean on_sci_query_tooltip (GtkWidget *widget,
gint x,
gint y,
gboolean keyboard_mode,
GtkTooltip *tooltip,
gpointer user_data);
static void read_setting_color (GKeyFile *kf,
const gchar *group,
const gchar *key,
gpointer value);
static void write_setting_color (GKeyFile *kf,
const gchar *group,
const gchar *key,
gconstpointer value);
static void read_setting_boolean (GKeyFile *kf,
const gchar *group,
const gchar *key,
gpointer value);
static void write_setting_boolean (GKeyFile *kf,
const gchar *group,
const gchar *key,
gconstpointer value);
/* cache */
static git_buf G_blob_contents = { 0 };
static guint G_blob_contents_tag = 0;
/* global state */
static GAsyncQueue *G_queue = NULL;
static GThread *G_thread = NULL;
static gulong G_source_id = 0;
static gboolean G_monitoring_enabled = TRUE;
static GtkWidget *G_undo_menu_item = NULL;
static struct {
gint num;
gint style;
guint32 color;
} G_markers[MARKER_COUNT] = {
{ -1, SC_MARK_LEFTRECT, 0x73d216 },
{ -1, SC_MARK_LEFTRECT, 0xf57900 },
{ -1, SC_MARK_LEFTRECT, 0xcc0000 }
};
/* settings description */
static const struct {
const gchar *group;
const gchar *key;
gpointer value;
void (*read) (GKeyFile *kf,
const gchar *group,
const gchar *key,
gpointer value);
void (*write) (GKeyFile *kf,
const gchar *group,
const gchar *key,
gconstpointer value);
} G_settings_desc[] = {
{ "general", "monitor-repository", &G_monitoring_enabled,
read_setting_boolean, write_setting_boolean },
{ "colors", "line-added", &G_markers[MARKER_LINE_ADDED].color,
read_setting_color, write_setting_color },
{ "colors", "line-changed", &G_markers[MARKER_LINE_CHANGED].color,
read_setting_color, write_setting_color },
{ "colors", "line-removed", &G_markers[MARKER_LINE_REMOVED].color,
read_setting_color, write_setting_color }
};
static void
buf_zero (git_buf *buf)
{
if (buf) {
buf->ptr = NULL;
buf->size = 0;
#if ! CHECK_LIBGIT2_VERSION(1, 4)
buf->asize = 0;
#else
/* we don't really need this field, but the documentation states that all
* fields should be set to 0, so fill it as well */
buf->reserved = 0;
#endif
}
}
static void
clear_cached_blob_contents (void)
{
if (G_blob_contents.ptr) {
git_buf_dispose (&G_blob_contents);
buf_zero (&G_blob_contents);
}
G_blob_contents_tag = 0;
}
/* similar to old git_blob_filtered_content() but makes sure the caller owns
* the data in the output buffer -- and uses a boolean return */
static gboolean
get_blob_contents (git_buf *out,
git_blob *blob,
const char *as_path,
int check_for_binary_data)
{
/* libgit2 1.4 changed buffer API quite a bit */
#if ! CHECK_LIBGIT2_VERSION(1, 4)
gboolean success = TRUE;
if (git_blob_filtered_content (out, blob, as_path,
check_for_binary_data) != 0)
return FALSE;
/* Workaround for https://github.com/libgit2/libgit2/pull/3187
* We want to own the buffer, which git_buf_grow(buf, 0) was supposed to do,
* but there is a corner case where it doesn't do what it should and
* truncates the buffer contents, so we fix this manually. */
if (out->asize == 0) {
size_t target_size = out->size;
if ((target_size & 7) == 0) {
target_size++;
}
success = (git_buf_grow (out, target_size) == 0);
}
return success;
#else /* libgit2 >= 1.4 */
/* Here we can assume we will always get a buffer we own (at least as of
* 2022-06-05 it is the case), so there's no need for a pendent to the
* previous git_buf_grow() shenanigans.
* This code path does the same as the older git_blob_filtered_content()
* but with non-deprecated API */
git_blob_filter_options opts;
git_blob_filter_options_init (&opts, GIT_BLOB_FILTER_OPTIONS_VERSION);
if (check_for_binary_data)
opts.flags |= GIT_BLOB_FILTER_CHECK_FOR_BINARY;
else
opts.flags &= ~GIT_BLOB_FILTER_CHECK_FOR_BINARY;
return git_blob_filter(out, blob, as_path, &opts) == 0;
#endif
}
/* get the file blob for @relpath at HEAD */
static gboolean
repo_get_file_blob_contents (git_repository *repo,
const gchar *relpath,
git_buf *contents,
int check_for_binary_data)
{
git_reference *head = NULL;
gboolean success = FALSE;
if (git_repository_head (&head, repo) == 0) {
git_commit *commit = NULL;
if (git_commit_lookup (&commit, repo, git_reference_target (head)) == 0) {
git_tree *tree = NULL;
if (git_commit_tree (&tree, commit) == 0) {
git_tree_entry *entry = NULL;
if (git_tree_entry_bypath (&entry, tree, relpath) == 0) {
git_blob *blob;
if (git_blob_lookup (&blob, repo, git_tree_entry_id (entry)) == 0) {
success = get_blob_contents (contents, blob, relpath,
check_for_binary_data);
git_blob_free (blob);
}
git_tree_entry_free (entry);
}
git_tree_free (tree);
}
git_commit_free (commit);
}
git_reference_free (head);
}
return success;
}
static void
free_job (gpointer data)
{
AsyncBlobContentsJob *job = data;
/* unlikely, but if we still have the buffer, free it */
if (job->buf.ptr) {
git_buf_dispose (&job->buf);
}
g_free (job->path);
g_slice_free1 (sizeof *job, job);
}
static gboolean
report_work_in_idle (gpointer data)
{
AsyncBlobContentsJob *job = data;
/* update cached blob */
clear_cached_blob_contents ();
G_blob_contents = job->buf;
G_blob_contents_tag = job->buf.ptr ? job->tag : 0;
job->callback (job->path, job->buf.ptr ? &job->buf : NULL, job->user_data);
buf_zero (&job->buf);
return FALSE;
}
static GFileMonitor *
monitor_repo_file (git_repository *repo,
const gchar *subpath,
GCallback changed_callback,
gpointer user_data)
{
GFile *file = NULL;
GError *err = NULL;
GFileMonitor *monitor = NULL;
gchar *path = g_build_filename (git_repository_path (repo),
subpath, NULL);
file = g_file_new_for_path (path);
monitor = g_file_monitor (file, 0, NULL, &err);
if (err) {
g_warning ("Failed to monitor %s: %s", path, err->message);
g_error_free (err);
} else {
g_signal_connect (monitor, "changed", changed_callback, user_data);
}
g_object_unref (file);
g_free (path);
return monitor;
}
/* monitors the current reference HEAD points to (probably a branch) */
static GFileMonitor *
monitor_head_ref (git_repository *repo,
GCallback changed_callback,
gpointer user_data)
{
git_reference *head = NULL;
GFileMonitor *monitor = NULL;
if (! git_repository_head_detached (repo) &&
git_repository_head (&head, repo) == 0) {
monitor = monitor_repo_file (repo, git_reference_name (head),
changed_callback, user_data);
git_reference_free (head);
}
return monitor;
}
/* checks whether @path points somewhere inside @dir and returns the pointer
* inside @path starting the relative path, or NULL */
static const gchar *
path_dir_contains (const gchar *dir,
const gchar *path)
{
#ifdef G_OS_WIN32
/* FIXME: handle drive letters and such */
# define NORM_PATH_CH(c) (((c) == '\\') ? '/' : (c))
#else
# define NORM_PATH_CH(c) (c)
#endif
g_return_val_if_fail (dir != NULL, NULL);
g_return_val_if_fail (path != NULL, NULL);
while (*dir && NORM_PATH_CH (*dir) == NORM_PATH_CH (*path)) {
dir++, path++;
}
return *dir ? NULL : path;
}
/* gets the Git path for @repo pointing to @sys_path, or NULL */
static gchar *
get_path_in_repository (git_repository *repo,
const gchar *sys_path)
{
const gchar *workdir = git_repository_workdir (repo);
const gchar *rel_path = path_dir_contains (workdir, sys_path);
#ifdef G_OS_WIN32
if (rel_path) {
/* we want an internal Git path, which uses UNIX format */
gchar *p;
gchar *repo_path = g_strdup (rel_path);
for (p = repo_path; *p; p++) {
if (*p == '\\') {
*p = '/';
}
}
return repo_path;
}
return NULL;
#else
return g_strdup (rel_path);
#endif
}
static gpointer
worker_thread (gpointer data)
{
GAsyncQueue *queue = data;
git_repository *repo = NULL;
GFileMonitor *monitors[2] = { NULL, NULL };
AsyncBlobContentsJob *job;
guint i;
while ((job = g_async_queue_pop (queue)) != QUIT_THREAD_JOB) {
const gchar *path = job->path;
if (repo && (job->force ||
! path_dir_contains (path, git_repository_workdir (repo)))) {
/* FIXME: this can fail with nested repositories */
git_repository_free (repo);
repo = NULL;
for (i = 0; i < G_N_ELEMENTS (monitors); i++) {
if (monitors[i]) {
g_object_unref (monitors[i]);
monitors[i] = NULL;
}
}
}
if (! repo) {
gchar *dirname = g_path_get_dirname (path);
if (git_repository_open_ext (&repo, dirname, 0, NULL) == 0) {
if (git_repository_is_bare (repo)) {
git_repository_free (repo);
repo = NULL;
} else if (G_monitoring_enabled) {
/* we need to monitor HEAD, in case of e.g. branch switch (e.g.
* git checkout -b will switch the ref we need to watch) */
monitors[0] = monitor_repo_file (repo, "HEAD",
G_CALLBACK (on_git_repo_changed),
GINT_TO_POINTER (TRUE));
/* and of course the real ref (branch) for when changes get committed */
monitors[1] = monitor_head_ref (repo, G_CALLBACK (on_git_repo_changed),
GINT_TO_POINTER (FALSE));
}
}
g_free(dirname);
}
buf_zero (&job->buf);
if (repo) {
gchar *relpath = get_path_in_repository (repo, path);
if (relpath) {
if (! repo_get_file_blob_contents (repo, relpath, &job->buf, 0)) {
git_buf_dispose (&job->buf);
buf_zero (&job->buf);
}
g_free (relpath);
}
}
g_idle_add_full (G_PRIORITY_LOW, report_work_in_idle, job, free_job);
}
for (i = 0; i < G_N_ELEMENTS (monitors); i++) {
if (monitors[i]) {
g_object_unref (monitors[i]);
monitors[i] = NULL;
}
}
if (repo) {
git_repository_free (repo);
}
return NULL;
}
static void
get_cached_blob_contents_async (const gchar *path,
guint tag,
gboolean force,
BlobContentsReadyFunc callback,
gpointer user_data)
{
if ((! force && G_blob_contents.ptr && tag == G_blob_contents_tag) ||
! path) {
callback (path, &G_blob_contents, user_data);
} else {
AsyncBlobContentsJob *job = g_slice_alloc (sizeof *job);
job->force = force;
job->tag = tag;
job->path = g_strdup (path);
job->callback = callback;
job->user_data = user_data;
buf_zero (&job->buf);
if (! G_thread) {
G_queue = g_async_queue_new ();
#if GLIB_CHECK_VERSION (2, 32, 0)
G_thread = g_thread_new (PLUGIN"/blob-worker", worker_thread, G_queue);
#else
G_thread = g_thread_create (worker_thread, G_queue, FALSE, NULL);
#endif
}
g_async_queue_push (G_queue, job);
}
}
static gint
allocate_marker (ScintillaObject *sci,
guint marker)
{
g_return_val_if_fail (marker < MARKER_COUNT, -1);
if (G_markers[marker].num == -1) {
gint i;
G_markers[marker].num = -2;
/* markers 0-1 and 25-31 are reserved */
for (i = 2; G_markers[marker].num < 0 && i < 25; i++) {
gint sym = scintilla_send_message (sci, SCI_MARKERSYMBOLDEFINED, i, 0);
if (sym == SC_MARK_AVAILABLE ||
sym == 0 /* unfortunately it's also SC_MARK_CIRCLE */) {
guint j;
/* check if we already allocate it but not defined it yet */
for (j = 0; j < MARKER_COUNT && G_markers[j].num != i; j++) {
/* nothing */
}
if (j == MARKER_COUNT) {
G_markers[marker].num = i;
}
}
}
}
return G_markers[marker].num;
}
static gboolean
allocate_resources (ScintillaObject *sci)
{
guint i;
if (g_object_get_qdata (G_OBJECT (sci), RESOURCES_ALLOCATED_QTAG)) {
return TRUE;
}
/* allocate all markers first so we have all or nothing */
for (i = 0; i < MARKER_COUNT; i++) {
if (allocate_marker (sci, i) < 0) {
return FALSE;
}
}
for (i = 0; i < MARKER_COUNT; i++) {
scintilla_send_message (sci, SCI_MARKERDEFINE,
G_markers[i].num, G_markers[i].style);
scintilla_send_message (sci, SCI_MARKERSETBACK,
G_markers[i].num,
/* Scintilla uses BGR */
((G_markers[i].color & 0xff0000) >> 16) |
((G_markers[i].color & 0x00ff00)) |
((G_markers[i].color & 0x0000ff) << 16));
}
/* setup tooltips */
gtk_widget_set_has_tooltip (GTK_WIDGET (sci), TRUE);
g_signal_connect (sci, "query-tooltip",
G_CALLBACK (on_sci_query_tooltip), NULL);
g_object_set_qdata (G_OBJECT (sci), RESOURCES_ALLOCATED_QTAG,
sci /* anything non-NULL */);
return TRUE;
}
static void
release_resources (ScintillaObject *sci)
{
if (g_object_get_qdata (G_OBJECT (sci), RESOURCES_ALLOCATED_QTAG)) {
guint j;
for (j = 0; j < MARKER_COUNT; j++) {
if (G_markers[j].num >= 0) {
scintilla_send_message (sci, SCI_MARKERDEFINE,
G_markers[j].num, SC_MARK_AVAILABLE);
}
}
g_signal_handlers_disconnect_by_func (sci, on_sci_query_tooltip, NULL);
g_object_set_qdata (G_OBJECT (sci), RESOURCES_ALLOCATED_QTAG, NULL);
}
}
/* checks whether @encoding needs to be converted to UTF-8 */
static gboolean
encoding_needs_conversion (const gchar *encoding)
{
return (encoding &&
! utils_str_equal (encoding, "UTF-8") &&
! utils_str_equal (encoding, "None"));
}
/*
* @brief Converts encoding
* @param buffer Input and output buffer
* @param length Input and output buffer length
* @param free_buffer whether @p buffer should be freed when replaced
* @param to Target encoding
* @param from Source encoding
* @param error Return location for errors, or @c NULL
* @returns @c TRUE if @p buffer should be freed, or @c FALSE otherwise.
*
* @warning This function has a very weird API, but it is practical for
* how it's used.
* @note the only way to tell if the conversion succeeded when @p free_buffer
* is @c TRUE is to compare the output value of @buffer against the
* one it had as an input value.
*
* Converts between encodings (using g_convert()) in-place.
*
* The @p buffer is both an input and output parameter. As an input
* parameter, it is used as a constant buffer pointer and is never
* modified nor freed. As an output parameter, it is an allocated chunk
* of memory that should be freed with @c g_free().
* If the conversion succeeds, it replaces @p buffer and @p length with
* the converted values and returns @c TRUE. If it fails, it does not
* modify the values and returns @p free_buffer so that the passed-in
* variables can be used as a fallback if the conversion was optional.
*/
static gboolean
convert_encoding_inplace (gchar **buffer,
gsize *length,
gboolean free_buffer,
const gchar *to,
const gchar *from,
GError **error)
{
gsize tmp_len;
gchar *tmp_buf = g_convert (*buffer, (gssize) *length, to, from,
NULL, &tmp_len, error);
if (tmp_buf) {
if (free_buffer) {
g_free (*buffer);
}
*buffer = tmp_buf;
*length = tmp_len;
free_buffer = TRUE;
}
return free_buffer;
}
static gboolean
add_utf8_bom (gchar **buffer,
gsize *length,
gboolean free_buffer)
{
gchar *new_buf = g_malloc (*length + 3);
new_buf[0] = (gchar) 0xef;
new_buf[1] = (gchar) 0xbb;
new_buf[2] = (gchar) 0xbf;
memcpy (&new_buf[3], *buffer, *length);
if (free_buffer) {
g_free (*buffer);
}
*buffer = new_buf;
*length += 3;
return TRUE;
}
static int
diff_buf_to_doc (const git_buf *old_buf,
GeanyDocument *doc,
git_diff_hunk_cb hunk_cb,
void *payload)
{
ScintillaObject *sci = doc->editor->sci;
git_diff_options opts;
gchar *buf;
size_t len;
gboolean free_buf = FALSE;
int ret;
buf = (gchar *) scintilla_send_message (sci, SCI_GETCHARACTERPOINTER, 0, 0);
len = sci_get_length (sci);
/* add the BOM if needed */
if (doc->has_bom) {
/* UTF-8 BOM, converted below */
free_buf = add_utf8_bom (&buf, &len, free_buf);
}
/* convert the buffer back to in-file encoding if necessary */
if (encoding_needs_conversion (doc->encoding)) {
free_buf = convert_encoding_inplace (&buf, &len, free_buf,
doc->encoding, "UTF-8", NULL);
}
git_diff_options_init (&opts, GIT_DIFF_OPTIONS_VERSION);
/* no context lines, and no need to bother about binary checks */
opts.context_lines = 0;
opts.flags = GIT_DIFF_FORCE_TEXT;
ret = git_diff_buffers (old_buf->ptr, old_buf->size, NULL,
buf, len, NULL, &opts, NULL, NULL, hunk_cb, NULL,
payload);
if (free_buf) {
g_free (buf);
}
return ret;
}
static int
diff_hunk_cb (const git_diff_delta *delta,
const git_diff_hunk *hunk,
void *data)
{
ScintillaObject *sci = data;
gint line;
if (hunk->new_lines > 0) {
guint marker = hunk->old_lines > 0 ? MARKER_LINE_CHANGED : MARKER_LINE_ADDED;
for (line = hunk->new_start; line < hunk->new_start + hunk->new_lines; line++) {
scintilla_send_message (sci, SCI_MARKERADD, line - 1, G_markers[marker].num);
}
} else {
line = REMOVED_MARKER_POS (hunk->new_start);
scintilla_send_message (sci, SCI_MARKERADD, line,
G_markers[MARKER_LINE_REMOVED].num);
}
return 0;
}
static GtkWidget *
get_widget_for_buf_range (GeanyDocument *doc,
const git_buf *contents,
gint line_start,
gint n_lines)
{
ScintillaObject *sci = editor_create_widget (doc->editor);
const GeanyIndentPrefs *iprefs = editor_get_indent_prefs (doc->editor);
gint width = 0;
gint height = 0;
gint zoom;
gint i;
GtkAllocation alloc;
gchar *buf = contents->ptr;
gsize buf_len = contents->size;
gboolean free_buf = FALSE;
gtk_widget_get_allocation (GTK_WIDGET (doc->editor->sci), &alloc);
highlighting_set_styles (sci, doc->file_type);
if (iprefs->type == GEANY_INDENT_TYPE_BOTH) {
scintilla_send_message (sci, SCI_SETTABWIDTH, iprefs->hard_tab_width, 0);
} else {
scintilla_send_message (sci, SCI_SETTABWIDTH, iprefs->width, 0);
}
scintilla_send_message (sci, SCI_SETINDENT, iprefs->width, 0);
zoom = scintilla_send_message (doc->editor->sci, SCI_GETZOOM, 0, 0);
scintilla_send_message (sci, SCI_SETZOOM, zoom, 0);
/* hide stuff we don't wanna see */
scintilla_send_message (sci, SCI_SETHSCROLLBAR, 0, 0);
scintilla_send_message (sci, SCI_SETVSCROLLBAR, 0, 0);
scintilla_send_message (sci, SCI_SETCHANGEHISTORY, SC_CHANGE_HISTORY_DISABLED, 0);
for (i = 0; i < SC_MAX_MARGIN; i++) {
scintilla_send_message (sci, SCI_SETMARGINWIDTHN, i, 0);
}
/* convert the buffer to UTF-8 if necessary */
if (encoding_needs_conversion (doc->encoding)) {
free_buf = convert_encoding_inplace (&buf, &buf_len, free_buf,
"UTF-8", doc->encoding, NULL);
}
scintilla_send_message (sci, SCI_ADDTEXT, buf_len, (sptr_t) buf);
if (free_buf) {
g_free (buf);
}
/* we need to enable extra scroll after last line so that SETFIRSTVISIBLELINE
* really places the line we want on top of the view, even if the line is
* close to the end and wouldn't possibly end on top otherwise */
scintilla_send_message (sci, SCI_SETENDATLASTLINE, 0, 0);
scintilla_send_message (sci, SCI_SETFIRSTVISIBLELINE, line_start, 0);
/* compute the size of the area we want to see */
for (i = line_start; i < line_start + n_lines; i++) {
gint pos = sci_get_line_end_position (sci, i);
gint end_x = scintilla_send_message (sci, SCI_POINTXFROMPOSITION, 0, pos);
height += scintilla_send_message (sci, SCI_TEXTHEIGHT, i, 0);
width = MAX (width, end_x);
if (height > alloc.height) {
break;
}
}
/* We need 2 extra pixels of width:
* 1 to avoid cropping the rightmost vertical bar of letters like H and M,
* 1 to avoid spurious line wrapping (issue #425). */
gtk_widget_set_size_request (GTK_WIDGET (sci),
MIN (width + 2, alloc.width),
MIN (height + 1, alloc.height));
/* Size request seems to scroll Scintilla view so we have to re-set visible lines again */
scintilla_send_message (sci, SCI_SETFIRSTVISIBLELINE, line_start, 0);
return GTK_WIDGET (sci);
}
static gboolean
is_first_line_removed (gint line, gint new_hunk_start, gint new_hunk_lines)
{
return line == 1 && new_hunk_start == 0 && new_hunk_lines == 0;
}
static int
tooltip_diff_hunk_cb (const git_diff_delta *delta,
const git_diff_hunk *hunk,
void *data)
{
TooltipHunkData *thd = data;
if (thd->found) {
return 1;
}
if (hunk->old_lines > 0 &&
(is_first_line_removed (thd->line, hunk->new_start, hunk->new_lines) ||
(thd->line >= hunk->new_start &&
thd->line < hunk->new_start + MAX (1, hunk->new_lines)))) {
GtkWidget *old = get_widget_for_buf_range (thd->doc, thd->buf,
hunk->old_start - 1,
hunk->old_lines);
gtk_tooltip_set_custom (thd->tooltip, old);
thd->found = old != NULL;
}
return thd->found;
}
static gboolean
on_sci_query_tooltip (GtkWidget *widget,
gint x,
gint y,
gboolean keyboard_mode,
GtkTooltip *tooltip,
gpointer user_data)
{
gint min_x;
gint max_x;
ScintillaObject *sci = (ScintillaObject *) widget;
GeanyDocument *doc = document_get_current ();
gboolean has_tooltip = FALSE;
/* for some reason the widget isn't the current one during tab switch, so
* give up silently when we receive a query for a non-current widget */
if (! doc || doc->editor->sci != sci) {
return FALSE;
}
min_x = scintilla_send_message (sci, SCI_GETMARGINWIDTHN, 0, 0);
max_x = min_x + scintilla_send_message (sci, SCI_GETMARGINWIDTHN, 1, 0);
if (x >= min_x && x <= max_x &&
G_blob_contents.ptr && G_blob_contents_tag == doc->id) {
gint pos = scintilla_send_message (sci, SCI_POSITIONFROMPOINT, x, y);
gint line = sci_get_line_from_position (sci, pos);
gint mask = scintilla_send_message (sci, SCI_MARKERGET, line, 0);
if (mask & ((1 << G_markers[MARKER_LINE_CHANGED].num) |
(1 << G_markers[MARKER_LINE_REMOVED].num))) {
TooltipHunkData thd = TOOLTIP_HUNK_DATA_INIT (line + 1, doc,
&G_blob_contents, tooltip);
diff_buf_to_doc (&G_blob_contents, doc, tooltip_diff_hunk_cb, &thd);
has_tooltip = thd.found;
}
}
return has_tooltip;
}
static void
update_diff (const gchar *path,
git_buf *contents,
gpointer data)
{
GeanyDocument *doc = document_get_current ();
if (doc && doc->id == GPOINTER_TO_UINT (data)) {
ScintillaObject *sci = doc->editor->sci;
gboolean allocated = !! g_object_get_qdata (G_OBJECT (sci),
RESOURCES_ALLOCATED_QTAG);
if (allocated) {
guint i;
/* clear previous markers */
for (i = 0; i < MARKER_COUNT; i++) {
scintilla_send_message (sci, SCI_MARKERDELETEALL, G_markers[i].num, 0);
}
}
gtk_widget_set_visible (G_undo_menu_item, contents != NULL);
if (contents && (allocated || allocate_resources (sci))) {
diff_buf_to_doc (contents, doc, diff_hunk_cb, sci);
} else if (! contents && allocated) {
/* if we don't have contents, it probably means the document doesn't
* match any object known by Git, so next attempts will fail just the
* same. So, drop allocated resources if any (if it used to be a valid
* object, e.g. the document was renamed to something unknown to Git) */
release_resources (sci);
}
}
}
static gboolean
do_update_diff_idle (guint doc_id,
gboolean force)
{