Reformat 122 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright 1997 Acorn Computers Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/***************************************************/
/* File   : Reformat.c                             */
17 18 19
/*                                                 */
/* Purpose: Functions to handle page reformatting. */
/*                                                 */
20
/* Author : A.D.Hodgkinson                         */
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
/* History: 03-Dec-96: Created                     */
/*          16-Apr-97: First merge with T.Cheal's  */
/*                     table code...               */
/*          22-May-97: Amazingly, *still* trying   */
/*                     to get this to work.        */
/*          18-Jun-97: Hpmh; works, but very slow. */
/*                     Will need to rewrite at     */
/*                     some stage; for the moment, */
/*                     moved a few bits over to    */
/*                     Tables.c as they fitted in  */
/*                     better over there.          */
/***************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "swis.h"
#include "flex.h"

#include "HTMLLib.h" /* HTML library API, Which will include html2_ext.h, tags.h and struct.h */

#include "wimp.h"
#include "wimplib.h"
#include "event.h"

#include "svcprint.h"
#include "Global.h"
#include "FromROSLib.h"
#include "MiscDefs.h"
#include "Utils.h"

#include "Browser.h"
55
#include "Fetch.h" /* (Which itself includes URLstat.h) */
56 57 58 59 60 61
#include "FetchPage.h"
#include "FontManage.h"
#include "Forms.h"
#include "History.h"
#include "Images.h"
#include "Memory.h"
62
#include "Object.h"
63 64 65 66 67 68 69 70 71 72
#include "Redraw.h"
#include "Tables.h"
#include "Toolbars.h"

#include "Reformat.h"

/* Local constant definitions */

#define BULLET_GAP 12

73
/* Static function prototypes */
74

75 76 77 78 79 80
static int               reformat_istext           (HStream * tp);
static int               reformat_useless_token    (HStream * tp);
static int               reformat_newline_check    (HStream * current, HStream * last, int offset);
static int               reformat_datasize         (HStream * p);
static _kernel_oserror * reformat_token_width      (reformat_width_data * w, unsigned int flags);
static void              reformat_check_visited    (browser_data * b, HStream * token);
81

82 83
static _kernel_oserror * reformat_add_line         (browser_data * b, reformat_cell * cell);
static _kernel_oserror * reformat_add_line_chunk   (browser_data * b, reformat_cell * cell);
84

85
static _kernel_oserror * reformat_format_from_now  (browser_data * b, int lastline);
86

87 88 89
static _kernel_oserror * reformat_text_line_height (browser_data * b, HStream * tp, int * top, int * bot);
static _kernel_oserror * reformat_check_height     (int toplevel, browser_data * b, reformat_cell * d, int line, HStream * tp, HStream * tpLast, int offset);
static int               reformat_reformatter_r    (unsigned int flags, browser_data * b, reformat_cell * d, HStream * streambase);
90

91 92 93 94
/* Local compilation options */

#undef SUPPORT_NOBR

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
// static void              reformat_strip_prespace (browser_data * b, int chunk, HStream * tp);

/*************************************************/
/* reformat_formatting()                         */
/*                                               */
/* Returns 0 if reformatting is not in progress, */
/* else non-zero.                                */
/*                                               */
/* Parameters: Pointer to the browser_data       */
/*             structure associated with the     */
/*             page which might be reformatting. */
/*                                               */
/* Returns:    0 if reformatting is not in       */
/*             progress, else it is.             */
/*************************************************/

int reformat_formatting(browser_data * b)
{
113
//  if (b->suspend_format) Printf("reformat_formatting: %p suspend_format set\n",b);
114 115
//  else if (b->last_token)
//  {
116 117
//    if (!b->last_token->next) Printf("reformat_formatting: %p b->last_token->next = NULL\n",b);
//    else if (b->last_token->next && !(b->last_token->next->flags & HFlags_DealtWithToken)) Printf("reformat_formatting: %p last_token->next HFlags NULL\n",b);
118
//    else if (b->cell->nlines <= 0) Printf("reformat_formatting: %p will return b->final_token != NULL: %d\n",b,b->final_token != NULL);
119
//    else Printf("reformat_formatting: %p will return 1\n",b);
120
//  }
121
//  else if (b->cell->nlines <= 0) Printf("reformat_formatting: %p will return b->final_token != NULL: %d\n",b,b->final_token != NULL);
122
//  else Printf("reformat_formatting: %p will return 1\n",b);
123

124 125 126 127 128 129 130 131 132
  /* Reformatting had been suspended due to an error */

  if (b->suspend_format) return 0;

  if (b->last_token)
  {
    /* If we've not overrun the tokens dealt with by the fetcher, */
    /* the fetcher could have exitted and this could be the last  */
    /* token (so we've finished).                                 */
133
    /*                                                            */
134
    /* The check for a 'next' token is done as final_token only   */
135 136
    /* records main token stream tokens dealt with by the         */
    /* preprocessor. It is possible for a precise set of          */
137
    /* circumstances to leave last_token and final_token          */
138 139 140
    /* equivalent due to table parsing, though there is more data */
    /* in the main token stream after it (this happened during    */
    /* testing, so it isn't all that rare).                       */
141

142
    if (!b->last_token->next) return 0;
143

144 145 146
    /* If the token after the last one dealt with by the   */
    /* fetcher had not been looked at by the preprocessor, */
    /* the reformatter must have exitted for that reason.  */
147

148
    if (b->last_token->next && !(b->last_token->next->flags & HFlags_DealtWithToken)) return 0;
149 150 151
  }

  /* If there are no lines, are there any HStream structures? */
152 153
  /* If so, the preprocessor has got stuff from the fetcher   */
  /* but the reformatter hasn't built anything with them yet. */
154

155
  if (b->cell->nlines <= 0) return (b->final_token != NULL);
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

  /* If none of the above, we must still be formatting */

  return 1;
}

/*************************************************/
/* reformat_stop()                               */
/*                                               */
/* Suspends a reformat, flagging that this has   */
/* been done in the browser_data structure.      */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             with the details of the reformat  */
/*             process to stop inside it.        */
/*************************************************/

_kernel_oserror * reformat_stop(browser_data * b)
{
  b->suspend_format = 1;

  return toolbars_set_button_states(b);
}

/*************************************************/
/* reformat_istext()                             */
/*                                               */
/* Returns 1 if an HStream structure represents  */
/* neither a horizontal rule nor an image.       */
/*                                               */
/* Parameters: Pointer to the HStream structure. */
/*                                               */
/* Returns:    1 if the struct represents text,  */
/*             else 0.                           */
/*************************************************/

static int reformat_istext(HStream * tp)
{
194 195
  return (
           ((tp->style) & (IMG | HR)) == 0 &&
196
           tp->tagno != TAG_TABLE          &&
197
           !ISOBJECT(tp)                   &&
198 199 200 201 202 203
           !
           (
             tp->tagno         == TAG_INPUT &&
             HtmlINPUTtype(tp) == inputtype_IMAGE
           )
         );
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
}

/*************************************************/
/* reformat_token_width()                        */
/*                                               */
/* Fills in the 'width' and 'bytes' fields of a  */
/* reformat_width_data structure according to    */
/* the contents of the token (HStream structure) */
/* that the reformat_width_data structure points */
/* to (this structure is defined in Reformat.h). */
/*                                               */
/* The idea is to fit the token into maxwidth    */
/* coordinates (in millipoints). The actual      */
/* width is returned (which may be greater than, */
/* or less than maxwidth) and the number of      */
/* bytes used to make that width is returned.    */
/*                                               */
/* Parameters: Pointer to a reformat_width_data  */
222
/*             structure (see Reformat.h);       */
223
/*                                               */
224 225
/*             A flags word, as ppassed to       */
/*             reformat_reformatter.             */
226
/*                                               */
227 228 229
/* Returns:    Fills in the structure's 'width'  */
/*             and 'bytes' fields with width and */
/*             byte count information.           */
230 231 232 233 234
/*************************************************/

static _kernel_oserror * reformat_token_width(reformat_width_data * w, unsigned int flags)
{
  _kernel_oserror * e = NULL;
Kevin Bracey's avatar
Kevin Bracey committed
235
  BBox box;
236 237 238

  /* Deal with tables */

239
  if (w->tp->tagno == TAG_TABLE)
240 241 242 243 244 245 246 247 248 249 250 251
  {
    reformat_cell * cellarray;
    table_stream  * table = (table_stream *) w->tp;
    int             size;
    int             toplevel;

    #ifdef TRACE
      if (tl & (1u<<20)) Printf("reformat_token_width: Dealing with table, token %p\n",table);
    #endif

    tables_count_table(w->b, table);

252 253
    size = table->ColSpan * table->RowSpan;

254 255
    #ifdef TRACE

256 257 258 259 260
      if (tl & (1u<<20))
      {
        Printf("reformat_token_width: Size of table is %d\n",size);
        if (!size) Printf("                      (Table has no cells...)\n");
      }
261 262 263

    #endif

264
    if (size) tables_position_table(w->b, table);
265 266

    #ifdef TRACE
267
      if (tl & (1u<<20)) Printf("reformat_token_width: Tag is now 0x%x\n",w->tp->tag);
268 269
    #endif

270
    /* If the table has no cells, may need to clear an existing cell array */
271

272
    if (!size)
273
    {
274
      if (table->cells) HtmlFree(table->cells);
275

276 277 278 279 280 281 282
      table->ncells = 0;
    }
    else
    {
      /* If we've got an existing cell array and the number of cells has */
      /* not changed, don't need to do anything. Otherwise, (re)allocate */
      /* the cell array.                                                 */
283

284 285 286
      if (!table->cells || table->ncells != size)
      {
        reformat_cell * old_cells = table->cells;
287

288
        /* Now allocate a new cell array and initialise the cell contents */
289

290
        table->cells = HtmlMalloc(size * sizeof(reformat_cell), table);
291

292 293
        /* If the allocation fails, can't possibly continue so jump */
        /* back to poll loop after reporting the error.             */
294

295
        if (!table->cells) show_error_cont(make_no_table_memory_error(9));
296

297
        /* Otherwise, initialise the cell contents */
298

299
        tables_init_table(w->b, table, table->cells);
300

301
        /* Copy over any old cells ('ncells' still holds the old number) */
302

303 304 305 306 307
        if (table->ncells && old_cells)
        {
          memcpy(table->cells, old_cells, table->ncells * sizeof(reformat_cell));

          /* Free the old cell array */
308

309 310
          HtmlFree(old_cells);
        }
311

312 313 314 315
        /* Now update 'ncells' */

        table->ncells = size;
      }
316
    }
317

318
    cellarray = table->cells;
319

320 321 322 323 324 325 326 327 328
    if (cellarray)
    {
      /* Find the width and height of the cells and fix their positions */
      /* as millipoint offsets from the top left of the table.          */
      /*                                                                */
      /* If the reformatter flags say not to generate lines, then we    */
      /* must be doing a width finding session as part of a parent      */
      /* table, so toplevel is 0. Otherwise, this is the highest level  */
      /* and toplevel is therefore set to 1.                            */
329

330 331
      if (flags & Reformatter_Virtual) toplevel = 1;
      else                             toplevel = 0;
332

333 334
      w->width = tables_width_table (toplevel, w->b, table, w->maxwid, cellarray, flags);
      w->bytes = tables_height_table(toplevel, w->b, table,            cellarray);
335

336 337
      tables_fix_table(w->b, table, cellarray);
    }
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

    #ifdef TRACE
      if (tl & (1u<<20)) Printf("reformat_token_width: Tag is now 0x%x\n",w->tp->tag);
    #endif

    /* Return the cell array pointer for convenience (may prove useful */
    /* to have this in the reformatter some time...).                  */

    w->data = (char *) cellarray;

    return e;
  }

  /* Deal with forms: Text-based elements */

353 354 355 356 357
  else if (
            w->tp->tagno == TAG_SELECT   ||
            w->tp->tagno == TAG_TEXTAREA ||
            w->tp->tagno == TAG_INPUT
          )
358
  {
359 360 361 362 363
    if (
         w->tp->tagno         == TAG_SELECT         ||
         w->tp->tagno         == TAG_TEXTAREA       ||
         HtmlINPUTtype(w->tp) == inputtype_PASSWORD ||
         HtmlINPUTtype(w->tp) == inputtype_TEXT
364 365
       )
    {
366 367 368
      int h;
      int done = 0;
      int length;
369

370
      if (w->tp->tagno == TAG_TEXTAREA)
371 372 373 374 375 376 377 378
      {
        /* Text areas */

        length = w->tp->cols;

        if (length == 1) length = 2;
        else if (length < 2) length = 30;

379
        done = 0;
380
      }
381
      else if (w->tp->tagno == TAG_SELECT)
382 383 384
      {
        /* SELECT elements (have pop-up menus) */

385 386
        int    width, l;
        int    extra = 0;
387 388 389 390 391 392 393 394
        char * p;

        e = read_sprite_size("fgright", &width, NULL);
        if (e) return e;

        width += 32; /* Account for border and gap */
        convert_to_points(width, &extra);

395 396
        /* Need to find out the actual used width, or we end up */
        /* generally overestimating the required size.          */
397

398
        p      = (char *) HtmlSELECToptions(w->tp) + 8;
399
        h      = fm_find_token_font(w->b, w->tp, 0);
400 401 402 403
        l      = 0;
        width  = 0;
        length = 0; /* Not used, but stops compiler giving warnings */

404 405 406 407 408 409 410 411 412 413
        /* Some fields can hold the selNONE or selMANY text, as well */
        /* as the menu item texts.                                   */

        if (HtmlSELECTmultiple(w->tp) || *p == 0xff)
        {
          e = fm_get_string_width(h,
                                  lookup_token("selNONE:<None>",0,0),
                                  Reformat_AsWideAsPossible_MP,
                                  strlen(tokens),
                                  -1,
414
                                  NULL,
415 416 417 418 419 420 421 422 423 424 425 426
                                  &width);

          if (!e && width > l) l = width;
        }

        if (HtmlSELECTmultiple(w->tp))
        {
          e = fm_get_string_width(h,
                                  lookup_token("selMANY:<Many>",0,0),
                                  Reformat_AsWideAsPossible_MP,
                                  strlen(tokens),
                                  -1,
427
                                  NULL,
428 429 430 431 432 433 434
                                  &width);

          if (!e && width > l) l = width;
        }

        /* Look for the width of the widest OPTION field */

435
        while (*p != 0xff)
436 437
        {
          p++;
438 439 440 441 442 443

          e = fm_get_string_width(h,
                                  p,
                                  Reformat_AsWideAsPossible_MP,
                                  strlen(p),
                                  -1,
444
                                  NULL,
445 446 447 448 449 450 451 452 453
                                  &width);

          if (e)
          {
            erb   = *e, e = &erb;
            width = 16000; /* Arbitrary! Give it 40 OS units on error */
            break;
          }

454 455
          /* Record if this is the widest and skip to the next field */

456 457
          if (width > l) l = width;

458 459 460
          p += strlen(p) + 1;
          p += strlen(p) + 1;
        }
461

462 463 464
        /* Set the width and flag that we've done the calculation */
        /* already so code lower down doesn't try.                */

465 466
        w->width = l + extra;
        done     = 1;
467 468 469 470 471
      }
      else
      {
        /* One line writable */

Kevin Bracey's avatar
Kevin Bracey committed
472
        length = HtmlINPUTsize(w->tp);
473 474 475 476 477 478 479

        if (length == 1) length = 2;
        else if (length < 2)
        {
          length = w->tp->maxlen;
          if (length > 40) length = 40;
        }
480 481

        done = 0;
482 483
      }

484 485 486 487
      /* Some cases above may have worked out the width already. */
      /* For those that haven't, do it on the basis of 'length', */
      /* holding the maximum number of characters, and the       */
      /* width of the widest character possible in the item.     */
488

489 490
      if (!done)
      {
491 492
        BBox box;

493 494 495
        if (length == 1) length = 2;
        else if (length < 2) length = 20;

496 497 498
        /* Finding the width based on font BBox multipled by the */
        /* field length usually is a significant overestimation, */
        /* so use a number instead - this is typically closer.   */
499

500
        h = fm_find_token_font(w->b, w->tp, 0);
501

502
        e = fm_char_box(h, '0', &box);
503

504
        if (e) erb = *e, e = &erb;
505 506 507
        else
        {
          w->width = ((box.xmax - box.xmin) * length) + 20;
508

509 510
          convert_to_points(w->width, &w->width);
        }
511
      }
512 513 514 515 516

      w->bytes = 0;

      return e;
    }
Kevin Bracey's avatar
Kevin Bracey committed
517
    else switch(HtmlINPUTtype(w->tp))
518
    {
519 520
      case inputtype_SUBMIT: /* No break - same as RESET */
      case inputtype_BUTTON: /* Again, no break          */
Kevin Bracey's avatar
Kevin Bracey committed
521
      case inputtype_RESET:
522
      {
Kevin Bracey's avatar
Kevin Bracey committed
523
        const char * p;
524 525 526 527 528 529 530 531
        int    h, length, end;

        p = form_button_text(w->tp);
        length = strlen(p);
        end = 0;

        while(end < length && p[end] != '\n') end++;

532
        h = fm_find_token_font(w->b, w->tp, 0);
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
        e = fm_get_string_width(h,
                                p,
                                Reformat_AsWideAsPossible_MP,
                                end - w->offset,
                                -1,
                                &w->bytes,
                                &w->width);

        if (e) erb = *e, e = &erb;

        w->width += 400 * 4 * 12; /* Account for border */
        w->bytes  = 0;

        return e;
      }
      break;

Kevin Bracey's avatar
Kevin Bracey committed
550
      case inputtype_CHECKBOX:
551 552 553 554 555 556 557 558 559
      {
        w->bytes = 0;

        read_sprite_size("fopton", &w->width, NULL);

        convert_to_points(w->width, &w->width);
      }
      break;

Kevin Bracey's avatar
Kevin Bracey committed
560
      case inputtype_RADIO:
561 562 563 564 565 566 567 568 569
      {
        w->bytes = 0;

        read_sprite_size("fradioon", &w->width, NULL);

        convert_to_points(w->width, &w->width);
      }
      break;

Kevin Bracey's avatar
Kevin Bracey committed
570
      case inputtype_HIDDEN:
571 572 573 574
      {
        w->width = w->bytes = 0;
      }
      break;
Kevin Bracey's avatar
Kevin Bracey committed
575 576 577

      case inputtype_IMAGE:
      {
578
        goto do_image; /* See below */
Kevin Bracey's avatar
Kevin Bracey committed
579 580
      }
      break;
581 582
    }
  }
583 584 585

  /* Handle OBJECT, EMBED and APPLET tags */

586
  else if (ISOBJECT(w->tp))
587 588 589 590 591 592 593 594 595 596
  {
    RetError(reformat_get_object_size(w->b, w->tp, &box));

    w->width = box.xmax - box.xmin;

    convert_to_points(w->width, &w->width);
  }

  /* Handle images */

597 598
  else if (w->tp->style & IMG)
  {
599
do_image: /* Used by switch statement above */
600 601 602 603 604 605

    w->bytes = 0;
    w->width = 0;

    /* Now get the size of the image for reformatting purposes */

606
    RetError(reformat_get_image_size(w->b, w->tp, &box));
607 608 609 610 611 612 613 614 615

    w->width = box.xmax - box.xmin;

    convert_to_points(w->width, &w->width);
  }
  else if (w->tp->style & HR)
  {
    /* For a horizontal rule, there's no extra data to put in (so */
    /* the w->bytes field is zero) and the width is as wide as    */
616 617
    /* the specified maximum width, unless the HR specifies a     */
    /* particular width directly.                                 */
618 619 620 621 622 623 624
    /*                                                            */
    /* The special case of finding min/max widths is checked in   */
    /* the flags here, as otherwise any HR tag can force the      */
    /* width up to maxwid - which may be very large.              */

    w->bytes = 0;

625 626 627 628 629 630 631 632 633 634
    if (!HR_HAS_WIDTH(w->tp) || HR_WIDTH_UNITS(w->tp) == UNITS_PERCENT)
    {
      if (
           !(flags & Reformatter_FindingWidest)   &&
           !(flags & Reformatter_FindingSmallest)
         )
      {
        if (HR_HAS_WIDTH(w->tp)) w->width = (w->maxwid * HR_WIDTH(w->tp)) / 100;
        else                     w->width = w->maxwid;
      }
635

636 637 638 639 640 641 642 643
      else w->width = 0;
    }
    else
    {
      w->width = HR_WIDTH(w->tp) * 2; /* 1 'web pixel' = 2 OS units */

      convert_to_points(w->width, &w->width);
    }
644 645 646 647 648 649 650 651 652 653 654 655 656
  }
  else if (ISBULLET(w->tp)) /* ISBULLET is defined in Fetch.h */
  {
    /* For a bullet, there is again no extra data so bytes = 0, */
    /* and the width is taken from the sprite width of the      */
    /* bullet point.                                            */

    w->bytes = 0;

    convert_to_points(reformat_bullet_width(w->tp->indent), &w->width);
  }
  else
  {
657
    int h, end, split;
658

659
    /* Can't do anything if there's no text */
660

661 662 663 664 665 666 667 668 669 670
    if (!w->data || !*w->data)
    {
      w->bytes = 0;
      w->width = 0;
    }
    else
    {
      /* Loop round until a newline is found, or the end of the  */
      /* string is reached, starting at the offset into the data */
      /* specified by the 'offset' field.                        */
671

672
      end = w->offset;
673

674
      while (w->data[end] && w->data[end] != '\n') end++;
675

676 677
      /* If the text is preformatted, set a null split character. */
      /* Else specify splitting on spaces.                        */
678

679
      split = (w->tp->style & PRE) ? -1 : ' ';
680

681
      /* Get a font handle for rendering the token */
682

683
      h = fm_find_token_font(w->b, w->tp, 0);
684

685 686 687 688
      /* If end > offset, the loop above must have gone through at least */
      /* one non-newline character in the string, or there was no string */
      /* to look through; find the width of the string (the call won't   */
      /* mind if there's no string, it'll just return 0)                 */
689

690 691 692 693 694
      if (end > w->offset) e = fm_get_string_width(h,
                                                   w->data + w->offset,
                                                   w->maxwid,
                                                   end - w->offset,
                                                   split,
695

696 697
                                                   &w->bytes,
                                                   &w->width);
698

699 700 701
      /* If finding the minimum or maximum width for tables, add a little to */
      /* the above width to account for italics etc. - the font manager will */
      /* not have returned the upper limit on either side.                   */
702

703 704 705 706 707
      if (
           (flags & Reformatter_FindingWidest)   ||
           (flags & Reformatter_FindingSmallest)
         )
         w->width += 3200;
708

709 710 711 712
      /* If the scan for a newline finished before the end of the string (so */
      /* a newline was found) and the chunk of data defined by the call to   */
      /* fm_get_string_width above gave a string ending in a newline, add 1  */
      /* to the bytes counter to ensure that the chunk includes it.          */
713

714 715
      if (w->data[end] && w->data[w->offset + w->bytes] == '\n') w->bytes++;
    }
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
  }

  return e;
}

/*************************************************/
/* reformat_useless_token()                      */
/*                                               */
/* Checks to see if a token (HStream struct) is  */
/* of any use to the reformatter.                */
/*                                               */
/* Parameters: Pointer to the HStream struct.    */
/*                                               */
/* Returns:    1 = the token is useless, else 0. */
/*************************************************/

static int reformat_useless_token(HStream * tp)
{
  if (ISHEAD(tp)) return 1;
  if (ISNULL(tp)) return 1;

737 738
  if (tp->flags & HFlags_IgnoreObject) return 1;

739 740 741
  if (
       ISBODY(tp)   &&
       !tp->tag     &&
742
       !tp->tagno   &&
743 744 745 746 747 748 749 750 751 752 753 754 755 756
       !tp->text    &&
       !tp->anchor  &&
       !tp->src     &&
       !tp->enctype &&
       !tp->name    &&
       !tp->value   &&
       !tp->target  &&
       (
         tp->style == 0x00000000 ||
         tp->style == 0x80000000
       )
     )
     return 1;

757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
  return 0;
}

/*************************************************/
/* reformat_newline_check()                      */
/*                                               */
/* Works out whether or not there should be a    */
/* line break in the page, according to the      */
/* token (HStream structure) that is currently   */
/* being considered and the token that was last  */
/* considered, and the offset into the data of   */
/* the tokens.                                   */
/*                                               */
/* Parameters: Pointer to the current token (the */
/*             HStream structure that is being   */
/*             dealt with by the reformatter,    */
/*             say, at the moment);              */
774
/*                                               */
775 776
/*             Pointer to the last token that    */
/*             was dealt with;                   */
777
/*                                               */
778 779 780 781 782 783 784 785 786 787 788 789 790
/*             Data offset into the tokens.      */
/*                                               */
/* Returns:    0 if there is no line break       */
/*             needed, or a value between 1 and  */
/*             8 that says 'yes, line break      */
/*             needed' and also holds details of */
/*             the conditions that were met to   */
/*             determine the line break was      */
/*             needed.                           */
/*************************************************/

static int reformat_newline_check(HStream * current, HStream * last, int offset)
{
791 792 793 794 795 796 797
  /* It generally looks better if there's a line break for tables, */
  /* though this is theoretically not necessary. In practice you   */
  /* find various line spacing and redraw problems without the     */
  /* break - this may get sorted one day...!                       */

  if (current->tagno == TAG_TABLE || last->tagno == TAG_TABLE) return 9;

798 799 800 801 802 803
  /* If the current token represents a horizontal rule and the last token also */
  /* represented one, with no offset indicating extra data in the tokens (and  */
  /* provided that there is actually a last token!), then return 1.            */

  if (((current->style) & HR) || ((!offset) && (last) && ((last->style) & HR))) return 1;

804 805 806 807 808 809 810 811
  /* If we have a paragraph break but the last item was a <li> tag, and we are */
  /* at the top of the line, then HTML like '<ul><li><p>Text' is being used -  */
  /* we should ignore the <p> tag. The position of this line of code relative  */
  /* to other checks in this function is obviously quite important (so be      */
  /* careful with it!)...                                                      */

  if (!offset && (current->style & P) && (last->style & LI)) return 0;

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
  /* If the tag itself indicates that a linebreak is needed, and we are at the */
  /* start of this line (offset into it is zero), return 2. This may be due to */
  /* <P>, <BR> and the like, in the document source.                           */

  if ((!offset) && ((current->style) & LINEBREAK)) return 2;

  /* If, again, this is the start of a line, and the pointer to the previous */
  /* token dealt with is not null, proceed with other line break checks.     */

  if ((!offset) && (last))
  {
    /* If the indentation has changed since the last token (e.g. a new list has */
    /* been started or an old one closed between the two tokens) then return 3. */

    if (current->indent != last->indent) return 3;

    /* If the header type changed between the two tokens, then provided the     */
    /* last token wasn't a list item (in which case a line break will already   */
    /* have been put in) return 4.                                              */

    if (((current->style & H_MASK) != (last->style & H_MASK)) && !(last->style & LI)) return 4;

    /* When certain tags are turned on or off, we want a linebreak. For example */
    /* it looks tidier for preformatted text to have a gap above and below it,  */
    /* rather than having it touch the previous and following text. The macro   */
    /* LINEBREAKSW (defined in Reformat.h) has a list of these tags ORed        */
    /* together to form a mask - if this mask changes between the tokens, one   */
    /* of the listed tags must have turned on or off. So we want a line break;  */
    /* hence, return 5.                                                         */

    if ((current->style & LINEBREAKSW) != (last->style & LINEBREAKSW)) return 5;

    /* CENTRED is defined in Reformat.h, and is 1 if the token holds data that  */
    /* should be displayed centred in the page. If switching from centred to    */
    /* uncentred text or vice versa, there must be a line break. So return 6.   */

    if (CENTRED(current) != CENTRED(last)) return 6;

    /* Some tags need a line break when they turn on, for example at the start  */
    /* of certain special kinds of list. The LINEBREAKON macro is defined in    */
    /* reformat.h and contains an ORed together list of such tags (just like    */
    /* the LINEBREAKSW macro used above) - so if the current token has one of   */
    /* these turned on, but the last token had it turned off, we want another   */
    /* line break; return 7.                                                    */

    if ((current->style & LINEBREAKON) && !(last->style & LINEBREAKON)) return 7;

    /* Similarly, some tags need a line break when they turn off; for example,  */
    /* headers look better if they have a gap underneath them. So again, there  */
    /* is a macro (LINEBREAKOFF) in Reformat.h which has a list of these tags   */
    /* and a value of 8 is returned if we go from one of these being turned     */
    /* on to one being turned off.                                              */

    if (!(current->style & LINEBREAKOFF) && (last->style & LINEBREAKOFF)) return 8;
  }

  /* If none of the above conditions are met, we need no line break - return 0. */

  return 0;
}

/*************************************************/
/* reformat_newline()                            */
/*                                               */
/* Returns 1 if a line break should be inserted  */
/* onto the page, or 0 if not. Does this by      */
878 879 880
/* calling reformat_newline_check and is only    */
/* interested in if the value the call returned  */
/* was zero or not.                              */
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
/*                                               */
/* Parameters: As for reformat_newline_check.    */
/*                                               */
/* Returns:    1 = line break required, else 0.  */
/*************************************************/

int reformat_newline(HStream * current, HStream * last, int offset)
{
  return (reformat_newline_check(current, last, offset) != 0);
}

/*************************************************/
/* reformat_datasize()                           */
/*                                               */
/* Returns the size of standard data pointed to  */
/* by an HStream (e.g. the length of any text    */
/* string it points to).                         */
/*                                               */
/* Parameters: Pointer to the HStream struct     */
/*                                               */
901
/* Returns:    Size of associated data in bytes. */
902 903 904 905
/*************************************************/

static int reformat_datasize(HStream * tp)
{
906
  /* Is this a text item? */
907

908
  if (!reformat_istext(tp)) return 0;
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925

  /* If the HStream has a pointer to some text, return the */
  /* length of that text, else return zero.                */

  return (tp->text ? strlen(tp->text) : 0);
}

/*************************************************/
/* reformat_shift_vertically()                   */
/*                                               */
/* Shifts all lines between two given line       */
/* numbers (inclusive) by a given y coordinate,  */
/* in OS units. A redraw is generated with       */
/* Wimp_BlockCopy if moved lines lie inside the  */
/* visible area of the browser window.           */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
926 927
/*             holding information on the lines; */
/*                                               */
928
/*             The line number at which to start */
929 930
/*             (inclusive);                      */
/*                                               */
931
/*             The line number at which to end   */
932 933
/*             (inclusive);                      */
/*                                               */
934
/*             The value to shift the lines by,  */
935
/*             in OS units - since the Y coords  */
936 937 938 939 940 941 942 943
/*             of the lines are for a window,    */
/*             a negative value would move the   */
/*             lines down the window and vice    */
/*             versa.                            */
/*************************************************/

_kernel_oserror * reformat_shift_vertically(browser_data * b, int start, int end, int y_shift)
{
944 945 946 947
  _kernel_oserror         * e;
  reformat_cell           * cell = b->cell;
  int                       line;
  WimpGetWindowStateBlock   s;
948 949 950 951 952 953 954 955 956 957

  if (!y_shift) return NULL;

  /* Limit check start and end, and exit if there appear */
  /* to be no lines to move                              */

  if (start > cell->nlines - 1) return NULL;
  if (start < 0) start = 0;
  if (end > cell->nlines - 1) end = cell->nlines - 1;
  if (end < 0) end = 0;
958
  if (start > end) line = start, start = end, end = line;
959 960 961 962 963

  if ((end < 0) || (start < 0) || (!cell->ldata)) return NULL;

  /* Alter the lines' y-coordinates */

964
  for (line = start; line <= end; line ++) cell->ldata[line].y += y_shift;
965

966 967
  /* Have to force a redraw of the entire page to ensure */
  /* that image positions are updated                    */
968

969 970 971
  s.window_handle = b->window_handle;
  e = wimp_get_window_state(&s);
  if (e) return e;
972

973
  coords_box_toworkarea(&s.visible_area, (WimpRedrawWindowBlock *) &s);
974

975 976 977 978 979
  return wimp_force_redraw(s.window_handle,
                           s.visible_area.xmin,
                           s.visible_area.ymin,
                           s.visible_area.xmax,
                           s.visible_area.ymax);
980 981 982 983 984 985 986 987 988 989 990 991 992 993
}

/*************************************************/
/* reformat_format_from()                        */
/*                                               */
/* Starts a new reformat session, possibly       */
/* starting after a given last line (i.e. from   */
/* a certain point in the page, rather than the  */
/* whole page).                                  */
/*                                               */
/* The reformat session may be postponed until   */
/* later according to the RefoTime and RefoWait  */
/* entires in the Choices file.                  */
/*                                               */
994 995 996 997 998 999
/* The defined way to ensure all line and chunk  */
/* data for a given browser is freed, including  */
/* that tied up in tables, is by calling with    */
/* the browser_data struct, -1, 1, and -1 (see   */
/* parameters list below).                       */
/*                                               */
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
/* Parameters: A pointer to a browser_data       */
/*             structure for which the reformat  */
/*             is to take place;                 */
/*                                               */
/*             The number of the last valid      */
/*             reformat_line structure;          */
/*                                               */
/*             1 to format now, else the request */
/*             may be delayed for some time;     */
/*                                               */
/*             For requests generated by the     */
/*             resizing of images, pass the      */
/*             image number, else pass -1.       */
/*************************************************/

_kernel_oserror * reformat_format_from(browser_data * b, int lastline, int immediate, int image)
{
  _kernel_oserror * e;

1019 1020 1021 1022 1023
  /* Do we delay these requests? Yes if told to in the Choices,  */
  /* in the function parameters, or if we're showing an external */
  /* image (want to see that come in progressively, not wait for */
  /* a reformat which is in this particular case completely      */
  /* trivial anyway).                                            */
1024

1025 1026 1027 1028 1029 1030 1031 1032
  if (
       !choices.refo_wait ||
       immediate          ||
       b->displayed == Display_External_Image
     )
  {
    reformat_format_from_now(b, lastline);
  }
1033 1034
  else
  {
1035
    if (b->refo_time)
1036 1037 1038 1039 1040 1041 1042
    {
      /* If there's already a pending request, is the line number */
      /* specified for this one lower than the one already there? */
      /* If so, then use that higher line, else stick with the    */
      /* old one. Nothing else to do - the null handler takes     */
      /* care of it all.                                          */

1043
      if (lastline < b->refo_line) b->refo_line = lastline;
1044 1045 1046 1047 1048 1049 1050 1051 1052
    }
    else
    {
      /* This is the first reformat request; so set the timer and */
      /* install a null handler for it.                           */

      e = _swix(OS_ReadMonotonicTime,
                _OUT(0),

1053
                &b->refo_time);
1054 1055 1056

      if (e) return e;

1057
      b->refo_line = lastline;
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

      register_null_claimant(Wimp_ENull, (WimpEventHandler *) reformat_format_timer, b);
    }
  }

  return NULL;
}

/*************************************************/
/* reformat_format_timer()                       */
/*                                               */
/* Calls the reformatter after a delay given by  */
/* the Choices file entry 'RefoTime', according  */
1071 1072 1073
/* to the start time specified by the            */
/* 'refo_time' field of the browser_data         */
/* structure.                                    */
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
/*                                               */
/* Parameters are as standard for a Wimp event   */
/* handler.                                      */
/*************************************************/

int reformat_format_timer(int eventcode, WimpPollBlock * b, IdBlock * idb, browser_data * handle)
{
  int timenow;

  /* If there appears to be no initiation time specified in the      */
  /* browser_data structure, dereigster and exit (being cautions...) */

1086
  if (!handle->refo_time)
1087
  {
1088
    handle->refo_time = 1; /* So that reformat_stop_pending will deregister this handler */
1089

1090
    reformat_stop_pending(handle);
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103

    return 0;
  }

  /* Otherwise, get the current time into 'timenow' */

  if (_swix(OS_ReadMonotonicTime,
            _OUT(0),

            &timenow)) return 0;

  /* Do we need to reformat yet? */

1104
  if (timenow - handle->refo_time > choices.refo_time)
1105 1106 1107
  {
    /* reformat_format_from_now will deregister this handler */

1108
    ChkError(reformat_format_from_now(handle, handle->refo_line));
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
  }

  return 0;
}

/*************************************************/
/* reformat_format_from_now()                    */
/*                                               */
/* Starts a new reformat session, possibly       */
/* starting after a given last line (i.e. from   */
/* a certain point in the page, rather than the  */
/* whole page).                                  */
/*                                               */
/* The reformat session will be stared           */
/* immediately - it will not be delayed. Don't   */
/* call this directly - go through               */
/* reformat_format_from instead.                 */
/*                                               */
/* Parameters: A pointer to a browser_data       */
/*             structure for which the reformat  */
/*             is to take place;                 */
/*                                               */
/*             The number of the last valid      */
/*             reformat_line structure.          */
/*************************************************/

static _kernel_oserror * reformat_format_from_now(browser_data * b, int lastline)
{
  int             bottom = 0;
  reformat_cell * cell   = b->cell;

  /* If this browser had any queued reformats, cancel them */

1142
  if (b->refo_time)
1143
  {
1144
    if (b->refo_line < lastline) lastline = b->refo_line;
1145

1146
    reformat_stop_pending(b);
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
  }

  /* Line numbers less than -1 are invalid, and can't end */
  /* on a line greater than the number of lines present!  */

  if (lastline < -1) lastline = -1;
  if (lastline >= cell->nlines) lastline = cell->nlines - 1;

  /* Clear the flag that says formatting is suspended due to error */

  b->suspend_format = 0;

  /* Clear the field holding the last token number for which */
  /* reformatting was definitely completed                   */

  b->last_token = NULL;

  /* If lastline holds a valid line number, set bottom to the */
  /* bottom y coordinate of the last line. Otherwise leave    */
  /* bottom set at 0 (we're reformatting to no lines).        */

  if (lastline >= 0) bottom = cell->ldata[lastline].y;

  /* If there's existing line data, need to ensure that all  */
  /* memory allocated in table cells is freed before getting */
  /* rid of the lines after lastline.                        */

  tables_free_memory(1, b, cell, lastline + 1);

  /* If we're reformatting to less than the current number of */
  /* lines, 'chop off' those that are left over.              */

  if ((lastline + 1) < cell->nlines)
  {
    int size;//, topline;

//    /* Before anything else, mark the token currently displayed at the */
//    /* top of the page so it can be shown after the reformat.          */
//
//    topline = browser_top_line(b, cell, 0) - 1;
//
//    if (topline >= 0 && (lastline + 1) < topline)
//    {
//      b->display_request = cell->cdata[cell->ldata[topline].chunks].t;
//      b->display_offset  = cell->cdata[cell->ldata[topline].chunks].o;
//      b->display_vscroll = 0;
//    }

    /* Size = offset of line chunks for the last line, plus  */
    /*        the number of line chunks times the size of a  */
    /*        chunk. I.e. the offset for the end of the line */
    /*        chunks for the last line - so size = size of   */
    /*        data that is needed for all the line chunks    */
    /*        with lastline chunks present.                  */

    if (lastline < 0) size = 0;
    else
    {
      /* If it turns out this line has no chunks, need to use the chunk address */
      /* and number of chunks for the previous line; unless, of course, this is */
      /* line 0, in which case there are no previous lines to refer to.         */

      if (!cell->ldata[lastline].n)
      {
        if (lastline == 0) size = 0;
        else size = (cell->ldata[lastline - 1].chunks + /* Base array offset into chunks                                    */
                    cell->ldata[lastline - 1].n)      * /* Add number of chunks for this line to get total number of chunks */
                    sizeof(reformat_line_chunk);        /* Multiply by size of a reformat_line_chunk to get total size      */
      }

      /* Otherwise, we're OK; the last line has line chunks. */

      else size = (cell->ldata[lastline].chunks +
                  cell->ldata[lastline].n)      *
                  sizeof(reformat_line_chunk);
    }

    /* Clip the number of lines to the new value */

    cell->nlines = lastline + 1;

    /* Make sure that the right amount of memory is allocated */

    #ifdef TRACE
      if (tl & (1u<<12)) Printf("reformat_format_from: Chunk CK_LINE set to %d\n",(lastline + 1) * sizeof(reformat_line));
    #endif

    memory_set_chunk_size(b, cell, CK_LINE, (lastline + 1) * sizeof(reformat_line));

    #ifdef TRACE
      if (tl & (1u<<12)) Printf("reformat_format_from: Chunk CK_LDAT set to %d\n",size);
    #endif

    memory_set_chunk_size(b, cell, CK_LDAT, size);
  }

  if (!printing)
  {
    /* Ensure null events are claimed for the rest of the reformat */

    if (!b->fetch_handler) fetchpage_claim_nulls(b);

    /* Update the status bar */

    toolbars_update_status(b, Toolbars_Status_Formatting);
  }

1254 1255 1256 1257
  /* Ensure the pointer shape is OK */

  browser_pointer_check(0, NULL, NULL, b);

1258 1259 1260 1261 1262 1263
  /* Redraw the bottom line of the window if not printing */

  return (!printing ? browser_update_bottom(b, bottom) : NULL);
}

/*************************************************/
1264
/* reformat_stop_pending()                       */
1265
/*                                               */
1266 1267
/* Stops any pending reformats from happening,   */
/* deregistering handlers etc. as needed.        */
1268 1269 1270 1271 1272
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the queue.            */
/*************************************************/

1273
void reformat_stop_pending(browser_data * b)
1274
{
1275
  if (b->refo_time) deregister_null_claimant(Wimp_ENull, (WimpEventHandler *) reformat_format_timer, b);
1276

1277 1278
  b->refo_time = 0;
  b->refo_line = Reformat_UnrealisticallyHighLineNumber;
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
}

/*************************************************/
/* reformat_get_image_size()                     */
/*                                               */
/* Gets a BBox for a specified image in OS       */
/* coordinates relative to the font base line    */
/* and left hand edge.                           */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
1290
/*                                               */
1291
/*             A token address for the image;    */
1292
/*                                               */
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
/*             Pointer to a BBox in which the    */
/*             relevant coords are returned.     */
/*                                               */
/* Assumes:    Pointer to the BBox may not be    */
/*             NULL.                             */
/*************************************************/

_kernel_oserror * reformat_get_image_size(browser_data * b, HStream * tp, BBox * box)
{
  _kernel_oserror * e;
1303
  imgalign          align;
1304 1305 1306 1307 1308 1309 1310 1311 1312
  fm_face           h;
  BBox              hbox;
  int               height = 0;

  /* We can't easily find out how high text is surrounding */
  /* the image for align=top, align=middle or whatever,    */
  /* but we can do a reasonable guess based on whatever    */
  /* font the given token would use if it held text.       */

1313
  h = fm_find_token_font(NULL, tp, 0);
1314 1315 1316 1317 1318 1319 1320

  if (h)
  {
    if (!fm_font_box(h, &hbox)) height = hbox.ymax - hbox.xmin;

    fm_lose_font(NULL, h);
  }
1321 1322

  /* Get the image size from the image library */
1323 1324 1325 1326

  e = image_get_token_image_size(b, tp, box);
  if (e) return e;

1327 1328 1329
  /* Deal with alignments */

  if (tp->style & IMG) /* It'll either be an IMG or an INPUT TYPE=IMAGE item */
1330
  {
1331 1332 1333
    if      ((tp->type & TYPE_ALIGN_MASK) == TYPE_MIDDLE) align = imgalign_MIDDLE;
    else if ((tp->type & TYPE_ALIGN_MASK) == TYPE_TOP)    align = imgalign_TOP;
    else                                                  align = imgalign_NONE;
1334
  }
1335
  else align = HtmlINPUTalign(tp);
1336

1337
  switch (align)
1338
  {
Kevin Bracey's avatar
Kevin Bracey committed
1339
    case imgalign_MIDDLE:
1340
    {
1341 1342
      int hh = height / 3; /* Technically '/ 2', but '/ 3' looks, on average, better in practice */

Kevin Bracey's avatar
Kevin Bracey committed
1343 1344
      box->ymin -= box->ymax / 2;
      box->ymax /= 2;
1345 1346 1347

      box->ymin += hh;
      box->ymax += hh;
1348 1349
    }
    break;
Kevin Bracey's avatar
Kevin Bracey committed
1350 1351

    case imgalign_TOP:
1352
    {
1353 1354
      box->ymin = height - box->ymax;
      box->ymax = height;
1355 1356
    }
    break;
1357 1358 1359 1360 1361 1362
  }

  /* Deal with links - need to account for a border */
  /* of maxlen * 2 pixels width. ISLINK is defined  */
  /* in Fetch.h.                                    */

1363
  if (tp->style & IMG)
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
  {
    int b;

    b = tp->maxlen * 2;

    box->xmax += b;
    box->ymax += b;
    box->xmin -= b;
    box->ymin -= b;
  }

  return NULL;
}

1378 1379 1380 1381 1382 1383 1384 1385
/*************************************************/
/* reformat_get_object_size()                    */
/*                                               */
/* Gets a BBox for a specified Object in OS      */
/* coordinates relative to the font base line    */
/* and left hand edge.                           */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
1386
/*             relevant to the Object;           */
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
/*                                               */
/*             A token address for the Object;   */
/*                                               */
/*             Pointer to a BBox in which the    */
/*             relevant coords are returned.     */
/*                                               */
/* Assumes:    Pointer to the BBox may not be    */
/*             NULL.                             */
/*************************************************/

_kernel_oserror * reformat_get_object_size(browser_data * b, HStream * tp, BBox * box)
{
1399
  imgalign align;
1400 1401 1402 1403 1404

  /* Get the Object size from the Object library */

  RetError(object_get_token_object_size(b, tp, box));

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
  /* Deal with alignments */

  align = HtmlOBJECTalign(tp);

  switch (align)
  {
    case imgalign_MIDDLE:
    {
      box->ymin -= box->ymax / 2;
      box->ymax /= 2;
    }
    break;

    // Sort this out, as with image handling

    case imgalign_TOP:
    {
      box->ymin =- box->ymax;
      box->ymax = 0;
    }
    break;
  }

  /* Account for a border */

  if (HtmlOBJECTborder(tp))
  {
    int b;

    b = HtmlOBJECTborder(tp) * 2;

    box->xmax += b;
    box->ymax += b;
    box->xmin -= b;
    box->ymin -= b;
  }
1441 1442 1443

  return NULL;
}
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 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
/*************************************************/
/* reformat_get_placeholder_size()               */
/*                                               */
/* Gets a BBox that a placeholder would fill     */
/* based on given ALT text to plot inside it.    */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the placeholder;      */
/*                                               */
/*             Pointer to an HStream struct      */
/*             representing the placeholder;     */
/*                                               */
/*             Pointer to the ALT text (or NULL  */
/*             or a null string for no text);    */
/*                                               */
/*             Pointer to a BBox, in which the   */
/*             required bounding box for the     */
/*             placeholder is written.           */
/*                                               */
/* Assumes:    Pointer to the BBox may not be    */
/*             NULL.                             */
/*************************************************/

void reformat_get_placeholder_size(browser_data * b, HStream * tp, const char * text, BBox * box)
{
  int  h, temp, size;
  BBox fbox;

  /* Quick sanity check */

  if (!box) return;

  box->xmin = box->ymin = 0;

  if (!b || !tp || !text || !*text)
  {
    box->xmax = ImageDefaultOSSize_X;
    box->ymax = ImageDefaultOSSize_Y;

    return;
  }

  /* Claim the font */

  size = (fm_size(tp->fontsize) * 80) / 100;

  h = fm_find_font(b,
                   "sans",
                   size,
                   size,
                   0,
                   0);

  /* Find the string width of the ALT text */

  fm_get_string_width(h,
                      text,
                      Reformat_AsWideAsPossible_MP,
                      strlen(text),
                      -1,
                      &temp,
                      &box->xmax);

  convert_to_os(box->xmax, &box->xmax);

  /* Find the font height */

  fm_font_box(h, &fbox);

  /* As well as subtracting ymin (the y minimum coordinate */
  /* of the font bbox) from ymax, need to also add some    */
  /* height to give a gap between the text and slabbed box */
  /* that's drawn to mark the image's position.            */

  box->ymax = fbox.ymax - fbox.ymin;

  convert_to_os(choices.font_size, &temp);

1522
  if (temp < 20) temp = 20;
1523 1524

  box->ymax += temp;
1525
  box->xmax += temp + temp / 2; /* Looks better to have extra horizontally */
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

  /* Don't want to force the page width up just because of */
  /* ALT text in images, especially in narrow items such   */
  /* as navigation frames, so limit check xmax.            */

  // Currently this is done by an absolute hard coded upper
  // limit, but ultimately it would ideally be limited e.g.
  // by cell width. Just as soon as I work out a nice way
  // of doing that... (Remember, you may not know the cell
  // width at times when this is being called to try and
  // determine it; yet you must return consistent and
  // appropriate values subsequently for redraw purposes).

  {
    int remain;

    convert_to_os(b->left_margin + b->right_margin, &remain);

    remain = b->display_width - remain;
    if (remain > 320) remain = 320;

    if (box->xmax > remain) box->xmax = remain;
  }

  /* Finished */

  return;
}
1554

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
/*************************************************/
/* reformat_bullet_width()                       */
/*                                               */
/* Returns the width of a given bullet in OS     */
/* units.                                        */
/*                                               */
/* Parameters: The bullet number (in the Sprites */
/*             file, bullets are named b1, b2,   */
/*             ...bn).                           */
/*************************************************/

int reformat_bullet_width(int bullet)
{
1568
  char spr[32];
1569 1570
  int  w;

1571
  sprintf(spr, "b%d\0", (bullet + bullets - 1) % bullets);
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592

  if (read_sprite_size(spr, &w, NULL)) w = 32;

  /* See top of the file for BULLET_GAP */

  return w + BULLET_GAP;
}

/*************************************************/
/* reformat_bullet_height()                      */
/*                                               */
/* Returns the height of a given bullet in OS    */
/* units.                                        */
/*                                               */
/* Parameters: The bullet number (in the Sprites */
/*             file, bullets are named b1, b2,   */
/*             ...bn).                           */
/*************************************************/

int reformat_bullet_height(int bullet)
{
1593
  char spr[32];
1594 1595
  int  h;

1596
  sprintf(spr, "b%d\0", (bullet + bullets - 1) % bullets);
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617

  if (read_sprite_size(spr, NULL, &h)) h = 32;

  return h;
}

/*************************************************/
/* reformat_y_offset()                           */
/*                                               */
/* Returns the y offset from the top of a page,  */
/* in OS units, for all lines on that page.      */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             representing the page.            */
/*                                               */
/* Returns:    y offset for all the lines on the */
/*             page, in OS units, from the top.  */
/*************************************************/

int reformat_y_offset (browser_data * b)
{
1618 1619
  int offset;

1620 1621
  if (!controls.swap_bars) offset = toolbars_button_height(b) + toolbars_url_height(b);
  else                     offset = toolbars_status_height(b);
1622

1623 1624
  /* The '4' accounts for the bottom window frame of the toolbars */

1625 1626 1627 1628 1629
  if (offset) offset += wimpt_dy();

  if (!b->ancestor) offset += b->leading; /* Only put a gap at the top for base browsers, not for frames */

  return -offset;
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
/*************************************************/
/* reformat_text_line_height()                   */
/*                                               */
/* Works out how tall a line of text should be,  */
/* returning the height above and below the      */
/* notional text baseline in OS units.           */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the line;             */
/*                                               */
/*             Pointer to an HStream which is    */
/*             used to determine what font the   */
/*             line would use;                   */
/*                                               */
/*             Pointer to an int, in which the   */
/*             height above the baseline is      */
/*             written;                          */
/*                                               */
/*             Pointer to an int, in which the   */
/*             height below the baseline is      */
/*             written.                          */
/*                                               */
/* Assumes:    Either int pointer may be NULL.   */
/*             If the HStream pointer is NULL, a */
/*             value based on the base (normal)  */
/*             font size will be used.           */
/*************************************************/

static _kernel_oserror * reformat_text_line_height(browser_data * b, HStream * tp, int * top, int * bot)
{
  int  h;
  int  rettop, retbot;
  BBox box;

  if (tp) h = fm_find_token_font(b, tp, 1);
  else    h = fm_find_font(b, "serif", choices.font_size, choices.font_size, 0, 0);

//  {
//     int face, size, italic, bold, scale;

  RetError(fm_font_box(h, &box));

  /* We know the font is 'size' 16ths, so we can work */
  /* out the line spacing from this. Don't use the    */
  /* font metrics - otherwise, bold text (say) will   */
  /* force the line spacing higher than plain.        */

1679
  rettop = box.ymax - ((b->page_is_text && !choices.system_font) ? b->leading * 2 : 0);
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
  retbot = -box.ymin + b->leading;

//     fm_token_font_info(tp, &face, &size, &italic, &bold);
//
//     bot = b->leading;
//
//     convert_to_points(1, &scale);
//     top += (size * 1000) / (16 * scale);

  if (top) *top = rettop;
  if (bot) *bot = retbot;

  return NULL;
}

1695 1696 1697 1698 1699
/*************************************************/
/* reformat_check_height()                       */
/*                                               */
/* Looks at the contents of a reformat_line      */
/* structure and ensures that it's y coordinate, */
1700
/* height and font baseline offset fields are    */
1701 1702 1703
/* correctly filled in.                          */
/*                                               */
/* Parameters: 1 for all external callers, but   */
1704
/*             will be 0 if it calls itself      */
1705 1706 1707 1708 1709 1710 1711 1712
/*             internally;                       */
/*                                               */
/*             Pointer to a browser_data struct  */
/*             relevant to the line;             */
/*                                               */
/*             Pointer to a reformat_cell struct */
/*             that the line lies in;            */
/*                                               */
1713
/*             Number of the line to alter;      */
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
/*                                               */
/*             Pointer to the token that may     */
/*             cause the line height to alter;   */
/*                                               */
/*             Pointer to the last token dealt   */
/*             with by the reformatter;          */
/*                                               */
/*             Offset into the current token's   */
/*             data.                             */
/*                                               */
/* Returns:    Fills in bits of the line struct, */
/*             as mentioned above.               */
/*************************************************/

static _kernel_oserror * reformat_check_height(int toplevel, browser_data * b, reformat_cell * d, int line, HStream * tp, HStream * tpLast, int offset)
{
  _kernel_oserror * e;
1731 1732 1733 1734 1735
  int               top     = 0;
  int               bot     = 0;
  int               setpara = 0; /* Flags that a paragraph break should be added later on */

  if (!d) d = b->cell;
1736

1737 1738
  /* Some initial white space calculations. All these rely on the */
  /* item being at the start of a paragraph - 'offset' is zero.   */
1739

1740
  if (!offset)
1741
  {
1742
    /* If the token represents a line break, include a gap, unless */
1743
    /* we're at the top of a page / cell or just after a LI tag.   */
1744

1745 1746 1747 1748 1749 1750
    if (
         line > 0              &&
         !(tpLast->style & LI) &&
         (tp->style & P)
       )
       setpara = 1;
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761

    /* Alternatively, if the indent has changed, insert some */
    /* space above the item (but don't do this for UL and DL */
    /* items, as these are handled more carefully later).    */

    else if (
              tpLast                       &&
              tpLast->indent != tp->indent &&
              !(tp->style & UL)            &&
              !(tp->style & DL)
            )
1762
            setpara = 1;
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772

    /* The next few require text before them to gain a gap, or if */
    /* the last tag was BR and the tag before that was text, the  */
    /* gaps can still be added as BR just breaks the line.        */

    else if (
              tpLast &&
              (
                (tpLast->style & PCDATA) ||
                (
1773
                  (tpLast->tagno == TAG_BR)      &&
1774 1775 1776 1777 1778 1779 1780 1781
                  tpLast->prev                   &&
                  (tpLast->prev->style & PCDATA)
                )
              )
            )
    {
      /* Want a space above UL items */

1782
      if (tp->style & UL) setpara = 1;
1783 1784 1785 1786 1787 1788 1789 1790 1791

      /* If a header type has changed, and we are dealing with a */
      /* text token, insert a gap above the item to push it away */
      /* either from the text above or from the header above.    */

      else if (
                (tp->style & PCDATA) &&
                redraw_header(tp->style) != redraw_header(tpLast->style)
              )
1792
              setpara = 1;
1793 1794 1795 1796 1797 1798 1799

      /* If we're about to enter a definition list, the 'spaces if */
      /* indent changes' code above will make the spaces look odd  */
      /* unless we also give a space above the first item in the   */
      /* definition list (the DT elements are not indented, so no  */
      /* white space would have been inserted so far).             */

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
      else if (tp->style & DL) setpara = 1;
    }
  }

  /* If flagged to do so, set 'top' for an initial paragraph break */

  if (setpara)
  {
    int texttop, textbot;

    RetError(reformat_text_line_height(b,
                                       NULL,
                                       &texttop,
                                       &textbot));

    top = ((texttop + textbot) * 7) >> 3;
  }

  /* BRs - a single BR between bits of text will force a new line and be the     */
  /* first token in the new line, but will then have other tokens in that same   */
  /* line. It should not alter the line height itself under these circumstances. */
  /* However, two consecutive BRs should - that is, when the second is found, it */
  /* should force a P-style break, and so-on for all subsequent BRs. It is also  */
  /* the case that a BR at the top of a page / cell should similarly force a     */
  /* paragraph-like break.                                                       */

  {
    HStream * fol; /* First On Line */

    fol = d->cdata[d->ldata[line].chunks].t;

    if (
1832
         (fol->tagno == TAG_BR) &&
1833 1834 1835
         (
           (
             fol->prev &&
1836
             (fol->prev->tagno == TAG_BR)
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
           )
           || line == 0
         )
       )
    {
      int texttop, textbot;

      RetError(reformat_text_line_height(b,
                                         tp,
                                         &texttop,
                                         &textbot));

      top = texttop + textbot;
1850
    }
1851
  }
1852 1853 1854

  /* Find out the height of an image */

1855 1856 1857
  if (
       (tp->style & IMG) ||
       (
1858
         tp->tagno         == TAG_INPUT &&
1859 1860 1861
         HtmlINPUTtype(tp) == inputtype_IMAGE
       )
     )
1862 1863 1864
  {
    BBox box;

1865
    RetError(reformat_get_image_size(b, tp, &box));
1866

1867 1868
    top +=  box.ymax;
    bot  = -box.ymin;
1869 1870
  }

1871 1872
  /* Deal with OBJECT, APPLET and EMBED tags */

1873
  else if (ISOBJECT(tp))
1874 1875 1876 1877 1878 1879 1880 1881 1882
  {
    BBox box;

    RetError(reformat_get_object_size(b, tp, &box));

    top += box.ymax;
    bot  = -box.ymin;
  }

1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
  /* Size of a horizontal rule; the rule is plotted */
  /* centred vertically within its bounding box so  */
  /* there is no need to set both bot and top to    */
  /* the same value. With top = 0, setting bot is   */
  /* enough.                                        */

  else if (tp->style & HR)
  {
    int size;

    /* Deal with a (vertical) size specifier */

    if (HR_HAS_SIZE(tp))
    {
      /* (Only recognise pixels at present) */

      switch (HR_SIZE_UNITS(tp))
      {
        case UNITS_PIXELS: size = HR_SIZE(tp) * 2; break;

        default: size = 4; break;
      }
    }
    else size = 4;

    if (size < 24) size = 24;

1910
    bot = size + 4;
1911 1912 1913 1914
  }

  /* A few easy to work out forms elements */

1915 1916 1917 1918
  else if (
            tp->tagno         == TAG_INPUT &&
            HtmlINPUTtype(tp) == inputtype_CHECKBOX
          )
1919
  {
1920 1921 1922 1923
    int size;

    read_sprite_size("fopton", NULL, &size);
    top += size - 8;
1924 1925 1926
    bot = 8;
  }

1927 1928 1929 1930
  else if (
            tp->tagno         == TAG_INPUT &&
            HtmlINPUTtype(tp) == inputtype_RADIO
          )
1931
  {
1932 1933 1934 1935
    int size;

    read_sprite_size("fradioon", NULL, &size);
    top += size - 8;
1936 1937 1938 1939 1940 1941 1942
    bot = 8;
  }

  /* Height of a bullet point */

  else if (ISBULLET(tp))
  {
1943
    top += reformat_bullet_height(tp->indent);
1944 1945
  }

1946
  else if (tp->tagno == TAG_TABLE)
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
  {
    /* Don't do anything! h is already correct */

    tp = tp; /* Make sure the compiler gets the if..else if.. etc. right */
  }

  /* If the above matches aren't found, use a more general routine */

  else
  {
    /* Get the bounding box of the font that should be used for the token */
1958 1959
    /* if we've got some text, and we're either a visible forms element   */
    /* or the text consists of more than one single space.                */
1960

1961
    if (
1962 1963 1964 1965 1966 1967 1968
         (
           (tp->style & FORM)        &&
           tp->tagno != TAG_FORM     &&
           tp->tagno != TAG_FORM_END &&
           HtmlINPUTtype(tp) != inputtype_HIDDEN
         )
         ||
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
         (
           (tp->text) &&
           (
             tp->text[0] &&
             !
             (
               tp->text[0] == ' '  &&
               tp->text[1] == '\0'
             )
           )
         )
       )
1981
    {
1982
      int texttop, textbot;
1983

1984 1985 1986 1987
      RetError(reformat_text_line_height(b,
                                         tp,
                                         &texttop,
                                         &textbot));
1988

1989 1990
      top += texttop;
      bot =  textbot;
1991 1992 1993 1994 1995
    }
  }

  /* Work out height of various forms elements */

1996
  if (tp->tagno == TAG_TEXTAREA)
1997 1998 1999
  {
    /* Text areas, based on the number of rows */

2000 2001 2002
    BBox box;
    int  h;
    int  r;
2003
    int  lh, lb;
2004

2005
    h = fm_find_token_font(b, tp, 0);
2006 2007
    e = fm_font_box(h, &box);
    if (e) return e;
2008 2009 2010

    r = tp->rows;
    if (r < 2) r = 2;
2011 2012 2013 2014 2015

    form_get_linesize(&box, &lh, &lb);

    bot += lh * (r - 1) + 8; /* + 8 for the border; r - 1 as bot is already below the first text line, so drop it by (rows - 1) more  */
    top += 8;
2016
  }
2017
  else if (tp->tagno == TAG_SELECT)
2018 2019 2020 2021 2022 2023 2024 2025 2026
  {
    /* Selection lists - a pop-up menu icon */

    int h;

    if (read_sprite_size("fgright", NULL, &h)) h = 44;

    bot += 8;
    top += 8;
2027

2028 2029
    if (top + bot < h) top += h - top - bot;
  }
2030
  else if (tp->tagno == TAG_INPUT)
2031 2032 2033
  {
    /* General input types */

Kevin Bracey's avatar
Kevin Bracey committed
2034
    switch(HtmlINPUTtype(tp))
2035
    {
Kevin Bracey's avatar
Kevin Bracey committed
2036 2037
      case inputtype_TEXT: /* No break - same as PASSWORD */
      case inputtype_PASSWORD:
2038
      {
2039 2040
        bot += 8;
        top += 8;
2041
      }
2042
      break;
2043

Kevin Bracey's avatar
Kevin Bracey committed
2044
      case inputtype_SUBMIT: /* No break - same as RESET */
2045
      case inputtype_BUTTON: /* Again, no break          */
Kevin Bracey's avatar
Kevin Bracey committed
2046
      case inputtype_RESET:
2047
      {
2048 2049
        bot += 8;
        top += 12;
2050
      }
2051 2052 2053 2054
      break;
    }
  }

2055 2056 2057 2058 2059
  /* Round up top and bot to a multiple of 4 */

  if (top & 3) top += 4 - (top & 3);
  if (bot & 3) bot += 4 - (bot & 3);

2060 2061 2062 2063
  /* 'top' will correspond to the line height above the font baseline. */
  /* If it is greater than the current value, extend the top of the    */
  /* line by the difference. Move the line y coordinate down to make   */
  /* room for the extra height.                                        */
2064 2065 2066 2067 2068 2069

  if (top > (d->ldata[line].h - d->ldata[line].b))
  {
    int diff;

    diff = top - (d->ldata[line].h - d->ldata[line].b);
2070

2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
    d->ldata[line].h += diff;
    d->ldata[line].y -= diff;
  }

  /* Similarly, if bot is greater than the offset of the baseline from */
  /* the bottom of the line, account for the extra offset.             */

  if (bot > d->ldata[line].b)
  {
    int diff;

    diff = bot - d->ldata[line].b;

2084 2085
    d->ldata[line].h += diff; /* (Since 'h' is the total height above and below the baseline) */
    d->ldata[line].b += diff;
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
    d->ldata[line].y -= diff;
  }

  return NULL;
}

/*************************************************/
/* reformat_check_visited()                      */
/*                                               */
/* Looks at a given token and compares it to the */
/* global history, setting a bit in the flags    */
/* word if a link it represents has been visited */
/* before.                                       */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the token;            */
/*                                               */
/*             Pointer to the token.             */
/*************************************************/

static void reformat_check_visited(browser_data * b, HStream * token)
{
2108
  if (ISLINK(token) && history_visited(token->anchor)) token->flags |= HFlags_LinkVisited;
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
}

/*************************************************/
/* reformat_check_extent()                       */
/*                                               */
/* Sets the browser window vertical extent to    */
/* match the page, by looking at the last line   */
/* in the line list.                             */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             holding details of the window to  */
/*             alter.                            */
/*************************************************/

_kernel_oserror * reformat_check_extent(browser_data * b)
{
2125 2126 2127 2128 2129 2130
  /* Nothing to do for small fetch windows */

  if (b->small_fetch) return NULL;

  /* Otherwise exit through the extent setting routines */

2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
  return reformat_set_extent(b, -reformat_return_extent(b, NULL));
}

/*************************************************/
/* reformat_return_extent()                      */
/*                                               */
/* Returns the height of a page in OS units,     */
/* according to its current formatted state.     */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             holding details of the page;      */
/*                                               */
/*             Pointer to a reformat_cell struct */
/*             holding redraw information.       */
/*************************************************/

int reformat_return_extent(browser_data * b, reformat_cell * cell)
{
  int extent = 0;

  if (!cell) cell = b->cell;

  if (cell->ldata) extent = -cell->ldata[cell->nlines - 1].y;

  return extent;
}

/*************************************************/
/* reformat_set_extent()                         */
/*                                               */
/* Sets the browser window vertical extent. The  */
/* extent can only ever grow.                    */
/*                                               */
/* Parameters: A pointer to a browser_data       */
/*             structure containing details of   */
/*             the window to alter;              */
2167
/*                                               */
2168 2169 2170 2171 2172 2173 2174 2175
/*             A new vertical extent in OS units */
/*             - this is a *negative* number,    */
/*             expressed as a downward offset    */
/*             from the top of the window.       */
/*************************************************/

_kernel_oserror * reformat_set_extent(browser_data * b, int y_extent)
{
2176 2177 2178
  WimpGetWindowStateBlock s;
  BBox                    new_extent;
  int                     hbot, width;
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188

  #ifdef TRACE
    if (tl & (1u<<8)) Printf("\nreformat_set_extent: Called, -y_extent = %d\n",-y_extent);
  #endif

  /* For windows with frames, don't want to mess around with the extent */

  if (b->nchildren) return NULL;

  s.window_handle = b->window_handle;
2189
  RetError(wimp_get_window_state(&s));
2190 2191 2192 2193

  /* Y extent is set to the requested value plus an amount for the toolbars */
  /* and an extra amount for aesthetics.                                    */

2194 2195
  if (!controls.swap_bars) hbot = toolbars_status_height(b);
  else                     hbot = toolbars_button_height(b) + toolbars_url_height(b);
2196 2197

  y_extent -= (hbot + b->leading);
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214

  /* Ensure that the extent is at least as great as the minimum height */

  if ((-y_extent) < b->min_height) y_extent = -(b->min_height);

  /* For the height, don't want to resize below the current */
  /* visible height. Things are a bit messy due to the      */
  /* negative signs on extent, etc.                         */

  if ((-y_extent) < (s.visible_area.ymax - s.visible_area.ymin)) y_extent = -(s.visible_area.ymax - s.visible_area.ymin);

  new_extent.ymax = 0;
  new_extent.ymin = y_extent;

  /* x extent must only match or be larger than the visible */
  /* area, never smaller.                                   */

2215 2216 2217
  width = s.visible_area.xmax - s.visible_area.xmin;

  if (b->display_width < width) b->display_width = width;
2218 2219 2220 2221 2222
  if (b->display_extent < b->display_width) b->display_extent = b->display_width;

  new_extent.xmin = 0;
  new_extent.xmax = b->display_extent;

2223 2224
  /* Update height, too */

2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
  {
    int h1, h2;

    h1 = toolbars_button_height(b) + toolbars_url_height(b);
    h2 = toolbars_status_height(b);

    if (h1) h1 += wimpt_dy();
    if (h2) h2 += wimpt_dy();

    b->display_height = s.visible_area.ymax - s.visible_area.ymin - h1 - h2;
  }
2236

2237 2238
  /* Set the extent */

2239
  RetError(window_set_extent(0,b->self_id,&new_extent));
2240 2241 2242 2243 2244 2245 2246 2247

  /* Can't set extent so visible area is now outside the work area; */
  /* call wimp_open_window to make sure scroll positions are OK.    */

  {
    ObjectId    po;
    ComponentId pc;

2248
    RetError(toolbox_get_parent(0, b->self_id, &po, &pc));
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340

    return toolbox_show_object(0, b->self_id, 1, (void *) &s.visible_area, po, pc);
  }
}

/*************************************************/
/* reformat_add_line()                           */
/*                                               */
/* Adds a line to the array of line structures.  */
/* The contents are NOT initialised.             */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the page;             */
/*                                               */
/*             Pointer to the reformat_cell      */
/*             structure to add the chunks to.   */
/*************************************************/

static _kernel_oserror * reformat_add_line(browser_data * b, reformat_cell * cell)
{
  _kernel_oserror * e;

  #ifdef TRACE
    if (tl & (1u<<8)) Printf("reformat_add_line: Called with cell %p, cell->nlines = %d\n",cell,cell->nlines);
  #endif

  /* Allocate memory for the new number of lines */

  #ifdef TRACE
    if (tl & (1u<<12)) Printf("reformat_add_line: Chunk CK_LINE set to %d\n",(cell->nlines + 1) * sizeof(reformat_line));
  #endif

  e = memory_set_chunk_size(b,
                            cell,
                            !cell->table ? CK_LINE : CK_LINV, /* Variable granularity allocation for table cells */
                            (cell->nlines + 1) * sizeof(reformat_line));
  if (e) return e;

  /* Increment the line counter in the browser_data structure */

  cell->ldata[cell->nlines].x = cell->ldata[cell->nlines].y = 0;

  cell->nlines++;

//  memset( - something! - ,0,sizeof(reformat_line));

  #ifdef TRACE
    if (tl & (1u<<8)) Printf("reformat_add_line: Successful with cell->nlines = %d\n",cell->nlines);
  #endif

  return NULL;
}

/*************************************************/
/* reformat_add_line_chunk()                     */
/*                                               */
/* Adds a line chunk to the array of line chunks */
/* associated with a particular line structure.  */
/* This is complicated slightly by the variable  */
/* length of the arrays of line chunks. The new  */
/* chunk's contents are NOT initialised.         */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the page;             */
/*                                               */
/*             Pointer to the reformat_cell      */
/*             structure to add the chunks to.   */
/*************************************************/

static _kernel_oserror * reformat_add_line_chunk(browser_data * b, reformat_cell * cell)
{
  int               size, cline = cell->nlines - 1;
  _kernel_oserror * e;

  #ifdef TRACE
    if (tl & (1u<<8)) Printf("reformat_add_line_chunk: Called\n");
  #endif

  /* The function can only ever add a chunk to the end of the list. */
  /* So the chunk must belong to the last line in the list, and     */
  /* if it is the first chunk for the line structure that line      */
  /* structure's pointer to the chunks will be filled in. The chunk */
  /* counter for that line is incremented.                          */

  #ifdef TRACE
    /* If there are no lines, we can't proceed - something has gone wrong */

    if (!cell->nlines)
    {
      erb.errnum = 0;

      strcpy(erb.errmess,
2341
             "Serious internal error - There are no line structures defined in reformat_add_line_chunk; must exit immediately.");
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
      show_error(&erb);
    }
  #endif

  /* If there is no chunk data already, this is the first   */
  /* chunk allocation so the block size we want to move to  */
  /* is easy to work out.                                   */

  if (!cell->cdata) size = sizeof(reformat_line_chunk);
  else
  {
    /* We want to find the current size of data and put it into size. To do this, */
    /* get the last line's offset to the chunks and add the number of chunks it   */
    /* claims to have multiplied by the size of one chunk. The complication is    */
    /* that the last line(s) may not have any chunks, so we need to go back to    */
    /* a line that does, if that is the case.                                     */

    while (!cell->ldata[cline].n && cline >= 0) cline --;

    #ifdef TRACE
      if (cline < 0)
      {
        erb.errnum = 0;

        strcpy(erb.errmess,
2367
               "Serious internal error - No lines have associated chunks defined in reformat_add_line_chunk; must exit immediately.");
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
        show_error(&erb);
      }
    #endif

    size = (cell->ldata[cline].chunks +
            cell->ldata[cline].n + 1) *
            sizeof(reformat_line_chunk);
  }

  // if (cell->cdata) Printf("!! Consistency check - Current block size for chunks  = %p\n",(void *) flex_size((flex_ptr) &cell->cdata));
  // else Printf("!! Consistency check - Current block size for chunks  = none allocated\n");
  // Printf("!!                     New block size to be allocated = %p\n",(void *) size);

  /* Now allocate the memory */

  #ifdef TRACE
    if (tl & (1u<<12)) Printf("reformat_add_line_chunk: Chunk CK_LDAT set to %d\n",size);
  #endif

  e = memory_set_chunk_size(b,
                            cell,
                            !cell->table ? CK_LDAT : CK_LDAV, /* Variable granularity allocation for table cells */
                            size);
  if (e) return e;

  /* Update the chunk counter on the last line and the base chunk */
  /* array number, if it wasn't already set (when the line is     */
  /* created, the chunks field is filled with -1. When the first  */
  /* chunk is added for the line the chunks field is filled in,   */
  /* and it is left alone subsequently - which is exactly what we */
  /* want, as the chunks field holds the base array index of the  */
  /* chunks for the line, not the last chunk array index.         */

  cline = cell->nlines - 1;
  cell->ldata[cline].n++;
  if (cell->ldata[cline].chunks < 0) cell->ldata[cline].chunks = (int) size / sizeof(reformat_line_chunk) - 1;

  /* Success */

  #ifdef TRACE
    if (tl & (1u<<8)) Printf("reformat_add_line_chunk: Successful\n");
  #endif

  return NULL;
}

/*************************************************/
/* reformat_reformatter()                        */
/*                                               */
/* The actual working end of the reformat        */
/* routines - takes the list of HStream structs  */
/* (or tokens) and turns them into reformat_line */
/* structures for the redraw routines etc.       */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             containing all the info on the    */
/*             fetch for which reformatting is   */
/*             to take place.                    */
/*************************************************/

void reformat_reformatter(browser_data * b)
{
  reformat_reformatter_r(0, b, b->cell, b->stream);
2431 2432 2433 2434 2435 2436

  /* The browser may have the input focus inside a forms */
  /* item, so after each loop of the reformatter ask the */
  /* forms library to ensure the caret position is OK.   */

  form_caret_may_need_moving(b);
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
}

/*************************************************/
/* reformat_reformatter_r()                      */
/*                                               */
/* Recursive back-end to reformat_reformatter.   */
/*                                               */
/* Parameters: Flags (see Reformat.h);           */
/*                                               */
/*             Pointer to a browser_data struct  */
/*             relevant to the reformat session; */
/*                                               */
/*             Pointer to the reformat_cell      */
/*             struct that is to be acted upon;  */
/*                                               */
/*             Pointer to the first token in the */
/*             list of HStreams to use if there  */
/*             is no evidence of a previous      */
/*             incomplete reformat session in    */
/*             the browser_data structure.       */
/*                                               */
/* Returns:    Width of the widest line that was */
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
/*             generated, in millipoints. This   */
/*             includes the left hand margin /   */
/*             gap; however, if there is no      */
/*             stream to reformat, 0 is returned */
/*             rather than purely the left hand  */
/*             margin plus zero to indicate this */
/*             special case to the caller.       */
/*             Ideally the caller should never   */
/*             invoke the reformatter without a  */
/*             stream though, it's not very      */
/*             efficient...                      */
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
/*************************************************/

static int reformat_reformatter_r(unsigned int flags, browser_data * b, reformat_cell * d, HStream * streambase)
{
  int                   lnCurr        = -1;
  int                   cnCurr        = -1;
  int                   cnLast        = 0;
  _kernel_oserror     * e             = NULL;
  HStream             * tpCurr        = NULL, * tpLast   = NULL;
  HStream             * tnCurr        = NULL, * tnLast   = NULL;
  int                   bottom        = 0,      extent   = 0;
  int                   newlines      = 0,      newline  = 0;
  int                   newchunks     = 0,      newchunk = 0;
  int                   done          = 0;
  int                   linewidth     = 0;
  int                   widest        = 0;
  int                   offset        = 0;
  reformat_width_data   wd;
2488
  int                   displaywidth, left_margin, right_margin;
2489
  int                   toplevel, doall, fromstart, noalloc;
2490
  int                   token_has_text;
2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552

  /* Read various flags */

  toplevel  = !(flags & Reformatter_KeepGoingToEnd); /* (This may get more complex, hence 'doall' is not just '!toplevel') */
  doall     = (flags & Reformatter_KeepGoingToEnd);
  fromstart = (flags & Reformatter_FromStreamStart);

  if (doall) noalloc = (flags & Reformatter_Virtual);
  else       noalloc = 0;

  /* If there is more than one line, find the y coordinate */
  /* of the last one and put it into 'bottom'              */

  if      (d->nlines > 2)  bottom = d->ldata[d->nlines - 2].y;
  else if (d->nlines == 1) bottom = d->ldata[0].y;

  /* This y coordinate is for the last line, so it also gives the vertical extent */

  extent = bottom;

  /* Work out the current width to format to, in millipoints. */
  /* The width is the size of the visible area, but not less  */
  /* than min_width.                                          */

  if      (flags & Reformatter_FindingWidest)   displaywidth = Reformat_AsWideAsPossible_MP;
  else if (flags & Reformatter_FindingSmallest) displaywidth = 1600;
  else convert_to_points(redraw_display_width(b, d), &displaywidth);

  if (d->nlines && !noalloc)
  {
    /* If there are some lines, set up the local variables */
    /* according to the last line's contents.              */

    int i;

    /* Set lnCurr to the last line, and set cnLast to the first chunk */
    /* number on that line. Note that if the line has no chunks, the  */
    /* routine steps back one. The function will exit if it turns out */
    /* that the first line has no chunks (after all, there's nothing  */
    /* to format if this is the case!)                                */

    lnCurr = d->nlines - 1;

    while (!d->ldata[lnCurr].n && lnCurr >= 0) lnCurr --;
    if (lnCurr < 0) return 0;

    cnLast = d->ldata[lnCurr].chunks;

    /* Get the address of the HStream associated with the */
    /* first chunk of the last line into tpLast.          */

    tpLast = d->cdata[cnLast].t;

//    /* Since the current tag is be at the start of this line,   */
//    /* strip out any preceeding spaces in it (the function      */
//    /* deals with the special case of preformatted text, etc.). */
//
//    reformat_strip_prespace(b, cnCurr, tpCurr);

    /* Set 'linewidth' to the indentation requried at this line, */
    /* and add the widths of the line chunks to this.            */

2553
    linewidth = redraw_left_gap(b, d, tpLast);
2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585

    for (
          i = 0;
          i < d->ldata[lnCurr].n;
          i++, cnLast++
        )
        linewidth += d->cdata[cnLast].w;

    if (linewidth > widest) widest = linewidth;

    /* If the current line has at least 1 chunk... */

    if (d->ldata[lnCurr].n)
    {
      /* Set cnLast to now hold the number of the last chunk for the */
      /* last line, and tpCurr and tpLast to hold the address of the */
      /* token associated with the chunk.                            */

      cnLast = d->ldata[lnCurr].n + d->ldata[lnCurr].chunks - 1;
      tnCurr = tnLast = tpCurr = tpLast = d->cdata[cnLast].t;

      /* Set 'offset' to the offset into the token associated with the last */
      /* chunk in the last line, plus the amount of data to take from that  */
      /* token - i.e. it points to the first unused byte in that token,     */
      /* as far as the last chunk of the last line is concerned.            */

      offset = d->cdata[cnLast].o + d->cdata[cnLast].l;

      /* If the number of bytes into the token is <=0, then find out the */
      /* total size of data normally associated with the token (e.g. the */
      /* string length of any text it points to) and put this in offset. */

2586 2587 2588 2589 2590 2591 2592 2593
      if (d->cdata[cnLast].l <= 0)
      {
        /* In this case associated data will *almost* always be zero length, */
        /* in terms of text, but there are some rare circumstances when it   */
        /* won't be. Hence the reformat_datasize call.                       */

        offset = reformat_datasize(tpLast);
      }
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639

      /* If the tag represents text, points to a text string, and that text */
      /* string terminates in a new line character, then need to start on a */
      /* new line.                                                          */

      if (
           offset > 0                       &&
           reformat_istext(tpCurr)          &&
           tpCurr->text                     &&
           tpCurr->text[offset - 1] == '\n'
         )
         newline = 1;
    }
    else newchunk = 1; /* Otherwise, flag that a chunk needs adding */
  }

  /* There are no line structures currently present; we aren't, then, */
  /* going to add to an existing line and need to flag that a new     */
  /* line must be created before chunks can be added.                 */

  else newline = 1;

  /* Loop round the reformatter whilst there is no error, the reformat */
  /* hasn't completed (we are still reformatting and the 'done' flag   */
  /* isn't set), and the number of new lines dealt with is less than   */
  /* 10 (don't want to do too much in one go, or the Desktop will      */
  /* feel very jerky) or we haven't flagged a new line is needed - the */
  /* reformat will only keep going for a certain number of lines, but  */
  /* won't stop mid-line.                                              */

  while (
          !e    &&
          !done &&
          (
            doall         ||
            newlines < 10 ||
            !newline
          )
          && reformat_formatting(b)
        )
  {
    /* tpCurr points the the token we're currently dealing with. If */
    /* this is NULL, or the offset into that token seems to point   */
    /* past its associated data, we've finished with the token. So  */
    /* move onto another, or if there are no more, set 'done' to 1. */

2640 2641 2642
    if (tpCurr) token_has_text = tpCurr->text ? reformat_istext(tpCurr) : 0;
    else        token_has_text = 0;

2643 2644 2645 2646
    // Used to be 'if (!tpCurr || offset >= reformat_datasize(tpCurr))'
    // Really should check that the below never differs from it.

    if (!token_has_text || offset < 0 || !tpCurr->text[offset])
2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
    {
      /* Record the last token that was dealt with in the browser_data structure */

      if (!fromstart) b->last_token = tnLast;

      /* Advance to the next token after that last one */

      if (tpLast) tnCurr = tnLast->next;
      else        tnCurr = streambase;

      /* Proceed if we haven't just run out of tokens */

      if (tnCurr && (tnCurr->flags & HFlags_DealtWithToken))
      {
        tpCurr = tnCurr;

        /* If this token isn't of any use to the reformatter (it */
        /* might correspond to header information rather than    */
        /* body text, say), keep getting new tokens until they   */
        /* are useful or we run out. If we run out, set 'done'   */
        /* again to show that the tokens have all been dealt     */
        /* with.                                                 */

2670 2671 2672 2673
        while (
                tpCurr                                  &&
                (tpCurr->flags & HFlags_DealtWithToken) &&
                reformat_useless_token(tpCurr))
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684
        {
          if (!fromstart) b->last_token = tpCurr; /* Update the record of the last token dealt with */
          tnCurr = tpCurr = tpCurr->next;         /* Get the pointer to the new token               */
        }

        /* If we've ended up off the end of the token list (tpCurr is */
        /* NULL) or on a token that the fetcher hasn't dealt with yet */
        /* (the HFlags_DealtWithToken bit in the flags word is unset) */
        /* then signal that the reformatter should exit by setting    */
        /* 'done' to 1.                                               */

2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
        if (!tpCurr) done = 1;
        else
        {
          if (!(tpCurr->flags & HFlags_DealtWithToken))
          {
            b->last_token = tpCurr->prev;
            tpCurr        = NULL;
            tnCurr        = NULL;
            done          = 1;
          }
        }
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712

        /* Offset is set to 0 to show this is a new token, and we haven't */
        /* dealt with any of the data in it yet.                          */

        offset = 0;
      }

      /* The current token number was greater than the number of tokens - */
      /* we've run out of tokens, so flag that this in 'done'.            */

      else done = 1;
    }

    /* Continue with the reformat if it hasn't been flagged as finished through 'done'. */

    if (!done)
    {
2713 2714 2715
      /* The left hand margin - zero for horizontal rules, which can span the whole     */
      /* display (their actual visible extent is determined by the redraw routine);     */
      /* else equal to the result of redraw_left_gap in Redraw.c (converted to points). */
2716

2717
      left_margin = redraw_left_gap(b, d, tpCurr);
2718

2719 2720
      /* Can't have a margin greater than display width, but this consideration */
      /* only applies if we're not finding the smallest the stream can be.      */
2721

2722
      if (!(flags & Reformatter_FindingSmallest) && left_margin > displaywidth) left_margin = 0;
2723

2724
      /* The right hand gap value */
2725

2726
      right_margin = redraw_right_gap(b, d, tpCurr);
2727

2728 2729 2730 2731
      /* Can't have margins greater than the display width */

      if (left_margin + right_margin > displaywidth) right_margin = 0;

2732 2733 2734
//      /* If the text is not preformatted and the line width has gone over */
//      /* over the available display width, flag that a new line is needed */
//
2735
      if (!newline && !(tpCurr->style & PRE) && linewidth > displaywidth - right_margin) newline = 1;
2736 2737 2738 2739 2740 2741

      /* If the difference between the current and last tags say we should */
      /* put in a line break, flag this in newline.                        */

      if (!newline && reformat_newline(tpCurr,tpLast,offset)) newline = 1;

2742 2743
      /* Right, if newline is set, create a new line. */

2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
      if (newline)
      {
        int y = 0;

        newline  = 0;
        newchunk = 1;
        newlines ++;

        if (!noalloc)
        {
          /* Set y to hold the y coordinate the line is to be placed */
          /* at. This will either be determined by the previous      */
          /* line's y coordinate or if there are no lines, the       */
          /* toolbars and aesthetic lead-in considerations. The line */
          /* at this stage is of zero height; as it's height grows,  */
          /* the y value worked out here has the height subtracted   */
          /* from it to get the actual line position.                */

          if (lnCurr >= 0) y = d->ldata[lnCurr].y;

          /* (The 4 is to allow for the window frame of the toolbars) */

          else y = toplevel ? reformat_y_offset(b) : 0;

          /* If there aren't any new chunks, the bottom line hasn't */
          /* changed so set bottom to y; this stops the unchanged   */
          /* line being redrawn.                                    */

          if (!newchunks) bottom = y;

          /* Add the new line structure */

          e = reformat_add_line(b, d);
        }
        else e = NULL;

        /* If the addition was successful, fill in various details */

        if (!e)
        {
          tpCurr = tnCurr;
          tpLast = tnLast;

          if (!noalloc)
          {
            /* Advance the current line number in lnCurr to this new line */

            lnCurr = d->nlines - 1;

2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
            /* Set the line height as zero, and baseline offset as zero. We */
            /* have no contents with which to do anything different yet.    */
            /* Changing 'b' will move the font baseline relative to the     */
            /* line base, and force the line height up. 'h' is the line     */
            /* height total including the baseline offset.                  */
            /*                                                              */
            /* When reformat_check_height is called, it will go through     */
            /* working out values called 'top' and 'bot'. The first is the  */
            /* amount by which the line height above the baseline (i.e.     */
            /* ...[...].h - ...[...].b) is to be extended; the second is    */
            /* the amount by which the space below the baseline is to be    */
            /* extended. These can thus be played about with to do vertical */
            /* alignment on images and so-forth.                            */
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820

            d->ldata[lnCurr].h = 0;
            d->ldata[lnCurr].y = y;
            d->ldata[lnCurr].b = 0;

            /* The line has no chunks associated with it yet. */

            d->ldata[lnCurr].n      = 0;
            d->ldata[lnCurr].chunks = -1;
          }

          /* In light of this new line, set linewidth back to just the left margin,  */
          /* as there are no previous chunks to consider in working out chunk widths */
          /* in the add chunk code below.                                            */

2821
          linewidth = left_margin;
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832

          if (linewidth > widest) widest = linewidth;
        }

      /* End of newline check; if newline != 0, a new line is added to the line structure array. */
      }

      /* If there's no error, continue with the reformat procedure. */

      if (!e)
      {
2833 2834
        int available;

2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
//        /* If the image has a known width and height, the reformatter is  */
//        /* about to deal with it - so the image library can mark it as    */
//        /* redrawable now (otherwise, for delayed reformats, some images  */
//        /* which were cross referenced and did not have reformat sessions */
//        /* explicitly started for them, may get stuck in a                */
//        /* 'non-redrawable' state).                                       */
//        /*                                                                */
//        /* Important to call this *before* trying to find the item height */
//        /* or width, as the image size routines will lie about the real   */
//        /* size if they think the item is not redrawable because it has   */
//        /* not be reformatted yet - chicken and egg...                    */
//
//        // Mmm, nice. And robust too. Or Your Money Back (TM).
//        //
//        // Really *must* do something about this (but probably won't...)
//
//        if (
//             (tpCurr->style & IMG) ||
//             (
//               tpCurr->tagno         == TAG_INPUT &&
//               HtmlINPUTtype(tpCurr) == inputtype_IMAGE
//             )
//           )
//           image_token_check_redrawable(b, tpCurr);

        /* If the image has a known width and height, the reformatter */
        /* has dealt with it; so both mark it as redrawable, and lock */
        /* its size down.                                             */

        image_token_reformatted(b, tpCurr);

2866 2867 2868
        /* Fill in the reformat_width_data structure */

        wd.b      = b;
2869
        wd.d      = d;
2870
        wd.tp     = tpCurr;
2871
        wd.data   = reformat_istext(tpCurr) ? tpCurr->text : NULL;
2872 2873
        wd.offset = offset;

2874 2875 2876 2877 2878
        /* Tables, when specifying percentage widths, take up the whole */
        /* page - e.g. 100% when in an indented list will result in the */
        /* right hand edge of the table being off the page. Well, this  */
        /* is what MSIE / NN do anyway, despite it being stupid IMHO.   */

2879
        if (tpCurr->tagno == TAG_TABLE && (TABLE_HAS_WIDTH((table_stream *) tpCurr)))
2880 2881 2882 2883 2884 2885 2886 2887
        {
          available = displaywidth - redraw_left_margin(b, d) - right_margin;
        }
        else
        {
          available = displaywidth - linewidth - right_margin;
        }

2888
        /* The maximum width is 'very large' for preformatted text (effectively limitless).  */
2889
        /* Similarly, for any text items in NOBR, the width in effect is without a limit.    */
2890 2891 2892 2893 2894 2895 2896 2897 2898
        /* For other tokens, the left hand edge is at an indent equal to the left hand       */
        /* margin plus the summed widths of preceeding chunks (this is kept in 'linewidth'), */
        /* so the width is the available display width minus this left hand value.           */

        wd.maxwid = (
                      (
                        (tpCurr->style & PRE) &&
                        reformat_istext(tpCurr)
                      )
2899 2900 2901 2902 2903 2904 2905 2906 2907

                      #ifdef SUPPORT_NOBR
                        ||
                        (
                          (tpCurr->style & PCDATA) &&
                          (tpCurr->style & NOBR)
                        )
                      #endif

2908 2909 2910 2911
                    )

                    ?

2912 2913 2914
                    Reformat_AsWideAsPossible_MP : available;

        if (wd.maxwid < 0) wd.maxwid = 0;
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926

        /* Set the (returned) bytes and width fields to zero initially */

        wd.bytes = wd.width = 0;

        /* Find out the width */

        e = reformat_token_width(&wd, flags);

        /* Adjust the line height for tables based on */
        /* the data from the above call               */

2927
        if (tpCurr->tagno == TAG_TABLE)
2928 2929 2930
        {
          if (!noalloc)
          {
2931 2932 2933
            /* Take the height in millipoints (overloaded into wd.bytes) and use */
            /* this as the line height.                                          */

2934 2935
            convert_to_os(wd.bytes, &d->ldata[lnCurr].h);

2936 2937
            /* Correct the line's y coordinate given the above height. */

2938
            d->ldata[lnCurr].y -= d->ldata[lnCurr].h;
2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949

            /* P tags before tables get attached to the TABLE HStream itself. */

            if ((tpCurr->style & P) && (lnCurr > 0))
            {
              int texttop, textbot;

              e = reformat_text_line_height(b, NULL, &texttop, &textbot);

              if (!e) d->ldata[lnCurr].y -= texttop + textbot;
            }
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
          }

          wd.bytes = 0;
        }

        /* If the chunk width'd and defined by the above call ends in a newline character, */
        /* flag a line break is needed through newline = 1.                                */

        else if (reformat_istext(tpCurr) && wd.bytes && wd.data[wd.offset + wd.bytes - 1] == '\n') newline = 1;
      }

2961 2962 2963 2964
      /* A new chunk is forced by setting 'newchunk' if the previous item and this one    */
      /* should not be split up. For example, an LI bullet point and the text that        */
      /* follows it (if any) should appear on the same line.                              */

2965
      if (!e && !newchunk)
2966
      {
2967 2968 2969 2970 2971 2972 2973
        if (
             !offset                    &&
             tpCurr->prev               &&
             !(tpCurr->style & LI)      &&
             (tpCurr->prev->style & LI)
           )
           newchunk = 1;
2974 2975
      }

2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
      /* Proceed if there is no error, to add a chunk. If the current line has no chunks, */
      /* then one will always be added. If there are already chunks present, another is   */
      /* added only if it will fit in the display (wd.width is less than wd.maxwid), or   */
      /* if the text is preformatted (in which case you keep adding chunks until there's  */
      /* a line break in the source).                                                     */

      if (
           !e &&
           (
             newchunk              || /* Will be set if current line has no chunks yet */
             wd.width <= wd.maxwid ||
             (tpCurr->style & PRE)
           )
         )
      {
        newchunk = 0;
        newchunks ++;

        if (!noalloc) e = reformat_add_line_chunk(b, d);
        else          e = NULL;

        /* Proceed if the above didn't return an error */

        if (!e)
        {
          tpCurr = tnCurr;
          tpLast = tnLast;

          if (!noalloc)
          {
            /* Set cnCurr to the array index of the last (i.e new) chunk; */
            /* we know that if a new chunk has been added the last line   */
            /* must have at least the one chunk now, so no need for all   */
            /* the checking for various cases of lines not having chunks  */
            /* that has gone on elsewhere.                                */

            cnCurr = d->ldata[d->nlines - 1].chunks + d->ldata[d->nlines - 1].n - 1;

            /* Fill in the new line chunk */

            d->cdata[cnCurr].t = tpCurr;
            d->cdata[cnCurr].w = wd.width;
            d->cdata[cnCurr].o = offset;
            d->cdata[cnCurr].l = wd.bytes;

3021 3022 3023 3024
            /* If this holds an image, need to invalidate the x and y position */
            /* information that the redraw routines set up, as it may have     */
            /* moved. The new position will be set when the reformatted        */
            /* region is next redrawn.                                         */
3025

3026 3027 3028 3029 3030 3031 3032 3033
            if (
                 (tpCurr->style & IMG) ||
                 (
                   tpCurr->tagno         == TAG_INPUT &&
                   HtmlINPUTtype(tpCurr) == inputtype_IMAGE
                 )
               )
               image_set_token_image_position(b, tpCurr, -1, -1);
3034

3035
            #ifdef TRACE
3036
              if ((tl & (1u<<20)) && tpCurr->tagno == TAG_TABLE) Printf("reformat_reformatter_r: Added a table\n");
3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
            #endif

//            if (d->ldata[d->nlines - 1].n == 1)
//            {
//              /* Since the current chunk will be at the start of a new line, */
//              /* strip out any preceeding spaces in it (the function deals   */
//              /* with the special case of preformatted text, etc.).          */
//
//              reformat_strip_prespace(b, cnCurr, tpCurr);
//            }

//            if (d->ldata[d->nlines - 1].n == 1)
//            {
//              if (tpCurr->text && !(tpCurr->style & PRE))
//              {
//                while (*(tpCurr->text + d->cdata[cnCurr].o) == ' ' && d->cdata[cnCurr].l) d->cdata[cnCurr].o++, d->cdata[cnCurr].l--, offset++;
//              }
//            }


            /* Set the Visited flag if this token is a link and is in the global History */

            reformat_check_visited(b, tpCurr);

            /* Ensure the line's height details are updated in light of the new chunk */

            e = reformat_check_height(toplevel, b, d, lnCurr, tpCurr, tpLast, offset);
          }
          else e = NULL;

          if (!e)
          {
            int w;

3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082
//            if (!noalloc)
//            {
//              /* If a form had input focus, hopefully the forms library can now find */
//              /* the caret. This call will check if the token we're dealing with is  */
//              /* the currently editing one, and if so try to find its position and   */
//              /* move the caret as necessary. We do this only if 'noalloc' is unset, */
//              /* as if we're a 'virtual reformat loop', the token won't necessarily  */
//              /* have presence in any lines anyway. It might not be found if noalloc */
//              /* is unset anyway, but at least we increase the chances...            */
//
//              form_caret_may_be_moving(b, tnCurr);
//            }
3083

3084 3085
            /* Advance through the token data */

3086 3087 3088 3089 3090 3091 3092 3093
            if (wd.bytes <= 0) offset = -1; /* Flag we need a new token */
            else
            {
              int has_text;

              offset += wd.bytes;

              /* Need a new line if we've not run off the end of the text - */
3094 3095
              /* there must have been a split point within it. This is not  */
              /* true, though, if NOBR is set.                              */
3096 3097 3098 3099

              if (tpCurr) has_text = tpCurr->text ? reformat_istext(tpCurr) : 0;
              else        has_text = 0;

3100 3101 3102 3103 3104
              #ifdef SUPPORT_NOBR
                if (has_text && tpCurr->text[offset] && !(tpCurr->style & NOBR)) newline = 1;
              #else
                if (has_text && tpCurr->text[offset]) newline = 1;
              #endif
3105
            }
3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124

            /* Make the last poken pointer is now updated */

            tnLast = tnCurr;
            tpLast = tpCurr;

            /* Add the chunk's width to the line width total */

            linewidth += wd.width;

            if (linewidth > widest) widest = linewidth;

            /* Convert the width to OS units and compare to the minimum width for */
            /* the browser so far. If the width as gone up, i.e. there is an      */
            /* enforced minimum for whatever reason (preformatted text, say) then */
            /* update the minimum width field appropriately.                      */

            convert_to_os(linewidth, &w);

3125
            if (linewidth >= displaywidth - right_margin)
3126
            {
3127 3128
              /* ...But shouldn't flag a new line if NOBR is set... */

3129 3130 3131 3132 3133
              #ifdef SUPPORT_NOBR
                if (!(tpCurr->style & 0*NOBR)) newline = 1;
              #else
                newline = 1;
              #endif
3134

3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152
              if (!d->table && w > b->display_extent) b->display_extent = w;
            }
          }
        }
      }
      else newline = 1;
    }
  }

  /* If there has been an error, stop the reformat and report it */

  if (e)
  {
    reformat_stop(b);
    show_error_ret(e); /* This call returns to this point rather than jumping to the poll loop */
  }
  else
  {
3153
    browser_data * ancestor = utils_ancestor(b);
3154 3155 3156 3157 3158 3159 3160 3161

    /* For keyboard control, try to find something to select. */
    /* Browser windows that have children can't have visible  */
    /* tokens, so don't bother for them, and for anything     */
    /* with a selected item, check that it has't acquired     */
    /* children over the reformat - if it has, move the       */
    /* selection out of there.                                */

3162
    if (choices.keyboard_ctrl)
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260
    {
      /* Clear the selection if the owner has acquired children */

      if (ancestor->selected)
      {
        browser_data * owner = ancestor->selected_owner;

        if (owner && owner->nchildren) browser_clear_selection(owner, 0);
      }

      /* If there is no selection (whether this is due to the */
      /* above code or not), and the current browser has no   */
      /* children, try to select something in it.             */

      if (!ancestor->selected && !b->nchildren)
      {
        ancestor->selected = browser_find_first_selectable(b, NULL, 0);

        if (ancestor->selected) ancestor->selected_owner = b;
      }
    }
  }

  /* Make sure the window is the right size and ensure */
  /* that the altered regions are redrawn, unless      */
  /* we are printing (so the reformat doesn't actually */
  /* correspond to any real window).                   */

  if (toplevel && !printing)
  {
    reformat_check_extent(b);
    browser_update_bottom(b, bottom + 4);
  }

  /* Return the width of the widest line generated in this session, in millipoints */

  return widest;
}

/*************************************************/
/* reformat_format_cell()                        */
/*                                               */
/* Reformats a specific table cell to a given    */
/* width.                                        */
/*                                               */
/* Parameters: 1 for a top level call, 0 if      */
/*             being called as part of a nested  */
/*             table parse;                      */
/*                                               */
/*             Pointer to a browser_data struct  */
/*             relevant to the table;            */
/*                                               */
/*             Pointer to the first HStream      */
/*             structure in the stream that will */
/*             be formatted into the cell;       */
/*                                               */
/*             Pointer to the table_stream       */
/*             struct representing the table;    */
/*                                               */
/*             Pointer to the table's array of   */
/*             reformat_cell structures;         */
/*                                               */
/*             Allowed cell (column) width, in   */
/*             millipoints;                      */
/*                                               */
/*             Row number of the cell;           */
/*                                               */
/*             Column number of the cell.        */
/*                                               */
/* Returns:    Actual final cell width in        */
/*             millipoints.                      */
/*************************************************/

int reformat_format_cell(int toplevel, browser_data * b, HStream * streambase, table_stream * table,
                         reformat_cell * cellarray, int ColWidth, int Row, int Column)
{
  int             dheight;
  int             cellindex = Row * table->ColSpan + Column;
  reformat_cell * c;

  /* Can't do anything if the cell index is out of range */

  if (cellindex >= table->RowSpan * table->ColSpan) return 1600;
  else c = &cellarray[cellindex];

  #ifdef TRACE
    if (tl & (1u<<20))
    {
      Printf("tables_width_cell: %p %d %d %d %d\n",streambase,ColWidth,table->ColSpan,Row,Column);
      Printf("tables_width_cell in: %d\n", ColWidth / 400);
    }
  #endif

  /* Format the cell to the specified width. If 'toplevel' is 0, this is */
  /* being called as part of a format for a parent table, so don't       */
  /* generate lines (flag Virtual in the reformatter). Otherwise, allow  */
  /* line generation (don't flag Virtual).                               */

3261
  c->width = c->cellwidth = ColWidth;
3262

3263 3264
  if (c->width <= 400) c->width = 400; /* Give at least 1 OS unit to avoid possible problems in the reformatter */

3265 3266 3267 3268 3269 3270 3271 3272
  reformat_reformatter_r(Reformatter_KeepGoingToEnd            |
                         Reformatter_FromStreamStart           |
                         (toplevel ? Reformatter_Virtual : 0),

                         b,
                         c,
                         streambase);

3273 3274 3275 3276 3277 3278 3279 3280
  /* Set the height to the line list extent, rounded down to an */
  /* integer number of pixels.                                  */

  dheight = reformat_return_extent(b, c) & ~(wimpt_dy() - 1);

  /* Convert to millipoints for storing in the cell */

  convert_to_points(dheight, &c->height);
3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346

  #ifdef TRACE
    if (tl & (1u<<20))
    {
      Printf("width found is %d\n", c->width);
      Printf("height found is %d\n",c->height);
    }
  #endif

  return c->width;
}

/*************************************************/
/* reformat_find_cell_limits()                   */
/*                                               */
/* Works out the narrowest and widest widths a   */
/* given table cell could be, in millipoints.    */
/*                                               */
/* Parameters: 1 for a top level call, 0 if      */
/*             being called as part of a nested  */
/*             table parse;                      */
/*                                               */
/*             Pointer to a browser_data struct  */
/*             relevant to the table;            */
/*                                               */
/*             Pointer to the first HStream      */
/*             structure in the stream that the  */
/*             cell is to contain;               */
/*                                               */
/*             Pointer to the table_stream       */
/*             struct representing the table;    */
/*                                               */
/*             Pointer to the table's array of   */
/*             reformat_cell structures;         */
/*                                               */
/*             Row number of the cell;           */
/*                                               */
/*             Column number of the cell;        */
/*                                               */
/*             Pointer to an int, in which the   */
/*             minimum width is returned;        */
/*                                               */
/*             Pointer to an int, in which the   */
/*             maximum width is returned;        */
/*************************************************/

void reformat_find_cell_limits(int toplevel, browser_data * b, HStream * streambase, table_stream * table,
                               reformat_cell * cellarray, int Row, int Column, int * retmin, int * retmax)
{
  int             maxwidth  = 0;
  int             minwidth  = 0;
  int             cellindex = Row * table->ColSpan + Column;
  reformat_cell * c;

  /* Can't find the limits of something outside the cell range */
  /* of the table...                                           */

  if (cellindex >= table->RowSpan * table->ColSpan)
  {
    if (retmin) *retmin = 1600;
    if (retmax) *retmax = 1600;

    return;
  }
  else c = &cellarray[cellindex];

3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
  /* If we've already got values for this cell, return them now */

  if (c->minwid >= 0 && c->maxwid >= 0)
  {
    if (retmin) *retmin = c->minwid;
    if (retmax) *retmax = c->maxwid;

    return;
  }

3357 3358 3359 3360
  if (streambase)
  {
    /* Find the maximum width used by the cell; first, reformat */
    /* to a 'large width' (effectively, no line breaks).        */
3361

3362 3363 3364 3365
    maxwidth = reformat_reformatter_r(Reformatter_KeepGoingToEnd  |
                                      Reformatter_FindingWidest   |
                                      Reformatter_FromStreamStart |
                                      Reformatter_Virtual,
3366

3367 3368 3369
                                      b,
                                      c,
                                      streambase);
3370

3371 3372 3373 3374
    #ifdef TRACE
      if (c->nlines || c->ldata || c->cdata)
      {
        erb.errnum = Utils_Error_Custom_Normal;
3375

3376
        strcpy(erb.errmess,"Line or chunk data allocated inside reformat_find_cell_limits for maxwidth check");
3377

3378 3379 3380
        show_error_ret(&erb);
      }
    #endif
3381

3382
    /* Find the minimum width */
3383

3384 3385 3386 3387
    minwidth = reformat_reformatter_r(Reformatter_KeepGoingToEnd  |
                                      Reformatter_FindingSmallest |
                                      Reformatter_FromStreamStart |
                                      Reformatter_Virtual,
3388

3389 3390 3391
                                      b,
                                      c,
                                      streambase);
3392

3393 3394 3395 3396
    #ifdef TRACE
      if (c->nlines || c->ldata || c->cdata)
      {
        erb.errnum = Utils_Error_Custom_Normal;
3397

3398
        strcpy(erb.errmess,"Line or chunk data allocated inside reformat_find_cell_limits for minwidth check");
3399

3400 3401 3402 3403 3404
        show_error_ret(&erb);
      }
    #endif
  }
  else minwidth = maxwidth = redraw_left_margin(b, c);
3405

3406
  /* Account for cellpadding */
3407

3408 3409
  {
    int cellpadmp = table->cellpadding * 2;  /* 1 'web pixel' = 2 OS units, but only for right hand edge - redraw_left_margin takes care of the rest */
3410

3411 3412 3413 3414 3415
    convert_to_points(cellpadmp, &cellpadmp);

    minwidth += cellpadmp;
    maxwidth += cellpadmp;
  }
3416

3417 3418 3419 3420 3421
  /* Store the values */

  c->minwid = minwidth;
  c->maxwid = maxwidth;

3422 3423
  if (retmin) *retmin = minwidth;
  if (retmax) *retmax = maxwidth;
3424 3425 3426 3427

  /* Finished */

  return;
3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447
}

/*************************************************/
/* reformat_change_text()                        */
/*                                               */
/* Used to alter text in a tag, to provide (for  */
/* example) smart quotes handling.               */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             with information on the fetch     */
/*             Pointer to a token to alter.      */
/*                                               */
/* Assumes:    The browser_data struct may not   */
/*             be NULL, but the token pointer    */
/*             can be and the token does not     */
/*             have to contain text.             */
/*************************************************/

void reformat_change_text(browser_data * b, HStream * tp)
{
3448 3449
// Note that this, then, does nothing right now - fix this function up some time!

3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461
  return;

  if (tp && tp->text && !(tp->style & TT) && (reformat_istext(tp)))
  {
    char * curr = tp->text;

    while (*curr)
    {
      if (*curr == '`') *curr = 148; /* Always make this quote an opening quote */

      if (*curr == '\'') /* Dumb single quote */
      {
3462 3463 3464 3465
        if   (b->last_char == ' '
           || b->last_char == '('
           || b->last_char == 148  /* Opening double quote */
           || b->last_char == '\"')
3466 3467 3468 3469 3470 3471

             *curr = 144; /* Opening single quote */
        else *curr = 145; /* Closing single quote */
      }
      else if (*curr == '\"') /* Dumb double quote */
      {
3472 3473 3474 3475 3476
        if   (b->last_char == ' '
           || b->last_char == '('
           || b->last_char == 144  /* Opening single quote */
           || b->last_char == '\''
           || b->last_char == '`')
3477 3478 3479 3480

             *curr = 148; /* Opening double quote */
        else *curr = 149; /* Closing double quote */
      }
3481 3482
      else if (*curr == '-' && b->last_char == ' ') *curr = 151; /* 'en' dash */
//      else if (*curr == '-' && b->last_char == 151) memmove - something!
3483

3484
      b->last_char = *curr;
3485 3486 3487 3488 3489 3490 3491
      curr ++;
    }
  }

  /* If we have ALT text for an image, strip off any preceeding */
  /* spaces or [s, and any trailing spaces or ]s.               */

3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502
  else if (
            tp       &&
            tp->text &&
            (
              (tp->style & IMG) ||
              (
                tp->tagno         == TAG_INPUT &&
                HtmlINPUTtype(tp) == inputtype_IMAGE
              )
            )
          )
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
  {
    char * start, * end;
    char   last;
    int    len;

    len = strlen(tp->text);

    /* Get rid of preceeding characters */

    start = tp->text;
    end   = tp->text + len - 1;

    while (*start == ' ' || *start == '[') start ++;

    /* If there's anything left... */

    if (*start)
    {
      /* Get rid of trailing characters */

      while (*end == ' ' || *end == ']')
      {
        *end = '\0';
        end --;
      }
    }

    /* If there's still something left, move the */
    /* string contents down so tp->text points   */
    /* past the stripped preceeding chracters.   */

    if (start <= end) memmove(tp->text, start, strlen(start) + 1); /* 'strlen + 1' to get the string terminator */
    else
    {
      /* If there was nothing left, did we originally have     */
      /* enough to put '[]' to mark that there's no text left? */

      if (len > 1) strcpy(tp->text,"[]");
    }

3543 3544 3545 3546
    /* Now do smart quotes substitution. Need to do this  */
    /* separately from the main text routines as the      */
    /* last_char variable must not be changed by ALT text */
    /* - it stands alone for each image.                  */
3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580

    last = ' ';
    start = tp->text;

    while (*start)
    {
      if (*start == '\'' || *start == '`') /* Dumb single quote */
      {
        if   (last == ' '
           || last == '('
           || last == 148  /* Opening double quote */
           || last == '\"')

             *start = 144; /* Opening single quote */
        else *start = 145; /* Closing single quote */
      }
      else if (*start == '\"') /* Dumb double quote */
      {
        if   (last == ' '
           || last == '('
           || last == 144  /* Opening single quote */
           || last == '\''
           || last == '`')

             *start = 148; /* Opening double quote */
        else *start = 149; /* Closing double quote */
      }
      else if (*start == '-' && last == ' ') *start = 151; /* 'en' dash */

      last = *start;
      start ++;
    }
  }
}