gtktextbtree.c 164 KB
Newer Older
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
/*
 * gtktextbtree.c --
 *
 *      This file contains code that manages the B-tree representation
 *      of text for the text buffer and implements character and
 *      toggle segment types.
 *
 * Copyright (c) 1992-1994 The Regents of the University of California.
 * Copyright (c) 1994-1995 Sun Microsystems, Inc.
 * Copyright (c) 2000      Red Hat, Inc.
 * Tk -> Gtk port by Havoc Pennington <hp@redhat.com>
 *
 * This software is copyrighted by the Regents of the University of
 * California, Sun Microsystems, Inc., and other parties.  The
 * following terms apply to all files associated with the software
 * unless explicitly disclaimed in individual files.
 * 
 * The authors hereby grant permission to use, copy, modify,
 * distribute, and license this software and its documentation for any
 * purpose, provided that existing copyright notices are retained in
 * all copies and that this notice is included verbatim in any
 * distributions. No written agreement, license, or royalty fee is
 * required for any of the authorized uses.  Modifications to this
 * software may be copyrighted by their authors and need not follow
 * the licensing terms described here, provided that the new terms are
 * clearly indicated on the first page of each file where they apply.
 * 
 * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY
 * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
 * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION,
 * OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
 * NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
 * AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
 * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 *
 * GOVERNMENT USE: If you are acquiring this software on behalf of the
 * U.S. government, the Government shall have only "Restricted Rights"
 * in the software and related documentation as defined in the Federal
 * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
 * are acquiring the software on behalf of the Department of Defense,
 * the software shall be classified as "Commercial Computer Software"
 * and the Government shall have only "Restricted Rights" as defined
 * in Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the
 * foregoing, the authors grant the U.S. Government and others acting
 * in its behalf permission to use and distribute the software in
 * accordance with the terms specified in this license.
 * 
 */

#include "gtktextbtree.h"
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include "gtksignal.h"
#include "gtktexttag.h"
#include "gtktexttagtable.h"
#include "gtktextlayout.h"
#include "gtktextiterprivate.h"
#include "gtkdebug.h"
66
#include "gtktextmarkprivate.h"
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

/*
 * Types
 */


/*
 * The structure below is used to pass information between
 * gtk_text_btree_get_tags and inc_count:
 */

typedef struct TagInfo {
  int numTags;                  /* Number of tags for which there
                                 * is currently information in
                                 * tags and counts. */
  int arraySize;                        /* Number of entries allocated for
                                         * tags and counts. */
  GtkTextTag **tags;           /* Array of tags seen so far.
                                * Malloc-ed. */
  int *counts;                  /* Toggle count (so far) for each
                                 * entry in tags.  Malloc-ed. */
} TagInfo;


/*
 * This is used to store per-view width/height info at the tree nodes.
 */

typedef struct _NodeData NodeData;

struct _NodeData {
  gpointer view_id;
  NodeData *next;

  /* Height and width of this node */
  gint height;
  gint width : 24;
  
  /* boolean indicating whether the height/width need to be recomputed */
  gint valid : 8;
};


/*
 * The data structure below keeps summary information about one tag as part
 * of the tag information in a node.
 */

typedef struct Summary {
  GtkTextTagInfo *info;                     /* Handle for tag. */
  int toggle_count;                     /* Number of transitions into or
                                         * out of this tag that occur in
                                         * the subtree rooted at this node. */
  struct Summary *next;         /* Next in list of all tags for same
                                 * node, or NULL if at end of list. */
} Summary;

/*
 * The data structure below defines a node in the B-tree.
 */

struct _GtkTextBTreeNode {
  GtkTextBTreeNode *parent;         /* Pointer to parent node, or NULL if
                                     * this is the root. */
  GtkTextBTreeNode *next;           /* Next in list of siblings with the
                                     * same parent node, or NULL for end
                                     * of list. */
  Summary *summary;             /* First in malloc-ed list of info
                                 * about tags in this subtree (NULL if
                                 * no tag info in the subtree). */
  int level;                            /* Level of this node in the B-tree.
                                         * 0 refers to the bottom of the tree
                                         * (children are lines, not nodes). */
  union {                               /* First in linked list of children. */
    struct _GtkTextBTreeNode *node;         /* Used if level > 0. */
    GtkTextLine *line;         /* Used if level == 0. */
  } children;
  int num_children;                     /* Number of children of this node. */
  int num_lines;                        /* Total number of lines (leaves) in
                                         * the subtree rooted here. */
  int num_chars;                        /* Number of chars below here */

  NodeData *node_data;
};


/*
 * Used to store the list of views in our btree
 */

typedef struct _BTreeView BTreeView;

struct _BTreeView {
  gpointer view_id;
  GtkTextLayout *layout;
  BTreeView *next;
  BTreeView *prev;
};

/*
 * And the tree itself
 */

struct _GtkTextBTree {
  GtkTextBTreeNode *root_node;          /* Pointer to root of B-tree. */
  GtkTextTagTable *table;
  GHashTable *mark_table;
  guint refcount;
  GtkTextLineSegment *insert_mark;
  GtkTextLineSegment *selection_bound_mark;
  GtkTextBuffer *buffer;
  BTreeView *views;
  GSList *tag_infos;
  guint tag_changed_handler;
  guint tag_removed_handler;
  /* Incremented when a segment with a byte size > 0
     is added to or removed from the tree (i.e. the
     length of a line may have changed, and lines may
     have been added or removed). This invalidates
     all outstanding iterators.
  */
  guint chars_changed_stamp;
  /* Incremented when any segments are added or deleted;
     this makes outstanding iterators recalculate their
     pointed-to segment and segment offset.
  */
  guint segments_changed_stamp;
194 195 196 197

  GtkTextLine *end_iter_line;
  
  guint end_iter_line_stamp;
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
};


/*
 * Upper and lower bounds on how many children a node may have:
 * rebalance when either of these limits is exceeded.  MAX_CHILDREN
 * should be twice MIN_CHILDREN and MIN_CHILDREN must be >= 2.
 */

/* Tk used MAX of 12 and MIN of 6. This makes the tree wide and
   shallow. It appears to be faster to locate a particular line number
   if the tree is narrow and deep, since it is more finely sorted.  I
   guess this may increase memory use though, and make it slower to
   walk the tree in order, or locate a particular byte index (which
   is done by walking the tree in order).
   
   There's basically a tradeoff here. However I'm thinking we want to
   add pixels, byte counts, and char counts to the tree nodes,
   at that point narrow and deep should speed up all operations,
   not just the line number searches.
*/

#if 1
#define MAX_CHILDREN 12
#define MIN_CHILDREN 6
#else
#define MAX_CHILDREN 6
#define MIN_CHILDREN 3
#endif

/*
 * Prototypes
 */

static BTreeView        *gtk_text_btree_get_view                 (GtkTextBTree     *tree,
                                                                  gpointer          view_id);
static void              gtk_text_btree_rebalance                (GtkTextBTree     *tree,
                                                                  GtkTextBTreeNode *node);
static GtkTextLine     * get_last_line                           (GtkTextBTree     *tree);
static void              post_insert_fixup                       (GtkTextBTree     *tree,
                                                                  GtkTextLine      *insert_line,
                                                                  gint              char_count_delta,
                                                                  gint              line_count_delta);
static void              gtk_text_btree_node_adjust_toggle_count (GtkTextBTreeNode *node,
                                                                  GtkTextTagInfo   *info,
                                                                  gint              adjust);
static gboolean          gtk_text_btree_node_has_tag             (GtkTextBTreeNode *node,
                                                                  GtkTextTag       *tag);

static void             segments_changed                (GtkTextBTree     *tree);
static void             chars_changed                   (GtkTextBTree     *tree);
static void             summary_list_destroy            (Summary          *summary);
static GtkTextLine     *gtk_text_line_new               (void);
static void             gtk_text_line_destroy           (GtkTextBTree     *tree,
                                                         GtkTextLine      *line);
static void             gtk_text_line_set_parent        (GtkTextLine      *line,
                                                         GtkTextBTreeNode *node);
static void             gtk_text_btree_node_remove_data (GtkTextBTreeNode *node,
                                                         gpointer          view_id);


static NodeData         *node_data_new          (gpointer  view_id);
static void              node_data_destroy      (NodeData *nd);
static void              node_data_list_destroy (NodeData *nd);
static NodeData         *node_data_find         (NodeData *nd,
                                                 gpointer  view_id);

static GtkTextBTreeNode     *gtk_text_btree_node_new                  (void);
static void                  gtk_text_btree_node_invalidate_downward  (GtkTextBTreeNode *node);
static void                  gtk_text_btree_node_invalidate_upward    (GtkTextBTreeNode *node,
								       gpointer          view_id);
static NodeData *            gtk_text_btree_node_check_valid          (GtkTextBTreeNode *node,
								       gpointer          view_id);
static NodeData *            gtk_text_btree_node_check_valid_downward (GtkTextBTreeNode *node,
								       gpointer          view_id);
static void                  gtk_text_btree_node_check_valid_upward   (GtkTextBTreeNode *node,
								       gpointer          view_id);

static void                  gtk_text_btree_node_remove_view         (BTreeView        *view,
                                                                      GtkTextBTreeNode *node,
                                                                      gpointer          view_id);
static void                  gtk_text_btree_node_destroy             (GtkTextBTree     *tree,
                                                                      GtkTextBTreeNode *node);
static NodeData         *    gtk_text_btree_node_ensure_data         (GtkTextBTreeNode *node,
                                                                      gpointer          view_id);
static void                  gtk_text_btree_node_remove_data         (GtkTextBTreeNode *node,
                                                                      gpointer          view_id);
static void                  gtk_text_btree_node_get_size            (GtkTextBTreeNode *node,
                                                                      gpointer          view_id,
                                                                      gint             *width,
                                                                      gint             *height);
static GtkTextBTreeNode *    gtk_text_btree_node_common_parent       (GtkTextBTreeNode *node1,
								      GtkTextBTreeNode *node2);
static void get_tree_bounds       (GtkTextBTree     *tree,
                                   GtkTextIter      *start,
                                   GtkTextIter      *end);
static void tag_changed_cb        (GtkTextTagTable  *table,
                                   GtkTextTag       *tag,
                                   gboolean          size_changed,
                                   GtkTextBTree     *tree);
static void tag_removed_cb        (GtkTextTagTable  *table,
                                   GtkTextTag       *tag,
                                   GtkTextBTree     *tree);
static void cleanup_line          (GtkTextLine      *line);
static void recompute_node_counts (GtkTextBTree     *tree,
				   GtkTextBTreeNode *node);
static void inc_count             (GtkTextTag       *tag,
                                   int               inc,
                                   TagInfo          *tagInfoPtr);

static void summary_destroy       (Summary          *summary);

static void gtk_text_btree_link_segment   (GtkTextLineSegment *seg,
                                           const GtkTextIter  *iter);
static void gtk_text_btree_unlink_segment (GtkTextBTree       *tree,
                                           GtkTextLineSegment *seg,
                                           GtkTextLine        *line);


static GtkTextTagInfo *gtk_text_btree_get_tag_info          (GtkTextBTree   *tree,
                                                             GtkTextTag     *tag);
static GtkTextTagInfo *gtk_text_btree_get_existing_tag_info (GtkTextBTree   *tree,
                                                             GtkTextTag     *tag);
static void            gtk_text_btree_remove_tag_info       (GtkTextBTree   *tree,
                                                             GtkTextTag     *tag);


/* Inline thingies */

static inline void
segments_changed(GtkTextBTree *tree)
{
  tree->segments_changed_stamp += 1;
}

static inline void
chars_changed(GtkTextBTree *tree)
{
  tree->chars_changed_stamp += 1;
}

/*
 * BTree operations
 */

GtkTextBTree*
gtk_text_btree_new (GtkTextTagTable *table,
                    GtkTextBuffer *buffer)
{
  GtkTextBTree *tree;
  GtkTextBTreeNode *root_node;
  GtkTextLine *line, *line2;

  g_return_val_if_fail(GTK_IS_TEXT_TAG_TABLE(table), NULL);
  g_return_val_if_fail(GTK_IS_TEXT_BUFFER(buffer), NULL);
  
  /*
   * The tree will initially have two empty lines.  The second line
   * isn't actually part of the tree's contents, but its presence
   * makes several operations easier.  The tree will have one GtkTextBTreeNode,
   * which is also the root of the tree.
   */

  /* Create the root node. */
  
  root_node = gtk_text_btree_node_new();
  
  line = gtk_text_line_new();
  line2 = gtk_text_line_new();

  root_node->parent = NULL;
  root_node->next = NULL;
  root_node->summary = NULL;
  root_node->level = 0;
  root_node->children.line = line;
  root_node->num_children = 2;
  root_node->num_lines = 2;
  root_node->num_chars = 2;
  
  line->parent = root_node;
  line->next = line2;

  line->segments = char_segment_new("\n", 1);

  line2->parent = root_node;
  line2->next = NULL;
  line2->segments = char_segment_new("\n", 1);

  /* Create the tree itself */
  
  tree = g_new0(GtkTextBTree, 1);
  tree->root_node = root_node;
  tree->table = table;
  tree->views = NULL;

  /* Set these to values that are unlikely to be found
     in random memory garbage. */
  tree->chars_changed_stamp = 49;
  tree->segments_changed_stamp = 243;
397 398 399

  tree->end_iter_line_stamp = tree->chars_changed_stamp - 1;
  tree->end_iter_line = NULL;
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
  
  gtk_object_ref(GTK_OBJECT(tree->table));
  gtk_object_sink(GTK_OBJECT(tree->table));

  tree->tag_changed_handler = gtk_signal_connect(GTK_OBJECT(tree->table),
                                                 "tag_changed",
                                                 GTK_SIGNAL_FUNC(tag_changed_cb),
                                                 tree);

  tree->tag_removed_handler = gtk_signal_connect(GTK_OBJECT(tree->table),
                                                 "tag_removed",
                                                 GTK_SIGNAL_FUNC(tag_removed_cb),
                                                 tree);
  
  tree->mark_table = g_hash_table_new(g_str_hash, g_str_equal);

  /* We don't ref the buffer, since the buffer owns us;
     we'd have some circularity issues. The buffer always
     lasts longer than the BTree
  */
  tree->buffer = buffer;
  
  {
    GtkTextIter start;

    gtk_text_btree_get_iter_at_line_char(tree, &start, 0, 0);
    

428 429 430 431 432 433 434 435 436 437
    tree->insert_mark =
      (GtkTextLineSegment*) gtk_text_btree_set_mark(tree,
                                                    NULL,
                                                    "insert",
                                                    FALSE,
                                                    &start,
                                                    FALSE);
    
    tree->insert_mark->body.mark.not_deleteable = TRUE;
    
438 439
    tree->insert_mark->body.mark.visible = TRUE;
    
440 441 442 443 444 445 446 447 448
    tree->selection_bound_mark =
      (GtkTextLineSegment*) gtk_text_btree_set_mark(tree,
                                                    NULL,
                                                    "selection_bound",
                                                    FALSE,
                                                    &start,
                                                    FALSE);

    tree->selection_bound_mark->body.mark.not_deleteable = TRUE;
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
    
    mark_segment_ref(tree->insert_mark);
    mark_segment_ref(tree->selection_bound_mark);
  }

  tree->refcount = 1;
  
  return tree;
}

void
gtk_text_btree_ref (GtkTextBTree *tree)
{
  g_return_if_fail(tree != NULL);
  g_return_if_fail(tree->refcount > 0);
  
  tree->refcount += 1;
}

static void
mark_destroy_foreach(gpointer key, gpointer value, gpointer user_data)
{
  mark_segment_unref(value);
}

void
gtk_text_btree_unref (GtkTextBTree *tree)
{
  g_return_if_fail(tree != NULL);
  g_return_if_fail(tree->refcount > 0);

  tree->refcount -= 1;

  if (tree->refcount == 0)
    {      
      gtk_text_btree_node_destroy(tree, tree->root_node);

      g_hash_table_foreach(tree->mark_table,
                           mark_destroy_foreach,
                           NULL);
      g_hash_table_destroy(tree->mark_table);
      
      mark_segment_unref(tree->insert_mark);
      mark_segment_unref(tree->selection_bound_mark);

      gtk_signal_disconnect(GTK_OBJECT(tree->table),
                            tree->tag_changed_handler);

      gtk_signal_disconnect(GTK_OBJECT(tree->table),
                            tree->tag_removed_handler);
      
      gtk_object_unref(GTK_OBJECT(tree->table));

      g_free(tree);
    }
}

GtkTextBuffer*
gtk_text_btree_get_buffer (GtkTextBTree *tree)
{
  return tree->buffer;
}

guint
gtk_text_btree_get_chars_changed_stamp (GtkTextBTree *tree)
{
  return tree->chars_changed_stamp;
}

guint
gtk_text_btree_get_segments_changed_stamp (GtkTextBTree *tree)
{
  return tree->segments_changed_stamp;
}

void
gtk_text_btree_segments_changed (GtkTextBTree *tree)
{
  g_return_if_fail(tree != NULL);
  segments_changed(tree);
}

/*
 * Indexable segment mutation
 */

void
gtk_text_btree_delete (GtkTextIter *start,
                       GtkTextIter *end)
{
  GtkTextLineSegment *prev_seg;             /* The segment just before the start
                                             * of the deletion range. */
  GtkTextLineSegment *last_seg;             /* The segment just after the end
                                             * of the deletion range. */
  GtkTextLineSegment *seg, *next;
  GtkTextLine *curline;
  GtkTextBTreeNode *curnode, *node;
  GtkTextBTree *tree;
  GtkTextLine *start_line;
  GtkTextLine *end_line;
  GtkTextLine *deleted_lines = NULL;	    /* List of lines we've deleted */
  gint start_byte_offset;
  
  g_return_if_fail(start != NULL);
  g_return_if_fail(end != NULL);
  g_return_if_fail(gtk_text_iter_get_btree(start) ==
                   gtk_text_iter_get_btree(end));

  gtk_text_iter_reorder(start, end);
  
  tree = gtk_text_iter_get_btree(start);
  
  {
    /*
     * The code below is ugly, but it's needed to make sure there
     * is always a dummy empty line at the end of the text.  If the
     * final newline of the file (just before the dummy line) is being
     * deleted, then back up index to just before the newline.  If
     * there is a newline just before the first character being deleted,
     * then back up the first index too, so that an even number of lines
     * gets deleted.  Furthermore, remove any tags that are present on
     * the newline that isn't going to be deleted after all (this simulates
     * deleting the newline and then adding a "clean" one back again).
     */

    gint line1;
    gint line2;
    
577 578
    line1 = gtk_text_iter_get_line(start);
    line2 = gtk_text_iter_get_line(end);
579 580 581 582 583 584 585 586
    
    if (line2 == gtk_text_btree_line_count(tree))
      {
        GtkTextTag** tags;
        int array_size;
        GtkTextIter orig_end;
        
        orig_end = *end;
587
        gtk_text_iter_prev_char(end);
588 589 590
        
        --line2;

591
        if (gtk_text_iter_get_line_offset(start) == 0 &&
592 593
            line1 != 0)
          {
594
            gtk_text_iter_prev_char(start);
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
            --line1;
          }
        
        tags = gtk_text_btree_get_tags(end,
                                       &array_size);
        
        if (tags != NULL)
          {
            int i;

            i = 0;
            while (i < array_size)
              {
                gtk_text_btree_tag(end, &orig_end, tags[i], FALSE);
                
                ++i;
              }

            g_free(tags);
          }
      }
  }
  
  /* Broadcast the need for redisplay before we break the iterators */
  gtk_text_btree_invalidate_region(tree, start, end);

  /* Save the byte offset so we can reset the iterators */
622
  start_byte_offset = gtk_text_iter_get_line_index(start);
623
  
624 625
  start_line = gtk_text_iter_get_text_line(start);
  end_line = gtk_text_iter_get_text_line(end);
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
  
  /*
   * Split the start and end segments, so we have a place
   * to insert our new text.
   *
   * Tricky point:  split at end first;  otherwise the split
   * at end may invalidate seg and/or prev_seg. This allows
   * us to avoid invalidating segments for start.
   */

  last_seg = gtk_text_line_segment_split(end);
  if (last_seg != NULL)
    last_seg = last_seg->next;
  else
    last_seg = end_line->segments;

  prev_seg = gtk_text_line_segment_split(start);
  if (prev_seg != NULL)
    {
      seg = prev_seg->next;
      prev_seg->next = last_seg;
    }
  else
    {
      seg = start_line->segments;
      start_line->segments = last_seg;
    }

  /* notify iterators that their segments need recomputation,
     just for robustness. */
  segments_changed(tree);
  
  /*
   * Delete all of the segments between prev_seg and last_seg.
   */

  curline = start_line;
  curnode = curline->parent;
  while (seg != last_seg)
    {
      gint char_count = 0;
    
      if (seg == NULL)
        {
          GtkTextLine *nextline;

          /*
           * We just ran off the end of a line.  First find the
           * next line, then go back to the old line and delete it
           * (unless it's the starting line for the range).
           */

          nextline = gtk_text_line_next(curline);
          if (curline != start_line)
            {
              if (curnode == start_line->parent)
                start_line->next = curline->next;
              else
                curnode->children.line = curline->next;
              
              for (node = curnode; node != NULL;
                   node = node->parent)
                {
                  node->num_lines -= 1;
                }
              
              curnode->num_children -= 1;
	      curline->next = deleted_lines;
	      deleted_lines = curline;
            }
          
          curline = nextline;
          seg = curline->segments;

          /*
           * If the GtkTextBTreeNode is empty then delete it and its parents,
           * recursively upwards until a non-empty GtkTextBTreeNode is found.
           */

          while (curnode->num_children == 0)
            {
              GtkTextBTreeNode *parent;

              parent = curnode->parent;
              if (parent->children.node == curnode)
                {
                  parent->children.node = curnode->next;
                }
              else
                {
                  GtkTextBTreeNode *prevnode = parent->children.node;
                  while (prevnode->next != curnode)
                    {
                      prevnode = prevnode->next;
                    }
                  prevnode->next = curnode->next;
                }
              parent->num_children--;
              g_free(curnode);
              curnode = parent;
            }
          curnode = curline->parent;
          continue;
        }

      next = seg->next;
      char_count = seg->char_count;
    
      if ((*seg->type->deleteFunc)(seg, curline, 0) != 0)
        {
          /*
           * This segment refuses to die.  Move it to prev_seg and
           * advance prev_seg if the segment has left gravity.
           */
        
          if (prev_seg == NULL)
            {
              seg->next = start_line->segments;
              start_line->segments = seg;
            }
          else
            {
              seg->next = prev_seg->next;
              prev_seg->next = seg;
            }
          if (seg->type->leftGravity)
            {
              prev_seg = seg;
            }
        }
      else
        {
          /* Segment is gone. Decrement the char count of the node and
             all its parents. */
          for (node = curnode; node != NULL;
               node = node->parent)
            {
              node->num_chars -= char_count;
            }
        }
    
      seg = next;
    }

  /*
   * If the beginning and end of the deletion range are in different
   * lines, join the two lines together and discard the ending line.
   */

  if (start_line != end_line)
    {
      BTreeView *view;
      GtkTextBTreeNode *ancestor_node;
      
      GtkTextLine *prevline;

      for (seg = last_seg; seg != NULL;
           seg = seg->next)
        {
          if (seg->type->lineChangeFunc != NULL)
            {
              (*seg->type->lineChangeFunc)(seg, end_line);
            }
        }
      curnode = end_line->parent;
      for (node = curnode; node != NULL;
           node = node->parent)
        {
          node->num_lines--;
        }
      curnode->num_children--;
      prevline = curnode->children.line;
      if (prevline == end_line)
        {
          curnode->children.line = end_line->next;
        }
      else
        {
          while (prevline->next != end_line)
            {
              prevline = prevline->next;
            }
          prevline->next = end_line->next;
        }
      end_line->next = deleted_lines;
      deleted_lines = end_line;

      /* We now fix up the per-view aggregates. We add all the height and
       * width for the deleted lines to the start line, so that when revalidation
       * occurs, the correct change in size is seen.
       */
      ancestor_node = gtk_text_btree_node_common_parent (curnode, start_line->parent);
      view = tree->views;
      while (view)
	{
	  GtkTextLine *line;
	  GtkTextLineData *ld;
	  
	  gint deleted_width = 0;
	  gint deleted_height = 0;

	  line = deleted_lines;
	  while (line)
	    {
	      GtkTextLine *next_line = line->next;
	      ld = gtk_text_line_get_data (line, view->view_id);

	      if (ld)
		{
		  deleted_width = MAX (deleted_width, ld->width);
		  deleted_height += ld->height;
		}

	      if (!view->next)
		gtk_text_line_destroy(tree, line);
		
	      line = next_line;
	    }

	  if (deleted_width > 0 || deleted_height > 0)
	    {
	      ld = gtk_text_line_get_data (start_line, view->view_id);

	      /* FIXME: ld is _NOT_ necessarily non-null here, but there is currently
	       * no way to add ld without also validating the node, which would
	       * be improper at this point.
	       */
853 854
              /* This assertion does actually fail sometimes, must
                 fix before stable release -hp */
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
	      g_assert (ld);

	      ld->width = MAX (deleted_width, ld->width);
	      ld->height += deleted_height;
	      ld->valid = FALSE;
	    }
	  
	  gtk_text_btree_node_check_valid_downward (ancestor_node, view->view_id);
	  if (ancestor_node->parent)
	    gtk_text_btree_node_check_valid_upward (ancestor_node->parent, view->view_id);

	  view = view->next;
	}
      
      gtk_text_btree_rebalance(tree, curnode);
    }

  /*
   * Cleanup the segments in the new line.
   */

  cleanup_line(start_line);

  /*
   * Lastly, rebalance the first GtkTextBTreeNode of the range.
   */

  gtk_text_btree_rebalance(tree, start_line->parent);
  
  /* Notify outstanding iterators that they
     are now hosed */
  chars_changed(tree);
  segments_changed(tree);

  if (gtk_debug_flags & GTK_DEBUG_TEXT)
    gtk_text_btree_check(tree);

  /* Re-initialize our iterators */
  gtk_text_btree_get_iter_at_line(tree, start, start_line, start_byte_offset);
  *end = *start;
}

void
gtk_text_btree_insert (GtkTextIter *iter,
                       const gchar *text,
                       gint len)
{
  GtkTextLineSegment *prev_seg;     /* The segment just before the first
                                     * new segment (NULL means new segment
                                     * is at beginning of line). */
  GtkTextLineSegment *cur_seg;              /* Current segment;  new characters
                                             * are inserted just after this one. 
                                             * NULL means insert at beginning of
                                             * line. */
  GtkTextLine *line;           /* Current line (new segments are
                                * added to this line). */
  GtkTextLineSegment *seg;
  GtkTextLine *newline;
  int chunkSize;                        /* # characters in current chunk. */
  guint sol; /* start of line */
  guint eol;                      /* Pointer to character just after last
                                   * one in current chunk. */
  int line_count_delta;                /* Counts change to total number of
                                        * lines in file. */

  int char_count_delta;                /* change to number of chars */
  GtkTextBTree *tree;
  gint start_byte_index;
  GtkTextLine *start_line;
  
  g_return_if_fail(text != NULL);
  g_return_if_fail(iter != NULL);
  
  if (len < 0)
    len = strlen(text);

  /* extract iterator info */
  tree = gtk_text_iter_get_btree(iter);
933
  line = gtk_text_iter_get_text_line(iter);
934
  start_line = line;
935
  start_byte_index = gtk_text_iter_get_line_index(iter);
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

  /* Get our insertion segment split */
  prev_seg = gtk_text_line_segment_split(iter);
  cur_seg = prev_seg;

  /* Invalidate all iterators */
  chars_changed(tree);
  segments_changed(tree);
  
  /*
   * Chop the text up into lines and create a new segment for
   * each line, plus a new line for the leftovers from the
   * previous line.
   */

  eol = 0;
  sol = 0;
  line_count_delta = 0;
  char_count_delta = 0;
  while (eol < len)
    {
      for (; eol < len; eol++)
        {
          if (text[eol] == '\n')
            {
              eol++;
              break;
            }
        }
      chunkSize = eol - sol;

      seg = char_segment_new(&text[sol], chunkSize);

      char_count_delta += seg->char_count;
    
      if (cur_seg == NULL)
        {
          seg->next = line->segments;
          line->segments = seg;
        }
      else
        {
          seg->next = cur_seg->next;
          cur_seg->next = seg;
        }

      if (text[eol-1] != '\n')
        {
          break;
        }

      /*
       * The chunk ended with a newline, so create a new GtkTextLine
       * and move the remainder of the old line to it.
       */

      newline = gtk_text_line_new();
      gtk_text_line_set_parent(newline, line->parent);
      newline->next = line->next;
      line->next = newline;
      newline->segments = seg->next;
      seg->next = NULL;
      line = newline;
      cur_seg = NULL;
      line_count_delta++;    
    
      sol = eol;
    }

  /*
   * Cleanup the starting line for the insertion, plus the ending
   * line if it's different.
   */

  cleanup_line(start_line);
  if (line != start_line)
    {
      cleanup_line(line);
    }

  post_insert_fixup(tree, line, line_count_delta, char_count_delta);
  
  /* Invalidate our region, and reset the iterator the user
     passed in to point to the end of the inserted text. */
  {
    GtkTextIter start;
    GtkTextIter end;


    gtk_text_btree_get_iter_at_line(tree,
                                    &start,
                                    start_line,
                                    start_byte_index);
    end = start;

    /* We could almost certainly be more efficient here
       by saving the information from the insertion loop
       above. FIXME */
    gtk_text_iter_forward_chars(&end, char_count_delta);

    gtk_text_btree_invalidate_region(tree,
                                     &start, &end);


    /* Convenience for the user */
    *iter = end;
  }
}

void
Havoc Pennington's avatar
Havoc Pennington committed
1046 1047
gtk_text_btree_insert_pixbuf (GtkTextIter *iter,
                              GdkPixbuf   *pixbuf)
1048 1049 1050 1051 1052 1053 1054 1055
{
  GtkTextLineSegment *seg;
  GtkTextIter start;
  GtkTextLineSegment *prevPtr;
  GtkTextLine *line;
  GtkTextBTree *tree;
  gint start_byte_offset;
  
1056
  line = gtk_text_iter_get_text_line(iter);
1057
  tree = gtk_text_iter_get_btree(iter);
1058
  start_byte_offset = gtk_text_iter_get_line_index(iter);
1059
  
Havoc Pennington's avatar
Havoc Pennington committed
1060
  seg = gtk_text_pixbuf_segment_new (pixbuf);
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083

  prevPtr = gtk_text_line_segment_split(iter);
  if (prevPtr == NULL)
    {
      seg->next = line->segments;
      line->segments = seg;
    }
  else
    {
      seg->next = prevPtr->next;
      prevPtr->next = seg;
    }

  post_insert_fixup(tree, line, 0, seg->char_count);

  chars_changed(tree);
  segments_changed(tree);

  /* reset *iter for the user, and invalidate tree nodes */
  
  gtk_text_btree_get_iter_at_line(tree, &start, line, start_byte_offset);

  *iter = start;
1084
  gtk_text_iter_next_char(iter); /* skip forward past the pixmap */
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 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385

  gtk_text_btree_invalidate_region(tree, &start, iter);
}


/*
 * View stuff
 */

static GtkTextLine*
find_line_by_y(GtkTextBTree *tree, BTreeView *view,
               GtkTextBTreeNode *node, gint y, gint *line_top,
               GtkTextLine *last_line)
{
  gint current_y = 0;

  if (gtk_debug_flags & GTK_DEBUG_TEXT)
    gtk_text_btree_check(tree);
  
  if (node->level == 0)
    {
      GtkTextLine *line;

      line = node->children.line;

      while (line != NULL && line != last_line)
        {
          GtkTextLineData *ld;

	  ld = gtk_text_line_get_data (line, view->view_id);

	  if (ld)
	    {
	      if (y < (current_y + (ld ? ld->height : 0)))
		return line;

	      current_y += ld->height;
	      *line_top += ld->height;
	    }
          
          line = line->next;
        }
      return NULL;
    }
  else
    {
      GtkTextBTreeNode *child;

      child = node->children.node;

      while (child != NULL)
        {
          gint width;
          gint height;

          gtk_text_btree_node_get_size(child, view->view_id,
                                       &width, &height);

          if (y < (current_y + height))            
            return find_line_by_y(tree, view, child,
                                  y - current_y, line_top,
                                  last_line);

          current_y += height;
          *line_top += height;
          
          child = child->next;
        }
      
      return NULL;
    }
}

GtkTextLine *
gtk_text_btree_find_line_by_y (GtkTextBTree *tree,
			       gpointer      view_id,
			       gint          ypixel,
			       gint         *line_top_out)
{
  GtkTextLine *line;
  BTreeView *view;
  GtkTextLine *last_line;
  gint line_top = 0;
  
  view = gtk_text_btree_get_view (tree, view_id);
  g_return_val_if_fail (view != NULL, NULL);

  last_line = get_last_line (tree);
  
  line = find_line_by_y (tree, view, tree->root_node, ypixel, &line_top,
			 last_line);

  if (line_top_out)
    *line_top_out = line_top;

  return line;
}

static gint
find_line_top_in_line_list(GtkTextBTree *tree,
                           BTreeView *view,
                           GtkTextLine *line,
                           GtkTextLine *target_line,
                           gint y)
{
  while (line != NULL)
    {
      GtkTextLineData *ld;
              
      if (line == target_line)
	return y;

      ld = gtk_text_line_get_data (line, view->view_id);
      if (ld)
	y += ld->height;
              
      line = line->next;
    }
          
  g_assert_not_reached(); /* If we get here, our
                             target line didn't exist
                             under its parent node */
  return 0;
}

gint
gtk_text_btree_find_line_top (GtkTextBTree *tree,
                              GtkTextLine *target_line,
                              gpointer view_id)
{
  gint y = 0;
  BTreeView *view;
  GSList *nodes;
  GSList *iter;
  GtkTextBTreeNode *node;
  
  view = gtk_text_btree_get_view(tree, view_id);

  g_return_val_if_fail(view != NULL, 0);

  nodes = NULL;
  node = target_line->parent;
  while (node != NULL)
    {
      nodes = g_slist_prepend(nodes, node);
      node = node->parent;
    }

  iter = nodes;
  while (iter != NULL)
    {      
      node = iter->data;
      
      if (node->level == 0)
        {
          g_slist_free(nodes);
          return find_line_top_in_line_list(tree, view,
                                            node->children.line,
                                            target_line, y);
        }
      else
        {
          GtkTextBTreeNode *child;
          GtkTextBTreeNode *target_node;

          g_assert(iter->next != NULL); /* not at level 0 */
          target_node = iter->next->data;
          
          child = node->children.node;

          while (child != NULL)
            {
              gint width;
              gint height;

              if (child == target_node)
                break;
              else
                {
                  gtk_text_btree_node_get_size(child, view->view_id,
                                               &width, &height);
                  y += height;
                }
              child = child->next;
            }
          g_assert(child != NULL); /* should have broken out before we
                                      ran out of nodes */
        }

      iter = g_slist_next(iter);
    }

  g_assert_not_reached(); /* we return when we find the target line */
  return 0;  
}

void
gtk_text_btree_add_view (GtkTextBTree *tree,
                         GtkTextLayout *layout)
{
  BTreeView *view;
  GtkTextLine *last_line;
  GtkTextLineData *line_data;

  g_return_if_fail(tree != NULL);
  
  view = g_new(BTreeView, 1);

  view->view_id = layout;
  view->layout = layout;
  
  view->next = tree->views;
  view->prev = NULL;

  tree->views = view;

  /* The last line in the buffer has identity values for the per-view
   * data so that we can avoid special case checks for it in a large
   * number of loops
   */
  last_line = get_last_line (tree);
  
  line_data = g_new (GtkTextLineData, 1);
  line_data->view_id = layout;
  line_data->next = NULL;
  line_data->width = 0;
  line_data->height = 0;
  line_data->valid = TRUE;
  
  gtk_text_line_add_data (last_line, line_data);
}

void
gtk_text_btree_remove_view (GtkTextBTree *tree,
                            gpointer view_id)
{
  BTreeView *view;
  GtkTextLine *last_line;
  GtkTextLineData *line_data;

  g_return_if_fail(tree != NULL);
  
  view = tree->views;
  
  while (view != NULL)
    {
      if (view->view_id == view_id)
        break;

      view = view->next;
    }
  
  g_return_if_fail(view != NULL);

  if (view->next)
    view->next->prev = view->prev;

  if (view->prev)
    view->prev->next = view->next;

  if (view == tree->views)
    tree->views = view->next;

  /* Remove the line data for the last line which we added ourselves.
   * (Do this first, so that we don't try to call the view's line data destructor on it.)
   */
  last_line = get_last_line (tree);
  line_data = gtk_text_line_remove_data (last_line, view_id);
  g_free (line_data);
  
  gtk_text_btree_node_remove_view(view, tree->root_node, view_id);
  
  g_free(view);
}

void
gtk_text_btree_invalidate_region (GtkTextBTree *tree,
                                  const GtkTextIter *start,
                                  const GtkTextIter *end)
{
  BTreeView *view;
  
  view = tree->views;

  while (view != NULL)
    {
      gtk_text_layout_invalidate(view->layout, start, end);

      view = view->next;
    }
}

void
gtk_text_btree_get_view_size (GtkTextBTree *tree,
                              gpointer view_id,
                              gint *width,
                              gint *height)
{
  g_return_if_fail(tree != NULL);
  g_return_if_fail(view_id != NULL);
  
Tor Lillqvist's avatar
Tor Lillqvist committed
1386 1387
  gtk_text_btree_node_get_size(tree->root_node, view_id,
			       width, height);  
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
}

/*
 * Tag
 */

typedef struct {
  GtkTextIter *iters;
  guint count;
  guint alloced;
} IterStack;

static IterStack*
iter_stack_new(void)
{
  IterStack *stack;
  stack = g_new(IterStack, 1);
  stack->iters = NULL;
  stack->count = 0;
  stack->alloced = 0;
  return stack;
}

static void
iter_stack_push(IterStack *stack, const GtkTextIter *iter)
{
  stack->count += 1;
  if (stack->count > stack->alloced)
    {
      stack->alloced = stack->count*2;
      stack->iters = g_realloc(stack->iters,
                               stack->alloced*sizeof(GtkTextIter));
    }
  stack->iters[stack->count-1] = *iter;
}

static gboolean
iter_stack_pop(IterStack *stack, GtkTextIter *iter)
{
  if (stack->count == 0)
    return FALSE;
  else
    {
      stack->count -= 1;
      *iter = stack->iters[stack->count];
      return TRUE;
    }
}

static void
iter_stack_free(IterStack *stack)
{
  g_free(stack->iters);
  g_free(stack);
}

static void
iter_stack_invert(IterStack *stack)
{
  if (stack->count > 0)
    {
      guint i = 0;
      guint j = stack->count - 1;
      while (i < j)
        {
          GtkTextIter tmp;
      
          tmp = stack->iters[i];
          stack->iters[i] = stack->iters[j];
          stack->iters[j] = tmp;

          ++i;
          --j;
        }
    }
}

void
gtk_text_btree_tag (const GtkTextIter *start_orig,
                    const GtkTextIter *end_orig,
                    GtkTextTag *tag,
                    gboolean add)
{
  GtkTextLineSegment *seg, *prev;
  GtkTextLine *cleanupline;
  gboolean toggled_on;
  GtkTextLine *start_line;
  GtkTextLine *end_line;
  GtkTextIter iter;
  GtkTextIter start, end;
  GtkTextBTree *tree;  
  IterStack *stack;
  GtkTextTagInfo *info;
  
  g_return_if_fail(start_orig != NULL);
  g_return_if_fail(end_orig != NULL);
  g_return_if_fail(GTK_IS_TEXT_TAG(tag));
  g_return_if_fail(gtk_text_iter_get_btree(start_orig) ==
                   gtk_text_iter_get_btree(end_orig));

#if 0
  printf("%s tag %s from %d to %d\n",
         add ? "Adding" : "Removing",
         tag->name,
1492 1493
         gtk_text_buffer_get_offset(start_orig),
         gtk_text_buffer_get_offset(end_orig));
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
#endif
  
  if (gtk_text_iter_equal(start_orig, end_orig))
    return;
  
  start = *start_orig;
  end = *end_orig;
  
  gtk_text_iter_reorder(&start, &end);
  
  tree = gtk_text_iter_get_btree(&start);

  info = gtk_text_btree_get_tag_info(tree, tag);
  
1508 1509
  start_line = gtk_text_iter_get_text_line(&start);
  end_line = gtk_text_iter_get_text_line(&end);
1510 1511 1512 1513 1514 1515 1516 1517

  /* Find all tag toggles in the region; we are going to delete them.
     We need to find them in advance, because
     forward_find_tag_toggle() won't work once we start playing around
     with the tree. */
  stack = iter_stack_new();
  iter = start;
  /* We don't want to delete a toggle that's at the start iterator. */
1518 1519
  gtk_text_iter_next_char(&iter);
  while (gtk_text_iter_forward_to_tag_toggle(&iter, tag))
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
    {
      if (gtk_text_iter_compare(&iter, &end) >= 0)
        break;
      else
        iter_stack_push(stack, &iter);
    }

  /* We need to traverse the toggles in order. */
  iter_stack_invert(stack);
  
  /*
   * See whether the tag is present at the start of the range.  If
   * the state doesn't already match what we want then add a toggle
   * there.
   */

  toggled_on = gtk_text_iter_has_tag(&start, tag);
  if ( (add && !toggled_on) ||
       (!add && toggled_on) )
    {
      /* This could create a second toggle at the start position;
         cleanup_line() will remove it if so. */
      seg = toggle_segment_new(info, add);

      prev = gtk_text_line_segment_split(&start);
      if (prev == NULL)
        {
          seg->next = start_line->segments;
          start_line->segments = seg;
        }
      else
        {
          seg->next = prev->next;
          prev->next = seg;
        }
      
      /* cleanup_line adds the new toggle to the node counts. */
#if 0
      printf("added toggle at start\n");
#endif
      /* we should probably call segments_changed, but in theory
         any still-cached segments in the iters we are about to
         use are still valid, since they're in front
         of this spot. */
    }
  
  /*
   *
   * Scan the range of characters and delete any internal tag
   * transitions.  Keep track of what the old state was at the end
   * of the range, and add a toggle there if it's needed.
   *
   */

  cleanupline = start_line;
  while (iter_stack_pop(stack, &iter))
    {
      GtkTextLineSegment *indexable_seg;
      GtkTextLine *line;
      
1580
      line = gtk_text_iter_get_text_line(&iter);
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
      seg = gtk_text_iter_get_any_segment(&iter);
      indexable_seg = gtk_text_iter_get_indexable_segment(&iter);

      g_assert(seg != NULL);
      g_assert(indexable_seg != NULL);
      g_assert(seg != indexable_seg);
      
      prev = line->segments;

      /* Find the segment that actually toggles this tag. */
      while (seg != indexable_seg)
        {
          g_assert(seg != NULL);
          g_assert(indexable_seg != NULL);
          g_assert(seg != indexable_seg);
      
          if ( (seg->type == &gtk_text_toggle_on_type ||
                seg->type == &gtk_text_toggle_off_type) && 
               (seg->body.toggle.info == info) )
            break;
          else
            seg = seg->next;
        }

      g_assert(seg != NULL);
      g_assert(indexable_seg != NULL);
      
      g_assert(seg != indexable_seg); /* If this happens, then
                                         forward_to_tag_toggle was
                                         full of shit. */
      g_assert(seg->body.toggle.info->tag == tag);

      /* If this happens, when previously tagging we didn't merge
         overlapping tags. */
      g_assert( (toggled_on && seg->type == &gtk_text_toggle_off_type) ||
                (!toggled_on && seg->type == &gtk_text_toggle_on_type) );
      
      toggled_on = !toggled_on;

#if 0
      printf("deleting %s toggle\n",
             seg->type == &gtk_text_toggle_on_type ? "on" : "off");
#endif 
      /* Remove toggle segment from the list. */
      if (prev == seg)
        {
          line->segments = seg->next;
        }
      else
        {
          while (prev->next != seg)
            {
              prev = prev->next;
            }
          prev->next = seg->next;
        }

      /* Inform iterators we've hosed them. This actually reflects a
         bit of inefficiency; if you have the same tag toggled on and
         off a lot in a single line, we keep having the rescan from
         the front of the line. Of course we have to do that to get
         "prev" anyway, but here we are doing it an additional
         time. FIXME */
      segments_changed(tree);

      /* Update node counts */
      if (seg->body.toggle.inNodeCounts)
        {
          change_node_toggle_count(line->parent,
                                   info, -1);
          seg->body.toggle.inNodeCounts = FALSE;
        }

      g_free(seg);

      /* We only clean up lines when we're done with them, saves some
         gratuitous line-segment-traversals */
      
      if (cleanupline != line)
        {
          cleanup_line(cleanupline);
          cleanupline = line;
        }
    }

  iter_stack_free(stack);
  
  /* toggled_on now reflects the toggle state _just before_ the
     end iterator. The end iterator could already have a toggle
     on or a toggle off. */
  if ( (add && !toggled_on) ||
       (!add && toggled_on) )
    {
      /* This could create a second toggle at the start position;
         cleanup_line() will remove it if so. */
      
      seg = toggle_segment_new(info, !add);

      prev = gtk_text_line_segment_split(&end);
      if (prev == NULL)
        {
          seg->next = end_line->segments;
          end_line->segments = seg;
        }
      else
        {
          seg->next = prev->next;
          prev->next = seg;
        }
      /* cleanup_line adds the new toggle to the node counts. */
      g_assert(seg->body.toggle.inNodeCounts == FALSE);
#if 0
      printf("added toggle at end\n");
#endif
    }

  /*
   * Cleanup cleanupline and the last line of the range, if
   * these are different.
   */

  cleanup_line(cleanupline);
  if (cleanupline != end_line)
    {
      cleanup_line(end_line);
    }

  segments_changed(tree);
  
  if (gtk_debug_flags & GTK_DEBUG_TEXT)
    gtk_text_btree_check(tree);
}


/*
 * "Getters"
 */

GtkTextLine*
gtk_text_btree_get_line (GtkTextBTree *tree,
                         gint  line_number,
                         gint *real_line_number)
{
  GtkTextBTreeNode *node;
  GtkTextLine *line;
  int lines_left;
  int line_count;

  line_count = gtk_text_btree_line_count(tree);
  
  if (line_number < 0)
    {
      line_number = line_count;
    }
  else if (line_number > line_count)
    {
      line_number = line_count;
    }

  if (real_line_number)
    *real_line_number = line_number;
  
  node = tree->root_node;
  lines_left = line_number;

  /*
   * Work down through levels of the tree until a GtkTextBTreeNode is found at
   * level 0.
   */

  while (node->level != 0)
    {
      for (node = node->children.node;
           node->num_lines <= lines_left;
           node = node->next)
        {
#if 0
          if (node == NULL)
            {
              g_error("gtk_text_btree_find_line ran out of GtkTextBTreeNodes");
            }
#endif
          lines_left -= node->num_lines;
        }
    }

  /*
   * Work through the lines attached to the level-0 GtkTextBTreeNode.
   */

  for (line = node->children.line; lines_left > 0;
       line = line->next)
    {
#if 0
      if (line == NULL)
        {
          g_error("gtk_text_btree_find_line ran out of lines");
        }
#endif
      lines_left -= 1;
    }
  return line;  
}

GtkTextLine*
gtk_text_btree_get_line_at_char(GtkTextBTree      *tree,
                                gint                char_index,
                                gint               *line_start_index,
                                gint               *real_char_index)
{
  GtkTextBTreeNode *node;
  GtkTextLine *line;
  GtkTextLineSegment *seg;
  int chars_left;
  int chars_in_line;
  int bytes_in_line;
  
  node = tree->root_node;

  /* Clamp to valid indexes (-1 is magic for "highest index") */
  if (char_index < 0 || char_index >= node->num_chars)
    {
      char_index = node->num_chars - 1;
    }

  *real_char_index = char_index;
  
  /*
   * Work down through levels of the tree until a GtkTextBTreeNode is found at
   * level 0.
   */

  chars_left = char_index;
  while (node->level != 0)
    {
      for (node = node->children.node;
           chars_left >= node->num_chars;
           node = node->next)
        {
          chars_left -= node->num_chars;

          g_assert(chars_left >= 0);
        }
    }
  
  if (chars_left == 0)
    {
      /* Start of a line */

      *line_start_index = char_index;
      return node->children.line;
    }
  
  /*
   * Work through the lines attached to the level-0 GtkTextBTreeNode.
   */

  chars_in_line = 0;
  bytes_in_line = 0;
  seg = NULL;
  for (line = node->children.line; line != NULL; line = line->next)
    {
      seg = line->segments;
      while (seg != NULL)
        {
          if (chars_in_line + seg->char_count > chars_left)
            goto found; /* found our line/segment */
          
          chars_in_line += seg->char_count;
          
          seg = seg->next;
        }

      chars_left -= chars_in_line;
      
      chars_in_line = 0;
      seg = NULL;
    }

 found:
  
  g_assert(line != NULL); /* hosage, ran out of lines */
  g_assert(seg != NULL);

  *line_start_index = char_index - chars_left;
  return line;
}

GtkTextTag**
gtk_text_btree_get_tags (const GtkTextIter *iter,
                         gint *num_tags)
{
  GtkTextBTreeNode *node;
  GtkTextLine *siblingline;
  GtkTextLineSegment *seg;
  int src, dst, index;
  TagInfo tagInfo;
  GtkTextLine *line;
  GtkTextBTree *tree;
  gint byte_index;

#define NUM_TAG_INFOS 10
  
1884
  line = gtk_text_iter_get_text_line(iter);
1885
  tree = gtk_text_iter_get_btree(iter);
1886
  byte_index = gtk_text_iter_get_line_index(iter);
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003

  tagInfo.numTags = 0;
  tagInfo.arraySize = NUM_TAG_INFOS;
  tagInfo.tags = g_new(GtkTextTag*, NUM_TAG_INFOS);
  tagInfo.counts = g_new(int, NUM_TAG_INFOS);

  /*
   * Record tag toggles within the line of indexPtr but preceding
   * indexPtr. Note that if this loop segfaults, your
   * byte_index probably points past the sum of all
   * seg->byte_count */

  for (index = 0, seg = line->segments;
       (index + seg->byte_count) <= byte_index;
       index += seg->byte_count, seg = seg->next)
    {
      if ((seg->type == &gtk_text_toggle_on_type)
          || (seg->type == &gtk_text_toggle_off_type))
        {
          inc_count(seg->body.toggle.info->tag, 1, &tagInfo);
        }
    }

  /*
   * Record toggles for tags in lines that are predecessors of
   * line but under the same level-0 GtkTextBTreeNode.
   */

  for (siblingline = line->parent->children.line;
       siblingline != line;
       siblingline = siblingline->next)
    {
      for (seg = siblingline->segments; seg != NULL;
           seg = seg->next)
        {
          if ((seg->type == &gtk_text_toggle_on_type)
              || (seg->type == &gtk_text_toggle_off_type))
            {
              inc_count(seg->body.toggle.info->tag, 1, &tagInfo);
            }
        }
    }

  /*
   * For each GtkTextBTreeNode in the ancestry of this line, record tag
   * toggles for all siblings that precede that GtkTextBTreeNode.
   */

  for (node = line->parent; node->parent != NULL;
       node = node->parent)
    {
      GtkTextBTreeNode *siblingPtr;
      Summary *summary;

      for (siblingPtr = node->parent->children.node; 
           siblingPtr != node; siblingPtr = siblingPtr->next)
        {
          for (summary = siblingPtr->summary; summary != NULL;
               summary = summary->next)
            {
              if (summary->toggle_count & 1)
                {
                  inc_count(summary->info->tag, summary->toggle_count,
                            &tagInfo);
                }
            }
        }
    }

  /*
   * Go through the tag information and squash out all of the tags
   * that have even toggle counts (these tags exist before the point
   * of interest, but not at the desired character itself).
   */

  for (src = 0, dst = 0; src < tagInfo.numTags; src++)
    {
      if (tagInfo.counts[src] & 1)
        {
          g_assert(GTK_IS_TEXT_TAG(tagInfo.tags[src]));
          tagInfo.tags[dst] = tagInfo.tags[src];
          dst++;
        }
    }
  
  *num_tags = dst;
  g_free(tagInfo.counts);
  if (dst == 0)
    {
      g_free(tagInfo.tags);
      return NULL;
    }
  return tagInfo.tags;  
}

static void
copy_segment(GString *string,
             gboolean include_hidden,
             gboolean include_nonchars,             
             const GtkTextIter *start,
             const GtkTextIter *end)
{
  GtkTextLineSegment *end_seg;
  GtkTextLineSegment *seg;
  
  if (gtk_text_iter_equal(start, end))
    return;

  seg = gtk_text_iter_get_indexable_segment(start);
  end_seg = gtk_text_iter_get_indexable_segment(end);
  
  if (seg->type == &gtk_text_char_type)
    {
      gboolean copy = TRUE;
      gint copy_bytes = 0;
      gint copy_start = 0;

2004
      /* Don't copy if we're invisible; segments are invisible/not
2005 2006 2007 2008 2009
         as a whole, no need to check each char */
      if (!include_hidden &&
          gtk_text_btree_char_is_invisible(start))
        {
          copy = FALSE;
2010
          /* printf(" <invisible>\n"); */
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
        }

      copy_start = gtk_text_iter_get_segment_byte(start);

      if (seg == end_seg)
        {
          /* End is in the same segment; need to copy fewer bytes. */
          gint end_byte = gtk_text_iter_get_segment_byte(end);

          copy_bytes = end_byte - copy_start;
        }
      else
2023
        copy_bytes = seg->byte_count - copy_start;
2024 2025 2026 2027 2028 2029 2030 2031