Images 176 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   : Images.c                               */
17 18 19
/*                                                 */
/* Purpose: Image related functions.               */
/*                                                 */
20 21
/* Author : Merlyn Kline for Customer browser     */
/*          This source adapted by A.D.Hodgkinson  */
22
/*                                                 */
23 24 25 26 27 28 29 30 31 32
/* History: 28-Nov-96: Created with dummy function */
/*                     for temporary use in other  */
/*                     routines.                   */
/*          20-Jan-97: Filled in with most of the  */
/*                     functions present and       */
/*                     converted to the new data   */
/*                     structures where needed.    */
/*          15-Mar-97: Reorganised a bit, putting  */
/*                     functions in a more logical */
/*                     order to aid legibility.    */
33 34
/*          17-Dec-97: Added support for saving as */
/*                     a Draw file.                */
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
/***************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.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 "toolbox.h"

#include "svcprint.h"
#include "Global.h"
#include "FromROSLib.h"
56
#include "MiscDefs.h"
57 58 59
#include "Utils.h"

#include "Browser.h"
60 61
#include "Fetch.h" /* (Which itself includes URLstat.h) */
#include "FetchHTML.h"
62 63
#include "FetchPage.h"
#include "FontManage.h"
64
#include "ImgHistory.h"
65
#include "PrintStyle.h"
66
#include "Protocols.h"
67 68
#include "Redraw.h"
#include "Reformat.h"
69
#include "Save.h"
70
#include "SaveDraw.h"
71 72
#include "TokenUtils.h"
#include "Toolbars.h"
73
#include "URLutils.h"
74
#include "URLveneer.h"
75
#include "Windows.h"
76 77 78 79 80

#include "Images.h"

/* Statics */

81
static _kernel_oserror * image_load_chunk             (browser_data * b, int image, char * buffer, int bytes);
82 83 84 85 86
static void              image_remove_data            (browser_data * b, int image);
static void              image_remove_all_data        (browser_data * b, int image);
static void              image_delay                  (browser_data * b, int image);
static void              image_abandon                (browser_data * b, int image);
static void              image_delete_image_entry     (int image);
87
static void              image_refetch                (browser_data * b, int image, int priority, int redraw);
88 89 90 91

static _kernel_oserror * image_update_area            (browser_data * b, int x, int y, BBox * ubox, int image, int redraw);
static _kernel_oserror * image_update_image           (browser_data * b, int image, BBox * box);

92 93
static _kernel_oserror * image_register_filler        (int xref);

94 95 96 97 98 99
static int               image_data_offset            (browser_data * b, int image);
static int               image_count_fetches          (browser_data * b);

static int               image_get_token_image_xref   (browser_data * b, HStream * token);
static int               image_get_token_image_actual (browser_data * b, HStream * token);

100 101 102
static void              image_lock_image_size        (browser_data * b, int image);
static void              image_unlock_image_size      (browser_data * b, int image);
static _kernel_oserror * image_get_image_size         (browser_data * b, int image, BBox * box, int ignore_stored);
103
static _kernel_oserror * image_set_image_size         (browser_data * b, int image, BBox * box);
104

105 106
static int               image_can_be_saved_as_sprite (browser_data * b, int i);

107 108 109 110 111 112 113 114
/* Locals */

static image_info * idata       = NULL;
static char       * ddata       = NULL;
static int          nimages     = 0;
static int          lastimage   = 0;
static int          animhandler = 0;

115 116
static char       * unique_name = NULL;

117 118 119 120 121 122 123 124 125 126
/* For animated images, the filler function for the background of a   */
/* transparent image will get called only for the main image with the */
/* associated image data - not for any cross referenced images. These */
/* statics hold the browser and image being redrawn at any time, so   */
/* the filler function knows which cross referencing image is         */
/* actually being redrawn.                                            */

static int            image_redrawing   = -1;
static browser_data * browser_redrawing = NULL;

127 128 129 130
/* Local compilation options */

#undef TRACE_FETCH_STORE

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
// Unimplemented functions:

// /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
// static _kernel_oserror * image_savesprite_start_save1(image_info * ip,int * isize)
// {
//   int        size;
//
//   * isize=-1;
//   if(ip && ip->istore && ip->istore->width>0)
//   {
//     ERROUT((_kernel_oserror*)ip->istore->StartExport(ip->istore,&size));
//     size-=12; /* subtract the size of the sprite area header */
//   }
//   else
//   {
//     sprite_header * p;
//     sprite_area   * sa;
//     sprite_id     sid;
//
//     image_get_broken_sprite(&sa,&sid);
//     p=(sprite_header*)sid.s.addr;
//     size=WORDALIGN(p->next);
//   }
//   * isize=size;
//   return(NULL);
// }
//
// /* ----------------------------------------------------------------------*/
// _kernel_oserror * image_savesprite_start_save(browser_data * b,int token,int * isize)
// {
//   image_info * ip;
//
//   ip=image_get_token_image_xref(b,token);
//   return(image_savesprite_start_save1(ip,isize));
// }
//
//
// /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
// static int image_savesprite_save_image1(image_info * ip)
// {
//   sprite_header * p;
//   sprite_area   * sa;
//   sprite_id     sid;
//
//   if(ip && ip->istore && ip->istore->width>0)
//   {
//     int  len;
//     char buffer[2048];
//     int  skip=12; /* skip first 12 bytes (sprite area header) */
//
//     do
//     {
//       len=sizeof(buffer);
//       if(wimpt_complain((_kernel_oserror*)ip->istore->Export(ip->istore,buffer,&len))) return(0);
//       if(len-skip>0 && !save_write_bytes(buffer+skip,len-skip)) return(0);
//       skip-=len;
//       if(skip<0) skip=0;
//     } while(len);
//     return(1);
//   }
//   image_get_broken_sprite(&sa,&sid);
//   p=(sprite_header*)sid.s.addr;
//   return(save_write_bytes((void*)p,WORDALIGN(p->next)));
// }
//
// /* ----------------------------------------------------------------------*/
// int image_savesprite_save_image(browser_data * b,int token)
// {
//   image_info    * ip;
//
//   ip=image_get_token_image_xref(b,token);
//   return(image_savesprite_save_image1(ip));
// }
//
// /* ----------------------------------------------------------------------*/
// void image_savesprite_end_save(browser_data * b,int token)
// {
//   image_info * ip;
//
//   ip=image_get_token_image_xref(b,token);
//   if(ip && ip->istore && ip->istore->width>0) ip->istore->EndExport(ip->istore);
// }
//
// /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
// static int image_picture_saver(void * handle,char * pathname)
// {
//   browser       * b;
//   int           * si,token;
//   image_info    * ip;
//
//   pathname=pathname;
//   si=(int*)handle;
//   b=(browser*)si[0];
//   token=si[1];
//   ip=NULL;
//   if(token>0) ip=image_get_token_image_xref(b,token);
227
//   else if(b->background_image>0) ip=image_info_addr(b,b->background_image);
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
//   if(ip && ip->istore && ip->istore->width>0)
//   {
//     int  len;
//     char buffer[2048];
//
//     do
//     {
//       len=sizeof(buffer);
//       if(wimpt_complain((_kernel_oserror*)ip->istore->Export(ip->istore,buffer,&len))) return(0);
//       if(len && !save_write_bytes(buffer,len)) return(0);
//     } while(len);
//   }
//   else
//   {
//     sprite_area   area,* sa;
//     sprite_id     sid;
//     sprite_header * p;
//
//     image_get_broken_sprite(&sa,&sid);
//     p=(sprite_header*)sid.s.addr;
//     area.size=sizeof(sprite_area)+p->next;
//     area.number=1;
//     area.sproff=sizeof(sprite_area);
//     area.freeoff=area.size;
//     if(!save_write_bytes((void*)(&area.number),sizeof(area)-4)) return(0);
//     return(save_write_bytes((void*)p,p->next));
//   }
//   return(1);
// }
//
// /* ----------------------------------------------------------------------*/
// _kernel_oserror * image_save_picture(browser_data * b,int token)
// {
//   int        size,saveinfo[2];
//   char       pathname[256];
//   image_info * ip;
//
//   ip=NULL;
//   if(token && fetch_token_address(b,token)->style&IMG) ip=image_get_token_image_xref(b,token);
267
//   if(!ip && b->background_image>0)
268
//   {
269
//     ip=image_info_addr(b,b->background_image);
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
//     token=0;
//   }
//   if(ip && ip->istore && ip->istore->width>0) ip->istore->StartExport(ip->istore,&size);
//   else
//   {
//     sprite_area   * sa;
//     sprite_id     sid;
//     sprite_header * p;
//
//     image_get_broken_sprite(&sa,&sid);
//     p=(sprite_header*)sid.s.addr;
//     size=sizeof(sprite_area)+p->next-4;
//   }
//   saveinfo[0]=(int)b;
//   saveinfo[1]=token;
//   strcpy(pathname,msgs_lookup("sprfile:SpriteFile"));
//   save_saveas(FILETYPE_SPRITE,pathname,size,image_picture_saver,NULL,(void*)saveinfo);
//   if(ip && ip->istore && ip->istore->width>0) ip->istore->EndExport(ip->istore);
//   return(NULL);
// }

// /* ----------------------------------------------------------------------*/
// _kernel_oserror * image_saveback_start_save(browser_data * b,int * isize)
// {
//   image_info * ip;
//
296
//   ip=image_info_addr(b,b->background_image);
297 298 299 300 301 302 303 304
//   return(image_savesprite_start_save1(ip,isize));
// }
//
// /* ----------------------------------------------------------------------*/
// int image_saveback_save_image(browser_data * b)
// {
//   image_info    * ip;
//
305
//   ip=image_info_addr(b,b->background_image);
306 307 308 309 310 311 312 313
//   return(image_savesprite_save_image1(ip));
// }
//
// /* ----------------------------------------------------------------------*/
// void image_saveback_end_save(browser_data * b)
// {
//   image_info * ip;
//
314
//   ip=image_info_addr(b,b->background_image);
315 316 317
//   if(ip && idata[i].istore && idata[i].istore->width>0) idata[i].istore->EndExport(idata[i].istore);
// }

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
// **** static const char * image_get_url(HStream * t)
// **** {
// ****   if ISBODY(t)
// ****   {
// ****     if (t->tagno == TAG_TABLE) return NULL;
// ****     else if (t->style & IMG)   return t->src;
// ****     else if ISOBJECT(t)        return NULL; // Eeek
// ****     else if (t->style & FORM)
// ****     {
// ****       if (t->tagno == TAG_INPUT)
// ****       {
// ****         switch (HtmlINPUTtype(t))
// ****         {
// ****           case inputtype_IMAGE: return HtmlINPUTsrc(t);
// ****           default:              return NULL;
// ****         }
// ****       }
// ****       else return NULL;
// ****     }
// ****   }
// ****   else if ISFRAMESET(t) return NULL;
// ****   else if ISHEAD(t)
// ****   {
// ****     if (t->tag == BODY) return HtmlBODYbackground(t);
// ****   }
// ****
// ****   return NULL;
// **** }

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
/*************************************************/
/* image_load_chunk()                            */
/*                                               */
/* Tell the image library to deal with some of   */
/* image data we've fetched for a given image.   */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The image number, from 0 to       */
/*             nimages - 1;                      */
/*                                               */
/*             Pointer to a buffer containing    */
/*             the data, as a char *;            */
/*                                               */
/*             The amount of data in that        */
/*             buffer.                           */
/*************************************************/

366
static _kernel_oserror * image_load_chunk(browser_data * b, int image, char * buffer, int bytes)
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
{
  BBox              box;
  _kernel_oserror * e = NULL;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_load_chunk: Called for image %d\n",image);
  #endif

  /* If the library has filled in the istore field, tell it to */
  /* get some of the data we've fetched.                       */

  if (idata[image].istore) e = idata[image].istore -> Load(idata[image].istore,
                                                           buffer,
                                                           bytes,
                                                           &box);

383 384 385 386 387
  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_load_chunk: Exitting with error\n");
  #endif

  /* Return errors for STRICT_PARSER builds only */
388 389

  #ifdef STRICT_PARSER
390 391 392
    if (e) return e;
  #else
    if (e) return NULL;
393 394 395 396 397 398 399 400 401
  #endif

  /* Update the image on the page to reflect the new data */

  image_update_image(b, image, &box);

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_load_chunk: Successful\n");
  #endif
402 403

  return NULL;
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
}

/*************************************************/
/* image_remove_data()                           */
/*                                               */
/* Discards the fetched image data associated    */
/* with an image, but leaves the URL information */
/* alone.                                        */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The image number, from 0 to       */
/*             nimages - 1.                      */
/*************************************************/

static void image_remove_data(browser_data * b, int image)
{
  int p, oldsize, remove;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_remove_data: Called for image %d\n",image);
  #endif

  /* Get the current data size */

  oldsize = flex_size((flex_ptr) &ddata);

  /* The alloc field holds the total amount of data associated */
  /* with the image, and the ualloc field holds the amount     */
  /* that the URL uses. So subtract ualloc from alloc to get   */
  /* the amount that must be removed.                          */

  remove = idata[image].alloc - idata[image].ualloc;

  /* Need to shuffle the rest of the flex block */
  /* down and shrink the block, if this isn't   */
  /* the last image (i.e. p != oldsize).        */

  p = image_data_offset(b,image) + idata[image].alloc;

  if (p != oldsize) memmove(ddata + p - remove, ddata + p, oldsize - p);

  flex_extend((flex_ptr) &ddata, oldsize - remove);

  #ifdef TRACE
    flexcount -= remove;
    if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
  #endif

  /* Subtract the amount removed from the alloc field */
  /* and set isize to zero, i.e. we're not storing    */
  /* any image data anymore.                          */

  idata[image].alloc -= remove;
  idata[image].isize  = 0;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_remove_data: Successful\n");
  #endif
}

/*************************************************/
/* image_remove_all_data()                       */
/*                                               */
/* Discards the fetched image data associated    */
/* with an image, including URL information.     */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The image number, from 0 to       */
/*             nimages - 1.                      */
/*************************************************/

static void image_remove_all_data(browser_data * b, int image)
{
  int p, oldsize, remove;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_remove_all_data: Called for image %d\n",image);
  #endif

  /* Get the current data size */

  oldsize = flex_size((flex_ptr) &ddata);

  /* The alloc field holds the total amount of data associated */
  /* with the image.                                           */

  remove = idata[image].alloc;

  if (remove)
  {
    /* Need to shuffle the rest of the flex block */
    /* down and shrink the block, if this isn't   */
    /* the last image (i.e. p != oldsize).        */

    p = image_data_offset(b, image);

    if (p != oldsize) memmove(ddata + p, ddata + p + remove, oldsize - p - remove);

    flex_extend((flex_ptr) &ddata, oldsize - remove);

    #ifdef TRACE
      flexcount -= remove;
      if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
    #endif
  }

  /* Subtract the amount removed from the alloc field */
  /* and set isize to zero, i.e. we're not storing    */
  /* any image data anymore.                          */

  idata[image].alloc = 0;
  idata[image].isize = 0;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_remove_all_data: Successful\n");
  #endif
}

/*************************************************/
/* image_delay()                                 */
/*                                               */
/* Stop fetching data for an image, even if it   */
/* hasn't all been fetched, but allow the fetch  */
/* to continue later on.                         */
/*                                               */
533 534 535 536 537 538 539
/* Call with care. Keeping part of an image is   */
/* dangerous - ImageLib may object. Normally,    */
/* this should only be called for images which   */
/* have not started to fetch. Stopping an image  */
/* mid-fetch is more safely done through         */
/* image_abandon.                                */
/*                                               */
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The image number, from 0 to       */
/*             nimages - 1.                      */
/*************************************************/

static void image_delay(browser_data * b, int image)
{
  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_delay: Called for image %d\n",image);
  #endif

  /* Stop any fetching for the image */

  if (idata[image].handle) html_close(idata[image].handle);

  idata[image].handle  = 0;
  idata[image].delayed = 1;

  /* If this is a background, go back to the plain background */

562
  if (image == b->background_image) b->antialias_colour = redraw_backcol(b);
563 564 565 566 567 568 569 570 571 572 573 574 575

  if (idata[image].istore) image_update_image(b, image, NULL);

  /* There may be a new overall fetch status, so ensure the */
  /* status bar is up to date                               */

  toolbars_cancel_status(b, Toolbars_Status_GetPics);

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_delay: Successful\n");
  #endif
}

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
/*************************************************/
/* image_delay_fetches()                         */
/*                                               */
/* Stops any images which have not started to    */
/* fetch for a given browser from fetching at    */
/* all, by setting the image's 'delayed' flag.   */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images.           */
/*************************************************/

void image_delay_fetches(browser_data * b)
{
  if (nimages)
  {
    int image;

    for (image = 0; image < nimages; image++)
    {
      /* Only interested in non-cross referencing images */
      /* owned by this browser which are not fetching.   */

      if (
           idata[image].owner == b &&
           idata[image].xref < 0   &&
           !idata[image].handle
         )
         image_delay(b, image);
    }
  }
}

608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
/*************************************************/
/* image_abandon()                               */
/*                                               */
/* Stop fetching data for an image, even if it   */
/* hasn't all been fetched.                      */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The image number, from 0 to       */
/*             nimages - 1.                      */
/*************************************************/

static void image_abandon(browser_data * b, int image)
{
623 624
  BBox end;

625 626 627 628 629 630 631 632 633 634 635 636 637
  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_abandon: Called for image %d\n",image);
  #endif

  /* Stop any fetching for the image */

  if (idata[image].handle) html_close(idata[image].handle);

  idata[image].handle  = 0;
  idata[image].fetched = 1;

  /* If this is a background, go back to the plain background */

638
  if (image == b->background_image) b->antialias_colour = redraw_backcol(b);
639 640 641

  if (idata[image].istore)
  {
642 643
    /* Let this fail silently */

644
    idata[image].istore -> EndLoad(idata[image].istore, &end);
645 646

    /* Redraw the image */
647

648
    image_update_image(b, image, &end);
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
  }

  /* There may be a new overall fetch status, so ensure the */
  /* status bar is up to date                               */

  toolbars_cancel_status(b, Toolbars_Status_GetPics);

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_abandon: Successful\n");
  #endif
}

/*************************************************/
/* image_abort_fetches()                         */
/*                                               */
/* Stop fetching data for all images belonging   */
/* to a given browser, discarding all data for   */
/* those images. The fetches cannot be restarted */
/* after this!                                   */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images.           */
/*************************************************/

void image_abort_fetches(browser_data * b)
{
  int i;

  /* Loop through the images */

  for (i = 0; i < nimages; i++)
  {
    /* If owned by this browser... */

    if (idata[i].owner == b)
    {
      /* Mark the image as fetched (so pending images don't then */
      /* start to fetch after fetching images stop).             */

      idata[i].fetched = 1;

      /* Stop any images which are fetching */

      if (idata[i].handle)
      {
        html_close(idata[i].handle);
695 696
        idata[i].handle   = 0;
        idata[i].bytesgot = 0;
697 698 699

        /* If this is a background, go back to the plain background */

700
        if (i == b->background_image) b->antialias_colour = redraw_backcol(b);
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

        if (idata[i].istore)
        {
          #ifdef STRICT_PARSER

            /* Report any errors as Continue-only in strict parser mode */

            _kernel_oserror * e;

            e = idata[i].istore -> Delete(idata[i].istore);

            if (e)
            {
              e->errnum = Utils_Error_Custom_Message;
              show_error_ret(e);
            }

          #else

            /* If not in Strict mode, ignore any errors */

            idata[i].istore -> Delete(idata[i].istore);

          #endif

          idata[i].istore = NULL;

728 729 730 731 732 733
          /* Remove any fetched data (not URL information though) */

          image_remove_data(b, i);

          /* Redraw the item */

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
          browser_update_token(b, idata[i].token, 0, 0);
        }
      }
    }
  }

  /* There may be a new overall fetch status, so ensure the */
  /* status bar is up to date                               */

  toolbars_cancel_status(b, Toolbars_Status_GetPics);
}

/*************************************************/
/* image_new_image()                             */
/*                                               */
/* Starts fetching a new image. Creates a record */
/* in the idata flex block and increments the    */
/* image counter. If an image is already being   */
/* fetched with the same URL then a cross        */
/* reference is set up to point to that, else a  */
/* fetch is initiated.                           */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image to fetch;   */
/*                                               */
/*             Pointer to the URL to fetch;      */
/*                                               */
/*             The address of the token that led */
/*             to this function call, i.e. the   */
/*             token representing that image;    */
/*                                               */
/*             1 if the image is for the         */
/*             background (it will be turned     */
/*             into a sprite for fast plotting), */
768 769 770 771 772 773 774
/*             else 0. If 2, then the            */
/*             background_image field of the     */
/*             browser_data structure is filled  */
/*             in with the relevant image number */
/*             and the image will again be       */
/*             turned into a sprite for fast     */
/*             plotting.                         */
775 776
/*************************************************/

777
_kernel_oserror * image_new_image(browser_data * b, const char * url, HStream * token, int background)
778 779 780 781 782 783 784 785 786 787
{
  int       size, ok, ulen, xref;
  HStream * tp;

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

  /* Can't proceed without the URL to fetch! */

788
  if (!url) url = ""; /* Point to *something*, even if it is blank */
789 790 791 792 793 794 795 796 797

  xref = -1;
  tp   = token;

  /* Need to make sure we don't already have an image with this URL */
  /* if there are already some images present.                      */

  if (nimages)
  {
798
    int test = 1;
799

800 801 802 803
    /* If this is a File URL, check it's not scrap - don't allow cross */
    /* referencing if it is.                                           */

    if (!strncmp(url, FileMethod, sizeof(FileMethod) - 1))
804
    {
805
      char test_url[Limits_URL];
806

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
      /* Build the URL we'd be on for a scrap file fetch */

      StrNCpy0(test_url, Save_ScrapFile);

      urlutils_pathname_to_url(test_url, sizeof(test_url));

      /* If it's the same as the URL we've been given, don't */
      /* cross reference the image.                          */

      if (!strcmp(url, test_url)) test = 0;
    }

    if (test)
    {
      int i;

      for (i = 0; i < nimages; i++)
      {
        /* Can we simply create a cross reference to another image? */

        if (
             idata[i].alloc                                            &&  /* The image has data allocated for it                 */
             !strcmp(url, ddata + image_data_offset(b,i))              &&  /* This holds a URL which matches that passed in       */
             idata[i].xref < 0                                         &&  /* The image doesn't cross reference things itself     */
             idata[i].background == !!background                       &&  /* We're not trying to make a b/g an f/g or vice versa */
832
             (
833 834 835 836 837
               !background ||                                              /* This isn't a background image, or...                */
               (
                 background &&                                             /* If this is a background image, the background       */
                 idata[i].owner->background_colour == b->background_colour /* colours match in the two owner browsers             */
               )
838 839
             )
           )
840 841 842 843
        {
          xref = i;       /* If all of the above are satisfied, cross reference */
          i    = nimages; /* this image with the one it matches.                */
        }
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
      }
    }
  }

  if (xref >= 0) ulen = 0; /* Don't need any extra data for a cross referenced image. */
  else
  {
    ulen = (strlen(url) + 1);
    ulen = (int) WordAlign(ulen);
  }

  size = ulen;

  /* Allocate space for the image_info structure */

  if (idata)
  {
    int oldsize;

    oldsize = flex_size  ((flex_ptr) &idata);
    ok      = flex_extend((flex_ptr) &idata, oldsize + sizeof(image_info));
  }
  else ok   = flex_alloc ((flex_ptr) &idata, sizeof(image_info));

  /* Allocate space for the image data */

  if (ok && ddata)
  {
    int oldsize;

    #ifdef TRACE
      flexcount += sizeof(image_info);
      if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
    #endif

    oldsize = flex_size  ((flex_ptr) &ddata);
    ok      = flex_extend((flex_ptr) &ddata, oldsize + size);
  }
  else ok   = flex_alloc ((flex_ptr) &ddata, size);

  /* Throw back an error if out of memory */

  if (!ok)
  {
    erb.errnum = Utils_Error_Custom_Message;

    StrNCpy0(erb.errmess,
             lookup_token("NoMemImg:There is not enough free memory for any new images (%0).",
                          0,
                          "1"));

    return &erb;
  }

  #ifdef TRACE
    flexcount += size;
    if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
  #endif

  /* Increment the image counter, zero the contents of the image_info structure */
  /* and fill in some of the fields where contents are known now.               */

906
  memset(&idata[nimages], 0, sizeof(image_info)); /* Precautionary catch-all */
907

908 909 910 911 912 913 914
  idata[nimages].owner      = b;
  idata[nimages].x          = -1;
  idata[nimages].y          = -1;

  idata[nimages].alloc      = size;
  idata[nimages].ualloc     = ulen;
  idata[nimages].isize      = 0;
915

916 917
  idata[nimages].token      = tp;
  idata[nimages].xref       = xref;
918

919
  idata[nimages].background = !!background;
920
  idata[nimages].hadfiller  = 0;
921 922 923 924 925 926 927 928

  /* Set the 'delayed' flag if it's not a background image and */
  /* images are flagged as not being shown right now, or if it */
  /* is a backgrond image and backgrounds are flagged to be    */
  /* plain only.                                               */

  if (background)
  {
929
    idata[nimages].delayed   = !b->show_background;
930 931 932 933
    idata[nimages].canredraw = 1;

    /* Set the background image number */

934 935 936 937 938
    if (background == 2) b->background_image = nimages;
  }
  else
  {
    idata[nimages].delayed = (!b->show_foreground && b->displayed != Display_External_Image);
939 940
  }

941 942 943 944 945 946 947 948 949 950
  /* If there's data for a URL, copy it into the above allocated block */
  /* and ImageLib about the new image.                                 */

  if (ulen)
  {
    strcpy(ddata + image_data_offset(b, nimages), url);

    idata[nimages].istore = NewImage(NULL, background ? IMAGE_FAST : 0);
  }

951 952 953 954 955 956 957 958 959 960 961 962
  // This works, but you've then got to alter the dataoffset fields
  // of higher images whenever you remove any data from one lower in
  // the flex block. That's not implemented yet, and the speed penalty
  // of this may offset the gains in image_data_offset.
  //
  // if (!nimages) idata[nimages].dataoffset = 0;
  // else idata[nimages].dataoffset = idata[nimages - 1].dataoffset + alloc;

  /* If the image is not a background one, need to update the */
  /* width and height fields according to any details in the  */
  /* HTML source.                                             */

963
  if (!background)
964
  {
965
    /* Need to flag if the HTML gives us an absolute size */
966

967 968 969 970 971 972
    if (
         OBJECT_HAS_WIDTH   (token)                 &&
         OBJECT_HAS_HEIGHT  (token)                 &&
         OBJECT_WIDTH_UNITS (token) == UNITS_PIXELS &&
         OBJECT_HEIGHT_UNITS(token) == UNITS_PIXELS
       )
973 974 975 976 977 978 979 980 981 982 983 984 985 986
       idata[nimages].fixedsize = 1, idata[nimages].canredraw = 1;

    else
    {
      /* If reformats aren't immediate, image_update_image may ask for */
      /* one and then if canredraw is set, will start updating the     */
      /* image. This is invalid unless the reformat has definitely     */
      /* occurred (a full size image plots inside a default size       */
      /* placeholder...). However, if reformats happen straight away,  */
      /* we'll always be able to redraw.                               */

      if (!choices.refo_wait) idata[nimages].canredraw = 1;
      else                    idata[nimages].canredraw = 0;
    }
987

988 989
    idata[nimages].currw = idata[nimages].currh = -1;
  }
990 991 992

  nimages++;

993
  if (!ulen)
994
  {
995 996 997
    /* Since we aren't starting a fetch for this image, must call image_update_image  */
    /* on it to make sure any required reformats etc. (e.g. because a width or height */
    /* but not both was specified in the HTML) are carried out.                       */
998

999
    image_update_image(b, nimages - 1, NULL);
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
  }

  /* Reflect any change of status */

  toolbars_update_status(b, Toolbars_Status_GetPics);
  toolbars_set_button_states(b);

  /* Finished. */

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

  return NULL;
}

/*************************************************/
/* image_process_null()                          */
/*                                               */
/* The main engine of the image loading system.  */
/* Allows up to choices.maximages images to be   */
/* simultaneously fetched. Handles redraw,       */
/* memory allocation, out-of-memory fetch stops, */
/* and so-forth.                                 */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images.           */
/*************************************************/

_kernel_oserror * image_process_null(browser_data * b)
{
1031 1032
  _kernel_oserror * e;

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_process_null: Called\n");
  #endif

  /* If there are not maximages images being fetched and there are still  */
  /* images which have not started fetching, then start a fetch for one.  */
  /* Then do a 'get next chunk' on the next image with a fetch going      */
  /* on. Cause a screen update as appropriate.                            */

  if (nimages && b->fetch_status != BS_DATAFETCH)
  {
    int image, fetches;

    fetches = image_count_fetches(b);

    if (lastimage < 0 || lastimage >= nimages) lastimage = nimages - 1;

    image = lastimage;

    /* For all images up to and including the last one dealt with in a */
    /* null event, initiate fetches if they haven't already started.   */

    do
    {
      image ++;
      if (image >= nimages) image = 0;

      if (
           !idata[image].handle        &&
           !idata[image].fetched       &&
           !idata[image].delayed       &&
           idata[image].xref < 0       &&
           fetches < choices.maximages
         )
      {
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        e = html_get(ddata + image_data_offset(b,image), /* Document to fetch                */
                     NULL,                               /* Pointer to any extra data        */
                     (int *) &idata[image].handle,       /* Place to return the fetch handle */
                     URL_Method_http_GET,                /* Fetch method                     */

                     #ifndef SINGLE_USER
                       user.name,                        /* User name for MailServ, if using */
                     #else                               /* a multiuser version              */
                       NULL,
                     #endif

                     0,                                  /* 0 = Don't parse fetched data     */
1080
                     !b->reloading);                     /* 1 = Proxy can be used, 0 = can't */
1081 1082 1083

        if (e)
        {
1084 1085 1086 1087 1088
          /* Don't report it; countless 'I've failed' reports for */
          /* the very beginning of a fetch are not very helpful.  */
          /* Particularly, 'file not found' for file fetches, can */
          /* be major pain.                                       */

1089 1090
          image_abandon(b, image);
        }
1091 1092
      }
    }
1093
    while (image != lastimage && !idata[image].handle);
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

    lastimage = image;

    /* If the image we're now on has a fetch handle... */

    if (idata[image].handle)
    {
      char buffer[10240];

      /* ...And a fetch has already started... */

      if (idata[image].started)
      {
        int done, bytes;

        /* ...Then get the next chunk of data. If the fetch */
        /* call gives an error, abandon the image fetch and */
        /* exit.                                            */

1113 1114 1115 1116 1117 1118
        e = fetch_get_raw_data(NULL,                /* The browser_data structure */
                               idata[image].handle, /* Fetch handle */
                               buffer,              /* Buffer for fetched data */
                               sizeof(buffer),      /* Buffer's size */
                               &done,               /* 'done' = 1 for fetch completed, else 0 */
                               &bytes);             /* Number of bytes put into buffer */
1119 1120

        if (e)
1121
        {
1122 1123
          image_abandon(b, image);
          return e;
1124 1125 1126 1127
        }

        idata[image].bytesgot += bytes;

1128 1129 1130
        /* If the fetch_get_raw_data call resulted in data being fetched, */
        /* send that to the image library and reflect the fetched data in */
        /* the status bar.                                                */
1131 1132 1133

        if (bytes)
        {
1134 1135 1136 1137 1138 1139 1140 1141
          e = image_load_chunk(b, image, buffer, bytes);

          if (e)
          {
            image_abandon(b, image);
            return e;
          }

1142 1143 1144 1145 1146 1147 1148
          toolbars_update_progress(b);
        }

        /* If the fetch has finished, update everything as appropriate */

        if (done)
        {
1149 1150
          BBox end;

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
          html_close(idata[image].handle);

          idata[image].handle  = 0;
          idata[image].fetched = 1;
          idata[image].success = 1;

          if (idata[image].istore)
          {
            #ifdef STRICT_PARSER

              /* Report any errors as Continue-only in strict parser mode */

1163
              e = idata[image].istore -> EndLoad(idata[image].istore, &end);
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174

              if (e)
              {
                e->errnum = Utils_Error_Custom_Message;
                show_error_ret(e);
              }

            #else

              /* If not in Strict mode, ignore any errors */

1175
              idata[image].istore -> EndLoad(idata[image].istore, &end);
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192

            #endif
          }

          /* If the image is a background image and the library has */
          /* dealt with it (this is assumed to be the case if the   */
          /* library has assigned a width to the image) then get    */
          /* the background text colour from the library on the     */
          /* basis of the image's contents. Else, use the plain     */
          /* background colour.                                     */
          /*                                                        */
          /* Note that it is not until the call to BGCol that       */
          /* ImageLib actually turns the background image into a    */
          /* sprite in the current colour depth, so if this isn't   */
          /* called, the sprite will plot slowly resulting in       */
          /* (typically) painfully slow redraws.                    */

1193
          if (image == idata[image].owner->background_image)
1194
          {
1195 1196
            b->antialias_colour = redraw_backcol(b);

1197 1198 1199 1200 1201 1202 1203
            if (idata[image].istore->width > 0)
            {
              #ifdef STRICT_PARSER

                /* Report any errors as Continue-only in strict parser mode */

                e = idata[image].istore -> BGCol(idata[image].istore,
1204 1205
                                                 &b->antialias_colour,
                                                 b->background_colour != -1 && b->use_source_cols);
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

                if (e)
                {
                  e->errnum = Utils_Error_Custom_Message;
                  show_error_ret(e);
                }

              #else

                /* If not in Strict mode, ignore any errors */

                idata[image].istore -> BGCol(idata[image].istore,
1218 1219
                                             &b->antialias_colour,
                                             b->background_colour != -1 && b->use_source_cols);
1220 1221 1222 1223 1224

              #endif
            }
          }

1225
          image_update_image(b, image, &end);
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
        }
      }
      else
      {
        /* In this block of code, the current image has had a fetch */
        /* started for it, but hasn't fetched any data yet - so we  */
        /* haven't (for example) got a full header for the request. */

        int       remn, sofar, waiting;
        int       realsize;
        HStream * tptr;
        void    * store;

        /* Go in with no store; only interested in new data, as  */
        /* anything fetched so far goes into the ddata block. */

        store = NULL;

        /* At this stage, must put the data fetched so far back into the  */
        /* store. This is because headers may come in over several        */
        /* passes through the fetcher - if we give the fetcher an empty   */
        /* block each time, it won't be able to see the whole header      */
        /* block and the fetch fails (well, the image library keeps       */
        /* waiting for something to happen). At the time of writing this  */
        /* is demonstrated by the images at http://www.debenhams.co.uk/'. */

        if (idata[image].isize)
        {
          int p = image_data_offset(b, image) + idata[image].ualloc;

          /* Complain if the flex allocation fails, else copy the data across */

          if (!flex_alloc(&store, idata[image].isize))
          {
            image_abandon(b, image);

            return NULL;
          }
          else
          {
            #ifdef TRACE
              flexcount += idata[image].isize;
              if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
            #endif

            memcpy(store, ddata + p, idata[image].isize);
          }
        }

        #ifdef TRACE_FETCH_STORE

          if (store)
          {
            int  offset;
            int  size = flex_size(&store);
            char cha;
            int  nl   = 0;

            Printf("Image %d pre-fetch store:\n\n",image);

            for (offset = 0; offset < size; offset ++)
            {
              cha = ((char *) store)[offset];

              if (cha > 31) Printf("%c",cha);
              if (cha == 13 || cha == 10)
              {
                if (!nl)
                {
                  Printf("\n");
                  nl = 1;
                }
                else nl = 0;
              }
            }

            Printf("\nEnd of store\n\n");
          }

        #endif

        /* Call the fetch routine */

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
        e = html_get_next_token(b,
                                idata[image].handle,
                                &remn,
                                &sofar,
                                &tptr,
                                &waiting,
                                &store,
                                ddata + image_data_offset(b, image),
                                1);

        if (e)
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
        {
          /* If there's an error, free the store and ditch the image */

          if (store)
          {
            #ifdef TRACE
              flexcount -= flex_size(&store);
              if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
            #endif

            flex_free(&store);
          }
1332

1333 1334
          image_abandon(b, image);

1335 1336 1337 1338 1339
          #ifdef TRACE
            if (tl & (1u<<15)) Printf("image_process_null: Exitting with error\n");
          #endif

          return e;
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
        }

        #ifdef TRACE_FETCH_STORE

          if (store)
          {
            int  offset;
            int  size = flex_size(&store);
            char cha;
            int  nl   = 0;

            Printf("Image %d post-fetch store:\n\n",image);

            for (offset = 0; offset < size; offset ++)
            {
              cha = ((char *) store)[offset];

              if (cha > 31) Printf("%c",cha);
              if (cha == 13 || cha == 10)
              {
                if (!nl)
                {
                  Printf("\n");
                  nl = 1;
                }
                else nl = 0;
              }
            }

            Printf("\nEnd of store\n\n");
          }

        #endif

        /* How much data was added? */

        if (store) realsize = flex_size(&store) - idata[image].isize; /* We already had 'isize' bytes before the fetcher was entered */
        else       realsize = 0;

        /* If we've got data in the local store, copy it to the image store. */

        if (realsize >= 0)
        {
          int p, oldsize;

          /* oldsize holds the whole image data block size (for all images) */

          oldsize = flex_size((flex_ptr) &ddata);

          /* Allocate 'size' extra bytes, doing the relevant error handling */
          /* code if the allocation fails                                   */

          if (!flex_extend((flex_ptr) &ddata, oldsize + realsize))
          {
            #ifdef TRACE
              flexcount -= flex_size(&store);
              if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
            #endif

            flex_free(&store);

            image_abandon(b,image);

            erb.errnum = Utils_Error_Custom_Message;

            StrNCpy0(erb.errmess,
                     lookup_token("NoMemImg:There is not enough free memory for any new images (%0).",
                                  0,
                                  "2"));
            return &erb;
          }

          #ifdef TRACE

          else
          {
            flexcount += realsize;
            if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
          }

          #endif

          /* p points to the first byte after the data used by this image */

          p = image_data_offset(b, image) + idata[image].alloc;

          /* Move all data from p up to the end of the block (as was, hence */
          /* oldsize) along the block by size bytes, effectively creating   */
          /* a gap of that many bytes just after this image's data. If p    */
          /* = oldsize, this was the last image in the block and there's    */
          /* no data above it to move (so don't do the memmove).            */

          if (p != oldsize) memmove(ddata + p + realsize, ddata + p, oldsize - p);

          /* Copy the new data into that gap */

          memcpy(ddata + p, ((char *) store) + idata[image].isize, realsize);

          /* Update the image's image data and total data pointers */

          idata[image].alloc += realsize;
          idata[image].isize += realsize;
        }

        /* Act according to the fetch status */

        switch (waiting)
        {
          case 1: break; /* Nothing happened yet, or the HTTP response header is still coming in */
          case 2: break; /* Redirected, we can ignore and wait for the fetcher to cope */
          case 0: /* Not awaiting delivery (shouldn't happen in this context, but here 'just in case') */
          case 3: /* We have some data */
          {
            int i, n, n1;

            /* Flag that a fetch has started to happen */

            idata[image].started = 1;

            /* Set 'n' to the size of data that was fetched */

            if (store) n = flex_size(&store);
            else       n = 0;

            /* Increment the 'bytes so far' counter for the image */

            idata[image].bytesgot += n;

            /* Push the data into the library, in chunks defined by */
            /* the size of 'buffer' (allocated as a char[] above).  */

            i = 0;

            while (n)
            {
              n1 = n;

              if (n1 > sizeof(buffer)) n1 = sizeof(buffer);
              memcpy(buffer, (char *) store + i, n1);

              i += n1;
              n -= n1;

1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
              e = image_load_chunk(b, image, buffer, n1);

              if (e)
              {
                /* If there's an error, free the store and ditch the image */

                if (store)
                {
                  #ifdef TRACE
                    flexcount -= flex_size(&store);
                    if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
                  #endif

                  flex_free(&store);
                }

                image_abandon(b, image);

                #ifdef TRACE
                  if (tl & (1u<<15)) Printf("image_process_null: Exitting with error\n");
                #endif

                return e;
              }
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
            }

            /* Get rid of any accumulated data and update the status bar */

            image_remove_data(b, image);
            toolbars_update_progress(b);
          }
          break;
        }

        /* Free the temporary store, if it was used */

        if (store)
        {
          #ifdef TRACE
            flexcount -= flex_size(&store);
            if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
          #endif

          flex_free(&store);
        }

        /* Closure of long 'if' that deals with either continuing  */
        /* to fetch data for an image, or getting the first chunk  */
        /* of data for a fetch. (The code immediately above is for */
        /* getting the first chunk).                               */
      }
      /* Closure of long 'if' that sees if a fetch has started */
      /* for an image. (The code immediately above excutes if  */
      /* it has, else a fetch is started).                     */
    }

    /* Closure of long 'if' that checks to see if there are */
    /* images to be fetched, and that the fetch status is   */
    /* not BS_DATAFETCH (i.e. other fetch activity has      */
    /* ceased).                                             */
  }

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

  return NULL;
}

/*************************************************/
/* image_delete_image_entry()                    */
/*                                               */
/* Deletes an image_info structure from the      */
/* array of structures. The cross reference      */
/* image numbers of subsequent images are        */
/* adjusted appropriately.                       */
/*                                               */
/* The idata flex block is not shrunk; this is   */
/* expected to be done externally, to avoid      */
/* possibly freeing many small blocks            */
/* consecutively (which can be slow with flex).  */
/*                                               */
/* Parameters: Image number to remove.           */
/*************************************************/

static void image_delete_image_entry(int image)
{
  browser_data * b;
  int            i;

  nimages--;

  if (lastimage == image) lastimage--;
  if (lastimage >= nimages) lastimage = nimages - 1;

  /* Only need to alter xref numbers or move flex data */
  /* around if this wasn't the last image in the block */

  if (image < nimages) /* (Not 'nimages - 1' as nimages has been decremented by this point) */
  {
    memmove(&idata[image], &idata[image + 1], sizeof(image_info) * (nimages - image));

    for (i = image; i < nimages; i++)
    {
      #ifdef TRACE
        if (idata[i].xref == image) Printf("JUST DELETED IMAGE %d WHICH WAS XREF'D AND SHOULDN'T HAVE BEEN\n");
      #endif

1591 1592
      /* Did this cross reference an image which will have changed number? */

1593
      if (idata[i].xref > image) idata[i].xref--;
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610

      /* Did this have a filler function registered for it? */

      if (idata[i].hadfiller)
      {
        /* If so, then provided the filler function is still available, */
        /* reregister with the new image number.                        */

        if (!idata[i].istore->RegisterFiller)
        {
          idata[i].hadfiller = 0;
        }
        else
        {
          show_error_ret(image_register_filler(i));
        }
      }
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
    }
  }

  /* Need to also alter browser_data structures' background image */
  /* number fields.                                               */

  b = last_browser;

  while (b)
  {
1621
    if (b->background_image > image) b->background_image--;
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639

    b = b->previous;
  }
}

/*************************************************/
/* image_discard()                               */
/*                                               */
/* Discards all images for a given browser       */
/* window, freeing the memory and shutting down  */
/* any active fetches.                           */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images.           */
/*************************************************/

_kernel_oserror * image_discard(browser_data * b)
{
1640
  int newsize, i, xref;
1641 1642 1643 1644 1645 1646 1647

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("\nimage_discard: Called for %p\n\n", b);
  #endif

  if (!nimages) return NULL;

1648 1649 1650 1651
  /* See if any images cross reference those in the browser */
  /* for which images will be discarded. If so, 'move' the  */
  /* cross referencee over to be owned by the cross         */
  /* referencer.                                            */
1652 1653 1654 1655 1656 1657

  _swix(Hourglass_Start, _IN(0), 1);

  #ifdef TRACE
    if (tl & (1u<<15))
    {
1658 1659
      Printf("image_discard: First pass, checking for cross referencees owned by %p\n", b);
      Printf("               There are %d images before this pass.\n\n", nimages);
1660 1661 1662
    }
  #endif

1663
  for (i = nimages - 1; i >= 0; i--) /* Going backwards helps out flex */
1664
  {
1665
    xref = idata[i].xref;
1666

1667
    if (idata[i].owner != b && xref >= 0 && idata[xref].owner == b)
1668
    {
1669 1670 1671 1672 1673 1674 1675 1676
      /* Keep the xref image, since that holds the real data and */
      /* is doing all the fetching, etc. - it works out as less  */
      /* effort overall (especially in the second pass below) to */
      /* delete the cross referencing image. This may seem a bit */
      /* odd as though we've been called to delete the images    */
      /* owned by browser 'b', in the first pass we end up       */
      /* deleting structures owned by completely different       */
      /* browsers...                                             */
1677 1678

      #ifdef TRACE
1679
        if (tl & (1u<<15)) Printf("image_discard: Transferring cross referencer %d to cross referencee %d\n", i, xref);
1680 1681
      #endif

1682 1683 1684
      idata[xref].owner      = idata[i].owner;
      idata[xref].x          = idata[i].x;
      idata[xref].y          = idata[i].y;
1685

1686
      idata[xref].token      = idata[i].token;
1687

1688 1689 1690
      idata[xref].currw      = idata[i].currw;
      idata[xref].currh      = idata[i].currh;
      idata[xref].xref       = -1;
1691

1692
      idata[xref].delayed    = idata[i].delayed;
1693

1694 1695
      idata[xref].fixedsize  = idata[i].fixedsize;
      idata[xref].background = idata[i].background;
1696

1697 1698 1699
      idata[xref].hadfirst   = idata[i].hadfirst;
      idata[xref].canredraw  = idata[i].canredraw;
      idata[xref].priority   = idata[i].priority;
1700

1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
      /* Did the image we're transferring a new owner to have */
      /* RegisterFiller called for it, with the old owner?    */

      if (idata[xref].hadfiller)
      {
        /* If an image became a background, ImageLib may have withdrawn the */
        /* RegisterFiller function...                                       */

        if (!idata[xref].istore->RegisterFiller)
        {
          idata[xref].hadfiller = 0;
        }
        else
        {
          /* Recall the RegisterFiller function with the new owner details */

          show_error_ret(image_register_filler(xref));
        }
      }
1720

1721 1722 1723 1724 1725 1726 1727 1728 1729
      /* If this is a background image for the cross referencer... */

      if (i == idata[i].owner->background_image)
      {
        /* Update the browser_data 'background_image' field to point to the */
        /* new cross reference image number.                                */

        idata[i].owner->background_image = xref;
      }
1730

1731 1732 1733
      /* If the cross referencee was being fetched, may need to */
      /* claim fetch nulls in the cross referencer to finish    */
      /* the job.                                               */
1734

1735 1736 1737 1738 1739
      if (idata[xref].handle && !idata[i].owner->fetch_handler)
      {
        fetchpage_claim_nulls(idata[i].owner);
        toolbars_update_status(idata[i].owner, Toolbars_Status_GetPics);
      }
1740

1741
      /* Delete the cross referencer */
1742

1743 1744 1745
      #ifdef TRACE
        if (tl & (1u<<15)) Printf("image_discard: Deleting entry owned by %p that cross references image %d\n", idata[i].owner, idata[i].xref);
      #endif
1746

1747 1748 1749 1750
      image_remove_all_data(idata[i].owner, i);
      image_delete_image_entry(i);
    }
  }
1751

1752 1753 1754 1755 1756 1757 1758
  #ifdef TRACE
    if (tl & (1u<<15))
    {
      Printf("\nimage_discard: First pass complete, there are now %d images\n", nimages);
      Printf("               Second pass, removing remaining images owned by %p\n\n", b);
    }
  #endif
1759

1760
  /* Now delete any remaining images owned by the given browser */
1761

1762 1763 1764 1765 1766
  for (i = nimages - 1; i >= 0; i--) /* Going backwards helps out flex */
  {
    if (idata[i].owner == b)
    {
      /* If the image was being fetched, close that session */
1767

1768 1769 1770 1771 1772
      if (idata[i].handle)
      {
        html_close(idata[i].handle);
        idata[i].handle = 0;
      }
1773

1774 1775 1776
      if (idata[i].istore)
      {
        #ifdef STRICT_PARSER
1777

1778
          /* Report any errors as Continue-only in strict parser mode */
1779

1780
          _kernel_oserror * e;
1781

1782
          e = idata[i].istore -> Delete(idata[i].istore);
1783

1784 1785 1786 1787 1788
          if (e)
          {
            e->errnum = Utils_Error_Custom_Message;
            show_error_ret(e);
          }
1789

1790
        #else
1791

1792
          /* If not in Strict mode, ignore any errors */
1793

1794
          idata[i].istore -> Delete(idata[i].istore);
1795

1796
        #endif
1797 1798
      }

1799 1800 1801
      image_remove_all_data(b, i);
      image_delete_image_entry(i);
    }
1802 1803 1804
  }

  #ifdef TRACE
1805
    if (tl & (1u<<15)) Printf("\nimage_discard: Second pass complete, there are now %d images\n\n", nimages);
1806 1807 1808 1809 1810 1811 1812 1813 1814
  #endif

  /* If there is an animation handler present, but no animated */
  /* images remain, remove that handler.                       */

  if (animhandler)
  {
    int found = 0;

1815 1816 1817 1818
    #ifdef TRACE
      if (tl & (1u<<15)) Printf("image_discard: There is an animation handler present; checking to see if it can be removed\n");
    #endif

1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
    for (i = 0; i < nimages; i++)
    {
      if (idata[i].istore && idata[i].istore->animated)
      {
        found = 1;
        break;
      }
    }

    if (!found)
    {
1830 1831 1832 1833
      #ifdef TRACE
        if (tl & (1u<<15)) Printf("image_discard: Removing animation handler\n\n");
      #endif

1834 1835 1836
      deregister_null_claimant(Wimp_ENull, (WimpEventHandler *) image_animate_images, NULL);
      animhandler = 0;
    }
1837 1838 1839 1840 1841 1842 1843 1844 1845

    #ifdef TRACE

      else
      {
        if (tl & (1u<<15)) Printf("image_discard: The handler is still required\n\n");
      }

    #endif
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
  }

  /* Ensure the image_info data block matches the size of the images now present */

  newsize = nimages * sizeof(image_info);

  #ifdef TRACE
    {
      int oldsize;

      oldsize    = flex_size((flex_ptr) &idata);
      flexcount -= (oldsize - newsize);

      if (tl & (1u<<14)) Printf("**   flexcount: %d\n",flexcount);
    }
  #endif

  if (idata)
  {
    if (newsize) flex_extend((flex_ptr) &idata, newsize);
    else         flex_free((flex_ptr) &idata);
  }

  _swix(Hourglass_Off, 0);

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

  return NULL;
}

/*************************************************/
1879
/* image_refetch()                               */
1880
/*                                               */
1881
/* Reloads an image, redrawing as required and   */
1882
/* setting the priority flag as asked.           */
1883 1884 1885 1886
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images;           */
/*                                               */
1887 1888 1889 1890 1891
/*             The image number;                 */
/*                                               */
/*             Value to set Priority flag to (so */
/*             that if 'show foreground images'  */
/*             is turned off, the image will     */
1892 1893 1894 1895 1896 1897
/*             override it);                     */
/*                                               */
/*             1 to redraw the image, 0 to not   */
/*             bother (e.g. for many images,     */
/*             may want to redraw the whole      */
/*             window instead).                  */
1898 1899
/*************************************************/

1900
static void image_refetch(browser_data * b, int image, int priority, int redraw)
1901
{
1902
  int i;
1903

1904
  /* Sanity check */
1905

1906
  if (image < 0 || image >= nimages || !b) return;
1907

1908
  /* Use the cross referenced base image if necessary */
1909

1910 1911 1912 1913 1914 1915
  if (idata[image].xref >= 0) image = idata[image].xref;

  if (
       (
         !idata[image].fetched &&  /* If the image isn't fetched...  */
         idata[image].delayed      /* ...and was flagged as delayed, */
1916
       )
1917 1918 1919 1920 1921 1922 1923 1924 1925
       ||
       (
         idata[image].fetched  &&  /* or has fetched but...       */
         !idata[image].success &&  /* ...not successfully, and... */
         !idata[image].istore      /* ...it has no ImageLib entry */
       )
     )
  {
    /* If the image says it isn't fetched, reset its 'bytesgot' counter */
1926

1927
    if (!idata[image].fetched) idata[image].bytesgot = 0;
1928

1929
    /* Set up the flags */
1930

1931 1932 1933 1934
    idata[image].success  = 0;
    idata[image].delayed  = 0;
    idata[image].fetched  = 0;
    idata[image].priority = priority;
1935

1936
    /* If we deleted the ImageLib entry, need to recreate it */
1937

1938 1939 1940
    if (!idata[image].istore && idata[image].xref == -1)
    {
      idata[image].istore = NewImage(NULL, image == b->background_image ? IMAGE_FAST : 0);
1941
    }
1942 1943 1944 1945

    /* Now handle the fetching */

    if (!b->fetch_handler)
1946
    {
1947 1948
      fetchpage_claim_nulls(b);
      toolbars_update_status(b, Toolbars_Status_GetPics);
1949
    }
1950 1951 1952 1953 1954 1955 1956
  }
  else
  {
    /* If the image is already loaded, just redraw it */

    idata[image].priority = priority;
    idata[image].hadfirst = 0;
1957 1958

    if (redraw) image_update_image(b, image, NULL);
1959
  }
1960

1961
  /* Deal with all cross referencers of the base image */
1962

1963 1964 1965
  for (i = 0; i < nimages; i++)
  {
    if (idata[i].xref == image)
1966
    {
1967 1968
      idata[i].priority = priority;
      idata[i].hadfirst = 0;
1969 1970

      if (redraw) image_update_image(b, i, NULL);
1971
    }
1972 1973 1974 1975
  }
}

/*************************************************/
1976
/* image_reload()                                */
1977
/*                                               */
1978 1979 1980 1981 1982
/* Reloads an image, redrawing as required and   */
/* setting the priority flag so that even if a   */
/* browser has 'show foreground images' turned   */
/* off, the reloading image (and all that cross  */
/* reference it) will still be shown.            */
1983 1984
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
1985 1986 1987 1988
/*             relevant to the images;           */
/*                                               */
/*             Address of the token representing */
/*             the image.                        */
1989 1990
/*************************************************/

1991
void image_reload(browser_data * b, HStream * token)
1992
{
1993
  int image = image_get_token_image_xref(b, token);
1994

1995 1996
  if (image < 0) return;

1997
  image_refetch(b, image, 1, 1);
1998 1999 2000 2001 2002 2003 2004
}

/*************************************************/
/* image_restart_fetches()                       */
/*                                               */
/* If image loading has been suspended for any   */
/* reason, it can be resumed by calling this     */
2005 2006 2007 2008
/* function. Any images already loaded will be   */
/* reshown. The priority flag for images is not  */
/* set, so the browser must be set to display    */
/* foreground images for anything to show up.    */
2009 2010
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
2011 2012 2013 2014 2015 2016 2017
/*             relevant to the images;           */
/*                                               */
/*             1 to restart foreground fetches,  */
/*             else 0;                           */
/*                                               */
/*             1 to restart background fetches,  */
/*             else 0.                           */
2018 2019
/*************************************************/

2020
void image_restart_fetches(browser_data * b, int foreground, int background)
2021 2022 2023
{
  if (nimages)
  {
2024
    int image;
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036

    /* Loop round all the images */

    for (image = 0; image < nimages; image++)
    {
      /* If an image has not been fetched and is flagged as being */
      /* delayed, or an image has been fetched but has not been   */
      /* flagged as succesfully fetched and has not been dealt    */
      /* with by the image library (the istore field is NULL),    */
      /* then clear all the fetch flags for the image so that it  */
      /* will later be fetched.                                   */

2037
      if (idata[image].owner == b)
2038
      {
2039 2040 2041 2042 2043 2044
        /* Only fetch foreground or background images if asked to */

        if (
             (idata[image].background  && background) ||
             (!idata[image].background && foreground)
           )
2045
           image_refetch(idata[image].owner, image, 0, 0);
2046
      }
2047
    }
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
  }
}

/*************************************************/
/* image_update_area()                           */
/*                                               */
/* Updates (redraws) part of an image, which     */
/* will reflect any new data fetched for it if   */
/* the whole image hasn't been fetched yet.      */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The left hand X window coordinate */
/*             in OS units for the image;        */
/*                                               */
/*             The bottom Y window coordinate in */
/*             OS units for the image;           */
/*                                               */
/*             A BBox defining a rectangle       */
/*             relative to X and Y which is the  */
/*             area to update;                   */
/*                                               */
/*             The image number, from 0 to       */
/*             nimages - 1;                      */
/*                                               */
/*             1 to force a redraw (i.e. clear   */
/*             any previously drawn data first), */
/*             zero to not clear the region.     */
/*************************************************/

static _kernel_oserror * image_update_area(browser_data * b, int x, int y, BBox * ubox,
                                           int image, int redraw)
{
  _kernel_oserror       * e;
  WimpRedrawWindowBlock   r;
  int                     more, sx, sy;
  int                     xref;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_update_area: Called for image %d\n",image);
  #endif

  /* If the image cannot be redrawn yet, don't redraw it... */

  if (!idata[image].canredraw)
  {
    #ifdef TRACE
      if (tl & (1u<<15)) Printf("image_update_area: Image %d can't be redrawn yet (canredraw = 0)\n",image);
    #endif

    return NULL;
  }

  r.window_handle = b->window_handle;

  r.visible_area  = *ubox;

  r.visible_area.xmin += x;
  r.visible_area.ymin += y;
  r.visible_area.xmax += x;
  r.visible_area.ymax += (y + 4);

  /* Ensure that 'xref' holds the number of the given image, which may well */
  /* cross reference another, 'image', that has the actual render data.     */

  xref = image;
  if (idata[image].xref >= 0) image = idata[image].xref;

  /* If the image may acquire a mask during rendering, even if it is not    */
  /* initially transparent, need to force the area to redraw to clear first */

  if (
       idata[image].istore->mutable_mask ||
       redraw
     )
     wimp_force_redraw(r.window_handle,
                       r.visible_area.xmin,
                       r.visible_area.ymin,
                       r.visible_area.xmax,
                       r.visible_area.ymax);
  else
  {
    /* Otherwise, do a less flickery non-clearing update */

    wimp_update_window(&r, &more);

    sx = coords_x_toscreen(x, &r);
    sy = coords_y_toscreen(y, &r);

    while(more)
    {
      if (
2141
           b->show_foreground                     ||
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
           b->displayed == Display_External_Image ||
           idata[xref].priority
         )
      {
        browser_redrawing = b;
        image_redrawing   = xref;

        e = idata[image].istore -> Render(idata[image].istore,
                                          sx,
                                          sy,
                                          100,
                                          idata[xref].currw,
                                          idata[xref].currh);

        browser_redrawing = NULL;
        image_redrawing   = -1;

        #ifdef STRICT_PARSER
2160

2161 2162 2163 2164 2165
          if (e)
          {
            e->errnum = Utils_Error_Custom_Message;
            show_error_ret(e);
          }
2166

2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
        #endif
      }

      #ifdef ANTI_TWITTER

        if (!printing) anti_twitter(&r);

      #endif

      wimp_get_rectangle(&r,&more);
    }
  }

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

  return NULL;
}

/*************************************************/
/* image_update_image()                          */
/*                                               */
/* Update the specified image number on screen,  */
/* including all which cross reference it. If    */
/* the image has changed size on screen then     */
/* start a reformat from the first occurrence    */
/* (i.e. smallest token number), otherwise just  */
/* do an update on the relevant rectangle for    */
/* each occurrence.                              */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images;           */
/*                                               */
/*             The image number, from 0 to       */
/*             nimages - 1;                      */
/*                                               */
/*             Pointer (which may be NULL) to a  */
/*             BBox into which the image's size  */
/*             will be returned.                 */
/*************************************************/

static _kernel_oserror * image_update_image(browser_data * b, int image, BBox * box)
{
  /* Update the specified image number on the screen, including all       */
  /* which xref to it. If the image has changed size on screen then start */
  /* a reformat from the first occurrence (ie the smallest token number), */
  /* otherwise just do an update of the relevant rectangle for each       */
  /* occurrence.                                                          */

  int  i, actual;
  BBox whole, partial;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_update_image: Called for image %d\n",image);
  #endif

  /* If a BBox is passed in here, then the image will be redrawn in that */
  /* specific region. Otherwise, the region is derived from the image's  */
  /* size. The BBox 'whole' is used for the latter case, so by setting   */
  /* 'box' to the address of this if a BBox was *not* given, we can then */
  /* transparently use this elsewhere and update either the requested    */
  /* area or the whole image without needing special case code.          */
  /*                                                                     */
  /* If the image's 'hadfirst' flag is clear, it hasn't been through     */
  /* this function yet. In that case, want to ensure that the whole      */
  /* image is redrawn to clear any placeholder that will be plotted in   */
  /* its place; otherwise, only the part of the placeholder that         */
  /* corresponds to the requested redraw box will be cleared.            */

  if (!box || !idata[image].hadfirst) box = &whole;

  /* Now ensure that 'image' is the image with the render information, as */
  /* the rest of the code has to deal with all xref images to this one    */
  /* anyway.                                                              */
  /*                                                                      */
  /* So 'actual' is now the image number given to image_update_image, and */
  /* 'image' is the number of the image with associated render data; this */
  /* may be the same as 'actual' or may be equal to the contents of its   */
  /* 'xref' field.                                                        */

  actual = image;
  if (idata[image].xref >= 0) image = idata[image].xref;

  /* If there appears to be no data for the image, or it is less than */
  /* one pixel wide (i.e. not displayable for whatever reason), exit. */

  if (!idata[image].istore || (idata[image].istore && idata[image].istore->width < 1)) return NULL;

  /* Check if the image has become animated */

  if (idata[image].istore->animated)
  {
    /* If the image is animated and we haven't got a null handler */
    /* for animations, install one now.                           */

    if (!animhandler)
    {
      register_null_claimant(Wimp_ENull, (WimpEventHandler *) image_animate_images, NULL);
      animhandler = 1;
    }
2268 2269
  }

2270
  if (idata[image].istore -> RegisterFiller && !idata[image].hadfiller)
2271
  {
2272
    show_error_ret(image_register_filler(image));
2273 2274 2275 2276 2277
  }

  /* When the image library gets some data for an image it will fill */
  /* in the width_os and height_os fields of the istore structure    */
  /* that 'image' points to. If the HTML source didn't specify a     */
2278 2279 2280
  /* size for this or cross referencing images and the size is not   */
  /* the same as stored in currw / currh, flag that a reformat is    */
  /* needed for this image.                                          */
2281 2282

  if (
2283
       !idata[actual].hadfirst             &&
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
       idata[image].istore->width_os  >= 0 &&
       idata[image].istore->height_os >= 0
     )
  {
    for (i = 0; i < nimages; i++)
    {
      if (
           (
             idata[i].xref == image ||
             i == image
           )
           && !idata[i].fixedsize
         )
      {
2298
        BBox size;
2299

2300 2301 2302
        /* Ignore any existing currw and currh values - find the image */
        /* size based entirely on the HTML and the image itself        */

2303 2304
        image_get_image_size(b,
                             i,
2305 2306
                             &size,
                             1);
2307

2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
        /* Does the returned value differ from the stored size? If so, */
        /* flag that we must do a reformat for this image. It is up to */
        /* the reformatter to call back to routines in this source     */
        /* file and update currw and currh once the image is           */
        /* incorporated into a line array.                             */

        if (
             size.xmax != idata[i].currw ||
             size.ymax != idata[i].currh
           )
           idata[i].reformat = 1;
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
      }
    }
  }

  /* If the image is for the background, just refresh the window contents */
  /* with browser_update_window (remembering to update those windows that */
  /* cross reference the same background image, too).                     */

  {
    int            isbackground = 0;
    browser_data * check        = last_browser;

    /* First check if the image is the background of this browser. If */
    /* not then check all browsers.                                   */

2334
    if (actual == b->background_image || image == b->background_image) isbackground = 1;
2335 2336 2337 2338
    else
    {
      while (check && !isbackground)
      {
2339
        if (actual == check->background_image || image == check->background_image) isbackground = 1;
2340 2341 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 2367 2368 2369 2370 2371 2372

        check = check->previous;
      }
    }

    /* If this is a background, update all instances of the image */
    /* and exit the update routine here.                          */

    if (isbackground)
    {
      for (i = 0; i < nimages; i++)
      {
        if ((i == image || idata[i].xref == image) && idata[image].fetched)
        {
          browser_update_bottom(idata[i].owner, NULL);
        }
      }

      return NULL;
    }
  }

  /* Look through all images for cross references */

  whole.xmin = whole.ymin = 0;

  for (i = 0; i < nimages; i++)
  {
    /* If we're on the current image, or on one which  */
    /* references it, then proceed.                    */

    if (i == image || idata[i].xref == image)
    {
2373 2374 2375 2376
      int       l, x, y;
      int       noplot = 0;
      HStream * tp;
      BBox      ibox;
2377 2378 2379

      /* Set the 'whole' BBox to the size of the base image in OS units */

2380
      image_get_image_size(b, i, &whole, 0);
2381 2382 2383 2384

      /* Ensure the redraw box returned by the image Load call */
      /* (or the BBox 'whole' from above) is scaled to fit the */
      /* actual image's dimensions.                            */
2385 2386 2387 2388 2389
      /*                                                       */
      /* We don't scale if box = &whole, as in that case the   */
      /* bbox is already scaled, or if for some reason the     */
      /* width or height fields in the ImageLib image struct   */
      /* seem to be invalid.                                   */
2390

2391 2392 2393 2394 2395 2396
      if (
           box != &whole                      &&
           idata[image].istore->width_os  > 0 &&
           idata[image].istore->height_os > 0
         )
      {
2397 2398 2399 2400
        partial.xmin = (box->xmin * whole.xmax) / idata[image].istore->width_os;
        partial.ymin = (box->ymin * whole.ymax) / idata[image].istore->height_os;
        partial.xmax = (box->xmax * whole.xmax) / idata[image].istore->width_os;
        partial.ymax = (box->ymax * whole.ymax) / idata[image].istore->height_os;
2401 2402
      }
      else partial = *box;
2403 2404 2405 2406 2407 2408 2409 2410 2411

      /* If the image doesn't have position information, can't plot it */

      if (idata[i].x == -1 && idata[i].y == -1) noplot = 1;

      /* Only continue if the line containing a chunk */
      /* relating to the token which relates to this  */
      /* image (!) can be found.                      */

2412
      l = tokenutils_find_ancestor_line(idata[i].owner, idata[i].token);
2413 2414 2415 2416 2417 2418 2419 2420 2421
      if (l < 0) noplot = 1;

      /* May not be redrawing the image, but might still want to */
      /* reformat the page here if the size has changed.         */

      if (noplot)
      {
        if (!idata[i].hadfirst && !idata[i].fixedsize)
        {
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
          /* This is the first time we've known how big the image is since it   */
          /* was encountered in the HTML; record it in the image history, then. */

          if (idata[i].istore)
          {
            /* Ignore errors, this isn't vital */

            imghistory_record((const char **) &ddata,
                              image_data_offset(idata[i].owner, i),
                              idata[i].istore->width_os,
                              idata[i].istore->height_os);
          }

2435
          /* Now do the reformat, if the size changed */
2436

2437
          idata[i].hadfirst = 1;
2438 2439 2440 2441 2442 2443 2444

          if (idata[i].reformat)
          {
            idata[i].reformat = 0;

            reformat_format_from(idata[i].owner, l - 1, 0, i);
          }
2445 2446 2447 2448

         /* If we don't need to reformat, we can (potentially!) redraw */

          else idata[i].canredraw = 1;
2449 2450 2451 2452
        }
      }
      else
      {
2453 2454
        x  = idata[i].x;
        y  = idata[i].y;
2455 2456
        tp = idata[i].token;

2457 2458 2459 2460 2461
        if (
             !reformat_get_image_size(idata[i].owner,
                                      tp,
                                      &ibox)
           )
2462 2463 2464 2465 2466 2467
        {
          /* If the image size was obtained without error, */
          /* correct its X and Y coordinates appropriately */

          if (!idata[i].hadfirst)
          {
2468
            int do_redraw = 1;
2469

2470
            idata[i].hadfirst = 1;
2471

2472 2473
            /* Is the image size fixed in the HTML? If not, may need to do a */
            /* reformat.                                                     */
2474

2475
            if (!idata[i].fixedsize)
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
            {
              /* As above, this is the first time we've known how big the image is */
              /* since it was encountered in the HTML, so record it in the image   */
              /* history.                                                          */

              if (idata[i].istore)
              {
                /* Ignore errors, this isn't vital */

                imghistory_record((const char **) &ddata,
                                  image_data_offset(idata[i].owner, i),
                                  idata[i].istore->width_os,
                                  idata[i].istore->height_os);
              }

2491
              /* If the size changed, do a reformat */
2492

2493 2494 2495 2496 2497 2498 2499
              if (idata[i].reformat)
              {
                idata[i].reformat = 0;
                do_redraw         = 0; /* Reformatting - no extra redraws needed */

                reformat_format_from(idata[i].owner, l - 1, 0, i);
              }
2500 2501 2502 2503

              /* If we don't need to reformat, we can redraw */

              else idata[i].canredraw = 1;
2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
            }

            /* If no reformat was needed, just do a redraw (which clears the  */
            /* background first; see the very large comment earlier on).      */

            if (do_redraw)
            {
              image_update_area(idata[i].owner,
                                x,
                                y,
                                &partial,
                                i,
                                1);
2517
            }
2518 2519
          }

2520 2521
          /* Work out what region to redraw (may only require */
          /* a partial area update)                           */
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531

          else if (partial.ymax < partial.ymin)
          {
            BBox ubox = partial;

            /* If the y max coordinate is less than the y min coordinate, */
            /* redraw from ymin to the top of the image, and from ymax to */
            /* the bottom. That way can miss out a middle section.        */

            ubox.ymin = partial.ymin;
2532
            ubox.ymax = whole.ymax;
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559

            image_update_area(idata[i].owner,
                              x,
                              y,
                              &ubox,
                              i,
                              0);

            ubox.ymax = partial.ymax;
            ubox.ymin = 0;

            image_update_area(idata[i].owner,
                              x,
                              y,
                              &ubox,
                              i,
                              0);
          }
          else if (partial.xmax < partial.xmin)
          {
            BBox ubox = partial;

            /* Similarly, if xmax is less than xmin, draw from xmin to the */
            /* right hand side of the image and from xmax to the left, so  */
            /* a vertical strip in the middle may be untouched.            */

            ubox.xmin = partial.xmin;
2560
            ubox.xmax = whole.xmax;
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 2586 2587 2588 2589 2590

            image_update_area(idata[i].owner,
                              x,
                              y,
                              &ubox,
                              i,
                              0);

            ubox.xmax = partial.xmax;
            ubox.xmin = 0;

            image_update_area(idata[i].owner,
                              x,
                              y,
                              &ubox,
                              i,
                              0);
          }
          else
          {
            /* Otherwise, redraw the requested box */

            image_update_area(idata[i].owner,
                              x,
                              y,
                              &partial,
                              i,
                              0);
          }

2591
        /* Closure of 'if (!reformat_get_image_size(...))' */
2592 2593 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 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
        }

      /* Closure of 'if (noplot)' - code immediately above is */
      /* executed in the 'else' section.                      */
      }

    /* Closure of 'if (i == image || idata[i].xref == image)' */
    }

  /* Closure of loop running round all the images */
  }

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

  return NULL;
}

/*************************************************/
/* image_animate_images()                        */
/*                                               */
/* Checks all images to see if they need         */
/* updating. Designed to be called on null       */
/* events.                                       */
/*                                               */
/* Parameters are as standard for a Wimp event   */
/* handler.                                      */
/*************************************************/

int image_animate_images(int eventcode, WimpPollBlock * block, IdBlock * idb, browser_data * handle)
{
  int i, image, redraw;

  /* Scan round all images */

  for (i = 0; i < nimages; i++)
  {
    /* Find the image with associated render data */

    if (idata[i].xref >= 0) image = idata[i].xref;
    else                    image = i;

    /* Skip this image if it as already been dealt with */

    if (image >= i)
    {
      /* If this image does have such data, is flagged as */
      /* animated, and has a pointer to a NeedRedraw      */
      /* function, proceed.                               */

      if (
           idata[image].istore             &&
           idata[image].istore->animated   &&
           idata[image].istore->NeedRedraw
         )
      {
        BBox extent; // Not actually used yet...!

        #ifdef STRICT_PARSER

          /* Report any errors as Continue-only in strict parser mode */

          _kernel_oserror * e;

          e = idata[image].istore -> NeedRedraw(idata[image].istore, &redraw, &extent);

          if (e)
          {
            e->errnum = Utils_Error_Custom_Message;
            show_error_ret(e);
          }

        #else

          /* If not in Strict mode, ignore any errors */

          idata[image].istore -> NeedRedraw(idata[image].istore, &redraw, &extent);

        #endif

        /* Redraw the image, if required */

        if (redraw) image_update_image(idata[i].owner, i, NULL);
      }
    }
  }

  return 0;
}

2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
/*************************************************/
/* image_register_filler()                       */
/*                                               */
/* Registers the given image and it's owning     */
/* browser with ImageLib. Must be called for     */
/* cross referencing images only.                */
/*                                               */
/* Parameters: The image number to register.     */
/*************************************************/

static _kernel_oserror * image_register_filler(int xref)
{
  #ifdef STRICT_PARSER

    {
      _kernel_oserror * e;

      /* Report any errors as Continue-only in strict parser mode */

      e = idata[xref].istore -> RegisterFiller(idata[xref].istore,
                                               (FillerFunction *) image_fill_background,
                                               idata[xref].owner,
                                               (int *) xref);

      if (e)
      {
        e->errnum = Utils_Error_Custom_Message;
        return e;
      }
    }

  #else

    /* If not in Strict mode, don't report errors */

    idata[xref].istore -> RegisterFiller(idata[xref].istore,
                                         (FillerFunction *) image_fill_background,
                                         idata[xref].owner,
                                         (int *) xref);
  #endif

  idata[xref].hadfiller = 1;

  return NULL;
}

2729 2730 2731 2732 2733 2734 2735
/*************************************************/
/* image_fill_background()                       */
/*                                               */
/* Called as a FillerFunction for ImageLib,      */
/* this redraws the background image. Output     */
/* will probably have been redirected by         */
/* ImageLib at this point.                       */
2736 2737 2738 2739 2740 2741 2742
/*                                               */
/* The way the function is registered should     */
/* leave void * handle pointing to the browser   */
/* who's background will be redrawn, with int *  */
/* i actually being an int (not an int *)        */
/* holding the image number for which the        */
/* function was registered in the first place.   */
2743 2744 2745 2746 2747
/*************************************************/

_kernel_oserror * image_fill_background(void * handle, int * i)
{
  WimpGetWindowStateBlock   state;
2748 2749 2750
  _kernel_oserror         * e        = NULL;
  browser_data            * b        = (browser_data *) handle;

2751
  int                       image;
2752 2753 2754 2755 2756 2757
  int                       ximage   = (int) i;

  int                       noplot   = 0;
  int                       bimage   = -1;
  int                       bgcolour = -1;

2758 2759 2760
  int                       x, y, xorigin, yorigin;
  int                       w, h;

2761 2762 2763 2764
  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_fill_background: Called with %p, %d\n", handle, i);
  #endif

2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
  state.window_handle = b->window_handle;
  e = wimp_get_window_state(&state);
  if (e) return e;

  /* Should never happen, but you never know... */

  if (idata[ximage].xref >= 0) ximage = idata[ximage].xref;

  /* See the top of the file for details on browser_redrawing */
  /* and image_redrawing                                      */

  if (browser_redrawing) b = browser_redrawing;

  if (image_redrawing >= -1) image = image_redrawing;
  else                       image = ximage;

2781 2782 2783 2784 2785 2786 2787 2788
  #ifdef TRACE
    if (tl & (1u<<15))
    {
      Printf("image_fill_background: Decided to use %p, %d\n", b, image);
      Printf("image_fill_background: Image w, h = %d, %d\n",idata[image].currw,idata[image].currh);
    }
  #endif

2789 2790
  /* The image may exist in a table, and we should check what */
  /* background colour to draw if this is the case.           */
2791

2792
  if (idata[image].token->parent)
2793
  {
2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
    table_headdata * head  = idata[image].token->parent;
    table_row      * row   = NULL;
    table_stream   * table = NULL;

    if (head) row   = head->parent;
    if (row)  table = row->parent;

    if (table)
    {
      if (TABLE_HAS_BGCOL(table)) bgcolour = TABLE_BGCOL(table), noplot = 1;

      /* Individual cells can override the table */

      if (TD_HAS_BGCOL(head))     bgcolour = TD_BGCOL(head),     noplot = 1;
    }
2809 2810
  }

2811 2812 2813 2814 2815 2816 2817 2818 2819
  /* We may still have no defined background colour, in which */
  /* case check the main page background.                     */

  if (bgcolour == -1)
  {
    /* Can't plot a background image if there's no such image or */
    /* it's not fully fetched.                                   */

    if (b->background_image >= 0)
2820
    {
2821 2822
      bimage = b->background_image;
      if (idata[bimage].xref >= 0) bimage = idata[bimage].xref;
2823
    }
2824
    else bimage = -1, noplot = 1;
2825

2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
    #ifdef TRACE
      if (tl & (1u<<15))
      {
        if (bimage >= 0) Printf("image_fill_background: Background image = %d\n",bimage);
        else             Printf("image_fill_background: No background image\n");
      }
    #endif

    if (
         !noplot &&
         (
           !idata[bimage].fetched ||
           !idata[bimage].istore
         )
2840
       )
2841
       noplot = 1;
2842

2843 2844 2845 2846 2847 2848 2849
    if (
         !noplot              &&
         idata[bimage].istore &&
         (
           idata[bimage].istore->width_os  <= 0 ||
           idata[bimage].istore->height_os <= 0
         )
2850
       )
2851 2852 2853 2854
       noplot = 1;

    bgcolour = redraw_backcol(b);
  }
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871

  xorigin = -idata[image].x;
  yorigin = -idata[image].y;

  /* Ensure dithered background colours have a dithering */
  /* (ECF) pattern that starts in the right place        */

  e = _swix(OS_SetECFOrigin,
            _INR(0,1),

            -xorigin,
            -yorigin);

  if (e) return e;

  /* Do a blank rectangle if the image is transparent (has a mask) */
  /* or the image itself can't be plotted, or the browser window   */
2872 2873 2874
  /* set up not to plot background images, or we're printing and   */
  /* shouldn't plot backgrounds (we must plot something at this    */
  /* stage!).                                                      */
2875

2876 2877 2878
  if (
       noplot                            ||
       idata[bimage].istore->transparent ||
2879
       !b->show_background               ||
2880 2881 2882 2883 2884
       (
         printing &&
         !printstyle_show_all()
       )
     )
2885
  {
2886
    redraw_set_colour(bgcolour);
2887 2888 2889 2890 2891 2892 2893 2894 2895

    bbc_rectanglefill(0,
                      0,
                      idata[ximage].istore -> width_os,
                      idata[ximage].istore -> height_os);
  }

  /* If there's no background image that can be plotted, exit here */

2896
  if (
2897 2898
       !b->show_background ||
       noplot              ||
2899 2900 2901 2902 2903
       (
         printing &&
         !printstyle_show_all()
       )
     )
2904 2905 2906 2907 2908 2909 2910
  {
    #ifdef TRACE
      if (tl & (1u<<15)) Printf("image_fill_background: No background image to plot, so successful (exitting)\n");
    #endif

    return NULL;
  }
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934

  /* Find the scale for the background plotting; if the foreground */
  /* image is scaled, then plotting the background at 1:1 will     */
  /* make it look scaled by the same amount, and things won't      */
  /* match up. We could either prescale the foreground image and   */
  /* then plot into that prescaled image, but this takes a lot     */
  /* of memory, or we could try to stick with a post-scaled image. */
  /* In that case, the background can either be ignored or we can  */
  /* try to scale it down so though it will look blocky and low    */
  /* resolution, it will at least roughly line up with the things  */
  /* around the foreground. This code does the last of the three.  */
  /*                                                               */
  /* Note the faster, simpler routine for scalings of 1:1 - avoids */
  /* floating point.                                               */

  if (
       idata[image].currw != idata[ximage].istore->width_os  ||
       idata[image].currh != idata[ximage].istore->height_os
     )
  {
    BBox  redraw;
    float scalex, scaley;
    float tempx,  tempy;
    float tempw,  temph;
2935
    int   htop;
2936

2937 2938 2939 2940
    #ifdef TRACE
      if (tl & (1u<<15)) Printf("image_fill_background: Plotting scaled background\n");
    #endif

2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
    tempx = (float) idata[ximage].istore->width_os, tempy = (float) idata[ximage].istore->height_os;
    tempw = (float) idata[image].currw,             temph = (float) idata[image].currh;

    scalex = tempx / tempw;
    scaley = tempy / temph;

    /* Round the background image's width and height down to pixel boundaries */

    tempw = idata[bimage].istore->width_os;
    temph = idata[bimage].istore->height_os;

    w = ((int) (tempw * scalex + (float) 0.5)) & ~(wimpt_dx() - 1);
    h = ((int) (temph * scaley + (float) 0.5)) & ~(wimpt_dy() - 1);

    /* Work out the coordinates over which to tile the image */

    tempx = - (float) (idata[image].x);

2959 2960
    if (!controls.swap_bars) htop = toolbars_button_height(b) + toolbars_url_height(b);
    else                     htop = toolbars_status_height(b);
2961 2962 2963

    if (htop) htop += wimpt_dy();

2964
    tempy = - (float) idata[image].y
2965
            - (float) htop;
2966 2967 2968 2969 2970 2971 2972 2973

    xorigin = (int) (tempx * scalex + (float) 0.5) + 1;
    yorigin = (int) (tempy * scaley + (float) 0.5) + 1;

    /* Exit if the background size appears to be too small */

    if (w < 1 || h < 1) return NULL;

2974
    redraw.xmin = -((-xorigin) % w);
2975
    redraw.ymin = -h;
2976
    redraw.xmax = idata[ximage].istore->width_os;
2977
    redraw.ymax = idata[ximage].istore->height_os + (yorigin - idata[ximage].istore->height_os) % h - 1;
2978

2979
    idata[bimage].istore -> ModeChange(idata[bimage].istore);
2980

2981
    /* Render the image over the redraw region, with a scaled plot */
2982

2983
    for (y = redraw.ymax - h + 4; y >= redraw.ymin; y -= h)
2984
    {
2985
      for (x = redraw.xmin; x <= redraw.xmax; x += w)
2986 2987
      {
        e = (idata[bimage].istore -> Render(idata[bimage].istore,
2988 2989 2990 2991 2992
                                            x,
                                            y,
                                            100,
                                            w,
                                            h));
2993 2994 2995 2996 2997
        if (e) break;
      }

      if (e) break;
    }
2998

2999
    idata[bimage].istore -> ModeChange(idata[bimage].istore);
3000 3001 3002 3003
  }
  else
  {
    BBox redraw;
3004
    int  htop;
3005

3006 3007 3008 3009
    #ifdef TRACE
      if (tl & (1u<<15)) Printf("image_fill_background: Plotting unscaled background\n");
    #endif

3010 3011 3012 3013
    w = (idata[bimage].istore->width_os)  & ~(wimpt_dx() - 1);
    h = (idata[bimage].istore->height_os) & ~(wimpt_dy() - 1);

    xorigin = -idata[image].x;
3014

3015 3016
    if (!controls.swap_bars) htop = toolbars_button_height(b) + toolbars_url_height(b);
    else                     htop = toolbars_status_height(b);
3017 3018 3019 3020

    if (htop) htop += wimpt_dy();

    yorigin = -idata[image].y - htop;
3021 3022 3023 3024 3025

    /* Exit if the background size appears to be too small */

    if (w < 1 || h < 1) return NULL;

3026
    redraw.xmin = -((-xorigin) % w);
3027
    redraw.ymin = -h;
3028
    redraw.xmax = idata[ximage].istore->width_os;
3029
    redraw.ymax = idata[ximage].istore->height_os + (yorigin - idata[ximage].istore->height_os) % h - 1;
3030

3031
    idata[bimage].istore -> ModeChange(idata[bimage].istore);
3032

3033 3034
    /* Render the image over the redraw region, with an unscaled plot */

3035
    for (y = redraw.ymax - h + 4; y >= redraw.ymin; y -= h)
3036
    {
3037
      for (x = redraw.xmin; x <= redraw.xmax; x += w)
3038 3039
      {
        e = (idata[bimage].istore -> Render(idata[bimage].istore,
3040 3041 3042 3043 3044
                                            x,
                                            y,
                                            100,
                                            -1,
                                            -1));
3045 3046 3047 3048 3049
        if (e) break;
      }

      if (e) break;
    }
3050

3051
    idata[bimage].istore -> ModeChange(idata[bimage].istore);
3052 3053
  }

3054 3055 3056 3057
  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_fill_background: Successful\n");
  #endif

3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117
  return e;
}

/*************************************************/
/* image_redraw()                                */
/*                                               */
/* Does a high level redraw of an image, with    */
/* an outline to show where the image should be  */
/* if it isn't all plotted, or a slabbed box to  */
/* display broken or unfetched images.           */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Pointer to a RedrawWindowBlock    */
/*             struct which holds information    */
/*             about the current redraw session; */
/*                                               */
/*             Address of the token representing */
/*             the image;                        */
/*                                               */
/*             The X offset in window coords (so */
/*             OS units) of the left hand edge   */
/*             of the image;                     */
/*                                               */
/*             The Y offset in window coords (so */
/*             OS units) of the bottom edge of   */
/*             the image.                        */
/*************************************************/

_kernel_oserror * image_redraw(browser_data * b, WimpRedrawWindowBlock * r, HStream * token, int x, int y)
{
  int image, actual;
  int plotted = 0;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_redraw: Called with token %d\n", token);
  #endif

  /* Get the image number for the given token; 'actual' holds the actual */
  /* image for the given token, which may cross reference 'image', which */
  /* holds the actual render data.                                       */

  image = image_get_token_image_actual(b, token);

  if (image < 0) return NULL;

  actual = image;
  if (idata[actual].xref >= 0) image = idata[actual].xref;

  /* If the image has a fetched width and height, */
  /* and the browser choices specify that images  */
  /* should be shown (or the image itself has a   */
  /* high priority show bit set), display part or */
  /* all of the image.                            */

  if (
       image  >= 0 &&
       actual >= 0 &&
       (
3118
         b->show_foreground                     ||
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143
         b->displayed == Display_External_Image ||
         idata[actual].priority
       )
       && idata[actual].canredraw
       && idata[image].istore             /* Must check istore here, as if width / height are <= 0, */
       && idata[image].istore->width  > 0 /* the image library has no data for the image and will   */
       && idata[image].istore->height > 0 /* not have filled in (e.g.) the Render field. So you'd   */
     )                                    /* get a rather nasty abort trying to call it!            */
  {
    _kernel_oserror * e;

    browser_redrawing = b;
    image_redrawing   = actual;

    e = idata[image].istore -> Render(idata[image].istore,
                                      x,
                                      y,
                                      100,
                                      idata[actual].currw,
                                      idata[actual].currh);

    browser_redrawing = NULL;
    image_redrawing   = -1;

    #ifdef STRICT_PARSER
3144

3145 3146 3147 3148 3149
      if (e)
      {
        e->errnum = Utils_Error_Custom_Message;
        show_error_ret(e);
      }
3150

3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
    #endif

    if (!e) plotted = 1;
  }

  if (!plotted)
  {
    /* If the image was not plotted, either due to error or because there's */
    /* no data yet, plot a placeholder and any present ALT text instead.    */

3161 3162
    BBox         box;
    const char * text;
3163
    HStream    * tp   = NULL;
3164

3165
    image_get_image_size(b, actual, &box, 0);
3166 3167 3168 3169 3170 3171 3172 3173 3174

    box.xmin += x;
    box.ymin += y;
    box.xmax += x - box.xmin;
    box.ymax += y - box.ymin;

    box.xmin &= ~(wimpt_dx() - 1);
    box.ymin &= ~(wimpt_dy() - 1);

3175 3176 3177
    /* If an image, the ALT text wants to be from the actual image, not one */
    /* that might be being cross referenced.                                */

3178 3179
    tp   = (ISOBJECT(tp)) ? token                 : idata[actual].token;
    text = (ISOBJECT(tp)) ? HtmlOBJECTstandby(tp) : tp->text;
3180

3181 3182 3183 3184 3185
    redraw_draw_placeholder(b,
                            r,
                            &box,
                            tp,
                            text);
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
  }

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

  return NULL;
}

/*************************************************/
/* image_tile_window()                           */
/*                                               */
/* For a given redraw rectangle, tiles the       */
/* background image within that rectangle.       */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the window and image; */
/*                                               */
/*             Pointer to a WimpRedrawWindow-    */
/*             Block structure defining the area */
/*             over which to tile the image;     */
/*                                               */
/*             The X and Y coordinates to take   */
/*             as the tile origin, in OS units.  */
/*                                               */
/* Returns:    1 for success, 0 for failure.     */
/*************************************************/

int image_tile_window(browser_data * b, WimpRedrawWindowBlock * r, int xorigin, int yorigin)
{
  _kernel_oserror * e;
  int               x, y, w, h;
  int               xmin, ymax;
  int               image;

  #ifdef TRACE
3222
    if (tl & (1u<<15)) Printf("image_tile_window: Called, background_image = %d\n",b->background_image);
3223 3224 3225 3226
  #endif

  /* Can only tile if there's a background image defined and fully fetched */

3227
  if (b->background_image < 0) return 0;
3228

3229
  image = b->background_image;
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 3261 3262 3263 3264 3265
  if (idata[image].xref >= 0) image = idata[image].xref;

  if (!idata[image].fetched || !idata[image].istore) return 0;

  /* Round the width and height to pixel boundaries */

  w = idata[image].istore->width_os  & ~(wimpt_dx() - 1);
  h = idata[image].istore->height_os & ~(wimpt_dy() - 1);

  if (w < 1 || h < 1) return 0;

  /* Work out the coordinates over which to tile the image */

  xmin = coords_x_toworkarea(r->redraw_area.xmin,r);
  ymax = coords_y_toworkarea(r->redraw_area.ymax,r);

  xmin -= ((xmin - xorigin) % w);
  ymax -= ((ymax - yorigin) % h) + 1;

  xmin = coords_x_toscreen(xmin, r);
  ymax = coords_y_toscreen(ymax, r);

  /* Do a blank rectangle if the image is transparent (has a mask) */

  if (idata[image].istore->transparent)
  {
    redraw_set_colour(redraw_backcol(b));

    bbc_rectanglefill(r->redraw_area.xmin,
                      r->redraw_area.ymin,
                      r->redraw_area.xmax - r->redraw_area.xmin,
                      r->redraw_area.ymax - r->redraw_area.ymin);
  }

  /* Render the image over the redraw region */

3266
  for (y = ymax - h + 4; y >= r->redraw_area.ymin - h; y -= h)
3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 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
  {
    for (x = xmin; x <= r->redraw_area.xmax; x += w)
    {
      browser_redrawing = b;
      image_redrawing   = image;

      e = idata[image].istore -> Render(idata[image].istore,
                                        x,
                                        y,
                                        100,
                                        w,
                                        h);

      browser_redrawing = NULL;
      image_redrawing   = -1;

      #ifdef STRICT_PARSER

        if (e)
        {
          e->errnum = Utils_Error_Custom_Message;
          show_error_ret(e);

          return 0;
        }

      #else

        if (e) return 0;

      #endif
    }
  }

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

  return 1;
}

/*************************************************/
/* image_mark_as_redrawable()                    */
/*                                               */
/* Flags that an image may now be redrawn (this  */
/* is generally called because an unsized image  */
/* has found its size, asked for a reformat, and */
/* that reformat is about to take place).        */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The image number.                 */
/*************************************************/

void image_mark_as_redrawable(browser_data * b, int image)
{
  /* Mark the image as redrawable */

  if (idata[image].owner == b) idata[image].canredraw = 1;

  return;
}

/*************************************************/
3332
/* image_token_reformatted()                     */
3333
/*                                               */
3334 3335 3336
/* Called by a reformatter to signal an image is */
/* locked in a line array. Sets the image's      */
/* canredraw flag and locs the image's size.     */
3337 3338 3339 3340 3341 3342 3343 3344
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Pointer to an HStream struct      */
/*             representing the image.           */
/*************************************************/

3345
void image_token_reformatted(browser_data * b, HStream * token)
3346
{
3347
  int  image;
3348
  int  xref;
3349 3350 3351 3352 3353 3354

  /* Get the image number */

  image = image_get_token_image_actual(b, token);
  if (image < 0 || image > nimages) return;

3355 3356
  if (idata[image].xref >= 0) xref = idata[image].xref;
  else                        xref = image;
3357

3358
  /* Lock the image size */
3359

3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374
  image_lock_image_size(b, image);

  /* Exit if the image has no known real size yet - even if its size */
  /* is fixed in the HTML, there's no point marking it as redrawable */
  /* if there is no image data to redraw...!                         */

  if (
       !idata[xref].istore                ||
       idata[xref].istore->width_os  <= 0 ||
       idata[xref].istore->height_os <= 0
     )
     return;

  /* We do have some data and the reformatter has fixed the image in */
  /* the line array, so mark it as redrawable now.                   */
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401

  image_mark_as_redrawable(b, image);

  return;
}

/*************************************************/
/* image_mode_change()                           */
/*                                               */
/* Ensure images are up to date following a mode */
/* change.                                       */
/*************************************************/

_kernel_oserror * image_mode_change(void)
{
  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_mode_change: Called\n");
  #endif

  if (nimages)
  {
    int i;

    /* For each image, call the image library's mode change handling function */

    for (i = 0; i < nimages; i++)
    {
3402
      if (idata[i].istore && idata[i].istore->width > 0 && idata[i].istore -> ModeChange)
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444
      {
        #ifdef STRICT_PARSER

          /* Report any errors as Continue-only in strict parser mode */

          _kernel_oserror * e;

          e = idata[i].istore -> ModeChange(idata[i].istore);

          #ifdef TRACE
            if (tl & (1u<<15)) Printf("image_mode_change: Exitting with error\n");
          #endif

          if (e) return e;

        #else

          /* If not in Strict mode, ignore any errors */

          idata[i].istore -> ModeChange(idata[i].istore);

        #endif
      }
    }
  }

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

  return NULL;
}

/*************************************************/
/* image_data_offset()                           */
/*                                               */
/* Returns the offset into the ddata block of    */
/* the data associated with a given image.       */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image in          */
/*             question;                         */
3445
/*                                               */
3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506
/*             An image number, from 0 to        */
/*             nimages - 1.                      */
/*                                               */
/* Returns:    Pointer to the data associated    */
/*             with that image (as a char *).    */
/*************************************************/

static int image_data_offset(browser_data * b, int image)
{
  int i, count = 0;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_data_offset: Called for image %d, and exitting\n",image);
  #endif

  if (image <= 0) return 0; /* Image 0's data offset will be zero... */

  for (i = 0; i < image; count += idata[i].alloc, i++);

  return count;
}

/*************************************************/
/* image_count_fetches()                         */
/*                                               */
/* Counts how many fetches are being performed   */
/* for a given web page.                         */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the page and images   */
/*             being fetched.                    */
/*                                               */
/* Returns:    The number of image fetches that  */
/*             are currently in progress (this   */
/*             may be zero, of course).          */
/*************************************************/

static int image_count_fetches(browser_data * b)
{
  int i, c = 0;

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

  /* there is a fetch handle in their image_info structs. */

  for (i = 0; i < nimages; i++) if (idata[i].handle && idata[i].owner == b) c++;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_count_fetches: Exitting with %d\n",c);
  #endif

  return c;
}

/*************************************************/
/* image_fetching()                              */
/*                                               */
/* Returns 1 if there are any image fetches      */
/* going on at all, else 0 (faster than using    */
3507
/* image_count_fetches above if you don't care   */
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 3543 3544 3545 3546 3547 3548 3549 3550 3551
/* how many fetches there are).                  */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the inquiry.          */
/*                                               */
/* Returns:    1 if there are image fetches in   */
/*             progress, else 0.                 */
/*************************************************/

int image_fetching(browser_data * b)
{
  int i;

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

  for (i = 0; i < nimages; i++)
  {
    if (idata[i].handle && idata[i].owner == b)
    {
      #ifdef TRACE
        if (tl & (1u<<15)) Printf("image_fetching: Exitting, there is at least 1 fetch in progress\n");
      #endif

      return 1;
    }
  }

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_fetching: Exitting, no fetches in progress\n");
  #endif

  return 0;
}

/*************************************************/
/* image_fetched()                               */
/*                                               */
/* Determines if an image has been completely    */
/* fetched or not.                               */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
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 3581 3582 3583
/*             The image number, from 0 to       */
/*             nimages - 1.                      */
/*                                               */
/* Returns:    1 if the image has been fetched   */
/*             completely, else 0.               */
/*************************************************/

int image_fetched(browser_data * b, int image)
{
  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_fetched: Called for image %d\n",image);
  #endif

  if (image >= 0) return (idata[image].fetched);

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_fetched: Exitting with 0 (failed)\n");
  #endif

  return 0;
}

/*************************************************/
/* image_token_fetched()                         */
/*                                               */
/* Determines if an image has been completely    */
/* fetched or not, based on a token representing */
/* the image.                                    */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
3584
/*                                               */
3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605
/*             Pointer to a token representing   */
/*             the image.                        */
/*                                               */
/* Returns:    1 if the image has been fetched   */
/*             completely, else 0.               */
/*************************************************/

int image_token_fetched(browser_data * b, HStream * token)
{
  int image;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_token_fetched: Called for token %p\n",token);
  #endif

  image = image_get_token_image_xref(b, token);

  #ifdef TRACE
    if (tl & (1u<<15))
    {
      Printf("image_token_fetched: Represents image %d\n",image);
3606
      Printf("image_token_fetched: Exitting through image_fetched\n");
3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854
    }
  #endif

  return image_fetched(b, image);
}

/*************************************************/
/* image_total_bytes_fetched()                   */
/*                                               */
/* Works out the total number of bytes fetched   */
/* in images so far.                             */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images.           */
/*                                               */
/* Returns:    The number of bytes fetched in    */
/*             image data at the moment of       */
/*             calling the function.             */
/*************************************************/

int image_total_bytes_fetched(browser_data * b)
{
  int count = 0;

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

  /* Sum the fetched size of all images currently present, */
  /* if there are any to count.                            */

  if (nimages)
  {
    int image;

    for (image = 0; image < nimages; image++)
    {
      if (idata[image].owner == b) count += idata[image].bytesgot;
    }
  }

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_total_bytes_fetched: Exitting with %d\n",count);
  #endif

  return count;
}

/*************************************************/
/* image_count_pending()                         */
/*                                               */
/* Counts how many images are waiting to be      */
/* fetched, but have been delayed for whatever   */
/* reason.                                       */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images. Any       */
/*             images in child windows are also  */
/*             included in the count.            */
/*                                               */
/* Returns:    The number of images waiting to   */
/*             be fetched, counting any images   */
/*             in any child windows (if present) */
/*************************************************/

int image_count_pending(browser_data * b)
{
  int i, c = 0;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_count_pending: Called for %p\n",b);
  #endif

  if (b->nchildren)
  {
    for (i = 0; i < b->nchildren; i++)
    {
      c += image_count_pending(b->children[i]);
    }
  }
  else
  {
    for (i = 0; i < nimages; i++)
    {
      if (
           !idata[i].fetched   &&
           !idata[i].delayed   &&
           idata[i].xref < 0   &&
           idata[i].owner == b
         )
         c++;
    }
  }

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_count_pending: Exitting with %d for %p\n",c,b);
  #endif

  return c;
}

/*************************************************/
/* image_count_specific_pending()                */
/*                                               */
/* Counts how many images are waiting to be      */
/* fetched, but have been delayed for whatever   */
/* reason, for just the specified browser (not   */
/* including any child windows).                 */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images.           */
/*                                               */
/* Returns:    The number of images waiting to   */
/*             be fetched in the given browser.  */
/*************************************************/

int image_count_specific_pending(browser_data * b)
{
  int i, c = 0;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_count_specific_pending: Called for %p\n",b);
  #endif

  for (i = 0; i < nimages; i++)
  {
    if (
         !idata[i].fetched   &&
         !idata[i].delayed   &&
         idata[i].xref < 0   &&
         idata[i].owner == b
       )
       c++;
  }

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_count_specific_pending: Exitting with %d for %p\n",c,b);
  #endif

  return c;
}

/*************************************************/
/* image_count_delayed()                         */
/*                                               */
/* Returns the number of images which have been  */
/* delayed (could be fetched, but have been set  */
/* up to not fetch yet).                         */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the images.           */
/*************************************************/

int image_count_delayed(browser_data * b)
{
  int count = 0;

  if (nimages)
  {
    int  i;

    for(i = 0; i < nimages; i++)
    {
      if (
           (
             !idata[i].fetched &&
             idata[i].delayed
           )
           ||
           (
             idata[i].fetched  &&
             !idata[i].success &&
             !idata[i].istore
           )
         )
         count++;
    }
  }

  return count;
}

/*************************************************/
/* image_plot_started()                          */
/*                                               */
/* Returns 1 if a given image in a given browser */
/* has had some plotting done for it (so the     */
/* placeholder box and possibly ALT text will no */
/* longer be visible for it).                    */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The number of the image.          */
/*                                               */
/* Returns:    1 if the image has been partially */
/*             or completely plotted, else 0.    */
/*************************************************/

int image_plot_started(browser_data * b, int image)
{
  if (image < 0) return 0;

  if (!idata[image].istore) return 0;

  if (!idata[image].canredraw) return 0;

  if (idata[image].istore->width > 0) return 1;
  else                                return 0;
}

/*************************************************/
/* image_token_plot_started()                    */
/*                                               */
/* Returns 1 if a given image in a given browser */
/* has had some plotting done for it (so the     */
/* placeholder box and possibly ALT text will no */
/* longer be visible for it).                    */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Pointer to a token representing   */
/*             the image.                        */
/*                                               */
/* Returns:    1 if the image has been partially */
/*             or completely plotted, else 0.    */
/*************************************************/

int image_token_plot_started(browser_data * b, HStream * token)
{
  int image;

  image = image_get_token_image_xref(b, token);

  return image_plot_started(b, image);
}

/*************************************************/
/* image_get_token_image_xref()                  */
/*                                               */
/* Finds the image number associated with a      */
/* given token. The number will be the image     */
/* that actually has the associated image data,  */
/* not just one that cross references this data. */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
3855
/*                                               */
3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
/*             The token address.                */
/*                                               */
/* Returns:    The image number which references */
/*             that token, or -1 if none found.  */
/*************************************************/

static int image_get_token_image_xref(browser_data * b, HStream * token)
{
  int i, found = -1;

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

  /* If there are any images to deal with... */

  if (nimages)
  {
    /* ...then look through them all, seeing if the */
    /* image is referred to by the given token.     */

    for (i = 0; i < nimages; i++)
    {

      if (idata[i].token == token && idata[i].owner == b)
      {
        found = i;
        break;
      }
    }

    /* If an appropriate image was found, ensure it */
    /* is the one with render data attached, not    */
    /* just a cross reference image.                */

    if (found >= 0)
    {
      if (idata[found].xref >= 0) found = idata[found].xref;
    }
  }

  /* Return the image number, or -1 for failure */

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_get_token_image_xref: Exitting with %d\n", found);
  #endif

  return found;
}

/*************************************************/
/* image_get_token_image_actual()                */
/*                                               */
/* As image_get_token_image, but returns the     */
/* exact image number represented by the given   */
/* token rather than the cross referenced one    */
/* with the pointers to the image data.          */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The token address.                */
/*                                               */
/* Returns:    The image number which references */
/*             that token, or -1 if none found.  */
/*************************************************/

static int image_get_token_image_actual(browser_data * b, HStream * token)
{
  int i, found = -1;

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

  /* If there are any images to deal with... */

  if (nimages)
  {
    /* ...then look through them all, seeing if the */
    /* image is referred to by the given token.     */

    for (i = 0; i < nimages; i++)
    {

      if (idata[i].token == token && idata[i].owner == b)
      {
        found = i;
        break;
      }
    }
  }

  /* Return the image number, or -1 for failure */

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_get_token_image_actual: Exitting with %d\n", found);
  #endif

  return found;
}

3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067
/*************************************************/
/* image_lock_image_size()                       */
/*                                               */
/* Ask image_get_image_size for the size of an   */
/* image, making sure currw and currh are -1 so  */
/* that it works the size out from first         */
/* principles, then set that size jn currw and   */
/* currh for future reference.                   */
/*                                               */
/* Designed to be called by the reformatter when */
/* it encounters an image and stores it in a     */
/* line array.                                   */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Number of the image.              */
/*************************************************/

static void image_lock_image_size(browser_data * b, int image)
{
  BBox size;

  /* Rediscover the image size - so ignore any stored */
  /* values in currw and currh.                       */

  if (image_get_image_size(b, image, &size, 1)) return;

  /* Now lock the size by (re)storing it in currw and currh */

  idata[image].currw = size.xmax;
  idata[image].currh = size.ymax;

  return;
}

/*************************************************/
/* image_lock_token_image_size()                 */
/*                                               */
/* As image_lock_image_size, but takes a pointer */
/* to an HStream rather than an image number.    */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Pointer to an HStream struct      */
/*             representing the image.           */
/*************************************************/

void image_lock_token_image_size(browser_data * b, HStream * token)
{
  int  image = image_get_token_image_actual(b, token);

  if (image < 0) return;

  image_lock_image_size(b, image);

  return;
}

/*************************************************/
/* image_unlock_image_size()                     */
/*                                               */
/* Set currw and currh for an image to -1, so    */
/* that image_get_image_size will start working  */
/* the size out from first principles rather     */
/* than using any prestored value.               */
/*                                               */
/* Designed to be called by the reformatter when */
/* it destroys a line array with images in it.   */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Number of the image.              */
/*************************************************/

static void image_unlock_image_size(browser_data * b, int image)
{
  idata[image].currw = -1;
  idata[image].currh = -1;

  return;
}

/*************************************************/
/* image_unlock_token_image_size()               */
/*                                               */
/* As image_unlock_image_size, but takes a       */
/* pointer to an HStream rather than an image    */
/* number.                                       */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Pointer to an HStream struct      */
/*             representing the image.           */
/*************************************************/

void image_unlock_token_image_size(browser_data * b, HStream * token)
{
  int image = image_get_token_image_actual(b, token);

  if (image < 0) return;

  image_unlock_image_size(b, image);

  return;
}

4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081
/*************************************************/
/* image_get_image_size()                        */
/*                                               */
/* Returns the size of an image in OS units.     */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The image number, from 0 to       */
/*             nimages - 1, which may just be a  */
/*             cross referencing image (i.e. has */
/*             no directly associated data);     */
/*                                               */
/*             Pointer to a BBox into which the  */
4082 4083 4084 4085 4086 4087 4088 4089
/*             size information is placed (xmax  */
/*             and ymax fields filled with       */
/*             width and height currently - xmin */
/*             and ymin always zero);            */
/*                                               */
/*             1 to ignore the image's currw and */
/*             currh fields, else use those if   */
/*             they are present.                 */
4090 4091 4092 4093
/*                                               */
/* Assumes:    The BBox pointer is not NULL.     */
/*************************************************/

4094
static _kernel_oserror * image_get_image_size(browser_data * b, int image, BBox * box, int ignore_stored)
4095
{
4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108
  int       awidth      = 0; /* Available page / cell width */
  int       aheight     = 0; /* Same, but height            */

  int       real_width  = 0; /* The actual image dimensions (OS units) */
  int       real_height = 0; /* from ImageLib                          */

  int       width_os    = 0; /* The image size as it will appear on the page, taking  */
  int       height_os   = 0; /* account of any WIDTH or HEIGHT attributes in the HTML */

  int       actual;
  int       subtract;
  HStream * tp          = idata[image].token;

4109
  #ifdef TRACE
4110

4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131
    if (tl & (1u<<15)) Printf("image_get_image_size: Called for image %d\n",image);

    if (!box)
    {
      erb.errnum = Utils_Error_Custom_Normal;
      strcpy(erb.errmess,"Null pointer to BBox given to image_get_image_size");
      return &erb;
    }

    if (image < 0)
    {
      erb.errnum = Utils_Error_Custom_Normal;
      sprintf(erb.errmess,"Invalid image number %d passed to image_get_image_size (nimages = %d)", image, nimages);
      return &erb;
    }
    if (image > nimages)
    {
      erb.errnum = Utils_Error_Custom_Normal;
      sprintf(erb.errmess,"Out of range image number %d passed to image_get_image_size (nimages = %d)", image, nimages);
      return &erb;
    }
4132

4133
  #else
4134

4135
    if (!box || image < 0 || image >= nimages) return NULL;
4136

4137 4138
  #endif

4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
  /* Zero contents of the BBox */

  memset(box, 0, sizeof(BBox));

  /* Can we return a prestored size? */

  if (!ignore_stored && idata[image].currw >= 0 && idata[image].currh >= 0)
  {
    box->xmax = idata[image].currw;
    box->ymax = idata[image].currh;

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

    return NULL;
  }

4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
  /* If this cross references another image, get its number */

  if (idata[image].xref >= 0) actual = idata[image].xref;
  else                        actual = image;

  /* Work out the available width / height */

  if (!tp->parent)
  {
    awidth  = redraw_display_width (b, NULL);
    aheight = redraw_display_height(b, NULL);

    subtract = redraw_left_gap (b, b->cell, tp) +
               redraw_right_gap(b, b->cell, tp);
  }
  else
  {
    reformat_cell * cell = tokenutils_token_cell(b, tp);

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

4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197
    if (
         TD_HAS_WIDTH  (tp->parent) &&
         TD_WIDTH_UNITS(tp->parent) == UNITS_PIXELS
       )
       awidth = TD_WIDTH(tp->parent) * 2; /* 1 'web pixel' = 2 OS units */

    if (
         TD_HAS_HEIGHT  (tp->parent) &&
         TD_HEIGHT_UNITS(tp->parent) == UNITS_PIXELS
       )
       aheight = TD_HEIGHT(tp->parent) * 2; /* 1 'web pixel' = 2 OS units */

    subtract = redraw_left_gap (b, cell, tp) +
               redraw_right_gap(b, cell, tp);
  }

  convert_to_os(subtract, &subtract);
  awidth -= subtract;
  if (awidth < 0) awidth = 0;

4198
  /* Try to get the image size from the actual image data (i.e. ImageLib) */
4199 4200 4201 4202 4203 4204

  if (idata[actual].istore)
  {
    real_width  = idata[actual].istore->width_os;
    real_height = idata[actual].istore->height_os;
  }
4205

4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311
  /* If we don't seem to have anything, try the image history */

  if (real_width <= 0 && real_height <= 0)
  {
    imghistory_return_size((const char **) &ddata,
                           image_data_offset(idata[actual].owner, actual),
                           &real_width,
                           &real_height);
  }

  /* The image may have a specific width and height given in */
  /* the HTML.                                               */

  if (tp->tagno != TAG_INPUT)
  {
    /* The OBJECT macros work for IMGs as well as OBJECTs */

    if (OBJECT_HAS_WIDTH(tp))
    {
      switch (OBJECT_WIDTH_UNITS(tp))
      {
        default:
        case UNITS_PIXELS:  width_os = OBJECT_WIDTH(tp) * 2; break;
        case UNITS_PERCENT: width_os = awidth * OBJECT_WIDTH(tp) / 100; break;
      }
    }

    if (OBJECT_HAS_HEIGHT(tp))
    {
      switch (OBJECT_HEIGHT_UNITS(tp))
      {
        default:
        case UNITS_PIXELS:  height_os = OBJECT_HEIGHT(tp) * 2; break;
        case UNITS_PERCENT: height_os = aheight * OBJECT_HEIGHT(tp) / 100; break;
      }
    }
  }

  /* If width and height are both <= zero, try to find them out */
  /* from the image data itself                                 */

  if (width_os <= 0 && height_os <= 0)
  {
    if (real_width > 0 && real_height > 0)
    {
      width_os  = real_width;
      height_os = real_height;
    }
  }

  /* If width and height are still both <= zero, must go for a */
  /* default placeholder size instead.                         */

  if (width_os <= 0 && height_os <= 0) goto image_get_image_size_placeholder;

  /* We may have final values... */

  if (width_os > 0 && height_os > 0)
  {
    box->xmax = width_os;
    box->ymax = height_os;

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

    return NULL;
  }

  /* Otherwise, scale one from the other if possible - for this we must */
  /* have a real image size to get the proportions from                 */

  if (real_width <= 0 || real_height <= 0) goto image_get_image_size_placeholder;

  /* We know the true image size and can thus scale whichever dimension is */
  /* missing for the on-page size from the proportions of the real image.  */

  if (width_os <= 0)
  {
    /* Work out width based on the height */

    width_os = (height_os * real_width) / real_height;
  }
  else
  {
    /* Work out height based on the width */

    height_os = (width_os * real_height) / real_width;
  }

  /* We should now have both values, but if not, drop through to the */
  /* placeholder size routine.                                       */

  if (width_os > 0 && height_os > 0)
  {
    box->xmax = width_os;
    box->ymax = height_os;

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

    return NULL;
  }

image_get_image_size_placeholder:
4312 4313

  {
4314 4315
    /* Don't have precise image dimensions, so work it out from */
    /* any ALT text present or go for a default value.          */
4316

4317 4318
    HStream    * tp = NULL;
    const char * text;
4319 4320 4321

    if (image >= 0) tp = idata[image].token;

4322
    text = (ISOBJECT(tp)) ? HtmlOBJECTstandby(tp) : tp->text;
4323

4324
    reformat_get_placeholder_size(b, tp, text, box);
4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344
  }

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

  return NULL;
}

/*************************************************/
/* image_get_token_image_size()                  */
/*                                               */
/* As image_get_image_size above, but takes a    */
/* token address rather than an image number.    */
/* The default 'unknown' image size will be      */
/* returned if no image could be associated with */
/* the token (no error will be raised).          */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
4345
/*                                               */
4346
/*             A token address;                  */
4347
/*                                               */
4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367
/*             Pointer to a BBox into which the  */
/*             size information is placed.       */
/*                                               */
/* Assumes:    The BBox pointer is not NULL.     */
/*************************************************/

_kernel_oserror * image_get_token_image_size(browser_data * b, HStream * token, BBox * box)
{
  int image;

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

  image = image_get_token_image_actual(b, token);

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_get_token_image_size: Exitting through image_get_image_size\n");
  #endif

4368
  return image_get_image_size(b, image, box, 0);
4369 4370
}

4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468
/*************************************************/
/* image_set_image_size()                        */
/*                                               */
/* Sets the size of an image (currw, currh       */
/* fields) in OS units.                          */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             The image number, from 0 to       */
/*             nimages - 1, which may just be a  */
/*             cross referencing image (i.e. has */
/*             no directly associated data);     */
/*                                               */
/*             Pointer to a BBox from which the  */
/*             size information is read (xmax -  */
/*             xmin, ymax - ymin).               */
/*                                               */
/* Assumes:    The BBox pointer is not NULL.     */
/*************************************************/

static _kernel_oserror * image_set_image_size(browser_data * b, int image, BBox * box)
{
  #ifdef TRACE

    if (tl & (1u<<15)) Printf("image_set_image_size: Called for image %d\n",image);

    if (!box)
    {
      erb.errnum = Utils_Error_Custom_Normal;
      strcpy(erb.errmess,"Null pointer to BBox given to image_set_image_size");
      return &erb;
    }

    if (image < 0)
    {
      erb.errnum = Utils_Error_Custom_Normal;
      sprintf(erb.errmess,"Invalid image number %d passed to image_set_image_size (nimages = %d)", image, nimages);
      return &erb;
    }
    if (image > nimages)
    {
      erb.errnum = Utils_Error_Custom_Normal;
      sprintf(erb.errmess,"Out of range image number %d passed to image_set_image_size (nimages = %d)", image, nimages);
      return &erb;
    }

  #else

    if (image < 0 || image >= nimages) return NULL;

  #endif

  idata[image].currw = box->xmax - box->xmin;
  idata[image].currh = box->ymax - box->ymin;

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

  return NULL;
}

/*************************************************/
/* image_set_token_image_size()                  */
/*                                               */
/* As image_set_image_size above, but takes a    */
/* token address rather than an image number.    */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             A token address;                  */
/*                                               */
/*             Pointer to a BBox from which the  */
/*             size information is read (xmax -  */
/*             xmin, ymax - ymin).               */
/*                                               */
/* Assumes:    The BBox pointer is not NULL.     */
/*************************************************/

_kernel_oserror * image_set_token_image_size(browser_data * b, HStream * token, BBox * box)
{
  int image;

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

  image = image_get_token_image_actual(b, token);

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_set_token_image_size: Exitting through image_set_image_size\n");
  #endif

  return image_set_image_size(b, image, box);
}

4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518
/*************************************************/
/* image_get_token_actual_size()                 */
/*                                               */
/* Returns the width and height of an image, in  */
/* pixels, or 0 and 0 if it the size isn't known */
/* yet.                                          */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             A token address;                  */
/*                                               */
/*             Pointer to an int, in which the   */
/*             width is written;                 */
/*                                               */
/*             Pointer to an int, in which the   */
/*             height is written.                */
/*                                               */
/* Assumes:    All pointers are non-NULL and     */
/*             valid.                            */
/*************************************************/

void image_get_token_actual_size(browser_data * b, HStream * token, int * w, int * h)
{
  int image;

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

  image = image_get_token_image_xref(b, token);

  if (idata[image].istore)
  {
    *w = idata[image].istore -> width_os  / 2;
    *h = idata[image].istore -> height_os / 2;
  }
  else
  {
    *w = 0;
    *h = 0;
  }

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_get_token_actual_size: Exitting with width %d, height %d\n", *w, *h);
  #endif

  return;
}

4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538
/*************************************************/
/* image_get_back_image_size()                   */
/*                                               */
/* Finds out the size of the background image in */
/* OS units.                                     */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the background image; */
/*             Pointer to a BBox into which the  */
/*             size information is placed.       */
/*                                               */
/* Assumes:    That neither pointer is NULL.     */
/*************************************************/

_kernel_oserror * image_get_back_image_size(browser_data * b, BBox * box)
{
  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_get_back_image_size: Called, exitting through image_get_image_size\n");
  #endif

4539
  return (image_get_image_size(b, b->background_image, box, 1));
4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615
}

/*************************************************/
/* image_get_token_image_position()              */
/*                                               */
/* Returns the x and y fields of the image_info  */
/* structure for a given image.                  */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Pointer to the token representing */
/*             the image;                        */
/*                                               */
/*             Pointer to an int, in which the   */
/*             X coordinate is returned;         */
/*                                               */
/*             Pointer to an int, in which the   */
/*             Y coordinate is returned.         */
/*                                               */
/* Returns:    1 if the image could not be found */
/*             from the given token, or 0 for    */
/*             success.                          */
/*                                               */
/* Assumes:    Neither pointer is NULL.          */
/*************************************************/

int image_get_token_image_position(browser_data * b, HStream * t, int * x, int * y)
{
  int image = image_get_token_image_actual(b, t);

  if (image < 0) return 1;

  *x = idata[image].x;
  *y = idata[image].y;

  return 0;
}

/*************************************************/
/* image_set_token_image_position()              */
/*                                               */
/* Sets the x and y fields of the image_info     */
/* structure for a given image, so that it may   */
/* be [partially] plotted during a fetch.        */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Pointer to the token representing */
/*             the image;                        */
/*                                               */
/*             X coordinate (window coords);     */
/*                                               */
/*             Y coordinate (window coords).     */
/*                                               */
/* Returns:    Number of the image that was      */
/*             changed, or -1 if none could be   */
/*             found for the given token.        */
/*************************************************/

int image_set_token_image_position(browser_data * b, HStream * t, int x, int y)
{
  int image = image_get_token_image_actual(b, t);

  /* If an image was found, set the x and y coordinates */

  if (image >= 0)
  {
    idata[image].x = x;
    idata[image].y = y;
  }

  return image;
}

4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664
/*************************************************/
/* image_get_background_image_url()              */
/*                                               */
/* Returns the URL of a browser's current        */
/* background image.                             */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the background;       */
/*                                               */
/*             Pointer to a buffer to take the   */
/*             URL;                              */
/*                                               */
/*             Size of the buffer.               */
/*************************************************/

void image_get_background_image_url(browser_data * b, char * buffer, int size)
{
  int offset;
  int old_budge;
  int image = b ? b->background_image : -1;

  if (!buffer || size < 1) return;

  *buffer = 0;

  if (size < 2 || image < 0 || image >= nimages) return;

  /* Find the offset of the URL in the 'ddata' block */

  offset = image_data_offset(b, image);

  /* Lock flex */

  old_budge = flex_set_budge(0);

  /* Copy the URL in, ensuring termination */

  strncpy(buffer, ddata + offset, size);
  buffer[size - 1] = 0;

  /* Restore flex's previous budge state */

  flex_set_budge(old_budge);

  /* Finished */

  return;
}

4665 4666 4667 4668 4669 4670 4671 4672
/*************************************************/
/* image_convert_to_pixels()                     */
/*                                               */
/* Converts a given OS unit X and Y size to      */
/* pixel size, for a given image.                */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
4673
/*                                               */
4674 4675
/*             Pointer to the token representing */
/*             the image;                        */
4676
/*                                               */
4677 4678 4679 4680
/*             Pointer to an int which already   */
/*             contains the X size in OS units,  */
/*             which will have the pixel size    */
/*             returned into it;                 */
4681
/*                                               */
4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718
/*             A similar pointer for the Y size. */
/*                                               */
/* Assumes:    That no pointer is NULL.          */
/*************************************************/

void image_convert_to_pixels(browser_data * b, HStream * token, int * x, int * y)
{
  int image;

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

  image = image_get_token_image_xref(b, token);

  /* If the library has got enough information to fill in the */
  /* width of the image, proceed with the conversion          */

  if (image >= 0 && idata[image].istore->width > 0)
  {
    *x = *x * idata[image].istore->width  / idata[image].istore->width_os;
    *y = *y * idata[image].istore->height / idata[image].istore->height_os;
  }
  else
  {
    /* Can't find image - maybe it's not loaded... Assume 2 OS units per pixel. */

    *x = *x / 2;
    *y = *y / 2;
  }

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_convert_to_pixels: Successful\n");
  #endif
}

/*************************************************/
4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776
/* image_return_click_offset()                   */
/*                                               */
/* Calculate the coordinates of a click on an    */
/* image in pixels from the top left corner, as  */
/* required by image maps and image input        */
/* fields.                                       */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Pointer to a token representing   */
/*             the image;                        */
/*                                               */
/*             A WimpGetPointerInfo block        */
/*             pointer describing the mouse      */
/*             pointer's position;               */
/*                                               */
/*             Pointer to an int, in which the   */
/*             x offset is returned;             */
/*                                               */
/*             Pointer to an int, in which the   */
/*             y offset is returned.             */
/*                                               */
/* Assumes:    That the int pointers are not     */
/*             NULL.                             */
/*************************************************/

_kernel_oserror * image_return_click_offset(browser_data * b, HStream * t, WimpGetPointerInfoBlock * i, int * x, int * y)
{
  _kernel_oserror         * e;
  WimpGetWindowStateBlock   s;
  BBox                      box;

  /* Get the image's size and position on screen */

  s.window_handle = b->window_handle;

  e = wimp_get_window_state(&s);
  if (e) return e;

  e = image_get_token_image_size(b, t, &box);
  if (e) return e;

  if (image_get_token_image_position(b, t, x, y)) return NULL;

  *x = coords_x_toscreen(*x, (WimpRedrawWindowBlock *) &s);
  *y = coords_y_toscreen(*y, (WimpRedrawWindowBlock *) &s);

  /* Get the offset of the pointer position from the top left */
  /* of the image in ox and oy                                */

  *x = i->x - *x;
  *y = *y + (box.ymax - box.ymin) - i->y;

  image_convert_to_pixels(b, t, x, y);

  return NULL;
}
4777 4778

/*************************************************/
4779
/* image_can_be_saved_as_sprite                  */
4780
/*                                               */
4781 4782 4783
/* Returns 1 if a given image has data and can   */
/* be saved (the DumpSprite function is          */
/* present), else 0.                             */
4784
/*                                               */
4785 4786 4787
/* The image may cross reference another with    */
/* the actual data. If so, the return value will */
/* be referring to that cross referenced image.  */
4788
/*                                               */
4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823
/* Parameters: Pointer to a browser_data struct  */
/*             owning the image;                 */
/*                                               */
/*             Number of the image.              */
/*                                               */
/* Returns:    1 if the image can be saved as a  */
/*             sprite, else 0.                   */
/*************************************************/

static int image_can_be_saved_as_sprite(browser_data * b, int i)
{
  if (
       idata[i].istore                &&
       idata[i].istore->DumpSprite    &&
       idata[i].istore->width_os > 0  &&
       idata[i].istore->height_os > 0
     )
     return 1;

  return 0;
}

/*************************************************/
/* image_token_can_be_saved_as_sprite            */
/*                                               */
/* Returns 1 if a given image has data and can   */
/* be saved (the DumpSprite function is          */
/* present), else 0.                             */
/*                                               */
/* The image may cross reference another with    */
/* the actual data. If so, the return value will */
/* be referring to that cross referenced image.  */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             owning the image;                 */
4824 4825 4826 4827
/*                                               */
/*             Pointer to the token representing */
/*             the image, or NULL for the page's */
/*             background image.                 */
4828 4829 4830
/*                                               */
/* Returns:    1 if the image can be saved as a  */
/*             sprite, else 0.                   */
4831 4832
/*************************************************/

4833
int image_token_can_be_saved_as_sprite(browser_data * b, HStream * image)
4834 4835 4836 4837 4838
{
  int i;

  /* Find the image number */

4839
  if (!image) i = b->background_image;
4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850
  else        i = image_get_token_image_xref(b, image);

  /* Complain if we can't in TRACE builds */

  if (i < 0)
  {
    #ifdef TRACE

      erb.errnum = Utils_Error_Custom_Normal;

      sprintf(erb.errmess,
4851
              "In image_token_can_be_saved_as_sprite, can't find an image that is represented by the token %p for the browser %p.",
4852 4853 4854
              image,
              b);

4855
      show_error_ret(&erb);
4856 4857 4858

    #endif

4859
    return 0;
4860 4861
  }

4862
  /* Can it be saved? */
4863

4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886
  return image_can_be_saved_as_sprite(b, i);
}

/*************************************************/
/* image_export_sprite()                         */
/*                                               */
/* Saves an image represented by the given token */
/* as a sprite at the given path.                */
/*                                               */
/* Parameters: Pointer to the path to save to;   */
/*                                               */
/*             Pointer to a browser_data struct  */
/*             that owns the image;              */
/*                                               */
/*             Pointer to the token representing */
/*             the image, or NULL for the page's */
/*             background image.                 */
/*************************************************/

_kernel_oserror * image_export_sprite(char * path, browser_data * b, HStream * image)
{
  int i;

4887 4888 4889 4890
  if (!path || !*path) return NULL;

  save_record_path(path);

4891 4892
  /* Find the image number */

4893
  if (!image) i = b->background_image;
4894 4895 4896 4897 4898
  else        i = image_get_token_image_xref(b, image);

  /* Must have image data... */

  if (!image_can_be_saved_as_sprite(b, i))
4899 4900 4901 4902 4903 4904
  {
    #ifdef TRACE

      erb.errnum = Utils_Error_Custom_Normal;

      sprintf(erb.errmess,
4905
              "There is no data for this image in image_export_sprite.");
4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935

      return &erb;

    #endif

    return NULL;
  }

  /* Export the image */

  return idata[i].istore -> DumpSprite(idata[i].istore,
                                       path,
                                       -1);
}

/*************************************************/
/* image_sprite_size()                           */
/*                                               */
/* Returns the size that the given image would   */
/* be as a sprite on disc.                       */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             that owns the image;              */
/*                                               */
/*             Pointer to the token representing */
/*             the image, or NULL for the page's */
/*             background image.                 */
/*                                               */
/* Returns:    The size the image would be as a  */
/*             sprite file saved to disc, in     */
4936
/*             bytes (a guess only).             */
4937 4938 4939 4940 4941 4942
/*************************************************/

int image_sprite_size(browser_data * b, HStream * image)
{
  /* ...And for now, we don't know. */

4943
  return 4096;
4944
}
4945

4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107
/*************************************************/
/* image_export_original()                       */
/*                                               */
/* Saves an image represented by the given token */
/* in its original format to the given path.     */
/*                                               */
/* Parameters: Pointer to the path to save to;   */
/*                                               */
/*             Pointer to a browser_data struct  */
/*             that owns the image;              */
/*                                               */
/*             Pointer to the token representing */
/*             the image, or NULL for the page's */
/*             background image.                 */
/*************************************************/

_kernel_oserror * image_export_original(char * path, browser_data * b, HStream * image)
{
  char url[Limits_URL];
  int  i, offset;

  if (!path || !*path) return NULL;

  save_record_path(path);

  /* Find the image number */

  if (!image) i = b->background_image;
  else        i = image_get_token_image_xref(b, image);

  /* Must have image data... */

  offset = image_data_offset(b, i);

  if (!ddata[offset])
  {
    #ifdef TRACE

      erb.errnum = Utils_Error_Custom_Normal;

      sprintf(erb.errmess,
              "There is no URL for this image in image_export_original.");

      return &erb;

    #endif

    return NULL;
  }

  /* Start a fetch for this URL */

  strncpy(url, ddata + offset, sizeof(url));
  url[sizeof(url) - 1] = 0;

  RetError(windows_create_browser(url,
                                  NULL,
                                  NULL,
                                  NULL,
                                  Windows_CreateBrowser_SaveToFile));

  /* Set the title to the save pathname */

  {
    char title[Limits_Title];

    StrNCpy0(title, path);

    /* Don't treat any errors here as fatal */

    show_error_ret(window_set_title(0, last_browser->self_id, title));
  }

  /* Open the file */

  last_browser->save_file = fopen(path, "wb");

  if (!last_browser->save_file)
  {
    fetch_stop(last_browser, 0);
    RetLastE;
  }
  else
  {
    int bytes;

    /* Set the filetype to DEADDEAD, to represent an incomplete */
    /* file (particularly good on later Filers, which display   */
    /* a special sprite for this).                              */

    _swix(OS_File,
          _INR(0,2),

          2, /* Set load address */
          path,
          0xdeaddead);

    _swix(OS_File,
          _INR(0,1) | _IN(3),

          3, /* Set exec address */
          path,
          0xdeaddead);

    if (last_browser->source)
    {
        /* Any data in the source store represents already */
        /* fetched bits of the file. Must lock flex down   */
        /* over the save to make sure the heap doesn't     */
        /* shift over the call to fwrite.                  */

        flex_set_budge(0);

        bytes = fwrite(last_browser->source,
                       1,
                       flex_size((flex_ptr) &last_browser->source),
                       last_browser->save_file);

        flex_set_budge(1);

      /* If we didn't transfer as much as we expected, complain */

      if (bytes != flex_size((flex_ptr) &last_browser->source))
      {
        /* Report any errors */

        fetch_stop(last_browser, 0);
        RetLastE;
      }
      else
      {
        /* Otherwise, get rid of the data in the source store */
        /* as it's been written to the file.                  */

        flex_free((flex_ptr) &last_browser->source);
        last_browser->source = NULL;
      }
    }
  }

  return NULL;
}

/*************************************************/
/* image_original_size()                         */
/*                                               */
/* Returns the size of a given image in its      */
/* original format.                              */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             that owns the image;              */
/*                                               */
/*             Pointer to the token representing */
/*             the image, or NULL for the page's */
/*             background image.                 */
/*                                               */
/* Returns:    The size of the original image,   */
/*             in bytes (a guess only).          */
/*************************************************/

int image_original_size(browser_data * b, HStream * image)
{
5108
  int size = image_draw_file_size(b, image, 0);
5109

5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430
  if (size <= 0) return 0;
  else           return size + 12;
}

/*************************************************/
/* image_to_draw_file()                          */
/*                                               */
/* As image_redraw, but will output a sprite     */
/* to the Draw file being output by SaveDraw.c   */
/* (which must be active at the time this is     */
/* called). Assumes that the appropriate Draw    */
/* file object header has already been written.  */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Pointer to a RedrawWindowBlock    */
/*             struct which holds information    */
/*             about the current redraw session; */
/*                                               */
/*             Address of the token representing */
/*             the image;                        */
/*                                               */
/*             The X offset in window coords (so */
/*             OS units) of the left hand edge   */
/*             of the image;                     */
/*                                               */
/*             The Y offset in window coords (so */
/*             OS units) of the bottom edge of   */
/*             the image;                        */
/*                                               */
/*             1 to assume the image is already  */
/*             present as a sprite in            */
/*             'unique_name' else create the     */
/*             image first.                      */
/*                                               */
/* Returns:    0 if failed, 1 if successful; if  */
/*             failed, caller should try some    */
/*             alternative representation (e.g.  */
/*             write out a placeholder).         */
/*************************************************/

int image_to_draw_file(browser_data * b, WimpRedrawWindowBlock * r, HStream * token, int x, int y, int dont_create)
{
  int image, actual;
  int plotted = 0;

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_to_draw_file: Called with token %d\n", token);
  #endif

  /* Get the image number for the given token; 'actual' holds the actual */
  /* image for the given token, which may cross reference 'image', which */
  /* holds the actual render data.                                       */

  image = image_get_token_image_actual(b, token);

  if (image < 0) return NULL;

  actual = image;
  if (idata[actual].xref >= 0) image = idata[actual].xref;

  /* If the image has a fetched width and height, */
  /* and the browser choices specify that images  */
  /* should be shown (or the image itself has a   */
  /* high priority show bit set), display part or */
  /* all of the image.                            */

  if (
       image  >= 0 &&
       actual >= 0 &&
       (
         b->show_foreground                     ||
         b->displayed == Display_External_Image ||
         idata[actual].priority
       )
       && idata[actual].canredraw
       && idata[image].istore             /* Must check istore here, as if width / height are <= 0, */
       && idata[image].istore->width  > 0 /* the image library has no data for the image and will   */
       && idata[image].istore->height > 0 /* not have filled in (e.g.) the Render field. So you'd   */
       && idata[image].istore->DumpSprite /* get a rather nasty abort trying to call it!            */
       && image_can_be_saved_as_sprite(b, image)

//       && idata[image].istore->StartExport
//       && idata[image].istore->Export
//       && idata[image].istore->EndExport
     )
  {
    FILE            * input = NULL;
    _kernel_oserror * e     = NULL;

    int               written, ok;
    char              buffer[10240];

//    int               image_size = 0;

    browser_redrawing = b;
    image_redrawing   = actual;

    if (!dont_create || !unique_name)
    {
      unique_name = malloc(Limits_OS_Pathname);

      if (unique_name)
      {
        protocols_util_make_unique_name(unique_name, Limits_OS_Pathname);

        /* Output the sprite, skipping the first 12 bytes of sprite area header */

        e = idata[image].istore -> DumpSprite(idata[image].istore,
                                              unique_name,
                                              -1);
      }
    }

    if (e || !unique_name) ok = 0;
    else
    {
      ok = 1;

      input = fopen(unique_name, "rb");

      if (!input || !input->__file) ok = 0;
    }

    if (ok)
    {
      e = _swix(OS_Args,
                _INR(0,2),

                1,
                input->__file,
                12);

      if (e) ok = 0;
    }

    if (ok)
    {
      do
      {
        e = _swix(OS_GBPB,
                  _INR(0,3) | _OUT(3),

                  4,
                  input->__file,
                  buffer,
                  sizeof(buffer),

                  &written);

        if (!e && written < sizeof(buffer)) ok = savedraw_write_bytes(buffer, sizeof(buffer) - written);
        else                                ok = e ? 0 : 1;
      }
      while (!e && written < sizeof(buffer));
    }

    if (input)
    {
      fclose(input);

      if (unique_name) remove(unique_name);

      free(unique_name);
      unique_name = NULL;
    }

//    e       = idata[image].istore -> StartExport(idata[image].istore, &image_size);
//    ok      = 1;
//
//    written = 12;
//    e       = idata[image].istore -> Export(idata[image].istore, buffer, &written);
//
//    while (!e && ok && written)
//    {
//      written = sizeof(buffer);
//
//      e = idata[image].istore -> Export(idata[image].istore, buffer, &written);
//
//      if (!e) ok = savedraw_write_bytes(buffer, written);
//      else    ok = 0;
//    }
//
//    e = idata[image].istore -> EndExport(idata[image].istore);

    /* Flag if we succeeded */

    browser_redrawing = NULL;
    image_redrawing   = -1;

    if (!e && ok) plotted = 1;
  }

  #ifdef TRACE
    if (tl & (1u<<15)) Printf("image_to_draw_file: Exitting with %d\n", plotted);
  #endif

  return plotted;
}

/*************************************************/
/* image_draw_file_size()                        */
/*                                               */
/* Returns the amount of data that               */
/* image_to_draw_file would write to the output  */
/* file.                                         */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the image;            */
/*                                               */
/*             Address of the token representing */
/*             the image;                        */
/*                                               */
/*             1 to not delete the scrap file    */
/*             in 'unique_name' that this        */
/*             writes, else 0.                   */
/*                                               */
/* Returns:    0 if failed, else the amount of   */
/*             data that image_to-draw_file      */
/*             would write to the output file.   */
/*************************************************/

int image_draw_file_size(browser_data * b, HStream * token, int dont_delete)
{
  int image, actual;

  /* Get the image number for the given token; 'actual' holds the actual */
  /* image for the given token, which may cross reference 'image', which */
  /* holds the actual render data.                                       */

  image = image_get_token_image_actual(b, token);

  if (image < 0) return NULL;

  actual = image;
  if (idata[actual].xref >= 0) image = idata[actual].xref;

  /* If the image has a fetched width and height, */
  /* and the browser choices specify that images  */
  /* should be shown (or the image itself has a   */
  /* high priority show bit set), display part or */
  /* all of the image.                            */

  if (
       image  >= 0 &&
       actual >= 0 &&
       (
         b->show_foreground                     ||
         b->displayed == Display_External_Image ||
         idata[actual].priority
       )
       && idata[actual].canredraw
       && idata[image].istore             /* Must check istore here, as if width / height are <= 0, */
       && idata[image].istore->width  > 0 /* the image library has no data for the image and will   */
       && idata[image].istore->height > 0 /* not have filled in (e.g.) the Render field. So you'd   */
       && idata[image].istore->DumpSprite /* get a rather nasty abort trying to call it!            */
       && image_can_be_saved_as_sprite(b, image)

//       && idata[image].istore->StartExport
//       && idata[image].istore->Export
//       && idata[image].istore->EndExport
     )
  {
    _kernel_oserror * e          = NULL;
    int               image_size = 0;

    if (unique_name)
    {
      remove(unique_name);

      free(unique_name);
      unique_name = NULL;
    }

    unique_name = malloc(Limits_OS_Pathname);

    if (unique_name)
    {
      protocols_util_make_unique_name(unique_name, Limits_OS_Pathname);

      e = idata[image].istore -> DumpSprite(idata[image].istore,
                                            unique_name,
                                            -1);
    }

    if (!e && unique_name)
    {
      e = _swix(OS_File,
                _INR(0,1) | _OUT(4),

                17,
                unique_name,

                &image_size);

      if (!dont_delete)
      {
        remove(unique_name);

        free(unique_name);
        unique_name = NULL;
      }
    }

//    e = idata[image].istore -> StartExport(idata[image].istore, &image_size);
//
//    if (!e) idata[image].istore -> EndExport(idata[image].istore);

    /* Remember, we'd skip the first 12 bytes of sprite area header */
    /* in the output Draw file.                                     */

    if (!e && image_size > 12) return image_size - 12;
  }

  return 0;
}

/*************************************************/
/* image_tile_to_draw()                          */
/*                                               */
/* For a given redraw rectangle, tiles the       */
5431 5432
/* background image within that rectangle to a   */
/* Draw file.                                    */
5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the window and image; */
/*                                               */
/*             Pointer to a WimpRedrawWindow-    */
/*             Block structure defining the area */
/*             over which to tile the image;     */
/*                                               */
/*             The X and Y coordinates to take   */
/*             as the tile origin, in OS units;  */
/*                                               */
/*             Pointer to an int if wanting to   */
/*             know the size of the item only,   */
/*             else NULL (NB the int contents    */
/*             are not updated - the pointer is  */
/*             acting like a flag, basically).   */
/*                                               */
/* Returns:    0 if failed, else the amount of   */
/*             data that was output.             */
/*************************************************/

int image_tile_to_draw(browser_data * b, WimpRedrawWindowBlock * r, int xorigin, int yorigin, int * size)
{
  char              name[Limits_OS_Pathname];
  _kernel_oserror * e;
  FILE            * input = NULL;
  void            * block = NULL;
  int               image;
  int               tsize = 0;
  int               x, y, w, h;
  int               xmin, ymax;
  int               image_size;

  /* Can only tile if there's a background image defined and fully fetched */

  if (b->background_image < 0) return 0;

  image = b->background_image;
  if (idata[image].xref >= 0) image = idata[image].xref;

  if (!idata[image].fetched || !idata[image].istore) return 0;

  /* Round the width and height to pixel boundaries */

5477 5478
  w = idata[image].istore->width_os  & ~1;
  h = idata[image].istore->height_os & ~1;
5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640

  if (w < 1 || h < 1) return 0;

  /* Work out the coordinates over which to tile the image */

  xmin = coords_x_toworkarea(r->redraw_area.xmin,r);
  ymax = coords_y_toworkarea(r->redraw_area.ymax,r);

  xmin -= ((xmin - xorigin) % w);
  ymax -= ((ymax - yorigin) % h) + 1;

  xmin = coords_x_toscreen(xmin, r);
  ymax = coords_y_toscreen(ymax, r);

  /* Do a blank rectangle if the image is transparent (has a mask) */

  if (idata[image].istore->transparent)
  {
    redraw_set_colour(redraw_backcol(b));

    tsize += DSIZE_FRECT;

    if (!size)
    {
      if (!savedraw_rectangle_fill(OTD(r->redraw_area.xmin),
                                   OTD(r->redraw_area.ymin),
                                   OTD(r->redraw_area.xmax - r->redraw_area.xmin),
                                   OTD(r->redraw_area.ymax - r->redraw_area.ymin),
                                   redraw_backcol(b))) return 0;
    }
  }

  /* How big is each image going to be? */

  protocols_util_make_unique_name(name, sizeof(name));

  e = idata[image].istore -> DumpSprite(idata[image].istore,
                                        name,
                                        -1);

  if (!e)
  {
    e = _swix(OS_File,
              _INR(0,1) | _OUT(4),

              17,
              name,

              &image_size);
  }

  if (e || image_size <= 12) return 0;

  /* Subtract the sprite file header size */

  image_size -= 12;

  input = fopen(name, "rb");
  block = malloc(image_size);

  if (block && input && input->__file)
  {
    /* Load the image */

    e = _swix(OS_Args,
              _INR(0,2),

              1,
              input->__file,
              12);

    if (e) goto image_tile_to_draw_exit;

    e = _swix(OS_GBPB,
              _INR(0,3),

              4,
              input->__file,
              block,
              image_size);

    if (e) goto image_tile_to_draw_exit;

    fclose(input);
    input = NULL;

    /* Render the image over the redraw region */

    for (y = ymax - h + 4; y >= r->redraw_area.ymin - h; y -= h)
    {
      for (x = xmin; x <= r->redraw_area.xmax; x += w)
      {
        if (!size)
        {
          draw_spristrhdr hdr;
          int             ok;

          /* Write the item header */

          hdr.tag  = draw_OBJSPRITE;
          hdr.size = image_size + sizeof(hdr);

          hdr.bbox.xmin = OTD(x);
          hdr.bbox.ymin = OTD(y);
          hdr.bbox.xmax = OTD(x + w);
          hdr.bbox.ymax = OTD(y + h);

          if (!savedraw_write_bytes((char *) &hdr, sizeof(hdr))) goto image_tile_to_draw_exit;

          /* Write out the image */

          browser_redrawing = b;
          image_redrawing   = image;

          ok = savedraw_write_bytes(block, image_size);

          browser_redrawing = NULL;
          image_redrawing   = -1;

          if (!ok) goto image_tile_to_draw_exit;

          #ifdef STRICT_PARSER

            if (e)
            {
              e->errnum = Utils_Error_Custom_Message;
              show_error_ret(e);

              goto image_tile_to_draw_exit;
            }

          #else

            if (e) goto image_tile_to_draw_exit;

          #endif
        }

        tsize += image_size + sizeof(draw_spristrhdr);
      }
    }
  }

  /* Successful exit */

  if (input) fclose(input);
  if (block) free(block);

  remove(name);

  return tsize;

  /* Error condition exit */

image_tile_to_draw_exit:

  if (input) fclose(input);
  if (block) free(block);

  remove(name);

  return 0;
5641
}