summaryrefslogtreecommitdiffstats
path: root/common/region.c
blob: d1d7f4a040acadedbb6d4b04e8f8e2caf5b2875d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
/*
   Copyright (C) 2009 Red Hat, Inc.

   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 2 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 <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "region.h"
#include "rect.h"

//#define ALLOC_ON_STEAL
//#define REGION_DEBUG

#define FALSE 0
#define TRUE 1

#define MIN(x, y) (((x) <= (y)) ? (x) : (y))
#define MAX(x, y) (((x) >= (y)) ? (x) : (y))

#define ASSERT(x) if (!(x)) {                               \
    printf("%s: ASSERT %s failed\n", __FUNCTION__, #x);     \
    abort();                                                \
}

#ifdef REGION_DEBUG
#define REGION_IS_VALID(region) region_is_valid(region)
#else
#define REGION_IS_VALID(region) TRUE
#endif

static int rect_is_valid(const Rect *r)
{
    if (r->top > r->bottom || r->left > r->right) {
        printf("%s: invalid rect\n", __FUNCTION__);
        return FALSE;
    }
    return TRUE;
}

#ifdef REGION_TEST
static void rect_set(Rect *r, int32_t top, int32_t left, int32_t bottom, int32_t right)
{
    r->top = top;
    r->left = left;
    r->bottom = bottom;
    r->right = right;
    ASSERT(rect_is_valid(r));
}

#endif

static inline void __region_init(QRegion *rgn)
{
    rgn->num_rects = 0;
    rgn->rects = rgn->buf;
    rgn->rects_size = RECTS_BUF_SIZE;
}

void region_init(QRegion *rgn)
{
    __region_init(rgn);
    ASSERT(REGION_IS_VALID(rgn));
}

void region_clear(QRegion *rgn)
{
    rgn->num_rects = 0;
}

void region_destroy(QRegion *rgn)
{
    ASSERT(REGION_IS_VALID(rgn));
    if (rgn->rects != rgn->buf) {
        free(rgn->rects);
    }
}

void region_clone(QRegion *dest, const QRegion *src)
{
    ASSERT(REGION_IS_VALID(src));
    dest->bbox = src->bbox;
    if ((dest->num_rects = src->num_rects) <= RECTS_BUF_SIZE) {
        dest->rects = dest->buf;
        dest->rects_size = RECTS_BUF_SIZE;
    } else {
        dest->rects = (Rect *)malloc(sizeof(Rect) * dest->num_rects);
        dest->rects_size = dest->num_rects;
    }
    memcpy(dest->rects, src->rects, dest->num_rects * sizeof(Rect));
    ASSERT(REGION_IS_VALID(src));
    ASSERT(REGION_IS_VALID(dest));
}

int region_is_valid(const QRegion *rgn)
{
    if (rgn->num_rects) {
        uint32_t i;
        Rect bbox;

        if (!rect_is_valid(&rgn->bbox)) {
            return FALSE;
        }
        bbox = rgn->rects[0];
        if (!rect_is_valid(&bbox) || rect_is_empty(&bbox)) {
            return FALSE;
        }
        for (i = 1; i < rgn->num_rects; i++) {
            Rect *r;

            r = &rgn->rects[i];
            if (!rect_is_valid(r) || rect_is_empty(r)) {
                return FALSE;
            }

            Rect *priv = r - 1;
            if (r->top < priv->top) {
                return FALSE;
            } else if (r->top == priv->top) {
                if (r->bottom != priv->bottom) {
                    return FALSE;
                }
                if (r->left < priv->right) {
                    return FALSE;
                }
            } else if (priv->bottom > r->top) {
                return FALSE;
            }
            bbox.top = MIN(bbox.top, r->top);
            bbox.left = MIN(bbox.left, r->left);
            bbox.bottom = MAX(bbox.bottom, r->bottom);
            bbox.right = MAX(bbox.right, r->right);
        }
        return rect_is_equal(&bbox, &rgn->bbox);
    }
    return TRUE;
}

void region_dump(const QRegion *rgn, const char *prefix)
{
    char *indent;
    int len;
    uint32_t i;

    len = strlen(prefix);
    if (!(indent = (char *)malloc(len + 1))) {
        printf("%s: malloc failed\n", __FUNCTION__);
        return;
    }
    memset(indent, ' ', len);
    indent[len] = 0;


    printf("%sREGION: %p, size %u storage is %s, ",
           prefix,
           rgn,
           rgn->rects_size,
           (rgn->rects == rgn->buf) ? "BUF" : "MALLOC");

    if (rgn->num_rects == 0) {
        printf("EMPTY\n");
        return;
    }

    printf("num %u bounds (%d, %d, %d, %d)\n",
           rgn->num_rects,
           rgn->bbox.top,
           rgn->bbox.left,
           rgn->bbox.bottom,
           rgn->bbox.right);

    for (i = 0; i < rgn->num_rects; i++) {
        printf("%s  %12d %12d %12d %12d\n",
               indent,
               rgn->rects[i].top,
               rgn->rects[i].left,
               rgn->rects[i].bottom,
               rgn->rects[i].right);
    }
    free(indent);
    ASSERT(region_is_valid(rgn));
}

int region_is_empty(const QRegion *rgn)
{
    ASSERT(REGION_IS_VALID(rgn));
    return !rgn->num_rects;
}

#ifdef REGION_USE_IMPROVED

int region_is_equal(const QRegion *rgn1, const QRegion *rgn2)
{
    int test_res;

    ASSERT(REGION_IS_VALID(rgn1));
    ASSERT(REGION_IS_VALID(rgn2));

    if (rgn1->num_rects == 0 || rgn2->num_rects == 0) {
        return rgn1->num_rects == rgn2->num_rects;
    }

    if (!rect_is_equal(&rgn1->bbox, &rgn2->bbox)) {
        return FALSE;
    }

    test_res = region_test(rgn1, rgn2, REGION_TEST_LEFT_EXCLUSIVE | REGION_TEST_RIGHT_EXCLUSIVE);
    return !test_res;
}

#else

int region_is_equal(const QRegion *rgn1, const QRegion *rgn2)
{
    QRegion tmp_rgn;
    int ret;

    ASSERT(REGION_IS_VALID(rgn1));
    ASSERT(REGION_IS_VALID(rgn2));

    if (rgn1->num_rects == 0 || rgn2->num_rects == 0) {
        return rgn1->num_rects == rgn2->num_rects;
    }

    if (!rect_is_equal(&rgn1->bbox, &rgn2->bbox)) {
        return FALSE;
    }

    region_clone(&tmp_rgn, rgn1);
    region_xor(&tmp_rgn, rgn2);
    ret = region_is_empty(&tmp_rgn);
    region_destroy(&tmp_rgn);
    return ret;
}

#endif

typedef struct RgnOpCtx {
    Rect *now;
    Rect *end;
    Rect *scan_line;
    Rect r;
    Rect split;
#ifdef REGION_USE_IMPROVED
    int abort;
#endif
} RgnOpCtx;

static inline int op_ctx_is_valid(RgnOpCtx *ctx)
{
    return ctx->now != ctx->end;
}

static void op_context_next(RgnOpCtx *ctx)
{
    Rect *now;
    Rect *next;

    ASSERT(op_ctx_is_valid(ctx));
    now = ctx->now;
    next = now + 1;

    if (next == ctx->end || now->top != next->top) {
        if (now->bottom != ctx->r.bottom) { //h_split
            ctx->r.top = ctx->r.bottom;
            ctx->r.bottom = now->bottom;
            next = ctx->scan_line;
        } else {
            if (next == ctx->end) {
#ifdef REGION_USE_IMPROVED
                ctx->scan_line = ++ctx->now;
#else
                ++ctx->now;
#endif
                ctx->r.top = ctx->r.left = ctx->r.bottom = ctx->r.right = (1U << 31) - 1;
                return;
            }
            ctx->scan_line = next;
            ctx->r.top = next->top;
            ctx->r.bottom = next->bottom;
        }
    }
    ctx->r.left = next->left;
    ctx->r.right = next->right;
    ctx->now = next;
}

static void op_context_init(RgnOpCtx *ctx, uint32_t num_rects, Rect *rects)
{
    ctx->scan_line = ctx->now = rects;
    ctx->end = ctx->now + num_rects;
#ifdef REGION_USE_IMPROVED
    ctx->abort = FALSE;
#endif
    if (!op_ctx_is_valid(ctx)) {
        ctx->r.top = ctx->r.left = ctx->r.bottom = ctx->r.right = (1U << 31) - 1;
    } else {
        ctx->r = *ctx->now;
    }
}

static inline void op_ctx_h_split(RgnOpCtx *ctx, int32_t h_line)
{
    ctx->r.bottom = h_line;
    ctx->split = ctx->r;
    op_context_next(ctx);
}

static inline void op_ctx_v_split(RgnOpCtx *ctx, int32_t v_line)
{
    ctx->split = ctx->r;
    ctx->r.left = ctx->split.right = v_line;
    if (rect_is_empty(&ctx->r)) {
        op_context_next(ctx);
    }
}

static inline void op_ctx_split(RgnOpCtx *ctx, int32_t h_line)
{
    ASSERT(ctx->now == ctx->scan_line);
    ctx->r.bottom = h_line;
}

static void region_steal_rects(QRegion *rgn, uint32_t *num_rects, Rect **rects)
{
    ASSERT(REGION_IS_VALID(rgn));
    if ((*num_rects = rgn->num_rects)) {
        if (rgn->rects == rgn->buf) {
            *rects = (Rect *)malloc(sizeof(Rect) * rgn->num_rects);
            memcpy(*rects, rgn->rects, sizeof(Rect) * rgn->num_rects);
        } else {
            *rects = rgn->rects;
#ifdef ALLOC_ON_STEAL
            rgn->rects = (Rect *)malloc(sizeof(Rect) * rgn->num_rects);
            rgn->rects_size = rgn->num_rects;
            rgn->num_rects = 0;
            return;
#endif
        }
    } else {
        *rects = NULL;
    }
    __region_init(rgn);
    ASSERT(REGION_IS_VALID(rgn));
}

typedef struct JoinContext {
    QRegion *rgn;
    Rect *line0;
    Rect *line1;
    Rect *end;
} JoinContext;

static inline Rect *__get_line(QRegion *rgn, Rect *pos)
{
    Rect *end = rgn->rects + rgn->num_rects;

    if (pos < end) {
        int32_t line_top = pos->top;
        while (++pos < end && pos->top == line_top) {
            ASSERT((pos - 1)->right < pos->left); //join in region_push_rect
        }
    }
    return pos;
}

static inline int region_join_init(QRegion *rgn, JoinContext *context)
{
    context->rgn = rgn;
    context->end = __get_line(rgn, (context->line1 = rgn->rects));
    return context->end != context->line1;
}

static inline int region_join_next(JoinContext *context)
{
    context->line0 = context->line1;
    context->line1 = context->end;
    context->end = __get_line(context->rgn, context->line1);
    return context->end != context->line1;
}

static inline void region_join_join(JoinContext *context)
{
    Rect *pos_0 = context->line0;
    Rect *pos_1 = context->line1;
    int32_t bottom;
    QRegion *rgn;

    if (pos_0->bottom != pos_1->top) {
        return;
    }

    if (pos_1 - pos_0 != context->end - pos_1) {
        return;
    }

    for (; pos_1 < context->end; pos_0++, pos_1++) {
        if (pos_0->left != pos_1->left || pos_0->right != pos_1->right) {
            return;
        }
    }
    bottom = context->line1->bottom;
    pos_0 = context->line0;
    for (; pos_0 < context->line1; pos_0++) {
        pos_0->bottom = bottom;
    }
    rgn = context->rgn;
    memmove(context->line1, context->end,
            (unsigned long)(rgn->rects + rgn->num_rects) - (unsigned long)context->end);
    rgn->num_rects -= (context->line1 - context->line0);
    context->end = context->line1;
    context->line1 = context->line0;
}

static inline void region_join(QRegion *rgn)
{
    JoinContext context;

    ASSERT(REGION_IS_VALID(rgn));

    if (!region_join_init(rgn, &context)) {
        return;
    }
    while (region_join_next(&context)) {
        region_join_join(&context);
    }

    ASSERT(REGION_IS_VALID(rgn));
}

static void region_push_rect(QRegion *rgn, Rect *r)
{
    ASSERT(REGION_IS_VALID(rgn));
    ASSERT(rect_is_valid(r));
    if (rgn->num_rects == 0) {
        rgn->num_rects++;
        rgn->rects[0] = rgn->bbox = *r;
        return;
    } else {
        Rect *priv = &rgn->rects[rgn->num_rects - 1];

        if (priv->top == r->top && priv->right == r->left) {
            ASSERT(priv->bottom == r->bottom);
            priv->right = r->right;
            rgn->bbox.right = MAX(rgn->bbox.right, priv->right);
            return;
        }
        if (rgn->rects_size == rgn->num_rects) {
            Rect *old = rgn->rects;
            rgn->rects_size = rgn->rects_size * 2;
            rgn->rects = (Rect *)malloc(sizeof(Rect) * rgn->rects_size);
            memcpy(rgn->rects, old, sizeof(Rect) * rgn->num_rects);
            if (old != rgn->buf) {
                free(old);
            }
        }
        rgn->rects[rgn->num_rects++] = *r;
        rect_union(&rgn->bbox, r);
    }
}

#ifdef REGION_USE_IMPROVED

static Rect *op_context_find_area_below(RgnOpCtx *ctx, int32_t val)
{
    Rect *start = ctx->now;
    Rect *end = ctx->end;

    while (start != end) {
        int pos = (end - start) / 2;
        if (start[pos].bottom <= val) {
            start = &start[pos + 1];
        } else {
            end = &start[pos];
        }
    }
    return start;
}

static int op_context_skip_v(RgnOpCtx *ctx, int32_t top)
{
    Rect *end = op_context_find_area_below(ctx, top);
    if (end != ctx->now) {
        ctx->now = ctx->scan_line = end;
        if (ctx->now == ctx->end) {
            ctx->r.top = ctx->r.left = ctx->r.bottom = ctx->r.right = (1U << 31) - 1;
        } else {
            ctx->r = *ctx->now;
        }
        return TRUE;
    }
    return FALSE;
}

typedef void (*op_callback_t)(RgnOpCtx *context, Rect *, Rect *);

static void op_context_skip(RgnOpCtx *self, RgnOpCtx *other, op_callback_t on_self,
                            op_callback_t on_other)
{
    Rect *save1 = self->now;
    Rect *save2 = other->now;
    int more;
    do {
        op_context_skip_v(self, other->r.top);
        if (save1 != self->now) {
            if (on_self) {
                on_self(self, save1, self->now);
            }
            save1 = self->now;
        }
        more = op_context_skip_v(other, self->r.top);
        if (save2 != other->now) {
            if (on_other) {
                on_other(self, save2, other->now);
            }
            save2 = other->now;
        }
    } while (more && !self->abort);
}

static inline int op_context_more_overlap(RgnOpCtx *ctx, int32_t *bottom)
{
    if (!op_ctx_is_valid(ctx)) {
        return FALSE;
    }

    if (ctx->scan_line->bottom > *bottom && ctx->scan_line->top < *bottom) {
        *bottom = ctx->scan_line->bottom;
    }
    return ctx->scan_line->top < *bottom;
}

static inline void op_context_overlap(RgnOpCtx *self, RgnOpCtx *other, op_callback_t on_self,
                                      op_callback_t on_other, op_callback_t on_both)
{
    int32_t bottom = MAX(self->scan_line->bottom, other->scan_line->bottom);

    do {
        if (self->r.top < other->r.top) {
            op_ctx_h_split(self, MIN(other->r.top, self->r.bottom));
            if (on_self) {
                on_self(self, &self->split, &self->split + 1);
            }
        } else if (self->r.top > other->r.top) {
            op_ctx_h_split(other, MIN(self->r.top, other->r.bottom));
            if (on_other) {
                on_other(self, &other->split, &other->split + 1);
            }
        } else {
            if (self->r.bottom > other->r.bottom) {
                op_ctx_split(self, other->r.bottom);
            } else if (other->r.bottom > self->r.bottom) {
                op_ctx_split(other, self->r.bottom);
            }
            if (self->r.left < other->r.left) {
                op_ctx_v_split(self, MIN(other->r.left, self->r.right));
                if (on_self) {
                    on_self(self, &self->split, &self->split + 1);
                }
            } else if (self->r.left > other->r.left) {
                op_ctx_v_split(other, MIN(self->r.left, other->r.right));
                if (on_other) {
                    on_other(self, &other->split, &other->split + 1);
                }
            } else {
                int32_t right = MIN(self->r.right, other->r.right);
                op_ctx_v_split(self, right);
                op_ctx_v_split(other, right);
                if (on_both) {
                    on_both(self, &self->split, &self->split + 1);
                }
            }
        }
    } while (!self->abort && (op_context_more_overlap(self, &bottom) ||
                              op_context_more_overlap(other, &bottom)));
}

static inline void op_context_op(RgnOpCtx *self, RgnOpCtx *other, op_callback_t on_self,
                                 op_callback_t on_other, op_callback_t on_both)
{
    for (;;) {
        op_context_skip(self, other, on_self, on_other);
        if (self->abort || !op_ctx_is_valid(self)) {
            ASSERT(self->abort || !op_ctx_is_valid(other));
            return;
        }
        op_context_overlap(self, other, on_self, on_other, on_both);
    }
}

typedef struct SelfOpCtx {
    RgnOpCtx ctx;
    QRegion *rgn;
} SelfOpCtx;

static void add_rects(RgnOpCtx *ctx, Rect *now, Rect *end)
{
    SelfOpCtx *self_ctx = (SelfOpCtx *)ctx;
    for (; now < end; now++) {
        region_push_rect(self_ctx->rgn, now);
    }
}

static void region_op(QRegion *rgn, const QRegion *other_rgn, op_callback_t on_self,
                      op_callback_t on_other, op_callback_t on_both)
{
    SelfOpCtx self;
    RgnOpCtx other;
    uint32_t num_rects;
    Rect *rects;

    region_steal_rects(rgn, &num_rects, &rects);
    op_context_init(&self.ctx, num_rects, rects);
    self.rgn = rgn;
    op_context_init(&other, other_rgn->num_rects, other_rgn->rects);
    op_context_op(&self.ctx, &other, on_self, on_other, on_both);
    free(rects);
    region_join(rgn);
}

void region_or(QRegion *rgn, const QRegion *other_rgn)
{
    region_op(rgn, other_rgn, add_rects, add_rects, add_rects);
}

void region_and(QRegion *rgn, const QRegion *other_rgn)
{
    if (!region_bounds_intersects(rgn, other_rgn)) {
        region_clear(rgn);
        return;
    }
    region_op(rgn, other_rgn, NULL, NULL, add_rects);
}

void region_xor(QRegion *rgn, const QRegion *other_rgn)
{
    region_op(rgn, other_rgn, add_rects, add_rects, NULL);
}

void region_exclude(QRegion *rgn, const QRegion *other_rgn)
{
    if (!region_bounds_intersects(rgn, other_rgn)) {
        return;
    }
    region_op(rgn, other_rgn, add_rects, NULL, NULL);
}

typedef struct TestOpCtx {
    RgnOpCtx ctx;
    int result;
    int abort_on;
} TestOpCtx;


static void region_test_on_self(RgnOpCtx *ctx, Rect *now, Rect *end)
{
    TestOpCtx *test_ctx = (TestOpCtx *)ctx;
    test_ctx->result |= REGION_TEST_LEFT_EXCLUSIVE;
    test_ctx->result &= test_ctx->abort_on;
    if (test_ctx->result == test_ctx->abort_on) {
        test_ctx->ctx.abort = TRUE;
    }
}

static void region_test_on_other(RgnOpCtx *ctx, Rect *now, Rect *end)
{
    TestOpCtx *test_ctx = (TestOpCtx *)ctx;
    test_ctx->result |= REGION_TEST_RIGHT_EXCLUSIVE;
    test_ctx->result &= test_ctx->abort_on;
    if (test_ctx->result == test_ctx->abort_on) {
        test_ctx->ctx.abort = TRUE;
    }
}

static void region_test_on_both(RgnOpCtx *ctx, Rect *now, Rect *end)
{
    TestOpCtx *test_ctx = (TestOpCtx *)ctx;
    test_ctx->result |= REGION_TEST_SHARED;
    test_ctx->result &= test_ctx->abort_on;
    if (test_ctx->result == test_ctx->abort_on) {
        test_ctx->ctx.abort = TRUE;
    }
}

int region_test(const QRegion *rgn, const QRegion *other_rgn, int query)
{
    TestOpCtx self;
    RgnOpCtx other;

    op_context_init(&self.ctx, rgn->num_rects, rgn->rects);
    self.result = 0;
    self.abort_on = (query) ? query & REGION_TEST_ALL : REGION_TEST_ALL;
    op_context_init(&other, other_rgn->num_rects, other_rgn->rects);
    op_context_op(&self.ctx, &other, region_test_on_self, region_test_on_other,
                  region_test_on_both);
    return self.result;
}

#else

#define RIGION_OP_ADD_SELF (1 << 0)
#define RIGION_OP_ADD_OTHER (1 << 1)
#define RIGION_OP_ADD_COMMON (1 << 2)

static inline void region_on_self(QRegion *rgn, Rect *r, uint32_t op)
{
    ASSERT(REGION_IS_VALID(rgn));
    if (op & RIGION_OP_ADD_SELF) {
        region_push_rect(rgn, r);
    }
}

static inline void region_on_other(QRegion *rgn, Rect *r, uint32_t op)
{
    ASSERT(REGION_IS_VALID(rgn));
    if (op & RIGION_OP_ADD_OTHER) {
        region_push_rect(rgn, r);
    }
}

static inline void region_on_both(QRegion *rgn, Rect *r, uint32_t op)
{
    ASSERT(REGION_IS_VALID(rgn));
    if (op & RIGION_OP_ADD_COMMON) {
        region_push_rect(rgn, r);
    }
}

static void region_op(QRegion *rgn, const QRegion *other_rgn, uint32_t op)
{
    RgnOpCtx self;
    RgnOpCtx other;
    uint32_t num_rects;
    Rect *rects;

    ASSERT(REGION_IS_VALID(rgn));
    ASSERT(REGION_IS_VALID(other_rgn));
    region_steal_rects(rgn, &num_rects, &rects);

    op_context_init(&self, num_rects, rects);
    op_context_init(&other, other_rgn->num_rects, other_rgn->rects);

    while (op_ctx_is_valid(&self) || op_ctx_is_valid(&other)) {
        if (self.r.top < other.r.top) {
            op_ctx_h_split(&self, MIN(other.r.top, self.r.bottom));
            region_on_self(rgn, &self.split, op);
        } else if (self.r.top > other.r.top) {
            op_ctx_h_split(&other, MIN(self.r.top, other.r.bottom));
            region_on_other(rgn, &other.split, op);
        } else {
            if (self.r.bottom > other.r.bottom) {
                op_ctx_split(&self, other.r.bottom);
            } else if (other.r.bottom > self.r.bottom) {
                op_ctx_split(&other, self.r.bottom);
            }
            if (self.r.left < other.r.left) {
                op_ctx_v_split(&self, MIN(other.r.left, self.r.right));
                region_on_self(rgn, &self.split, op);
            } else if (self.r.left > other.r.left) {
                op_ctx_v_split(&other, MIN(self.r.left, other.r.right));
                region_on_other(rgn, &other.split, op);
            } else {
                int32_t right = MIN(self.r.right, other.r.right);
                op_ctx_v_split(&self, right);
                op_ctx_v_split(&other, right);
                region_on_both(rgn, &self.split, op);
            }
        }
    }
    free(rects);
    region_join(rgn);
}

void region_or(QRegion *rgn, const QRegion *other_rgn)
{
    region_op(rgn, other_rgn, RIGION_OP_ADD_SELF | RIGION_OP_ADD_OTHER | RIGION_OP_ADD_COMMON);
}

void region_and(QRegion *rgn, const QRegion *other_rgn)
{
    region_op(rgn, other_rgn, RIGION_OP_ADD_COMMON);
}

void region_xor(QRegion *rgn, const QRegion *other_rgn)
{
    region_op(rgn, other_rgn, RIGION_OP_ADD_SELF | RIGION_OP_ADD_OTHER);
}

void region_exclude(QRegion *rgn, const QRegion *other_rgn)
{
    region_op(rgn, other_rgn, RIGION_OP_ADD_SELF);
}

#endif


void region_offset(QRegion *rgn, int32_t dx, int32_t dy)
{
    Rect *now;
    Rect *end;
    ASSERT(REGION_IS_VALID(rgn));
    if (region_is_empty(rgn)) {
        return;
    }
    rect_offset(&rgn->bbox, dx, dy);
    now = rgn->rects;
    end = now + rgn->num_rects;
    for (; now < end; now++) {
        rect_offset(now, dx, dy);
    }
}

void region_add(QRegion *rgn, const Rect *r)
{
    ASSERT(REGION_IS_VALID(rgn));
    ASSERT(rect_is_valid(r));

    if (!rgn->num_rects) {
        if (rect_is_empty(r)) {
            return;
        }
        rgn->num_rects++;
        rgn->rects[0] = rgn->bbox = *r;
    } else {
        QRegion rect_rgn;
        region_init(&rect_rgn);
        region_add(&rect_rgn, r);
        region_or(rgn, &rect_rgn);
    }
}

void region_remove(QRegion *rgn, const Rect *r)
{
    ASSERT(REGION_IS_VALID(rgn));
    ASSERT(rect_is_valid(r));
    if (rgn->num_rects) {
        QRegion rect_rgn;

        region_init(&rect_rgn);
        region_add(&rect_rgn, r);
        region_exclude(rgn, &rect_rgn);
    }
}

#ifdef REGION_USE_IMPROVED

int region_intersects(const QRegion *rgn1, const QRegion *rgn2)
{
    int test_res;

    ASSERT(REGION_IS_VALID(rgn1));
    ASSERT(REGION_IS_VALID(rgn2));

    if (!region_bounds_intersects(rgn1, rgn2)) {
        return FALSE;
    }

    test_res = region_test(rgn1, rgn2, REGION_TEST_SHARED);
    return !!test_res;
}

#else

int region_intersects(const QRegion *rgn1, const QRegion *rgn2)
{
    QRegion tmp;
    int ret;

    ASSERT(REGION_IS_VALID(rgn1));
    ASSERT(REGION_IS_VALID(rgn2));

    region_clone(&tmp, rgn1);
    region_and(&tmp, rgn2);
    ret = !region_is_empty(&tmp);
    region_destroy(&tmp);
    return ret;
}

#endif

int region_bounds_intersects(const QRegion *rgn1, const QRegion *rgn2)
{
    return !region_is_empty(rgn1) && !region_is_empty(rgn2) &&
           rect_intersects(&rgn1->bbox, &rgn2->bbox);
}

#ifdef REGION_USE_IMPROVED

int region_contains(const QRegion *rgn, const QRegion *other)
{
    int test_res;

    ASSERT(REGION_IS_VALID(rgn));
    ASSERT(REGION_IS_VALID(other));

    test_res = region_test(rgn, other, REGION_TEST_RIGHT_EXCLUSIVE);
    return !test_res;
}

#else

int region_contains(const QRegion *rgn, const QRegion *other)
{
    QRegion tmp;
    int ret;

    ASSERT(REGION_IS_VALID(rgn));
    ASSERT(REGION_IS_VALID(other));

    region_clone(&tmp, rgn);
    region_and(&tmp, other);
    ret = region_is_equal(&tmp, other);
    region_destroy(&tmp);
    return ret;
}

#endif

int region_contains_point(const QRegion *rgn, int32_t x, int32_t y)
{
    if (region_is_empty(rgn)) {
        return FALSE;
    }
    Rect point;
    point.left = x;
    point.right = point.left + 1;
    point.top = y;
    point.bottom = point.top + 1;

    if (!rect_intersects(&rgn->bbox, &point)) {
        return FALSE;
    }

    Rect* now = rgn->rects;
    Rect* end = now + rgn->num_rects;

    for (; now < end; now++) {
        if (rect_intersects(now, &point)) {
            return TRUE;
        }
    }
    return FALSE;
}

#ifdef REGION_TEST

static void test(const QRegion *r1, const QRegion *r2, int *expected)
{
    printf("r1 is_empty %s [%s]\n",
           region_is_empty(r1) ? "TRUE" : "FALSE",
           (region_is_empty(r1) == *(expected++)) ? "OK" : "ERR");
    printf("r2 is_empty %s [%s]\n",
           region_is_empty(r2) ? "TRUE" : "FALSE",
           (region_is_empty(r2) == *(expected++)) ? "OK" : "ERR");
    printf("is_equal %s [%s]\n",
           region_is_equal(r1, r2) ? "TRUE" : "FALSE",
           (region_is_equal(r1, r2) == *(expected++)) ? "OK" : "ERR");
    printf("intersects %s [%s]\n",
           region_intersects(r1, r2) ? "TRUE" : "FALSE",
           (region_intersects(r1, r2) == *(expected++)) ? "OK" : "ERR");
    printf("contains %s [%s]\n",
           region_contains(r1, r2) ? "TRUE" : "FALSE",
           (region_contains(r1, r2) == *(expected++)) ? "OK" : "ERR");
}

enum {
    EXPECT_R1_EMPTY,
    EXPECT_R2_EMPTY,
    EXPECT_EQUAL,
    EXPECT_SECT,
    EXPECT_CONT,
};

int main(void)
{
    QRegion _r1, _r2, _r3;
    QRegion *r1 = &_r1;
    QRegion *r2 = &_r2;
    QRegion *r3 = &_r3;
    Rect _r;
    Rect *r = &_r;
    int expected[5];

    region_init(r1);
    region_init(r2);

    printf("dump r1 empty rgn [%s]\n", region_is_valid(r1) ? "VALID" : "INVALID");
    region_dump(r1, "");
    expected[EXPECT_R1_EMPTY] = TRUE;
    expected[EXPECT_R2_EMPTY] = TRUE;
    expected[EXPECT_EQUAL] = TRUE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");

    region_clone(r3, r1);
    printf("dump r3 clone rgn [%s]\n", region_is_valid(r3) ? "VALID" : "INVALID");
    region_dump(r3, "");
    expected[EXPECT_R1_EMPTY] = TRUE;
    expected[EXPECT_R2_EMPTY] = TRUE;
    expected[EXPECT_EQUAL] = TRUE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r3, expected);
    region_destroy(r3);
    printf("\n");

    rect_set(r, 0, 0, 100, 100);
    region_add(r1, r);
    printf("dump r1 [%s]\n", region_is_valid(r1) ? "VALID" : "INVALID");
    region_dump(r1, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = TRUE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");

    region_clear(r1);
    rect_set(r, 0, 0, 0, 0);
    region_add(r1, r);
    printf("dump r1 [%s]\n", region_is_valid(r1) ? "VALID" : "INVALID");
    region_dump(r1, "");
    expected[EXPECT_R1_EMPTY] = TRUE;
    expected[EXPECT_R2_EMPTY] = TRUE;
    expected[EXPECT_EQUAL] = TRUE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");

    rect_set(r, -100, -100, 0, 0);
    region_add(r1, r);
    printf("dump r1 [%s]\n", region_is_valid(r1) ? "VALID" : "INVALID");
    region_dump(r1, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = TRUE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");

    region_clear(r1);
    rect_set(r, -100, -100, 100, 100);
    region_add(r1, r);
    printf("dump r1 [%s]\n", region_is_valid(r1) ? "VALID" : "INVALID");
    region_dump(r1, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = TRUE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");


    region_clear(r1);
    region_clear(r2);

    rect_set(r, 100, 100, 200, 200);
    region_add(r1, r);
    printf("dump r1 [%s]\n", region_is_valid(r1) ? "VALID" : "INVALID");
    region_dump(r1, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = TRUE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");

    rect_set(r, 300, 300, 400, 400);
    region_add(r1, r);
    printf("dump r1 [%s]\n", region_is_valid(r1) ? "VALID" : "INVALID");
    region_dump(r1, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = TRUE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");

    rect_set(r, 500, 500, 600, 600);
    region_add(r2, r);
    printf("dump r2 [%s]\n", region_is_valid(r2) ? "VALID" : "INVALID");
    region_dump(r2, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = FALSE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = FALSE;
    test(r1, r2, expected);
    printf("\n");

    region_clear(r2);

    rect_set(r, 100, 100, 200, 200);
    region_add(r2, r);
    rect_set(r, 300, 300, 400, 400);
    region_add(r2, r);
    printf("dump r2 [%s]\n", region_is_valid(r2) ? "VALID" : "INVALID");
    region_dump(r2, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = FALSE;
    expected[EXPECT_EQUAL] = TRUE;
    expected[EXPECT_SECT] = TRUE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");

    region_clear(r2);

    rect_set(r, 100, 100, 200, 200);
    region_add(r2, r);
    printf("dump r2 [%s]\n", region_is_valid(r2) ? "VALID" : "INVALID");
    region_dump(r2, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = FALSE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = TRUE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");

    region_clear(r2);

    rect_set(r, -2000, -2000, -1000, -1000);
    region_add(r2, r);
    printf("dump r2 [%s]\n", region_is_valid(r2) ? "VALID" : "INVALID");
    region_dump(r2, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = FALSE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = FALSE;
    expected[EXPECT_CONT] = FALSE;
    test(r1, r2, expected);
    printf("\n");

    region_clear(r2);

    rect_set(r, -2000, -2000, 1000, 1000);
    region_add(r2, r);
    printf("dump r2 [%s]\n", region_is_valid(r2) ? "VALID" : "INVALID");
    region_dump(r2, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = FALSE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = TRUE;
    expected[EXPECT_CONT] = FALSE;
    test(r1, r2, expected);
    printf("\n");

    region_clear(r2);

    rect_set(r, 150, 150, 175, 175);
    region_add(r2, r);
    printf("dump r2 [%s]\n", region_is_valid(r2) ? "VALID" : "INVALID");
    region_dump(r2, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = FALSE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = TRUE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r2, expected);
    printf("\n");

    region_clear(r2);

    rect_set(r, 150, 150, 350, 350);
    region_add(r2, r);
    printf("dump r2 [%s]\n", region_is_valid(r2) ? "VALID" : "INVALID");
    region_dump(r2, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = FALSE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = TRUE;
    expected[EXPECT_CONT] = FALSE;
    test(r1, r2, expected);
    printf("\n");

    region_and(r2, r1);
    printf("dump r2 and r1 [%s]\n", region_is_valid(r2) ? "VALID" : "INVALID");
    region_dump(r2, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = FALSE;
    expected[EXPECT_EQUAL] = FALSE;
    expected[EXPECT_SECT] = TRUE;
    expected[EXPECT_CONT] = FALSE;
    test(r2, r1, expected);
    printf("\n");


    region_clone(r3, r1);
    printf("dump r3 clone rgn [%s]\n", region_is_valid(r3) ? "VALID" : "INVALID");
    region_dump(r3, "");
    expected[EXPECT_R1_EMPTY] = FALSE;
    expected[EXPECT_R2_EMPTY] = FALSE;
    expected[EXPECT_EQUAL] = TRUE;
    expected[EXPECT_SECT] = TRUE;
    expected[EXPECT_CONT] = TRUE;
    test(r1, r3, expected);
    printf("\n");


    region_destroy(r3);
    region_destroy(r1);
    region_destroy(r2);

    return 0;
}

#endif