Utils 98.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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.
 */
15 16 17 18 19 20 21 22 23
/***************************************************/
/* File   : Utils.c                                */
/*                                                 */
/* Purpose: Infrequently altered utilities.        */
/*                                                 */
/* Author : A.D.Hodgkinson                         */
/*                                                 */
/* History: 18-Oct-96: Created.                    */
/***************************************************/
24 25 26 27 28 29 30

#include "setjmp.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
31
#include <ctype.h>
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

#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 "swis.h"
#include "kernel.h"

#include "toolbox.h"
#include "event.h"
#include "quit.h"
#include "proginfo.h"
#include "window.h"
#include "gadgets.h"

#include "ToolAction.h" /* NOT the proper Toolbox header, as this needed OSLib... */

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

56
#include "Main.h"
57
#include "NestWimp.h"
58
#include "Save.h"
59
#include "Toolbars.h"
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

/* Debug build includes */

#ifdef TRACE

  /* Needed to check conversion to millipoints routines don't overflow */

  #include <math.h>

#endif

/* Finally, Utils.h itself */

#include "Utils.h"

75 76
/* Local definitions */

77 78 79
#define Acorn_Agent_Start     "Acorn-"
#define Acorn_Agent_Middle    " (RISC OS "
#define Acorn_Agent_End       ")"
80 81 82 83

#define Netscape_Agent_Start  "Mozilla/4.01 (Compatible; Acorn "
#define Netscape_Agent_Middle "; RISC OS "
#define Netscape_Agent_End    ")"
84 85 86 87 88

#define MillipointsPerOSUnit 400

/* Locals */

89
static int  millipoints_per_os_unit_x = 400; /* See read_os_to_points */
90 91 92 93 94 95
static int  millipoints_per_os_unit_y = 400;
static int  half_mppou_x              = 200;
static int  half_mppou_y              = 200;
static int  overflow_limit_x          = 0x28f5c1; /* = (0x3fffffff / 400) rounded down for caution*/
static int  overflow_limit_y          = 0x28f5c1;

96 97 98 99
/* Static function prototypes */

static char * lookup_in_given (MessagesFD * control, char * s, int flag, char * arg);

100
/*************************************************/
101 102 103 104 105 106 107 108 109 110 111 112 113 114
/* lookup_token()                                */
/*                                               */
/* Returns a pointer to an expanded message      */
/* token, or '!' if there was an error.          */
/*                                               */
/* NB, due to various limitations of C, the      */
/* lookup is done into a global fixed-size       */
/* buffer. So if you pass multiple calls to this */
/* function in as parameters to something else,  */
/* *it will fail* as each call points to the     */
/* same buffer (which will only contain data     */
/* from the last call).                          */
/*                                               */
/* Parameters: Pointer to a message token;       */
115
/*                                               */
116 117 118
/*             1 to report an error if the token */
/*             isn't found as well as returning  */
/*             a string of '!', else 0;          */
119
/*                                               */
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
/*             An optional pointer to an         */
/*             argument to substitute into the   */
/*             looked up string, or NULL.        */
/*                                               */
/* Returns:    Pointer to the full message text  */
/*             or '!' to signal an error; never  */
/*             a null pointer.                   */
/*                                               */
/* Assumes:    That the pointer to the message   */
/*             token is never NULL.              */
/*************************************************/

char * lookup_token(char * s, int flag, char * arg)
{
  #ifdef TRACE
135
    if (tl & (1u<<0)) Printf("lookup_token: Called, exitting through lookup_in_given\n");
136 137
  #endif

138 139
  return lookup_in_given(&meb, s, flag, arg);
}
140

141 142 143 144 145 146 147 148 149 150 151 152 153
/*************************************************/
/* lookup_choice()                               */
/*                                               */
/* As lookup_token, but looks up the token in    */
/* the Choices file, rather than the Messages    */
/* file.                                         */
/*                                               */
/* Parameters: As lookup_token.                  */
/*                                               */
/* Returns:    As lookup_token.                  */
/*                                               */
/* Assumes:    As lookup_token.                  */
/*************************************************/
154

155 156 157 158 159
char * lookup_choice(char * s, int flag, char * arg)
{
  #ifdef TRACE
    if (tl & (1u<<0)) Printf("lookup_choice: Called, exitting through lookup_in_given\n");
  #endif
160

161 162
  return lookup_in_given(chb, s, flag, arg);
}
163

164 165 166 167 168 169 170 171 172 173 174 175 176
/*************************************************/
/* lookup_control()                              */
/*                                               */
/* As lookup_token, but looks up the token in    */
/* the Controls file, rather than the Messages   */
/* file.                                         */
/*                                               */
/* Parameters: As lookup_token.                  */
/*                                               */
/* Returns:    As lookup_token.                  */
/*                                               */
/* Assumes:    As lookup_token.                  */
/*************************************************/
177

178 179
char * lookup_control(char * s, int flag, char * arg)
{
180
  #ifdef TRACE
181
    if (tl & (1u<<0)) Printf("lookup_control: Called, exitting through lookup_in_given\n");
182 183
  #endif

184
  return lookup_in_given(cob, s, flag, arg);
185 186
}

187
/*************************************************/
188
/* lookup_in_given()                             */
189
/*                                               */
190 191 192
/* Workhorse back-end to lookup_token,           */
/* lookup_choice and so-on. See lookup_token     */
/* for more information.                         */
193
/*                                               */
194 195 196 197 198
/* Parameters: A MessagesFD pointer, giving the  */
/*             control block of the file to      */
/*             look in;                          */
/*                                               */
/*             Pointer to a message token;       */
199
/*                                               */
200 201 202
/*             1 to report an error if the token */
/*             isn't found as well as returning  */
/*             a string of '!', else 0;          */
203
/*                                               */
204 205 206 207 208 209 210 211 212 213 214 215
/*             An optional pointer to an         */
/*             argument to substitute into the   */
/*             looked up string, or NULL.        */
/*                                               */
/* Returns:    Pointer to the full message text  */
/*             or '!' to signal an error; never  */
/*             a null pointer.                   */
/*                                               */
/* Assumes:    That the pointer to the message   */
/*             token is never NULL.              */
/*************************************************/

216
static char * lookup_in_given(MessagesFD * control, char * s, int flag, char * arg)
217 218 219 220
{
  _kernel_oserror * e;

  #ifdef TRACE
221
    if (tl & (1u<<0)) Printf("lookup_in_given: Lookup token '%s'\n",s);
222 223
  #endif

224
  if (strcmp(lasttokn, s))
225 226
  {
    #ifdef TRACE
227
      if (tl & (1u<<0)) Printf("lookup_in_given: Proceeding\n");
228 229 230 231 232 233 234
    #endif

    StrNCpy0(lasttokn, s);

    e = _swix(MessageTrans_Lookup,
              _INR(0,7),

235
              control,            /* Pointer to control block               */
236 237 238 239 240 241 242 243 244
              s,                  /* String to look up                      */
              tokens,             /* Global buffer to take looked up string */
              sizeof(tokens) - 1, /* Size of the buffer                     */
              arg,                /* Parameter 0                            */
              0,                  /* Parameter 1                            */
              0,                  /* Parameter 2                            */
              0);                 /* Parameter 3                            */

    tokens[Limits_Message - 1] = 0;
245 246 247 248 249 250 251

    if (e)
    {
      /* If the lookup fails, put '!' into the lookup buffer and if the */
      /* flag passed into the function is 1, report the error too.      */

      #ifdef TRACE
252
        if (tl & (1u<<0)) Printf("lookup_in_given: Failed\n");
253 254 255 256 257 258 259 260 261 262
      #endif

      *lasttokn = 0;
      strcpy(tokens, "!");

      if (flag == 1) show_error_cont(e);
    }
  }

  #ifdef TRACE
263
    if (tl & (1u<<0)) Printf("lookup_in_given: Returning %s\n",tokens);
264 265 266 267 268 269 270 271
  #endif

  return (char *) &tokens;
}

/*************************************************/
/* show_error()                                  */
/*                                               */
272 273
/* Reports a (generally serious) error and exits */
/* with EXIT_FAILURE.                            */
274
/*                                               */
275 276
/* Parameters: Pointer to a _kernel_oserror      */
/*             structure.                        */
277
/*                                               */
278
/* Assumes:    The pointer may be NULL.          */
279 280 281 282 283 284 285
/*************************************************/

void show_error(_kernel_oserror *e)
{
  if (e!=NULL)
  {
    _kernel_swi_regs r;
286 287
    char             name[Limits_TaskName];
    char             spri[Limits_OS_SpriteName];
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    WimpSysInfo      s;

    /* This call checks if errors can be reported in the Desktop, */
    /* or if they need to go into a command window (useful for    */
    /* CLI routines for example)                                  */

    s.r0=0;
    s.r1=0;
    wimp_read_sys_info(3,&s);

    if (s.r0==0) fprintf(stderr,"%s\n",e->errmess);
    else
    {
      StrNCpy0(name,lookup_token("_TaskName:Browse",0,0));  /* Task name for 'Message from...' */
      StrNCpy0(spri,lookup_token("_SpriName:!browse",0,0)); /* Sprite name to put in error box */

      r.r[0] = (int) e;                                       /* Pointer to error block           */
      r.r[1] = (2<<9)+(1<<8);                                 /* Category 2 (warning)             */
      r.r[2] = (int) &name;                                   /* Application name looked up above */
      r.r[3] = (int) &spri;                                   /* Sprite name looked up above      */
      r.r[4] = 1;                                             /* Sprite block pointer (1 = WIMP)  */
      r.r[5] = (int) lookup_token("ErrorBtns:Quit",0,0);      /* Custom button, 'Quit'            */

      _kernel_swi(Wimp_ReportError,&r,&r);
    }

    exit(EXIT_FAILURE); /* Exit after reporting the error */
  }
}

/*************************************************/
/* show_error_cont()                             */
/*                                               */
/* Reports an error but allows execution to then */
/* continue (rather than calling exit()) if the  */
/* user clicks on 'Continue' rather than 'Quit'. */
/* This is accomplished by a longjmp back into   */
325 326
/* wherever the setjmp was (e.g. in a poll       */
/* loop).                                        */
327
/*                                               */
328 329
/* Parameters: Pointer to a _kernel_oserror      */
/*             structure.                        */
330
/*                                               */
331
/* Assumes:    The pointer may be NULL.          */
332 333 334 335 336 337 338
/*************************************************/

void show_error_cont(_kernel_oserror *e)
{
  if (e!=NULL)
  {
    _kernel_swi_regs r;
339 340
    char             name[Limits_TaskName];
    char             spri[Limits_OS_SpriteName];
341 342 343 344 345 346 347 348 349 350
    WimpSysInfo      s;

    #ifdef TRACE
      if (e->errnum == Utils_Error_Custom_Fatal) e->errnum = Utils_Error_Custom_Normal;
    #endif

    /* Force 'Quit' only for fatal errors */

    if (e->errnum == Utils_Error_Custom_Fatal) show_error(e);

351
    /* This all works in much the same way as show_error above. */
352 353 354 355 356 357 358 359

    s.r0=0;
    s.r1=0;
    wimp_read_sys_info(3,&s);

    if (s.r0==0) fprintf(stderr,"%s\n",e->errmess);
    else
    {
360 361
      StrNCpy0(name, lookup_token("_TaskName:Browse",0,0));
      StrNCpy0(spri, lookup_token("_SpriName:!browse",0,0));
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

      r.r[0] = (int) e;
      r.r[1] = (2<<9)+(1<<8)+1;
      r.r[2] = (int) &name;
      r.r[3] = (int) &spri;
      r.r[4] = 1;

      /* Have a quit button if not running full screen and the */
      /* error number isn't one defined as having a Continue   */
      /* button only.                                          */

      if (
           e->errnum != Utils_Error_OS_Escape      &&
           e->errnum != Utils_Error_Custom_Message &&
           !choices.full_screen
         )
         r.r[5] = (int) lookup_token("ErrorBtns:Quit",0,0);

      else r.r[5] = 0;

      _kernel_swi(Wimp_ReportError,&r,&r);

384 385 386
      if (r.r[1] == 1) longjmp(env, Main_FromShowErrorCont);

      exit(EXIT_FAILURE); /* Exit if 'Quit' is selected */
387 388 389 390 391 392 393 394 395 396 397 398
    }
  }
}

/*************************************************/
/* show_error_ret()                              */
/*                                               */
/* Reports an error but allows execution to then */
/* continue (rather than calling exit()) if the  */
/* user clicks on 'Continue' rather than 'Quit'. */
/* This is accomplished by simply returning.     */
/*                                               */
399 400
/* Parameters: Pointer to a _kernel_oserror      */
/*             structure.                        */
401
/*                                               */
402
/* Assumes:    The pointer may be NULL.          */
403 404 405 406 407 408 409
/*************************************************/

void show_error_ret(_kernel_oserror *e)
{
  if (e!=NULL)
  {
    _kernel_swi_regs r;
410 411
    char             name[Limits_TaskName];
    char             spri[Limits_OS_SpriteName];
412 413 414 415 416 417 418 419 420 421
    WimpSysInfo      s;

    #ifdef TRACE
      if (e->errnum == Utils_Error_Custom_Fatal) e->errnum = Utils_Error_Custom_Normal;
    #endif

    /* Force 'Quit' only for fatal errors */

    if (e->errnum == Utils_Error_Custom_Fatal) show_error(e);

422
    /* This all works in much the same way as show_error above. */
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

    s.r0=0;
    s.r1=0;
    wimp_read_sys_info(3,&s);

    if (s.r0==0) fprintf(stderr,"%s\n",e->errmess);
    else
    {
      StrNCpy0(name,lookup_token("_TaskName:Browse",0,0));
      StrNCpy0(spri,lookup_token("_SpriName:!browse",0,0));

      r.r[0] = (int) e;
      r.r[1] = (2<<9)+(1<<8)+1;
      r.r[2] = (int) &name;
      r.r[3] = (int) &spri;
      r.r[4] = 1;

      /* Have a quit button if not running full screen and the */
      /* error number isn't one defined as having a Continue   */
      /* button only.                                          */

      if (
           e->errnum != Utils_Error_OS_Escape      &&
           e->errnum != Utils_Error_Custom_Message &&
           !choices.full_screen
         )
         r.r[5] = (int) lookup_token("ErrorBtns:Quit",0,0);

      else r.r[5] = 0;

      _kernel_swi(Wimp_ReportError,&r,&r);

      if (r.r[1] != 1) exit(EXIT_FAILURE); /* Exit if 'Quit' is selected, else return normally */
    }
  }
}

/*************************************************/
/* report_toolbox_error()                        */
/*                                               */
/* If the toolbox generates an error this funct- */
/* ion will be called to report it. Parameters   */
/* are as standard for a Toolbox event handler.  */
/*************************************************/

int report_toolbox_error(int eventcode,ToolboxEvent *event,IdBlock *idb,void *handle)
{
  ChkError((_kernel_oserror *) &event->data);

  return 1;
}

/*************************************************/
/* make_no_fetch_memory_error()                  */
/*                                               */
/* Typically called from Fetch.c, if a memory    */
/* claim fails early in a fetch. Stores an       */
/* appropriate error in the global error         */
/* block 'erb'.                                  */
/*                                               */
/* Parameters: A numerical value to include in   */
/*             the message to help the           */
/*             programmer know where the error   */
/*             came from.                        */
/*************************************************/

489
_kernel_oserror * make_no_fetch_memory_error(int stage)
490 491 492 493 494 495 496 497 498 499 500
{
  char num[20];

  sprintf(num, "%d", stage);

  erb.errnum =  0;

  StrNCpy0(erb.errmess,
           lookup_token("NoMemFet:There is not enough free memory to perform this fetch (%0).",
                        0,
                        num));
501 502

  return &erb;
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
}

/*************************************************/
/* make_no_cont_memory_error()                   */
/*                                               */
/* Called if a memory claim fails during a fetch */
/* - stores an appropriate error in the global   */
/* error block 'erb'.                            */
/*                                               */
/* Parameters: A numerical value to include in   */
/*             the message to help the           */
/*             programmer know where the error   */
/*             came from.                        */
/*************************************************/

518
_kernel_oserror * make_no_cont_memory_error(int stage)
519 520 521 522 523 524 525 526 527 528 529
{
  char num[20];

  sprintf(num, "%d", stage);

  erb.errnum =  0;

  StrNCpy0(erb.errmess,
           lookup_token("NoMemRea:There is not enough free memory to continue the page fetch (%0).",
                        0,
                        num));
530 531

  return &erb;
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
}

/*************************************************/
/* make_no_table_memory_error()                  */
/*                                               */
/* Typically called from Tables.c, if a memory   */
/* claim fails during table parsing routines.    */
/* Stores an appropriate error in the global     */
/* error block 'erb'.                            */
/*                                               */
/* Parameters: A numerical value to include in   */
/*             the message to help the           */
/*             programmer know where the error   */
/*             came from.                        */
/*************************************************/

548
_kernel_oserror * make_no_table_memory_error(int stage)
549 550 551 552 553 554 555 556 557 558 559
{
  char num[20];

  sprintf(num, "%d", stage);

  erb.errnum =  0;

  StrNCpy0(erb.errmess,
           lookup_token("NoMemTab:There is not enough free memory to display this table (%0).",
                        0,
                        num));
560 561

  return &erb;
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
}

/*************************************************/
/* make_no_memory_error()                        */
/*                                               */
/* A general error generation routine for failed */
/* memory claims. Stores the error in the global */
/* error block 'erb'.                            */
/*                                               */
/* Parameters: A numerical value to include in   */
/*             the message to help the           */
/*             programmer know where the error   */
/*             came from.                        */
/*************************************************/

577
_kernel_oserror * make_no_memory_error(int stage)
578 579 580 581 582 583 584 585 586 587 588
{
  char num[20];

  sprintf(num, "%d", stage);

  erb.errnum =  0;

  StrNCpy0(erb.errmess,
           lookup_token("NoMemGen:There is not enough free memory to continue this operation (%0).",
                        0,
                        num));
589 590

  return &erb;
591 592 593 594 595 596 597 598
}

/*************************************************/
/* show_centred()                                */
/*                                               */
/* Shows a Toolbox object centred to the screen, */
/* opened persistently where possible            */
/*                                               */
599 600 601 602 603 604
/* Parameters: An Object ID of any Toolbox       */
/*             object that will return its Wimp  */
/*             window handle when                */
/*             Toolbox_ObjectMiscOp is called    */
/*             for it with a reason code of 0 -  */
/*             e.g. Window, DCS, or ColourDBox.  */
605
/*                                               */
606
/* Assumes:    That the ID is a valid one.       */
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
/*************************************************/

void show_centred(ObjectId o)
{
  WimpGetWindowStateBlock w;
  ObjectId                p;
  BBox                    b;
  _kernel_oserror        *e;

  /* Get the Wimp window handle of the Toolbox object */
  /* and get its size using Wimp_GetWindowState. This */
  /* sounds simple, but there's a different function  */
  /* call to get the window handle for each object    */
  /* class. The best (but still poor) approach is to  */
  /* call the Toolbox_MiscOp SWI with a reason code   */
  /* of 0, which in most cases will mean 'return Wimp */
  /* window handle'. If this is not the case for an   */
  /* object type, the Wimp call will then fault and   */
  /* this error condition can be used to default down */
  /* to some coordinate value that seems appropriate. */

  w.window_handle = 0;

  _swix(Toolbox_ObjectMiscOp,
        _INR(0,2) | _OUT(0),

        0,
        o,
        0,

        &w.window_handle);

  e = wimp_get_window_state(&w);

  if (e != NULL)
  {
    w.visible_area.xmin = 480;
    w.visible_area.ymin = 320;
  }
  else
  {
    w.visible_area.xmin = w.visible_area.xmax - w.visible_area.xmin;
    w.visible_area.ymin = w.visible_area.ymax - w.visible_area.ymin;
  }

  /* Find the screen x and y size in pixels and scale them  */
  /* to OS units using OS_ReadModeVariable calls; also work */
  /* out the top left coordinates at the same time          */

  _swix(OS_ReadModeVariable,_INR(0,1) | _OUT(2),-1,11,&w.xscroll);
  _swix(OS_ReadModeVariable,_INR(0,1) | _OUT(2),-1,4,&w.yscroll);
  b.xmin = (((w.xscroll + 1) << w.yscroll) - w.visible_area.xmin) / 2;

  _swix(OS_ReadModeVariable,_INR(0,1) | _OUT(2),-1,12,&w.xscroll);
  _swix(OS_ReadModeVariable,_INR(0,1) | _OUT(2),-1,5,&w.yscroll);
  b.ymin = (((w.xscroll + 1) << w.yscroll) + w.visible_area.ymin) / 2;

  ChkError(toolbox_get_parent(0,o,&p,NULL));

  ChkError(toolbox_show_object(0,       /* Bit 0 set - Wimp_CreateMenu semantics;          */
                                        /* Bit 1 set - Wimp_CreateSubMenu semantics        */
                               o,       /* Object ID given to function                     */
                               2,       /* 0 - 'default position'; 1 - specify position in */
                                        /* full; 2 - use top left corner coordinate pair   */
                               &b.xmin, /* Top left corner coordinate pair                 */
                               p,       /* Parent object ID                                */
                               -1));    /* Parent component ID (not interested in that)    */
}

/*************************************************/
/* set_corrected_extent()                        */
/*                                               */
/* Sets the extent of a window, making sure that */
/* xmin = 0 and ymax = 0 (so ymin is negative,   */
/* etc. etc.) - this means that topx = topy = 0. */
/*                                               */
683 684 685 686 687 688 689 690
/* Parameters: Flags to pass to the Toolbox in   */
/*             the SetExtent call;               */
/*                                               */
/*             The object ID of the browser      */
/*             window to be altered;             */
/*                                               */
/*             Pointer to a BBox holding the     */
/*             extent coordinates.               */
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
/*************************************************/

_kernel_oserror * set_corrected_extent(unsigned int f, ObjectId o, BBox * w)
{
  BBox t;

  t.xmin = 0;
  t.ymin = w->ymin - w->ymax;
  t.xmax = w->xmax - w->xmin;
  t.ymax = 0;

  return window_set_extent(f,o,&t);
}

/*************************************************/
/* find_behind()                                 */
/*                                               */
/* Returns the window handle of the first non-   */
/* pane window in front of a given window.       */
/*                                               */
711 712 713 714 715 716
/* Parameters: The window handle in question.    */
/*                                               */
/* Returns:    Handle of the first non-pane      */
/*             window in front of the given one, */
/*             or -1 if it is at the top of the  */
/*             stack.                            */
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
/*************************************************/

int find_behind(int w)
{
  WimpGetWindowStateBlock s;

  s.window_handle = w;

  ChkError(wimp_get_window_state(&s));

  if (s.behind != -1)
  {
    do
    {
      s.window_handle = s.behind;
      ChkError(wimp_get_window_state(&s));
    }
    while(((s.flags & WimpWindow_Pane) != 0) && (s.behind != -1));

    s.behind = s.window_handle;
  }

  return s.behind;
}

/*************************************************/
/* find_tool_sizes()                             */
/*                                               */
/* Returns the title bar and scroll bar widths   */
/* in OS units, including their outlines.        */
/*                                               */
/* Parameters: Pointer to an int, in which the   */
/*             title bar height is placed;       */
750
/*                                               */
751 752 753
/*             Pointer to an int, in which the   */
/*             horizontal scroll bar bar height  */
/*             is placed;                        */
754
/*                                               */
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
/*             Pointer to an int, in which the   */
/*             vertical scroll bar width is      */
/*             placed.                           */
/*                                               */
/* Assumes:    Any of the pointers may be NULL.  */
/*************************************************/

_kernel_oserror * find_tool_sizes(int * theight, int * hheight, int * vwidth)
{
  _kernel_oserror           * e;
  WimpGetWindowOutlineBlock   outline;
  WimpGetWindowStateBlock     s;
  ObjectId                    o;
  int                         th, hh, vw;

  /* Create an object with a title bar and both scroll bars */

  e = toolbox_create_object(0, "ToolSizes", &o);
  if (e) return e;

  /* Open it behind the Pinboard */

  s.visible_area.xmin = 256;
  s.visible_area.ymin = 256;
  s.visible_area.xmax = 512;
  s.visible_area.ymax = 512;
  s.xscroll           = 0;
  s.yscroll           = 0;
  s.behind            = -3;

  e = toolbox_show_object(0, o, Toolbox_ShowObject_FullSpec, &s.visible_area, 0, -1);
  if (e) return e;

  /* Get the window state (for current visible area) and outline */

  e = window_get_wimp_handle(0, o, &s.window_handle);
  if (e) return e;

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

  outline.window_handle = s.window_handle;
  e = wimp_get_window_outline(&outline);
  if (e) return e;

  /* Work out the various sizes */

  th = outline.outline.ymax - s.visible_area.ymax;
  hh = s.visible_area.ymin - outline.outline.ymin;
  vw = outline.outline.xmax - s.visible_area.xmax;

  if (theight) *theight = th;
  if (hheight) *hheight = hh;
  if (vwidth)  *vwidth  = vw;

  /* Return via. deleting the temporary window */

  return toolbox_delete_object(0, o);
}

/*************************************************/
/* register_null_claimant()                      */
/*                                               */
/* Call if you want to claim null polls.         */
/*                                               */
820 821
/* Parameters: As for a Wimp event handler, but  */
/*             without the object ID.            */
822 823 824 825 826 827 828 829
/*************************************************/

void register_null_claimant(int eventcode,WimpEventHandler * handler,browser_data * handle)
{
  null_counter++;
  ChkError(event_register_wimp_handler(-1,eventcode,handler,handle));

  #ifdef TRACE
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
    if (tl & (1u<<2))
    {
      int   shut_up_compiler = (int)   handler;
      int * function_name    = (int *) shut_up_compiler;

      Printf("register_null_claimant:   Registered a claimant for browser %p\n", handle);

      /* If the word before the function address has ff in the high */
      /* byte, the function name starts as many bytes before the    */
      /* function address as specified in the low 3 bytes.          */

      function_name -= 1;

      if (((*function_name) & 0xff000000) == 0xff000000)
      {
        Printf("                          Handler is '\0213%s\0217'\n", (char *) (((char *) function_name) - ((*function_name) & 0x00ffffff)));
      }
      else
      {
        Printf("                          Cannot find handler's name; address is \02130x%08x\0217\n", (int) handler);
      }
    }
852 853 854 855 856 857 858 859 860 861 862
  #endif

  if (null_counter == 1)
  {
    unsigned int mask;

    ChkError(event_get_mask(&mask));
    mask = (mask & (~Wimp_Poll_NullMask));
    ChkError(event_set_mask(mask));

    #ifdef TRACE
863
      if (tl & (1u<<2)) Printf("register_null_claimant:   \0211Nulls claimed\0217\n");
864 865 866 867 868 869 870 871 872
    #endif
  }
}

/*************************************************/
/* deregister_null_claimant()                    */
/*                                               */
/* Call if you want to release null polls.       */
/*                                               */
873 874
/* Parameters: As for a Wimp event handler, but  */
/*             without the object ID.            */
875 876 877 878 879 880 881 882
/*************************************************/

void deregister_null_claimant(int eventcode,WimpEventHandler * handler,browser_data * handle)
{
  null_counter--;
  ChkError(event_deregister_wimp_handler(-1,eventcode,handler,handle));

  #ifdef TRACE
883
    if (tl & (1u<<2))
884
    {
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
      int   shut_up_compiler = (int)   handler;
      int * function_name    = (int *) shut_up_compiler;

      Printf("deregister_null_claimant: Deregistered a claimant for browser %p\n", handle);

      /* If the word before the function address has ff in the high */
      /* byte, the function name starts as many bytes before the    */
      /* function address as specified in the low 3 bytes.          */

      function_name -= 1;

      if (((*function_name) & 0xff000000) == 0xff000000)
      {
        Printf("                          Handler is '\0216%s\0217'\n", (char *) (((char *) function_name) - ((*function_name) & 0x00ffffff)));
      }
      else
      {
        Printf("                          Cannot find handler's name; address is \2160x%08x\0217\n", (int) handler);
      }
904 905 906 907 908 909 910 911 912 913 914 915 916 917
    }
  #endif

  if (null_counter < 0) null_counter = 0;

  if (!null_counter)
  {
    unsigned int mask;

    ChkError(event_get_mask(&mask));
    mask = (mask | Wimp_Poll_NullMask);
    ChkError(event_set_mask(mask));

    #ifdef TRACE
918
      if (tl & (1u<<2)) Printf("deregister_null_claimant: \0212Nulls released\0217\n");
919 920 921 922 923 924 925 926 927 928 929 930 931
    #endif
  }
}

/*************************************************/
/* intersection()                                */
/*                                               */
/* Takes two BBoxes and returns a pointer to a   */
/* third which is the the intersection between   */
/* the first two, or NULL, if they don't         */
/* intersect.                                    */
/*                                               */
/* Parameters: Pointer to a BBox;                */
932
/*                                               */
933 934 935 936 937 938 939 940 941 942 943
/*             Pointer to another BBox.          */
/*                                               */
/* Returns:    Pointer to a BBox which is the    */
/*             intersection of the given two,    */
/*             or NULL, if they don't intersect. */
/*************************************************/

BBox * intersection(BBox * a, BBox * b)
{
  static BBox intersect;

944 945 946
  #define max(a,b) ((a) > (b) ? (a) : (b))
  #define min(a,b) ((a) < (b) ? (a) : (b))

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  if (!a || !b) return NULL;

  if ((a->xmin >= b->xmax) || (a->xmax <= b->xmin) || (a->ymin >= b->ymax) || (a->ymax <= b->ymin)) return NULL;

  intersect.xmin = max(a->xmin,b->xmin);
  intersect.xmax = min(a->xmax,b->xmax);
  intersect.ymin = max(a->ymin,b->ymin);
  intersect.ymax = min(a->ymax,b->ymax);

  return &intersect;
}

/*************************************************/
/* set_graphics_intersection()                   */
/*                                               */
/* Intended for redraw loop routines, this sets  */
/* up a given graphics rectangle, but takes      */
/* account of the intersection between this and  */
/* the current (given) graphics rectangle for    */
/* the redraw. The rectangle *must* be restored  */
/* with restore_graphics_intersection() as soon  */
/* as the rectangle set here is finished with;   */
/* the caller must thus remember this rectangle  */
/* for later.                                    */
/*                                               */
/* Parameters: Pointer to a BBox describing the  */
/*             rectangle to set, where xmax and  */
/*             ymax are inclusive;               */
/*                                               */
/*             Pointer to a BBox describing the  */
/*             current graphics rectangle, where */
/*             xmax and ymax are exclusive (e.g. */
/*             as in a WimpRedrawWindowBlock's   */
/*             redraw_area BBox).                */
/*                                               */
/* Returns:    Pointer to a BBox describing the  */
/*             actual rectangle that was set. If */
/*             this is NULL, the two do not      */
/*             intersect at all and the redraw   */
/*             subsequent graphics window        */
/*             restoration can and should be     */
/*             skipped.                          */
/*************************************************/

BBox * set_graphics_intersection(BBox * rbox, BBox * cbox)
{
  BBox * ibox;
  BBox   ogrect = *cbox;

  ogrect.xmax -= 1;
  ogrect.ymax -= 1;

  ibox = intersection(rbox, &ogrect);

  if (!ibox) return NULL;

  bbc_gwindow(ibox->xmin, ibox->ymin, ibox->xmax, ibox->ymax);

  return ibox;
}

/*************************************************/
/* restore_graphics_intersection()               */
/*                                               */
/* Restores the Wimp's redraw graphics rectangle */
/* which was changed by a call to                */
/* set_graphics_intersection (which *must* have  */
/* been called before this restoring function).  */
/*                                               */
/* Parameters: Pointer to a BBox holding the     */
/*             graphics rectangle as it was      */
/*             before set_graphics_intersection  */
/*             was called, where xmax and ymax   */
/*             are exclusive (e.g. as in a       */
/*             WimpRedrawWindowBlock's           */
/*             redraw_area BBox).                */
/*************************************************/

void restore_graphics_intersection(BBox * cbox)
{
  BBox ogrect = *cbox;

  ogrect.xmax -= 1;
  ogrect.ymax -= 1;

  bbc_gwindow(ogrect.xmin, ogrect.ymin, ogrect.xmax, ogrect.ymax);
}

/*************************************************/
/* read_os_to_points()                           */
/*                                               */
/* To avoid having to use a SWI every time       */
/* a conversion is made between OS units and     */
/* points or vice versa, this initialises        */
/* some internal variables which are used        */
/* subsequently. It may be called on a mode      */
/* change, for example, to ensure things are up  */
/* to date.                                      */
/*                                               */
/* If printing, values of MillipointsPerOSUnit   */
/* as defined at the top of this file are used,  */
/* since you can't read it; it seems that during */
/* a print job, this call may *not* be used,     */
/* contrary to the information on PRM 3-573.     */
/* This bug caused *severe* grief during the     */
/* development of the print routines...          */
/*************************************************/

void read_os_to_points(void)
{
  int x = 1, y = 1;

  if (!printing)
  {
    if (
          _swix(Font_Converttopoints,
                _INR(1,2) | _OUTR(1,2),

                x,
                y,

                &x,
                &y)
       )
    {
      millipoints_per_os_unit_x = MillipointsPerOSUnit;
      millipoints_per_os_unit_y = MillipointsPerOSUnit;
    }
    else
    {
      millipoints_per_os_unit_x = x;
      millipoints_per_os_unit_y = y;
    }
  }
  else
  {
    millipoints_per_os_unit_x = MillipointsPerOSUnit;
    millipoints_per_os_unit_y = MillipointsPerOSUnit;
  }

  overflow_limit_x = (0x3fffffff / millipoints_per_os_unit_x) - 1;
  overflow_limit_y = (0x3fffffff / millipoints_per_os_unit_y) - 1;

  half_mppou_x = millipoints_per_os_unit_x / 2;
  half_mppou_y = millipoints_per_os_unit_y / 2;
}

/*************************************************/
/* convert_pair_to_os()                          */
/*                                               */
/* Converts from millipoints to OS units. The    */
/* scale factor is determined by a previous call */
/* to read_os_to_points.                         */
/*                                               */
/* Parameters: A coordinate in millipoints;      */
1102
/*                                               */
1103
/*             Another coord in millipoints;     */
1104
/*                                               */
1105 1106 1107
/*             Pointer to an int into which the  */
/*             first coordinate, converted to OS */
/*             units, is placed;                 */
1108
/*                                               */
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
/*             Similarly a pointer to an int for */
/*             the second coordinate.            */
/*                                               */
/* Assumes:    The pointers may NOT be NULL. The */
/*             input and output variables may be */
/*             the same (so passing in x, y, &x, */
/*             &y would work correctly).         */
/*************************************************/

void convert_pair_to_os(int x, int y, int * osx, int * osy)
{
  *osx = ((x + half_mppou_x) / millipoints_per_os_unit_x) & ~(wimpt_dx() - 1);
  *osy = ((y + half_mppou_y) / millipoints_per_os_unit_y) & ~(wimpt_dy() - 1);
}

/*************************************************/
/* convert_pair_to_points()                      */
/*                                               */
/* Converts from OS units to millipoints. The    */
/* scale factor is determined by a previous call */
/* to read_os_to_points.                         */
/*                                               */
/* Parameters: A coordinate in OS units;         */
1132
/*                                               */
1133
/*             Another coordinate in OS units;   */
1134
/*                                               */
1135 1136 1137
/*             Pointer to an int into which the  */
/*             first coordinate, converted to    */
/*             millipoints, is placed;           */
1138
/*                                               */
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
/*             Similarly a pointer to an int for */
/*             the second coordinate.            */
/*                                               */
/* Assumes:    The pointers may not be NULL. The */
/*             input and output variables may be */
/*             the same (so passing in x, y, &x, */
/*             &y would work correctly).         */
/*************************************************/

void convert_pair_to_points(int x, int y, int * mpx, int * mpy)
{
  #ifdef TRACE

    if (abs(x) > overflow_limit_x || abs(y) > overflow_limit_y)
    {
      erb.errnum = Utils_Error_Custom_Normal;
      sprintf(erb.errmess,
1156
              "convert_pair_to_points: Can't convert (%d, %d) to millipoints without overflow.",
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
              x,y);

      show_error_ret(&erb);

      *mpx = *mpy = 0;

      return;
    }

  #endif

  *mpx = x * millipoints_per_os_unit_x;
  *mpy = y * millipoints_per_os_unit_y;
}

/*************************************************/
/* convert_to_os()                               */
/*                                               */
1175 1176
/* As convert_pair_to_os, but only converts one  */
/* coordinate at a time.                         */
1177 1178
/*                                               */
/* Parameters: An x coordinate in millipoints;   */
1179
/*                                               */
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
/*             Pointer to an int into which the  */
/*             coordinate, converted to OS       */
/*             units, is placed.                 */
/*                                               */
/* Assumes:    That the pointer is not NULL. The */
/*             input and output variable may be  */
/*             the same (so passing in x, &x     */
/*             would work correctly);            */
/*                                               */
/*             If x and y scalings differ, this  */
/*             will only ever use the x scaling. */
/*************************************************/

void convert_to_os(int x, int * osx)
{
  *osx = ((x + half_mppou_x) / millipoints_per_os_unit_x) & ~(wimpt_dx() - 1);
}

/*************************************************/
/* convert_to_points()                           */
/*                                               */
1201 1202
/* As convert_pair_to_points, but only converts  */
/* one coordinate at a time.                     */
1203 1204
/*                                               */
/* Parameters: An x coordinate in OS units;      */
1205
/*                                               */
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
/*             Pointer to an int into which the  */
/*             coordinate, converted to milli-   */
/*             points, is placed.                */
/*                                               */
/* Assumes:    That the pointer is not NULL. The */
/*             input and output variable may be  */
/*             the same (so passing in x, &x     */
/*             would work correctly);            */
/*                                               */
/*             If x and y scalings differ, this  */
/*             will only ever use the x scaling. */
/*************************************************/

void convert_to_points(int x, int * mpx)
{
  #ifdef TRACE

    if (abs(x) > overflow_limit_x)
    {
      erb.errnum = Utils_Error_Custom_Normal;
      sprintf(erb.errmess,
              "convert_to_points: Can't convert '%d' to millipoints without overflow.",
              x);

      show_error_ret(&erb);

      *mpx = 0;

      return;
    }

  #endif

  *mpx = x * millipoints_per_os_unit_x;
}

/*************************************************/
/* convert_box_to_os()                           */
/*                                               */
1245 1246
/* As convert_pair_to_os, but converts the four  */
/* coordinates inside a BBox in one go.          */
1247 1248 1249
/*                                               */
/* Parameters: Pointer to a BBox containing      */
/*             coords in millipoints;            */
1250
/*                                               */
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
/*             Pointer to a BBox into which the  */
/*             first box's coords, converted to  */
/*             OS units, are placed.             */
/*                                               */
/* Assumes:    That neither pointer is NULL. The */
/*             two pointers may be the same (so  */
/*             passing in &box, &box would work  */
/*             correctly).                       */
/*************************************************/

void convert_box_to_os(const BBox * mp, BBox * os)
{
  os->xmin = ((mp->xmin + half_mppou_x) / millipoints_per_os_unit_x) & ~(wimpt_dx() - 1);
  os->ymin = ((mp->ymin + half_mppou_y) / millipoints_per_os_unit_y) & ~(wimpt_dy() - 1);
  os->xmax = ((mp->xmax + half_mppou_x) / millipoints_per_os_unit_x) & ~(wimpt_dx() - 1);
  os->ymax = ((mp->ymax + half_mppou_y) / millipoints_per_os_unit_y) & ~(wimpt_dy() - 1);
}

/*************************************************/
/* convert_box_to_points()                       */
/*                                               */
1272 1273
/* As convert_pair_to_points, but converts the   */
/* four coordinates inside a BBox in one go.     */
1274 1275 1276
/*                                               */
/* Parameters: Pointer to a BBox containing      */
/*             coords in OS units;               */
1277
/*                                               */
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
/*             Pointer to a BBox into which the  */
/*             first box's coords, converted to  */
/*             millipoints, are placed.          */
/*                                               */
/* Assumes:    That neither pointer is NULL. The */
/*             two pointers may be the same (so  */
/*             passing in &box, &box would work  */
/*             correctly).                       */
/*************************************************/

void convert_box_to_points(const BBox * os, BBox * mp)
{
  #ifdef TRACE

    if (
         abs(os->xmin) > overflow_limit_x ||
         abs(os->ymin) > overflow_limit_y ||
         abs(os->xmax) > overflow_limit_x ||
         abs(os->ymax) > overflow_limit_y
       )
    {
      erb.errnum = Utils_Error_Custom_Normal;
      sprintf(erb.errmess,
              "convert_box_to_points: Can't convert (%d, %d, %d, %d) to millipoints without overflow.",
              os->xmin,
              os->ymin,
              os->xmax,
              os->ymax);

      show_error_ret(&erb);

      mp->xmin = mp->ymin = 0;
      mp->xmax = mp->ymax = 0;

      return;
    }

  #endif

  mp->xmin = os->xmin * millipoints_per_os_unit_x;
  mp->ymin = os->ymin * millipoints_per_os_unit_y;
  mp->xmax = os->xmax * millipoints_per_os_unit_x;
  mp->ymax = os->ymax * millipoints_per_os_unit_y;
}

/*************************************************/
/* read_sprite_size()                            */
/*                                               */
/* Finds out the size of a given sprite in the   */
/* application's sprite pool in OS units.        */
/*                                               */
/* Parameters: Pointer to the sprite name;       */
1330
/*                                               */
1331 1332
/*             Pointer to int into which the     */
/*             sprite's width is returned;       */
1333
/*                                               */
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
/*             Pointer to int into which the     */
/*             sprite's height is returned.      */
/*                                               */
/* Assumes:    The name pointer is not NULL, but */
/*             either of the two int pointers    */
/*             may be.                           */
/*************************************************/

_kernel_oserror * read_sprite_size(char * name, int * width, int * height)
{
  int               w, h, m;
  _kernel_oserror * e;

  e = _swix(OS_SpriteOp,
            _INR(0,2) | _OUTR(3,4) | _OUT(6),

            0x128,
            sprite_block,
            name,

            &w,
            &h,
            &m);

  if (e) return e;

  w = w << bbc_modevar(m, BBC_XEigFactor);
  h = h << bbc_modevar(m, BBC_YEigFactor);

  if (width)  *width  = w;
  if (height) *height = h;

  return NULL;
}

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
/*************************************************/
/* utils_text_width()                            */
/*                                               */
/* Returns the width of a given piece of text,   */
/* in OS units, if it were to be plotted in the  */
/* Desktop. Wimp_TextOp is used if available,    */
/* else the width and spacing of the bitmap font */
/* is read and the width is calculated from      */
/* this instead.                                 */
/*                                               */
/* Parameters: Pointer to the text;              */
/*                                               */
/*             Pointer to an int, into which the */
/*             width is written;                 */
/*                                               */
/*             0 to work out the whole string    */
/*             width, or the number of chars to  */
/*             read.                             */
/*                                               */
/* Assumes:    Either pointer may be NULL;       */
/*                                               */
/*             If the number of chars to read is */
/*             greater than the string length,   */
/*             the value given is ignored and    */
/*             the string length used instead.   */
/*************************************************/

_kernel_oserror * utils_text_width(char * text, int * width, int scan)
{
1398 1399
  int cwidth, cspacing;
  int len;
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

  /* Return if there's no text or 'width' is NULL */

  if (!width) return NULL;

  if (!text || !*text)
  {
    *width = 0;
    return NULL;
  }

  /* Otherwise, set 'len' either to the string length, */
  /* if 'scan' is zero, or to the value of 'scan'.     */

  len = strlen(text);
  if (scan && scan < len) len = scan;

  /* Rather than try mucking about guessing what version number of */
  /* Wimp supports Wimp_TextOp, simply use the alternative method  */
  /* if the SWI raises an error.                                   */

  if (
       _swix(Wimp_TextOp,
             _INR(0,2) | _OUT(0),

             1,
             text,
             len,

             width)
     )
  {
    /* Find out the spacing (start of one char to start of next) */
    /* and width of the text the Wimp is using, assuming that if */
    /* there is no nested wimp, Wimp_TextOp is unavailable.      */

    int vars[3] = {
                    BBC_GCharSizeX,
                    BBC_GCharSpaceX,
                    -1
                  };

    RetError(bbc_vduvars(vars, vars));

    cwidth   = vars[0];
    cspacing = vars[1];

1447 1448 1449 1450
    /* cspacing gives how much to increment x by after plotting a   */
    /* character, and therefore includes cwidth; so to find the     */
    /* width, we'd use (len * cspacing) - (cspacing - cwidth),      */
    /* which simplifies to the below (plus conversion to OS units). */
1451

1452
    *width = ((len - 1) * cspacing + cwidth) * wimpt_dx();
1453 1454 1455 1456 1457 1458 1459
  }

  /* Finished */

  return NULL;
}

1460 1461 1462 1463 1464 1465 1466
/*************************************************/
/* set_gadget_state()                            */
/*                                               */
/* Greys or ungreys a gadget, only changing its  */
/* state to avoid flicker.                       */
/*                                               */
/* Parameters: Object ID the gadget resides in;  */
1467
/*                                               */
1468
/*             Component ID of the gadget;       */
1469
/*                                               */
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 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
/*             1 to grey, 0 to ungrey.           */
/*************************************************/

_kernel_oserror * set_gadget_state(ObjectId o, ComponentId c, int grey_state)
{
  _kernel_oserror * e;
  unsigned int      flags;

  e = gadget_get_flags(0, o, c, &flags);
  if (e) return e;

  /* Only change state, to avoid flicker. */

  if (!!grey_state != !!(flags & Gadget_Faded))
  {
    if (grey_state) flags |=  Gadget_Faded;
    else            flags &= ~Gadget_Faded;

    return gadget_set_flags(0, o, c, flags);
  }

  return NULL;
}

/*************************************************/
/* anti_twitter()                                */
/*                                               */
/* Calls the anti-twitter code over a given      */
/* redraw area.                                  */
/*                                               */
/* Parameters: Pointer to a WimpRedrawWindow     */
/*             block with the redraw_area BBox   */
/*             holding the area over which the   */
/*             anti-twitter code should be       */
/*             called.                           */
/*************************************************/

void anti_twitter(WimpRedrawWindowBlock * r)
{
  char         nhantitwitter[256];
  int          mode, ok = 1;
  unsigned int modeflags;

  #define AntiTwitter1 50
  #define AntiTwitter2 55

  #ifndef TRACE

    /* Older interlace modules only support modes 50 and 55 */
    /* directly, though can still appear to work in others. */

    _swix(OS_Byte,
          _IN(0) | _OUT(2),

          135,

          &mode);

    if (mode == AntiTwitter1 || mode == AntiTwitter2) ok = 1;
    else
    {
      /* If the current mode is not mode 50 or 55, this mode module  */
      /* may be new enough to support setting bit 8 of the modeflags */
      /* to indicate interlace.                                      */

      _swix(OS_ReadModeVariable,
            _INR(0,1) | _OUT(2),

            -1,
            0,

            &modeflags);

      ok = !!(modeflags & (1<<8));
    }

  #else

    /* For trace builds, always try to anti-twitter (allows testing */
    /* in certain non-interlaced Desktop screen modes)              */

    ok = 1;

    /* Hmph - stop compiler complaining about things not being used... */

    mode      = 0;
    modeflags = 0;

  #endif

  if (ok)
  {
    BBox   gwind;
    BBox * area;

    gwind.xmin = (bbc_vduvar(BBC_GWLCol)) * wimpt_dx();
    gwind.ymin = (bbc_vduvar(BBC_GWBRow)) * wimpt_dy();
    gwind.xmax = (bbc_vduvar(BBC_GWRCol) + 1) * wimpt_dx();
    gwind.ymax = (bbc_vduvar(BBC_GWTRow) + 1) * wimpt_dy();

    area = intersection(&gwind, &r->redraw_area);

    if (area)
    {
      sprintf(nhantitwitter,
              "%%NHAntiTwitter %d %d %d %d\n",

              area->xmin,
              area->ymin,
              area->xmax - area->xmin,
              area->ymax - area->ymin);

      _swix(OS_CLI,
            _IN(0),

            nhantitwitter);
    }
  }
}

1590
/*************************************************/
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
/* adjust()                                      */
/*                                               */
/* Returns 1 if Wimp_GetPointerInfo says that    */
/* Adjust is being pressed, else 0.              */
/*************************************************/

int adjust(void)
{
  WimpGetPointerInfoBlock info;

  wimp_get_pointer_info(&info);

  return !!(info.button_state & Wimp_MouseButtonAdjust);
}

1606
/*************************************************/
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
/* hide_gadget()                                 */
/*                                               */
/* Hides a given gadget by moving it out of the  */
/* visible area of the window it is in.          */
/*                                               */
/* Parameters: Object ID the gadget lies in;     */
/*             Component ID of the gadget.       */
/*                                               */
/* Returns:    1 if the gadget was moved out,    */
/*             else 0.                           */
/*************************************************/

int hide_gadget(ObjectId o, ComponentId c)
{
  BBox g;

  if (gadget_get_bbox(0, o, c, &g)) return 0;

  /* If the gadget has a large negative X coordinate, */
  /* assume it's been moved out already.              */

  if (g.xmin < -4096) return 0;

  /* Otherwise, move it */

  g.xmin -= 8192;
  g.xmax -= 8192;

  if (gadget_move_gadget(0, o, c, &g)) return 0;

  return 1;
}

1640
/*************************************************/
1641 1642
/* show_gadget()                                 */
/*                                               */
1643
/* Shows a given gadget hidden by hide_gadget.   */
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
/*                                               */
/* Parameters: Object ID the gadget lies in;     */
/*             Component ID of the gadget.       */
/*                                               */
/* Returns:    1 if the gadget was moved in,     */
/*             else 0.                           */
/*************************************************/

int show_gadget(ObjectId o, ComponentId c)
{
  BBox g;

  if (gadget_get_bbox(0, o, c, &g)) return 0;

  /* If the gadget hasn't got a large negative X coordinate, */
  /* assume it's not been moved out.                         */

  if (g.xmin > -4096) return 0;

  /* Otherwise, move it */

  g.xmin += 8192;
  g.xmax += 8192;

  if (gadget_move_gadget(0, o, c, &g)) return 0;

  return 1;
}

1673
/*************************************************/
1674 1675 1676
/* gadget_hidden()                               */
/*                                               */
/* Call to find out if a gadget has been moved   */
1677
/* out with hide_gadget or is still visible.     */
1678 1679 1680 1681 1682
/*                                               */
/* Parameters: Object ID the gadget lies in;     */
/*             Component ID of the gadget.       */
/*                                               */
/* Returns:    1 if the gadget is hidden else 0. */
1683
/*************************************************/
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

int gadget_hidden(ObjectId o, ComponentId c)
{
  BBox g;

  /* If there's an error getting the gadget's bounding box, then the gadget */
  /* is missing altogether or something else has gone wrong; in any case,   */
  /* safest action is to say it has been hidden.                            */

  if (gadget_get_bbox(0, o, c, &g)) return 1;

  /* Simple assumption that this much of a negative X value = gadget hidden */

  if (g.xmin < -4096) return 1;

  return 0;
}

1702
/*************************************************/
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
/* slab_gadget()                                 */
/*                                               */
/* Slabs a gadget in briefly, by setting its     */
/* Selected bit. Gadget must be made of one icon */
/* only.                                         */
/*                                               */
/* Parameters: Object ID the gadget lies in;     */
/*             Component ID of the gadget.       */
/*************************************************/

void slab_gadget(ObjectId o, ComponentId c)
{
  WimpSetIconStateBlock set;
  WimpGetIconStateBlock get;
  int                   icon[2];

  /* Get the icon number and window handle of the gadget */

  if (gadget_get_icon_list(0, o, c, icon, sizeof(icon), NULL)) return;
  if (window_get_wimp_handle(0, o, &get.window_handle)) return;
  get.icon_handle = icon[0];

  /* Get the icon state */

  if (wimp_get_icon_state(&get)) return;

  /* Set the flags as selected */

  set.window_handle = get.window_handle;
  set.icon_handle   = get.icon_handle;
  set.EOR_word      = get.icon.flags | WimpIcon_Selected;
  set.clear_word    = 0xffffffff;

  if (wimp_set_icon_state(&set)) return;

  /* Wait a while */

  {
    int time_now, time_start;

    _swix(OS_ReadMonotonicTime, _OUT(0), &time_start);

    do
    {
      _swix(OS_ReadMonotonicTime, _OUT(0), &time_now);
    }
    while (time_now - time_start < 15);
  }

  /* Restore the old flags */

  set.EOR_word = get.icon.flags;

  wimp_set_icon_state(&set);
}

1759
/*************************************************/
1760 1761 1762 1763 1764 1765 1766
/* slab_gadget_in()                              */
/*                                               */
/* Slabs a gadget in, by setting its Selected    */
/* bit. Gadget must be made of one icon only.    */
/*                                               */
/* Parameters: Object ID the gadget lies in;     */
/*             Component ID of the gadget.       */
1767
/*************************************************/
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794

void slab_gadget_in(ObjectId o, ComponentId c)
{
  WimpSetIconStateBlock set;
  WimpGetIconStateBlock get;
  int                   icon[2];

  /* Get the icon number and window handle of the gadget */

  if (gadget_get_icon_list(0, o, c, icon, sizeof(icon), NULL)) return;
  if (window_get_wimp_handle(0, o, &get.window_handle)) return;
  get.icon_handle = icon[0];

  /* Get the icon state */

  if (wimp_get_icon_state(&get)) return;

  /* Set the flags as selected */

  set.window_handle = get.window_handle;
  set.icon_handle   = get.icon_handle;
  set.EOR_word      = get.icon.flags | WimpIcon_Selected;
  set.clear_word    = 0xffffffff;

  wimp_set_icon_state(&set);
}

1795
/*************************************************/
1796 1797 1798 1799 1800 1801 1802
/* slab_gadget_out()                             */
/*                                               */
/* Slabs a gadget out, by clearing its Selected  */
/* bit. Gadget must be made of one icon only.    */
/*                                               */
/* Parameters: Object ID the gadget lies in;     */
/*             Component ID of the gadget.       */
1803
/*************************************************/
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830

void slab_gadget_out(ObjectId o, ComponentId c)
{
  WimpSetIconStateBlock set;
  WimpGetIconStateBlock get;
  int                   icon[2];

  /* Get the icon number and window handle of the gadget */

  if (gadget_get_icon_list(0, o, c, icon, sizeof(icon), NULL)) return;
  if (window_get_wimp_handle(0, o, &get.window_handle)) return;
  get.icon_handle = icon[0];

  /* Get the icon state */

  if (wimp_get_icon_state(&get)) return;

  /* Set the flags as unselected */

  set.window_handle = get.window_handle;
  set.icon_handle   = get.icon_handle;
  set.EOR_word      = get.icon.flags &~ WimpIcon_Selected;
  set.clear_word    = 0xffffffff;

  wimp_set_icon_state(&set);
}

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
/*************************************************/
/* utils_check_caret_restoration()               */
/*                                               */
/* Checks to see if the given dialogue has the   */
/* caret, and if it has a parent. If so, it'll   */
/* return the Object ID of that parent, else     */
/* NULL_ObjectId is written.                     */
/*                                               */
/* Parameters: The Object ID of the dialogue     */
/*             to check.                         */
/*************************************************/

ObjectId utils_check_caret_restoration(ObjectId window_id)
{
  WimpGetCaretPositionBlock   caret_b;
  int                         caret_w;
  ObjectId                    parent = NULL_ObjectId;
  _kernel_oserror           * e      = NULL;

  /* Do we have the input focus? */

  e = wimp_get_caret_position(&caret_b);

  if (!e)
  {
    e = window_get_wimp_handle(0,
                               window_id,
                               &caret_w);

    if (!e)
    {
      if (caret_w == caret_b.window_handle)
      {
        /* Yes, we have the caret. So move it back to the Print */
        /* dialogue - well, this object's parent, anyway.       */

        e = toolbox_get_parent(0,
                               window_id,
                               &parent,
                               NULL);

        if (e) parent = NULL_ObjectId;

        else if (parent == NULL_ObjectId)
        {
          /* Maybe there's an ancestor? (E.g. PrintDBox using an  */
          /* alternate window -> doesn't pass Parent info through */
          /* so we need the ancestor instead... sigh).            */

          e = toolbox_get_ancestor(0,
                                   window_id,
                                   &parent,
                                   NULL);

          if (e) parent = NULL_ObjectId;
        }
      }
    }
  }

  /* Finished */

  return parent;
}

/*************************************************/
/* utils_restore_caret()                         */
/*                                               */
/* If the given dialogue has the caret, put the  */
/* caret into the parent of this object, in the  */
/* default input focus position.                 */
/*                                               */
/* Parameters: The Object ID of the dialogue     */
/*             whos parent is to gain the caret. */
/*                                               */
/* Assumes:    The parent has a default caret    */
/*             position set up.                  */
/*************************************************/

_kernel_oserror * utils_restore_caret(ObjectId window_id)
{
  _kernel_oserror           * e = NULL;
  ObjectId                    parent;
  ComponentId                 focus_c;

  /* Do we have the input focus and a parent? */

  parent = utils_check_caret_restoration(window_id);

  if (parent != NULL_ObjectId)
  {
    /* Find the default caret position of the parent */

    e = window_get_default_focus(0,
                                 parent,
                                 &focus_c);

    /* Set the focus there */

    if (!e)
    {

      if (focus_c != NULL_ComponentId) gadget_set_focus(0,
                                                        parent,
                                                        focus_c);
    }
  }

  /* Finished */

  return e;
}

1944
/*************************************************/
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
/* copy_toolaction_info()                        */
/*                                               */
/* Copies the internal details of a given        */
/* ToolAction gadget to another.                 */
/*                                               */
/* Ident off, ident on, ident faded, select      */
/* action, adjust action and click-show details  */
/* are copied with ToolAction SWIs; the help     */
/* text is copied with gadget library calls.     */
/*                                               */
/* This does *not* copy state info, such as      */
/* on/off or greyed.                             */
/*                                               */
/* Parameters: Object ID the source gadget is    */
/*             in;                               */
1960
/*                                               */
1961
/*             Component ID of the source;       */
1962
/*                                               */
1963 1964
/*             Object ID the destination gadget  */
/*             is in;                            */
1965
/*                                               */
1966 1967 1968 1969 1970 1971
/*             Component ID of the destination.  */
/*************************************************/

_kernel_oserror * copy_toolaction_info(ObjectId src_o, ComponentId src_c, ObjectId dst_o, ComponentId dst_c)
{
  _kernel_oserror * e;
1972 1973 1974
  char              ident [Limits_ToolActionIdent];
  char              help  [Limits_Help];
  unsigned int      flags;
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 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 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 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
  int               adjust_act, select_act;
  int               adjust_cs,  select_cs;

  /* Off state ident string */

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,5),

            toolaction_SET_IDENT_OFF,
            src_o,
            ToolAction_GetIdent,
            src_c,
            ident,
            sizeof(ident));

  if (e) return e;

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,4),

            toolaction_SET_IDENT_OFF,
            dst_o,
            ToolAction_SetIdent,
            dst_c,
            ident);

  if (e) return e;

  /* On state ident string */

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,5),

            toolaction_SET_IDENT_ON,
            src_o,
            ToolAction_GetIdent,
            src_c,
            ident,
            sizeof(ident));

  if (e) return e;

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,4),

            toolaction_SET_IDENT_ON,
            dst_o,
            ToolAction_SetIdent,
            dst_c,
            ident);

  if (e) return e;

  /* Faded state ident string */

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,5),

            toolaction_SET_IDENT_FADE,
            src_o,
            ToolAction_GetIdent,
            src_c,
            ident,
            sizeof(ident));

  if (e) return e;

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,4),

            toolaction_SET_IDENT_FADE,
            dst_o,
            ToolAction_SetIdent,
            dst_c,
            ident);

  if (e) return e;

  /* Adjust and select actions */

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,3) | _OUTR(0,1),

            0,
            src_o,
            ToolAction_GetAction,
            src_c,

            &select_act,
            &adjust_act);

  if (e) return e;

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,5),

            0,
            dst_o,
            ToolAction_SetAction,
            dst_c,
            select_act,
            adjust_act);

  if (e) return e;

  /* Adjust and select click-shows */

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,3) | _OUTR(0,1),

            0,
            src_o,
            ToolAction_GetClickShow,
            src_c,

            &select_cs,
            &adjust_cs);

  if (e) return e;

  e = _swix(Toolbox_ObjectMiscOp,
            _INR(0,5),

            0,
            dst_o,
            ToolAction_SetClickShow,
            dst_c,
            select_cs,
            adjust_cs);

  if (e) return e;

  /* The gadget flags */

  e = gadget_get_flags(0, src_o, src_c, &flags);
  if (e) return e;

  e = gadget_set_flags(flags, dst_o, dst_c, flags);
  if (e) return e;

  /* Finally, the help text */

  e = gadget_get_help_message(0,
                              src_o,
                              src_c,
                              help,
                              sizeof(help),
                              NULL);

  if (e) return e;

  return gadget_set_help_message(0,
                                 dst_o,
                                 dst_c,
                                 help);
}

/*************************************************/
/* set_window_flags()                            */
/*                                               */
/* Sets the flags of a given window, assuming    */
/* the nested Wimp is available...               */
/*                                               */
/* Parameters: Window handle;                    */
/*             EOR word;                         */
/*             Clear word.                       */
/*                                               */
/* Assumes:    That a window manager that        */
/*             supports extended Wimp_OpenWindow */
/*             calls (R2 = 'TASK') is present.   */
/*                                               */
/* The flags are set according to                */
/*                                               */
/* new = (old BIC clear word) EOR EOR word       */
/*                                               */
/* i.e.:                                         */
/*                                               */
/* C  E  Effect                                  */
/* ------------                                  */
/* 0  0  Preserve bit                            */
/* 0  1  Toggle bit                              */
/* 1  0  Clear bit                               */
/* 1  1  Set bit                                 */
/*************************************************/

_kernel_oserror * set_window_flags(int window_handle, unsigned int clear_word, unsigned int eor_word)
{
  /* Block required for the extended Wimp_OpenWindow */

  typedef struct
  {
    WimpOpenWindowBlock open;
    unsigned int        flags;
  }
  ExtendedOpenBlock;

  _kernel_oserror         * e;
  WimpGetWindowStateBlock   s;
  unsigned int              parent, align;
  unsigned int              new_flags;
  ExtendedOpenBlock         ext_o;

  /* Get the current window details */

  s.window_handle = window_handle;

  e = _swix(Wimp_GetWindowState,
            _INR(1, 2) | _OUTR(3, 4),

            &s,
            Magic_Word_TASK, /* See MiscDefs.h */

            &parent,
            &align);

  if (e) return e;

  /* Obtain the new flags word */

  new_flags = (s.flags & ~clear_word) ^ eor_word;

  /* Fill in the new open block and reopen the window with it */

  ext_o.open.window_handle = s.window_handle;
  ext_o.open.visible_area  = s.visible_area;
  ext_o.open.xscroll       = s.xscroll;
  ext_o.open.yscroll       = s.yscroll;
  ext_o.open.behind        = s.behind;
  ext_o.flags              = new_flags;

  return _swix(Wimp_OpenWindow,
               _INR(1,4),

               &ext_o,
               Magic_Word_TASK,
               parent,
               align | Alignment_NewFlagsGiven);
}

/*************************************************/
/* debounce_keypress()                           */
/*                                               */
/* For some key presses (e.g. function keys), it */
/* is not desirable to let the key autorepeat.   */
/* This function sits in a tight loop waiting    */
/* for all keys to be released before exitting.  */
/*                                               */
/* Returns: 1 if a key was being pressed and the */
/*          function waited for its release,     */
/*          else 0.                              */
/*************************************************/

int debounce_keypress(void)
{
  int               key, waited = 0;
  _kernel_oserror * e;

  do
  {
    e = _swix(OS_Byte,
              _INR(0,1) | _OUT(1),

              121, /* Keyboard scan */
              0,   /* Scan all keys */

              &key);

    if (key != 255) waited = 1;
  }
  while (!e && key != 255);

  if (waited) _swix(OS_Byte, _INR(0,1), 21, 0); /* Flush keyboard buffer */

  return waited;
}

2251
/*************************************************/
2252 2253 2254 2255 2256 2257 2258 2259
/* task_from_window()                            */
/*                                               */
/* Returns the task handle of the owner of a     */
/* given window.                                 */
/*                                               */
/* Parameters: A window handle.                  */
/*                                               */
/* Returns:    Task handle of the window owner.  */
2260
/*************************************************/
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282

int task_from_window (int window_handle)
{
  WimpMessage  m;
  int          handle;

  m.hdr.size        = 20;
  m.hdr.your_ref    = 0;
  m.hdr.action_code = 0;

  if (
       wimp_send_message(Wimp_EUserMessageAcknowledge,
                         &m,
                         window_handle,
                         0,
                         &handle)
     )
     return 0;

  return handle;
}

2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
/*************************************************/
/* utils_browser_from_window()                   */
/*                                               */
/* Given a window handle, returns an associated  */
/* browser_data struct, if one may be found.     */
/*                                               */
/* Parameters: The window handle;                */
/*                                               */
/*             Pointer to a pointer to a         */
/*             browser_data struct, in which the */
/*             associated structure's address is */
/*             written, or NULL for none found / */
/*             there is an error.                */
/*                                               */
/* Assumes:    The last parameter may not be     */
/*             NULL (it is pointless to allow    */
/*             this).                            */
/*************************************************/

_kernel_oserror * utils_browser_from_window(int window_handle, browser_data ** browser)
{
2304
  ObjectId o = NULL, a = NULL;
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315

  *browser = NULL;

  /* Get the associated Object ID */

  RetError(window_wimp_to_toolbox(0,
                                  window_handle,
                                  -1,
                                  &o,
                                  NULL));

2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
  /* If this has an ancestor, check the ID against the ancestor's */
  /* toolbar IDs. This is because we could be a frame - in which  */
  /* case there is an ancestor - or a toolbar, in which case we   */
  /* want to return the browser_data struct for that ancestor.    */

  RetError(toolbox_get_ancestor(0, o, &a, NULL));

  if (a)
  {
    browser_data * ancestor = NULL;
    ObjectId       upper, lower;

    /* Get the ancestor's client handle */

    RetError(toolbox_get_client_handle(0, a, (void *) &ancestor));

    /* If a known browser, get the toolbars */

    if (is_known_browser(ancestor))
    {
      upper = toolbars_get_upper(ancestor);
      lower = toolbars_get_lower(ancestor);

      /* If either ID matches that which the message */
      /* came from, the return the ancestor ID.      */

      if (upper == o || lower == o)
      {
        *browser = ancestor;

        return NULL;
      }
    }
  }

2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
  /* Get its client handle */

  RetError(toolbox_get_client_handle(0, o, (void *) browser));

  /* If this is not a known browser, don't use it */

  if (!is_known_browser(*browser)) *browser = NULL;

  /* Finished */

  return NULL;
}

2364
/*************************************************/
2365 2366 2367
/* is_known_browser()                            */
/*                                               */
/* Finds out if the given browser_data struct is */
2368 2369 2370
/* in the list of known structures. The struct   */
/* may be NULL (0 would be returned), so this    */
/* doesn't need to be checked for externally.    */
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             to check.                         */
/*                                               */
/* Returns:    1 if the structure is in the list */
/*             or 0 if it isn't.                 */
/*************************************************/

int is_known_browser(browser_data * b)
{
  browser_data * check = last_browser;
  int            found = 0;

  /* If b is NULL, can't be a valid browser_data structure! */

  if (!b) return 0;

  /* Search the list */

  while (check && !found)
  {
    if (check == b) found = 1;
    else check = check->previous;
  }

  /* Return the search results */

  return found;
}

2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
/*************************************************/
/* utils_parent()                                */
/*                                               */
/* Works out a given browser_data structure's    */
/* parent. If there is only an ancestor or       */
/* neither an ancestor or parent, it returns     */
/* NULL.                                         */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             that you want the parent of.      */
/*                                               */
/* Returns:    Pointer to the structure's        */
/*             parent, or NULL if there is only  */
/*             an ancestor or no parents at all. */
/*                                               */
/* Assumes:    If it gets NULL, it returns NULL. */
/*************************************************/

browser_data * utils_parent(browser_data * b)
{
  if (!b) return NULL;

  if      (b->parent      && b->parent      != b->ancestor) return b->parent;
  else if (b->real_parent && b->real_parent != b->ancestor) return b->real_parent;

  return NULL;
}

2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
/*************************************************/
/* utils_ancestor()                              */
/*                                               */
/* Works out a given browser_data structure's    */
/* ancestor (which may be the given structure!). */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             that you want the ancestor of.    */
/*                                               */
/* Returns:    Pointer to the structure's        */
/*             ancestor.                         */
/*                                               */
/* Assumes:    If it gets NULL, it returns NULL. */
/*************************************************/

browser_data * utils_ancestor(browser_data * b)
{
  if (!b) return NULL;
2447

2448 2449 2450 2451
  if (b->ancestor) return b->ancestor;
  return b;
}

2452
/*************************************************/
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
/* encode_base64()                               */
/*                                               */
/* Passed a pointer to data and its length, this */
/* will fill the output buffer with Base64-      */
/* encoded data, returning the length of the     */
/* output data (this is not terminated).         */
/*                                               */
/* The length of the output will be -            */
/*                                               */
/* (length of input, rounded up to next multiple */
/* of 3) times 4                                 */
/*                                               */
/* - so make sure you have a big enough output   */
/* buffer.                                       */
/*                                               */
/* Parameters: Pointer to the data to encode;    */
/*                                               */
/*             Length of the data to encode;     */
/*                                               */
/*             Pointer to the output buffer.     */
/*                                               */
/* Assumes:    That the output buffer is big     */
/*             enough (see above).               */
2476
/*************************************************/
2477 2478 2479

int encode_base64(const char * in, int len, char * out)
{
2480 2481 2482 2483 2484 2485 2486 2487
  const static char * base64_table = "ABCDEFGHIJKLMNOP"
                                     "QRSTUVWXYZabcdef"
                                     "ghijklmnopqrstuv"
                                     "wxyz0123456789+/";
  unsigned long       chunk;
  char              * out_ptr      = out;
  int                 p            = 0;
  int                 i;
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518

  while (p < len)
  {
    chunk = 0;

    for (i = 0; i < 3; i++, p++)
    {
      if (p < len) chunk = (chunk << 8) | in[p];
      else         chunk = (chunk << 8);
    }

    *out++ = base64_table[chunk >> 18];
    *out++ = base64_table[(chunk >> 12) & 0x3f];

    if (p <= len + 1)
    {
      *out++ = base64_table[(chunk >> 6) & 0x3f];

      if (p <= len) *out++ = base64_table[chunk & 0x3f];
      else          *out++ = '=';
    }
    else
    {
      *out++ = '=';
      *out++ = '=';
    }
  }

  return out - out_ptr;
}

2519 2520 2521
/*************************************************/
/* utils_strcasecmp()                            */
/*                                               */
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
/* Function to compare two strings case          */
/* insensitively.                                */
/*                                               */
/* Originally by sbrodie.                        */
/*                                               */
/* The conversions to unsigned int stop the      */
/* compiler messing around with shifts all over  */
/* the place whilst trying to promote the chars  */
/* to int whilst retaining the sign.             */
/*                                               */
/* Problems: Choice of return value when strings */
/* do not match is based upon character number   */
/* rather than any alphabetic sorting.           */
2535 2536 2537 2538 2539 2540
/*                                               */
/* Parameters: As strcmp.                        */
/*                                               */
/* Returns:    As strcmp.                        */
/*************************************************/

2541
int utils_strcasecmp(const char *a, const char *b)
2542
{
2543
  for (;;)
2544
  {
2545 2546
    unsigned int f1 = *a++;
    unsigned int s1 = *b++;
2547

2548
    if (f1 == 0) return -s1;
2549

2550 2551 2552 2553 2554 2555 2556 2557 2558
    if (f1 != s1)
    {
      unsigned int f2     = (unsigned int) tolower(f1);
      unsigned int s2     = (unsigned int) tolower(s1);
      signed int   result = f2 - s2;

      if (result != 0) return result;
    }
  }
2559 2560
}

2561 2562 2563
/*************************************************/
/* utils_strncasecmp()                           */
/*                                               */
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
/* Function to compare two strings case          */
/* insensitively up to a maximum char count.     */
/*                                               */
/* Originally by sbrodie.                        */
/*                                               */
/* The conversions to unsigned int stop the      */
/* compiler messing around with shifts all over  */
/* the place whilst trying to promote the chars  */
/* to int whilst retaining the sign.             */
/*                                               */
/* Problems: Choice of return value when strings */
/* do not match is based upon character number   */
/* rather than any alphabetic sorting.           */
2577
/*                                               */
2578
/* Parameters: As strncmp.                       */
2579
/*                                               */
2580
/* Returns:    As strncmp.                       */
2581 2582 2583 2584
/*************************************************/

int utils_strncasecmp(const char * a, const char * b, unsigned int n)
{
2585
  for (; n; --n)
2586
  {
2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
    unsigned int f1 = *a++;
    unsigned int s1 = *b++;

    if (f1 == 0) return -s1;

    if (f1 != s1)
    {
      unsigned int f2     = (unsigned int) tolower(f1);
      unsigned int s2     = (unsigned int) tolower(s1);
      signed int   result = f2 - s2;

      if (result != 0) return result;
    }
2600 2601 2602 2603 2604 2605
  }

  return 0;
}

/*************************************************/
2606
/* utils_get_task_handle()                       */
2607
/*                                               */
2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
/* Returns the task handle of the given task     */
/* (name comparison is case insensitive).        */
/*                                               */
/* Parameters: Pointer to a null-terminated task */
/*             name;                             */
/*                                               */
/*             Pointer to an unsigned int, in    */
/*             which the task handle is written, */
/*             or 0 if the task is not found.    */
/*                                               */
/* Assumes:    Neither pointer may be NULL.      */
2619 2620
/*************************************************/

2621
_kernel_oserror * utils_get_task_handle(const char * task_to_get, unsigned int * found_handle)
2622 2623 2624 2625 2626
{
  _kernel_oserror * e;
  char            * c;
  int             * p;
  int               buffer  [32];
2627
  char              taskname[Limits_TaskName];
2628 2629
  int             * notused;
  int               t;
2630
  int               len    = strlen(task_to_get);
2631
  int               next   = 0;
2632
  unsigned int      handle = 0;
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

  do
  {
    e = _swix(TaskManager_EnumerateTasks,
              _INR(0,2) | _OUTR(0,1),

              next,
              buffer,
              sizeof(buffer),

              &next,
              &notused);

    if (e) return e;

    /* Go through as much of the buffer as the call said it used */

    for (p = buffer; p < notused && handle == 0; p += 4)
    {
      c = (char *) p[1];
      t = 0;

      memset(taskname, 0, sizeof(taskname));
      while (*c > 31 && t < sizeof(taskname) - 1) taskname[t++] = *c++;

2658
      if (!utils_strncasecmp(taskname, task_to_get, len)) handle = p[0];
2659 2660 2661 2662
    }
  }
  while (next >= 0 && handle == 0);

2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
  /* Return the handle */

  *found_handle = handle;

  return NULL;
}

/*************************************************/
/* utils_stop_proxy()                            */
/*                                               */
/* Stops the [WebServe] application by sending   */
/* an AppControl message.                        */
/*************************************************/

_kernel_oserror * utils_stop_proxy(void)
{
2679 2680
  unsigned int handle = 0;
  WimpMessage  msg;
2681 2682 2683 2684 2685

  /* First, get WebServe's task handle */

  RetError(utils_get_task_handle(lookup_token("ProxyName:Acorn WebServe",0,0), &handle));

2686 2687 2688 2689
  #ifdef TRACE

    if (!handle)
    {
2690
      /* Didn't find WebServe, so complain and exit */
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704

      erb.errnum = Utils_Error_Custom_Message;

      StrNCpy0(erb.errmess, "WebServe is not present");

      show_error_ret(&erb);

      return NULL;
    }

  #else

    if (!handle)
    {
2705
      /* Didn't find WebServe, so exit */
2706 2707 2708 2709 2710 2711

      return NULL;
    }

  #endif

2712
  /* If WebServe is present, send the message */
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724

  msg.hdr.size        = 32;
  msg.hdr.your_ref    = 0;
  msg.hdr.action_code = Wimp_MAppControl;

  msg.data.app_control.version = 1;
  msg.data.app_control.flags   = Wimp_MAppControl_ImmediateAction;
  msg.data.app_control.reason  = Wimp_MAppControl_Stop;

  return wimp_send_message(Wimp_EUserMessage, &msg, handle, -1, NULL);
}

2725 2726 2727 2728 2729 2730 2731
/*************************************************/
/* utils_len_printf()                            */
/*                                               */
/* Returns the length of a given printf string.  */
/* Can be useful for buffer length determination */
/* when wishing to use sprintf, for example.     */
/*                                               */
2732 2733 2734 2735 2736
/* This function runs *very* slowly. If it is    */
/* difficult / impossible to determine the       */
/* length (or upper limit of length) any other   */
/* way, use it; else find a different approach   */
/* (e.g. see utils_number_length).               */
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
/*                                               */
/* Parameters: As for printf.                    */
/*                                               */
/* Returns:    Length of the output string (as   */
/*             returned by vfprintf) or -1 if    */
/*             some error occurred.              */
/*************************************************/

int utils_len_printf(const char * format, ...)
{
  int       len;
  va_list   ptr;
  FILE    * fp;

  fp = fopen("Null:", "wb");
  if (!fp) return -1;

  va_start(ptr, format);
  len = vfprintf(fp, format, ptr);
  va_end(ptr);

  fclose(fp);

  return len;
}

2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
/*************************************************/
/* utils_number_length()                         */
/*                                               */
/* Returns the number of bytes the given number  */
/* would occupy if converted to a string by      */
/* sprintf with a '%d' specifier used in the     */
/* format string.                                */
/*                                               */
/* Parameters: The number to check.              */
/*                                               */
/* Returns:    The number of characters it would */
/*             occupy as a string.               */
/*                                               */
/* Assumes:    An 'int' is 32-bit signed.        */
/*************************************************/

int utils_number_length(int number)
{
  int len = 0;

  if (number < 0) len += 1, number = -number;

  if      (number < 10)         len += 1;
  else if (number < 100)        len += 2;
  else if (number < 1000)       len += 3;
  else if (number < 10000)      len += 4;
  else if (number < 100000)     len += 5;
  else if (number < 1000000)    len += 6;
  else if (number < 10000000)   len += 7;
  else if (number < 100000000)  len += 8;
  else if (number < 1000000000) len += 9;
  else                          len += 10;

  return len;
}

2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
/*************************************************/
/* utils_return_hash()                           */
/*                                               */
/* Returns a very crude hash number for a given  */
/* string.                                       */
/*                                               */
/* Parameters: Pointer to the string.            */
/*                                               */
/* Returns:    A hash number.                    */
/*************************************************/

unsigned int utils_return_hash(const char * s)
{
  unsigned int h = 0;

  if (!s) return 0;

  while (*s) h += *s++;

  return h;
}

2821
/*************************************************/
2822
/* utils_build_user_agent_string                 */
2823
/*                                               */
2824 2825
/* Works out an appropriate HTTP response User   */
/* Agent string.                                 */
2826
/*                                               */
2827 2828 2829 2830
/* Parameters: Flag to indicate fake Netscape    */
/*             header required.                  */
/*                                               */
/*             Pointer to a buffer to place the  */
2831
/*             string in;                        */
2832
/*                                               */
2833 2834 2835 2836
/*             Size of the buffer - note that a  */
/*             string longer than                */
/*             Limits_UserAgent will never be    */
/*             generated.                        */
2837 2838
/*************************************************/

2839
void utils_build_user_agent_string(int netscape, char * buffer, int buffer_size)
2840 2841
{
  _kernel_oserror * e;
2842
  char              agent[Limits_UserAgent];
2843 2844
  char              ver  [32];
  int               modnum, bcdver = 0;
2845
  const char      * agent_middle, * agent_end;
2846

2847 2848 2849 2850
  if (!buffer || !buffer_size) return;

  buffer[0] = '\0';

2851 2852 2853 2854
  /* The AGENT_... definitions are at the top of ths file.     */
  /*                                                           */
  /* First, the string start, e.g. 'Mozilla/2.0 (compatible; ' */

2855
  StrNCpy0(agent, netscape ? Netscape_Agent_Start : Acorn_Agent_Start);
2856 2857 2858 2859 2860 2861

  /* The browser name */

  *lasttokn = 0; /* Being very (maybe over?) cautions here */
  *tokens   = 0;
  lookup_token("_TaskName",1,0);
2862 2863

  /* Can't have spaces outside the comment field */
2864

2865
  if (!strchr(agent, '('))
2866 2867 2868
  {
    while (strchr(tokens, ' ')) *strchr(tokens, ' ') = '-';
  }
2869

2870 2871 2872
  if (strlen(tokens) + strlen(agent) + 2 < sizeof(agent))
  {
    strcat(agent, tokens);
2873 2874

    /* Separate version by a / outside the comment field (see HTTP 1.1 spec section 3.8) */
2875 2876 2877

    if (strchr(agent, '(')) strcat(agent, " ");
    else                    strcat(agent, "/");
2878 2879 2880 2881 2882 2883 2884
  }

  /* The browser version */

  *lasttokn = 0;
  *tokens   = 0;
  lookup_token("Version",1,0);
2885

2886
  /* Just do a simple version outside of the comment field */
2887

2888
  if (!strchr(agent, '('))
2889 2890 2891
  {
    if (strchr(tokens, ' ')) *strchr(tokens, ' ') = '\0';
  }
2892

2893 2894 2895 2896 2897 2898 2899
  /* Can't have nested ()s in the User Agent string */

  if (strchr(tokens, '(')) *strchr(tokens, '(') = '[';
  if (strchr(tokens, ')')) *strchr(tokens, ')') = ']';

  /* Append the version, if it'll fit */

2900 2901 2902 2903
  if (strlen(tokens) + strlen(agent) + 1 < sizeof(agent)) strcat(agent, tokens);

  /* Intermediate string */

2904 2905
  agent_middle = netscape ? Netscape_Agent_Middle : Acorn_Agent_Middle;
  if (strlen(agent) + strlen(agent_middle) + 1 < sizeof(agent)) strcat(agent, agent_middle);
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916

  /* Extract the Utility Module version number */

  e = _swix(OS_Module,
            _INR(0,1) | _OUT(1),

            18,
            "UtilityModule",

            &modnum);

2917
  if (e) return;
2918 2919 2920 2921 2922 2923 2924 2925 2926 2927

  e = _swix(OS_Module,
            _INR(0,2) | _OUT(6),

            20,
            modnum,
            -1,

            &bcdver);

2928
  if (e) return;
2929 2930 2931 2932 2933 2934 2935 2936 2937

  /* Write the version number and put it into the agent string */

  sprintf(ver, "%d.%02x", bcdver >> 16, (bcdver & 0xffff) >> 8);

  if (strlen(agent) + strlen(ver) + 1 < sizeof(agent)) strcat(agent, ver);

  /* Finish things off */

2938 2939
  agent_end = netscape ? Netscape_Agent_End : Acorn_Agent_End;
  if (strlen(agent) + strlen(agent_end) + 1 < sizeof(agent)) strcat(agent, agent_end);
2940

2941
  /* Copy into the given buffer */
2942

2943 2944
  strncpy(buffer, agent, buffer_size - 1);
  buffer[buffer_size - 1] = 0;
2945 2946 2947

  /* Finished. */

2948
  return;
2949
}
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997

/*************************************************/
/* utils_check_scrap()                           */
/*                                               */
/* If Save_ScrapFile (which should represent a   */
/* system variable name, see Save.h) does not    */
/* exist, report an appropriate error and        */
/* return 1. Else return 0.                      */
/*                                               */
/* Returns: See above.                           */
/*************************************************/

int utils_check_scrap(void)
{
  int              len;
  _kernel_swi_regs r;

  r.r[0] = (int) Save_ScrapVar;
  r.r[1] = (int) NULL;
  r.r[2] = -1;
  r.r[3] = 0;
  r.r[4] = 4;

  /* _swix will not work correctly for this particular SWI if */
  /* requiring the returned R2 value. Something to do with    */
  /* the call relying on generating an error, but _swix spots */
  /* it and pulls out earlier than the call expects. Or some  */
  /* such thing...                                            */

  _kernel_swi(OS_ReadVarVal, &r, &r);

  len = r.r[2];

  if (!len)
  {
    erb.errnum = Utils_Error_Custom_Message;
    sprintf(erb.errmess,
            "%s%s",
            Save_ScrapFile,
            lookup_token("NoScrapDef: not defined.",0,0));

    show_error_ret(&erb);

    return 1;
  }

  return 0;
}
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 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 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131

/*************************************************/
/* utils_canonicalise_path()                     */
/*                                               */
/* Take some pathname (which may include         */
/* a path or other general system variable) and  */
/* expand (or canonicalise) it.                  */
/*                                               */
/* Caller is responsible for calling free() on   */
/* the returned block.                           */
/*                                               */
/* Parameters: Pointer to the path to            */
/*             canonicalise;                     */
/*                                               */
/*             Pointer to a char *, which will   */
/*             be filled in with the address of  */
/*             a malloced block - the caller is  */
/*             responsible for freeing it.       */
/*                                               */
/* Returns:    If there is an error, it returns  */
/*             it, but it may return NULL and    */
/*             also return NULL as the pointer   */
/*             to the malloced block if some     */
/*             other internal failure occurred.  */
/*************************************************/

_kernel_oserror * utils_canonicalise_path(const char * in, char ** out)
{
  int required;

  if (!in || !*in || !out) return NULL;

  RetError(_swix(OS_FSControl,
                 _INR(0, 5) | _OUT(5),

                 37,   in,
                 NULL, NULL,
                 NULL, 0,

                 &required)); /* Path length not including terminator returned as MINUS r5 */

  *out = malloc(1 - required); /* (Yes, '1 - required' - see above!) */

  if (!*out) return make_no_memory_error(30);

  RetError(_swix(OS_FSControl,
                 _INR(0, 5) | _OUT(5),

                 37,   in,
                 *out, NULL,
                 NULL, 1 - required,

                 &required));

  /* Er, 'something' went wrong... PRMs say to check, but not what to */
  /* do if you don't get 1 back here and haven't had an error from    */
  /* the SWI call!                                                    */

  if (required != 1)
  {
    free (*out);
    *out = NULL;
  }

  return NULL;
}

/*************************************************/
/* utils_build_tree()                            */
/*                                               */
/* Takes a fully canonicalised pathname and      */
/* ensures that all the directories in the path  */
/* exist. This is useful if you are going to     */
/* save something to a temporary directory in    */
/* Scrap or somewhere in <Choices$Write>, say,   */
/* and need to ensure that the directory         */
/* structure you're addressing is present.       */
/*                                               */
/* Parameters: Pointer to the path to ensure is  */
/*             present.                          */
/*************************************************/

_kernel_oserror * utils_build_tree(const char * path)
{
  char * temp;
  char * p;
  int    level, len;

  /* Sanity check, and take a local copy of the path */

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

  len = strlen(path);

  temp = malloc(len + 1);
  if (!temp) return make_no_memory_error(31);

retry:

  level = 0;
  strcpy(temp, path);

  /* Create the directories */

  do
  {
    p = strrchr(temp, '.');

    if (p)
    {
      *p = '\0';

      if (!_swix(OS_File,
                 _INR(0,1) | _IN(4),

                 8,
                 temp,
                 0))
      {
        if (level) goto retry;
        else       break;
      }
    }

    level++;
  }
  while (p);

  /* Finished */

  free(temp);

  return NULL;
}