History 87.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright 1997 Acorn Computers Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/***************************************************/
/* File   : History.c                              */
17
/*                                                 */
18
/* Purpose: Handles the browser History.           */
19
/*                                                 */
20
/* Author : A.D.Hodgkinson                         */
21 22
/*                                                 */
/* History: 07-Feb-97: Created.                    */
23 24 25 26 27 28 29 30
/*                                                 */
/*          06-Nov-97: Major revision, largely a   */
/*                     complete rewrite to make    */
/*                     the system more flexible    */
/*                     and less prone to bugs (but */
/*                     still do Back/Forward as in */
/*                     Navigator 2, rather than    */
/*                     Navigator 3).               */
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
/***************************************************/

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

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

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

#include "toolbox.h"
#include "window.h"
#include "gadgets.h"
#include "menu.h"

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

#include "Browser.h"
57
#include "ChoiceDefs.h"
58
#include "FetchPage.h"
59
#include "Filetypes.h"
60
#include "Memory.h"
61 62
#include "OpenURL.h"
#include "Save.h"
63
#include "Toolbars.h"
64
#include "URLutils.h"
65 66 67 68
#include "Windows.h"

#include "History.h"

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
/**************************************************************************************************/
/*                                                                                                */
/* Browser History structure                                                                      */
/* =========================                                                                      */
/*                                                                                                */
/*          prev       next            The basic History structure is as pictured to the left.    */
/* (entry) <---- ENTRY ----> (entry)   Global History takes the form of a doubly-linked list of   */
/*                 | ^                 history_entry structures, which may point to another       */
/*            users| |parent           doubly-linked list of structures recording the usage of    */
/*                 | |                 a History item by a specific browser. Within these         */
/*                 | |                 history_user records, there are doubly-linked references   */
/*                 | |(user)           to other history_user structures referring to the same     */
/*                 | |^                browser - in this way, a local visit History is held. The  */
/*                 | ||prev            history_user structures point back to the history_entry    */
/*                 | ||                structures through the 'parent' field.                     */
/*                 v ||                                                                           */
/*    (LHPU) <---- USER ----> (LHNU)   LHPU and LHNU stand for 'Local History [Prev/Next] User'.  */
/*    history_prev    | history_next                                                              */
/*                    |                All memory allocations are through malloc, since the       */
/*                    |next            blocks in use are typically small and must not move (so a  */
/*                    v                granular allocation system or a shifting heap such as      */
/*                    (user)           that provided by flexlib would be inappropriate).          */
/*                                                                                                */
/* Two records are kept in the browser_data structure which are, as far as anyone else is         */
/* concerned, magic words. They are in fact both history_user pointers cast to void *. One is     */
/* updated every time a new history_user entry is created - this is needed so that prev/next      */
/* pointers within all the items relevant to the browser's local History may be updated quickly.  */
/* The other is a pointer to a history_user struct which when non-NULL, indicates a position      */
/* within the History itself.                                                                     */
/*                                                                                                */
/* Note that one history_entry may have several history_user structs threading through it for the */
/* same browser, if a user keeps going back to the same page by following links.                  */
/*                                                                                                */
/**************************************************************************************************/

/* Internationalisation support */

#ifdef UNIFONT
  #define CHARSET_SPECIFIER "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"
#else
  #define CHARSET_SPECIFIER "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n"
#endif
111

112
/* Local definitions */
113

114
#define HistoryWrite(fn) {written = (fn); if (written < 0) goto history_save_error;}
115

116
/* Main History list structures */
117

118
struct history_entry;
119

120 121 122
/* Record usage by a specific browser */

typedef struct history_user
123
{
124
  struct history_entry * parent;
125

126 127
  struct history_user  * next;
  struct history_user  * prev;
128

129 130
  struct history_user  * history_next; /* (For the browser history, this is NOT a linked list) */
  struct history_user  * history_prev;
131

132 133 134 135
  browser_data         * user;
  unsigned int           last_accessed;
}
history_user;
136

137 138
/* Global History structure, which points to */
/* an array of usage structures (see above)  */
139

140 141 142 143
typedef struct history_entry
{
  struct history_entry * next;
  struct history_entry * prev;
144

145 146
  url_description      * url; /* (Defined in URLutils.h) */
  unsigned int           hash;
147
  char                 * title;
148

149
  history_user         * users;
150

151 152 153
  unsigned int           last_accessed;
}
history_entry;
154

155
/* Static variables */
156

157
static history_entry   * history_base = NULL;
158

159 160
static void            * history_menu = NULL;
static int               menu_entries = 0;
161

162 163 164 165
static history_user   ** user_array   = NULL;
static history_entry  ** entry_array  = NULL;
static int               nusers       = 0;
static int               nentries     = 0;
166

167
/* Static function prototypes */
168

169 170
static history_entry   * history_find_entry      (const char * url);
static history_user    * history_find_user       (browser_data * b, history_entry * entry);
171

172 173 174
static _kernel_oserror * history_add_user        (browser_data * b, history_entry * found, history_user ** created);
static void              history_remove_user     (history_user * user);
static void              history_remove_entry    (browser_data * b, history_entry * entry);
175

176
static int               history_compare_entries (const void * first, const void * second);
177 178

/*************************************************/
179
/* history_find_entry()                          */
180
/*                                               */
181 182
/* Returns a pointer to a history_entry for a    */
/* given URL.                                    */
183
/*                                               */
184 185
/* Parameters: Pointer to a null-terminated URL  */
/*             string to find.                   */
186
/*                                               */
187 188 189 190
/* Returns:    Pointer to a history_entry struct */
/*             representing the given URL, or    */
/*             NULL if no such entry is found    */
/*             in the History.                   */
191 192
/*************************************************/

193
static history_entry * history_find_entry(const char * url)
194
{
195 196
  history_entry   * find = history_base;
  url_description * url_d;
197
  int               hash;
198

199
  if (!url || !*url) return NULL;
200

201
  /* Get a description of the URL - makes comparissons faster */
202

203 204
  url_d = urlutils_return_description(url);
  if (!url_d) return NULL;
205

206 207
  hash = utils_return_hash(url_d->full);

208
  /* Search the list */
209

210 211
  while (find)
  {
212
    if (hash == find->hash && !urlutils_urlddcmp(find->url, url_d)) break;
213

214 215
    find = find->next;
  }
216

217
  urlutils_free_description(url_d);
218

219
  return find;
220 221 222
}

/*************************************************/
223
/* history_find_user                             */
224
/*                                               */
225 226
/* Returns a pointer to a history_user for a     */
/* given browser in a given History entry.       */
227
/*                                               */
228 229 230 231 232 233 234 235 236
/* Parameters: Pointer to a browser_data struct  */
/*             represented by the entry;         */
/*                                               */
/*             Pointer to a history_entry struct */
/*             to search in.                     */
/*                                               */
/* Returns:    Pointer to a history_user struct  */
/*             representing the given browser or */
/*             NULL if no such entry is found.   */
237 238
/*************************************************/

239
static history_user * history_find_user(browser_data * b, history_entry * entry)
240
{
241
  history_user * user;
242

243
  if (!b || !entry) return NULL;
244

245
  /* Search the list */
246

247
  user = entry->users;
248

249 250 251
  while (user)
  {
    if (user->user == b) return user;
252

253 254
    user = user->next;
  }
255

256 257
  return NULL;
}
258

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
/*************************************************/
/* history_add_user()                            */
/*                                               */
/* Add an association of a given browser with a  */
/* given History entry, updating the browser's   */
/* record of where it is in the local History to */
/* the new association (user record). This last  */
/* step is required if subsequent additions are  */
/* to be correctly linked into the local History */
/* list (history_next and history_prev fields).  */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the association;      */
/*                                               */
/*             Pointer to a history_entry struct */
/*             to associate the browser to;      */
/*                                               */
/*             Pointer to a history_user *,      */
/*             in which the address of the new   */
/*             user record will be placed.       */
/*                                               */
/* Assumes:    The history_user * pointer may    */
/*             be NULL.                          */
/*************************************************/
283

284 285 286
static _kernel_oserror * history_add_user(browser_data * b, history_entry * found, history_user ** created)
{
  history_user * newuser;
287

288 289 290
  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_add_user: Called for browser %p, entry %p\n",b,found);
  #endif
291

292
  if (created) *created = NULL;
293

294
  newuser = malloc(sizeof(history_user));
295

296 297 298 299 300 301
  if (!newuser)
  {
    /* Oh just great, the allocation failed. Well, rather */
    /* than scrap everything, leave the global entry      */
    /* alone - just don't create the extra reference to   */
    /* this browser.                                      */
302

303 304 305
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_add_user: Could not allocate space for user record\n");
    #endif
306

307 308
    return make_no_memory_error(25);
  }
309

310 311 312
  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_add_user: New user record is %p\n", newuser);
  #endif
313

314 315
  /* Insert the item into the linked list of history_user */
  /* structures for this history_entry structure.         */
316

317
  newuser->parent = found;
318

319
  if (found->users) found->users->prev = newuser;
320

321 322
  newuser->next = found->users;
  newuser->prev = NULL;
323

324
  found->users  = newuser;
325

326 327
  /* Link the item into the linked list of history_user */
  /* structures forming the browser local history.      */
328

329 330 331
  newuser->history_prev = (history_user *) b->history_current;
  newuser->history_next = NULL;
  newuser->user         = b;
332

333
  /* Fill in the accessed time */
334

335
  newuser->last_accessed = found->last_accessed;
336

337 338 339 340
  /* If newuser->history_prev points in its history_next  */
  /* field to any other items, remove them, because we've */
  /* just branched the history at this point by adding    */
  /* the new item.                                        */
341

342 343 344 345
  if (newuser->history_prev && newuser->history_prev->history_next)
  {
    history_user * current = newuser->history_prev->history_next;
    history_user * next;
346

347 348 349
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_add_user: Adding from within an existing history; removing later entries...\n");
    #endif
350

351
    while (current)
352
    {
353
      next = current->history_next;
354 355

      #ifdef TRACE
356
        if (tl & (1u<<16)) Printf("history_add_user: Calling history_remove_user for user record %p\n",current);
357 358
      #endif

359
      history_remove_user(current);
360

361
      current = next;
362
    }
363
  }
364

365
  /* Fill in the link to the new structure */
366

367
  if (newuser->history_prev) newuser->history_prev->history_next = newuser;
368

369
  b->history_current = (void *) newuser;
370 371

  #ifdef TRACE
372
    if (tl & (1u<<16)) Printf("history_add_user: Successful\n");
373 374
  #endif

375 376
  if (created) *created = newuser;

377 378 379 380
  return NULL;
}

/*************************************************/
381
/* history_record()                              */
382
/*                                               */
383 384 385
/* Records the visiting of a given URL in the    */
/* History, optionally associating this visit    */
/* with a given browser.                         */
386
/*                                               */
387 388 389
/* If there is already an entry for this URL, it */
/* will simply have its latest visit time        */
/* record updated.                               */
390 391
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
392 393
/*             to associate the visit with, or   */
/*             NULL for none;                    */
394
/*                                               */
395 396
/*             Pointer to a null-terminated URL  */
/*             string to record.                 */
397 398
/*************************************************/

399
_kernel_oserror * history_record(browser_data * b, const char * url)
400
{
401 402
  history_entry * found   = NULL;
  history_user  * newuser = NULL;
403 404

  if (!url || !*url) return NULL;
405 406

  #ifdef TRACE
407
    if (tl & (1u<<16)) Printf("history_record: Called for %p and '%s'\n",b,url);
408 409
  #endif

410
  /* First, see if we have the URL present already */
411

412
  found = history_find_entry(url);
413

414 415 416 417
  /* If this is for a specific browser which is fetching */
  /* from its own local History, then we don't record    */
  /* anything (it'd corrupt the history ordering). We    */
  /* should, however, update the timestamps.             */
418

419
  if (b && b->from_history)
420
  {
421 422 423
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_record: Browser fetching from History; updating timestamps and exitting\n");
    #endif
424

425
    if (found)
426
    {
427
      found->last_accessed = time(NULL);
428

429
      newuser = history_find_user(b, found);
430

431
      if (newuser) newuser->last_accessed = found->last_accessed;
432 433
    }

434 435
    return NULL;
  }
436

437 438 439 440
  /* If not fetching from the local History, proceed as normal */

  if (!found)
  {
441
    #ifdef TRACE
442
      if (tl & (1u<<16)) Printf("history_record: No existing entry, so creating a new one\n");
443 444
    #endif

445
    /* Need to create an entry */
446

447 448 449 450 451 452 453
    found = malloc(sizeof(history_entry));

    if (!found)
    {
      #ifdef TRACE
        if (tl & (1u<<16)) Printf("history_record: Couldn't allocate space for entry\n");
      #endif
454

455 456
      return make_no_memory_error(25);
    }
457

458 459 460
    /* Need to turn the URL into a more complete description, */
    /* but if we get NULL back, memory allocation must have   */
    /* failed somewhere.                                      */
461

462
    found->url = urlutils_return_description(url);
463

464
    if (!found->url)
465
    {
466 467
      free(found);

468
      #ifdef TRACE
469
        if (tl & (1u<<16)) Printf("history_record: Couldn't allocate space for URL description\n");
470 471
      #endif

472
      return make_no_memory_error(25);
473
    }
474 475 476 477 478 479
    else
    {
      /* Create a hash number for the string */

      found->hash = utils_return_hash(found->url->full);
    }
480

481
    /* Link in the structure */
482

483 484
    found->prev = NULL;
    found->next = history_base;
485

486
    if (history_base) history_base->prev = found;
487

488
    history_base = found;
489

490
    /* Fill in some other fields */
491

492 493
    found->title = NULL;
    found->users = NULL;
494

495 496 497
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_record: OK, have entry %p with description block %p\n",found,found->url);
    #endif
498 499 500
  }

  #ifdef TRACE
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    else
    {
      if (tl & (1u<<16)) Printf("history_record: Already have an entry %p\n",found);
    }
  #endif

  /* Update the last accessed time for the global record */

  found->last_accessed = time(NULL);

  /* Always add a usage record for the browser, unless the URL being     */
  /* added matches that represented by the item the browser is currently */
  /* on in terms of its visit history.                                   */

  if (
       b &&
       (
         !b->history_current ||
         (
           ((history_user *) b->history_current)->parent != found
         )
       )
     )
     RetError(history_add_user(b, found, NULL));

  #ifdef TRACE
    if (tl & (1u<<16))
    {
      Printf("history_record: Successful. History size is now %d\n", history_count());
      Printf("                Exitting through expiry functions.\n");
    }
532 533
  #endif

534 535 536
  if (choices.expiry_age) RetError(history_expire(NULL, time(NULL) - choices.expiry_age));
  if (choices.max_size)   RetError(history_limit(choices.max_size));

537 538 539 540 541 542 543 544
  #ifdef SINGLE_USER

    if (choices.save_history == Choices_SaveHistory_Always)
    {
      return history_save(lookup_choice("HistorySave:Browse:User.History",0,0));
    }

  #endif
545

546 547 548 549
  return NULL;
}

/*************************************************/
550
/* history_inherit()                             */
551
/*                                               */
552 553 554 555 556 557
/* For any association in the History of a given */
/* base (parent) browser with a URL, create a    */
/* duplicate associaton with a given child       */
/* browser with the same visit timestamps. The   */
/* child browser thus inherits the history of    */
/* the parent.                                   */
558
/*                                               */
559 560 561
/* The history_current field of the child is set */
/* to the child's equivalent of the field in the */
/* parent.                                       */
562
/*                                               */
563 564
/* Parameters: Pointer to a browser_data struct  */
/*             representing the parent browser;  */
565
/*                                               */
566 567
/*             Pointer to a browser_data struct  */
/*             representing the child browser.   */
568
/*                                               */
569 570 571 572 573
/* Assumes:    The child browser has no existing */
/*             history references. If it does,   */
/*             then this will become detached as */
/*             the new references are put in     */
/*             place.                            */
574 575
/*************************************************/

576
_kernel_oserror * history_inherit(browser_data * parent, browser_data * child)
577
{
578 579 580 581
  history_user * parent_user;
  history_user * parent_current;
  history_user * child_user;
  history_user * child_equivalent = NULL;
582

583 584 585 586 587 588
  if (!parent || !child) return NULL;

  parent_user    = (history_user *) parent->history_current;
  parent_current = parent_user;

  if (!parent_user) return NULL; /* Nothing to inherit */
589

590
  /* Find the first item in the local History */
591

592 593 594 595 596 597 598
  while (parent_user->history_prev) parent_user = parent_user->history_prev;

  /* Now go through adding users for the new browser */

  child->history_current = NULL;

  while (parent_user)
599
  {
600 601 602 603 604 605 606 607 608 609 610 611 612
    /* Add the user record for the child */

    RetError(history_add_user(child, parent_user->parent, &child_user));

    /* If this record is equivalent to the history_current field */
    /* of the parent, remember the new user record's address in  */
    /* 'child_equivalent'.                                       */

    if (parent_user == parent_current) child_equivalent = child_user;

    /* Go on to the next user record in the parent's History */

    parent_user = parent_user->history_next;
613 614
  }

615 616
  /* Set the child's history_current field to the equivalent */
  /* of the same field in the parent.                        */
617

618
  if (child_equivalent) child->history_current = (void *) child_equivalent;
619

620
  /* Finished */
621

622
  return NULL;
623 624 625
}

/*************************************************/
626
/* history_remove_user()                         */
627
/*                                               */
628 629
/* Removes a given history_user record from the  */
/* various lists in which it may lie.            */
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
/* Parameters: Pointer to the history_user       */
/*             structure to remove.              */
/*************************************************/

static void history_remove_user(history_user * user)
{
  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_remove_user: Called for %p\n",user);
  #endif

  if (!user) return;

  /* Repoint within the linked list of items attached to a history_entry structure, */
  /* and within the local history list.                                             */

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

  if (user->history_prev) user->history_prev->history_next = user->history_next;
  if (user->history_next) user->history_next->history_prev = user->history_prev;

  /* If required, repoint the parent history_entry structure's 'users' field. */

  if (user == user->parent->users) user->parent->users = user->next;

  /* Does the owner browser point to this item? If so, invalidate */
  /* that pointer (set it to NULL).                               */

  if (
       is_known_browser(user->user)                 &&
       user->user->history_current == (void *) user
     )
     user->user->history_current = NULL;

  /* Finally, free the item. */

  free(user);

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

  return;
}

/*************************************************/
/* history_remove_entry()                        */
678
/*                                               */
679 680 681 682 683 684 685
/* Removes a given record from the History,      */
/* removes all associations with this entry,     */
/* and/or removes all associations between any   */
/* URLs in the History and a given browser. In   */
/* the latter case, URLs left with no            */
/* assocations are *not* removed; they stay as   */
/* global visit History records.                 */
686
/*                                               */
687 688 689
/* Parameters: Pointer to a browser_data struct  */
/*             to remove all associations for,   */
/*             or NULL to not do this;           */
690
/*                                               */
691 692 693
/*             Pointer to the history_entry      */
/*             struct to remove, or NULL not to  */
/*             do this;                          */
694
/*                                               */
695 696 697 698
/* Assumes:    Either or both pointers may be    */
/*             valid or NULL, though obviously   */
/*             there's little point calling with */
/*             both set to NULL...               */
699 700
/*************************************************/

701
static void history_remove_entry(browser_data * b, history_entry * entry)
702 703
{
  #ifdef TRACE
704
    if (tl & (1u<<16)) Printf("history_remove_entry: Called for browser %p, entry %p\n",b,entry);
705 706
  #endif

707
  if (entry)
708
  {
709 710
    history_user * user = entry->users;
    history_user * next;
711

712
    /* We've found the entry. First remove all user structures */
713 714

    #ifdef TRACE
715
      if (tl & (1u<<16)) Printf("history_remove_entry: Have found the entry - removing user records...\n");
716 717
    #endif

718 719 720
    while (user)
    {
      next = user->next;
721

722 723 724
      #ifdef TRACE
        if (tl & (1u<<16)) Printf("history_remove_entry: Calling history_remove_user for user record %p\n",user);
      #endif
725

726 727 728 729 730 731 732 733 734 735 736 737 738 739
      history_remove_user(user);

      user = next;
    }

    /* Point other History entries elsewhere too, and correct */
    /* the history_base pointer if required.                  */

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

    if (entry == history_base) history_base = entry->next;

    /* Free the URL description */
740 741

    #ifdef TRACE
742
      if (tl & (1u<<16)) Printf("history_remove_entry: Calling urlutils_free_description for URL description %p\n",entry->url);
743 744
    #endif

745 746 747
    urlutils_free_description(entry->url);

    /* Free the title string */
748

749 750 751
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_remove_entry: Freeing entry title string\n");
    #endif
752

753
    free(entry->title);
754

755
    /* Free the entry */
756 757

    #ifdef TRACE
758
      if (tl & (1u<<16)) Printf("history_remove_entry: Freeing entry itself\n");
759 760
    #endif

761
    free(entry);
762 763
  }

764
  /* Deal with removing all associations for a given browser */
765

766
  if (b)
767
  {
768 769
    history_user * user;
    history_user * next;
770 771

    #ifdef TRACE
772
      if (tl & (1u<<16)) Printf("history_remove_entry: Removing all user records for browser %p\n",b);
773 774
    #endif

775
    entry = history_base;
776

777 778 779 780 781 782 783 784 785 786 787
    /* Go through all entries... */

    while (entry)
    {
      user = entry->users;

      /* ...and all users (associations) in each entry... */

      while (user)
      {
        next = user->next;
788

789
        /* ...and remove any associated with the given browser. */
790

791 792 793 794 795 796 797 798
        if (user->user == b)
        {
          #ifdef TRACE
            if (tl & (1u<<16)) Printf("history_remove_entry: Calling history_remove_user for user record %p\n",user);
          #endif

          history_remove_user(user);
        }
799

800 801
        user = next;
      }
802

803 804 805
      entry = entry->next;
    }
  }
806

807
  /* Finished */
808 809

  #ifdef TRACE
810
    if (tl & (1u<<16)) Printf("history_remove_entry: Successful\n");
811 812
  #endif

813
  return;
814 815 816
}

/*************************************************/
817
/* history_remove()                              */
818
/*                                               */
819 820 821 822 823 824 825
/* Removes a record in the History of a given    */
/* URL and all associations with this URL,       */
/* and/or removes all associations between any   */
/* URLs in the History and a given browser. In   */
/* the latter case, URLs left with no            */
/* assocations are *not* removed; they stay as   */
/* global visit History records.                 */
826 827
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
828 829
/*             to remove all associations for,   */
/*             or NULL to not do this;           */
830
/*                                               */
831 832 833 834 835 836 837 838
/*             Pointer to a null-terminated URL  */
/*             string to remove, or NULL to not  */
/*             do this.                          */
/*                                               */
/* Assumes:    Either or both pointers may be    */
/*             valid or NULL, though obviously   */
/*             there's little point calling with */
/*             both set to NULL...               */
839 840
/*************************************************/

841
void history_remove(browser_data * b, const char * url)
842
{
843
  history_entry * entry = NULL;
844 845

  #ifdef TRACE
846
    if (tl & (1u<<16)) Printf("history_remove: Called for browser %p, URL address %p\n",b,url);
847 848
  #endif

849
  /* Deal with removing a specific URL */
850

851 852
  if (url)
  {
853
    #ifdef TRACE
854
      if (tl & (1u<<16)) Printf("history_remove: Removing entry for URL '%s'\n",url);
855 856
    #endif

857
    entry = history_find_entry(url);
858

859 860 861 862
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_remove: Entry for this URL %p\n",entry);
    #endif
  }
863

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_remove: Calling history_remove_entry\n");
  #endif

  history_remove_entry(b, entry);

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_remove: Successful. History size is now %d\n", history_count());
  #endif
}

/*************************************************/
/* history_add_title()                           */
/*                                               */
/* Associates a given title string with a given  */
/* URL and all associations with this URL,       */
/* and/or removes all associations between any   */
/* URLs in the History and a given browser.      */
/*                                               */
/* Parameters: Pointer to a null-terminated URL  */
/*             string for which the title is to  */
/*             be associated;                    */
/*                                               */
/*             Pointer to a null-terminated      */
/*             title string to associate with    */
/*             the URL.                          */
/*************************************************/

_kernel_oserror * history_add_title(const char * url, const char * title)
{
  history_entry * entry;

  if (!url || !*url || !title || !*title) return NULL;

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_add_title: Called for URL '%s'\n"
                              "                        and title '%s'\n",url,title);
  #endif

  /* Find the item */

  entry = history_find_entry(url);

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_add_title: Entry returned by history_find_entry is 0x%08x\n",entry);
  #endif

  if (!entry) return NULL;

  /* Add the title */

  free(entry->title);

  entry->title = malloc(strlen(title) + 1);

  if (!entry->title)
  {
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_add_title: Couldn't allocate space for title string\n");
    #endif

    return make_no_memory_error(26);
  }
  else strcpy(entry->title, title);

  /* Finished */

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_add_title: Successful. History size is now %d\n", history_count());
  #endif

  return NULL;
}

/*************************************************/
/* history_return_title()                        */
/*                                               */
/* Returns a title string (if any) associated    */
/* with a given URL.                             */
/*                                               */
/* Parameters: Pointer to a null-terminated URL  */
/*             string for which a title is to be */
/*             found.                            */
/*                                               */
/* Returns:    Pointer to a null-terminated      */
/*             title string associated with the  */
/*             URL, or NULL if either the URL    */
/*             had no associated title, or the   */
/*             URL couldn't be found in the      */
/*             History at all.                   */
/*************************************************/

char * history_return_title(char * url)
{
  history_entry * entry;
959

960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
  if (!url || !*url) return NULL;

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_return_title: Called for URL '%s'\n",url);
  #endif

  entry = history_find_entry(url);

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_return_title: Entry returned by history_find_entry is 0x%08x\n",entry);
  #endif

  if (!entry) return NULL;

  #ifdef TRACE

    if (tl & (1u<<16))
977
    {
978 979
      if (entry->title) Printf("history_return_title: Successful, returning '%s'\n",entry->title);
      else              Printf("history_return_title: Successful, but there is no title (returning NULL)\n");
980 981
    }

982 983 984 985
  #endif

  return entry->title;
}
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
/*************************************************/
/* history_expire()                              */
/*                                               */
/* Remove all associations of a URL which have   */
/* been visited before a given time (i.e. are    */
/* greater than a certain age). This may only be */
/* for associations with a specific browser.     */
/*                                               */
/* Any URL left with no associations and an      */
/* overall last visit time before that given     */
/* will be removed from the History completely.  */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             for which associations are to be  */
/*             expired, or NULL if the expiry is */
/*             for all History items;            */
/*                                               */
/*             Time (in time() function format)  */
/*             which a URL must have not been    */
/*             visited on or since for expiry to */
/*             take place - so to expire 1 day   */
/*             old URLs, say, you'd pass         */
/*             time() - 60*60*24.                */
/*************************************************/
1011

1012
_kernel_oserror * history_expire(browser_data * b, unsigned int time)
1013 1014 1015 1016 1017
{
  history_entry * this_entry;
  history_entry * next_entry;
  history_user  * this_user;
  history_user  * next_user;
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
  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_expire: Called for %p and time %d\n",b,time);
  #endif

  this_entry = history_base;

  /* Scan the main entry list */

  while (this_entry)
  {
    next_entry = this_entry->next;
    this_user  = this_entry->users;

    /* For each entry, scan the associated users */

    while (this_user)
    {
      next_user = this_user->next;

      /* If we've not been given a browser, or we have and it matches */
      /* the user for this user record, and the last accessed time is */
      /* earlier than that given (the record is older), remove it.    */

      if ((!b || this_user->user == b) && this_user->last_accessed < time)
      {
        #ifdef TRACE
          if (tl & (1u<<16)) Printf("history_expire: Calling history_remove_user for user record %p\n",this_user);
        #endif

        history_remove_user(this_user);
      }

      this_user = next_user;
    }

    /* If this item has no users [now], and the last accessed time */
    /* is earlier than that given (the entry is older), remove it. */

    if (!this_entry->users && this_entry->last_accessed < time)
1058 1059
    {
      #ifdef TRACE
1060
        if (tl & (1u<<16)) Printf("history_expire: Calling history_remove_entry for entry %p\n",this_entry);
1061 1062
      #endif

1063 1064 1065 1066 1067 1068 1069
      history_remove_entry(NULL, this_entry);
    }

    /* Next... */

    this_entry = next_entry;
  }
1070

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  openurl_update_popup();

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_expire: Successful, exitting through toolbars_set_all_button_states\n");
  #endif

  return toolbars_set_all_button_states();
}

/*************************************************/
/* history_count()                               */
/*                                               */
/* Counts the size in memory of all strings and  */
/* structures used by the History.               */
/*                                               */
/* Returns:    Size of all strings and structs   */
/*             used by the History, in bytes.    */
/*************************************************/

int history_count(void)
{
  int             count = 0;
  history_entry * entry = history_base;
  history_user  * user;

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

  while (entry)
  {
    /* Work out how much the entry takes up. First */
    /* the structure itself.                       */

    count += sizeof(entry);

    /* The title string, if present */

    if (entry->title) count += strlen(entry->title) + 1;

    /* The URL description, if present (should always be!) */

    if (entry->url)
    {
      /* This has a structure itself */

      count += sizeof(url_description);

      /* Then add in all the strings it can carry */

      if (entry->url->full)     count += strlen(entry->url->full)     + 1;
      if (entry->url->protocol) count += strlen(entry->url->protocol) + 1;
      if (entry->url->host)     count += strlen(entry->url->host)     + 1;
      if (entry->url->port)     count += strlen(entry->url->port)     + 1;
      if (entry->url->user)     count += strlen(entry->url->user)     + 1;
      if (entry->url->password) count += strlen(entry->url->password) + 1;
      if (entry->url->account)  count += strlen(entry->url->account)  + 1;
      if (entry->url->path)     count += strlen(entry->url->path)     + 1;
      if (entry->url->query)    count += strlen(entry->url->query)    + 1;
      if (entry->url->fragment) count += strlen(entry->url->fragment) + 1;
1131
    }
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

    /* Now deal with any user records in this entry */

    user = entry->users;

    while (user)
    {
      /* Only need to count the structure size itself here */

      count += sizeof(history_user);

      user = user->next;
    }

    /* Next entry */

    entry = entry->next;
  }

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_count: Successful, returning %d\n", count);
  #endif

  return count;
}

/*************************************************/
/* history_limit()                               */
/*                                               */
/* Counts the history size, and will expire the  */
/* oldest item if it is over the given size.     */
/* This continues until the history falls at or  */
/* below the given size limit.                   */
/*                                               */
/* This is quite a slow process.                 */
/*                                               */
/* Parameters: Size in bytes at or below which   */
/*             the history is to fall on exit.   */
/*************************************************/

1172
_kernel_oserror * history_limit(unsigned int size)
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
{
  int size_now;

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_limit: Called with limit size %d\n",size);
  #endif

  do
  {
    size_now = history_count();

    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_limit: Current size is %d\n",size_now);
    #endif

    if (size_now > size)
1189
    {
1190 1191 1192 1193 1194 1195
      history_entry * entry  = history_base;
      history_entry * old    = NULL;
      int             oldest = 0;

      /* If we're oversize, find the oldest item */

1196
      #ifdef TRACE
1197
        if (tl & (1u<<16)) Printf("history_limit: Need to remove entries\n");
1198 1199
      #endif

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
      while (entry)
      {
        if (!oldest || entry->last_accessed < oldest) oldest = entry->last_accessed, old = entry;

        entry = entry->next;
      }

      /* Now expire it */

      #ifdef TRACE
        if (tl & (1u<<16)) Printf("history_limit: Expiring entry %p\n", old);
      #endif

      if (old) history_remove_entry(NULL, old);
1214
    }
1215 1216

    /* Continue until we fall within the required size */
1217
  }
1218 1219 1220 1221 1222 1223
  while (size_now > size);

  /* Exit through a toolbar button update, as some local histories */
  /* may well have been disturbed by the loss of History entries.  */

  openurl_update_popup();
1224 1225

  #ifdef TRACE
1226
    if (tl & (1u<<16)) Printf("history_limit: Successful, exitting through toolbars_set_all_button_states\n");
1227 1228
  #endif

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
  return toolbars_set_all_button_states();
}

/*************************************************/
/* history_visited()                             */
/*                                               */
/* Returns 1 if a given URL is in the History,   */
/* else 0.                                       */
/*                                               */
/* Parameters: Pointer to a null-terminated URL  */
/*             string to look for.               */
/*                                               */
/* Returns:    1 if a record of this can be      */
/*             found in the History, else 0.     */
/*************************************************/

int history_visited(const char * url)
{
  if (history_find_entry(url)) return 1;

  return 0;
}

/*************************************************/
/* history_empty()                               */
/*                                               */
/* Inquire if there are any History items        */
/* present for a given browser or the global     */
/* History.                                      */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the enquiry, or NULL  */
/*             for the global History.           */
/*                                               */
/* Returns:    1 if there are no items, else 0.  */
/*************************************************/

int history_empty(browser_data * b)
{
  if (!b) return !history_base;

  return !b->history_current;
}

/*************************************************/
/* history_can_go_backwards()                    */
/*                                               */
/* Reports whether or not there are more pages   */
/* to go back to in the local History of a       */
/* given browser.                                */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the History.          */
/*                                               */
/* Returns:    1 if there are more items in the  */
/*             local history to go back to, else */
/*             0.                                */
/*************************************************/

int history_can_go_backwards(browser_data * b)
{
  history_user * user;

  if (!b) return 0;

  user = (history_user *) b->history_current;

  if (!user || !user->history_prev) return 0;

  return 1;
}

/*************************************************/
/* history_can_go_forwards()                     */
/*                                               */
/* Reports whether or not there are more pages   */
/* to go forward to in the local History of a    */
/* given browser.                                */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the History.          */
/*                                               */
/* Returns:    1 if there are more items in the  */
/*             local history to go forwards to,  */
/*             else 0.                           */
/*************************************************/

int history_can_go_forwards(browser_data * b)
{
  history_user * user;

  if (!b) return 0;

  user = (history_user *) b->history_current;

  if (!user || !user->history_next) return 0;

  return 1;
1327 1328 1329 1330 1331 1332
}

/*************************************************/
/* history_fetch_backwards()                     */
/*                                               */
/* When called, will fetch the previous page in  */
1333
/* a given browser's local History.              */
1334 1335
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
1336
/*             relevant to the History;          */
1337
/*                                               */
1338 1339 1340 1341 1342 1343 1344 1345
/*             1 to open the URL in a new window */
/*             or 0 to open it in the window to  */
/*             which the browser_data struct is  */
/*             relevant.                         */
/*************************************************/

_kernel_oserror * history_fetch_backwards(browser_data * b, int new_view)
{
1346 1347 1348
  history_user * user;
  const char   * url;

1349
  #ifdef TRACE
1350
    if (tl & (1u<<16)) Printf("history_fetch_backwards: Called for %p\n", b);
1351 1352
  #endif

1353 1354
  if (!is_known_browser(b)) return NULL;

1355 1356
  /* Only proceed if we're not right at the start of the history */

1357
  user = (history_user *) b->history_current;
1358

1359 1360
  if (!user || !user->history_prev)
  {
1361
    #ifdef TRACE
1362
      if (tl & (1u<<16)) Printf("history_fetch_backwards: Can't go back any further, exitting\n");
1363 1364
    #endif

1365
    return NULL;
1366
  }
1367

1368 1369 1370
  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_fetch_backwards: Proceeding\n");
  #endif
1371

1372 1373 1374 1375 1376
  /* Step backwards - even if we're going to open a new view, */
  /* when the child inherits the parent's history this needs  */
  /* to have been set up to make sure the child gains the     */
  /* right position in the inherited history list. We will    */
  /* correct the parent's history position later.             */
1377

1378
  b->history_current = (void *) (user->history_prev);
1379

1380
  /* Get a pointer to the URL */
1381

1382
  url = user->history_prev->parent->url->full;
1383

1384
  /* Flag that this will be a History based fetch */
1385

1386
  b->from_history = 1;
1387

1388
  /* Get the URL in either the same window or a new window. */
1389

1390 1391 1392 1393 1394
  if (!new_view)
  {
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_fetch_backwards: Exitting through fetchpage_new\n");
    #endif
1395

1396
    /* Fetch the URL, flagging not to record this URL in the history */
1397

1398 1399 1400 1401 1402
    return (fetchpage_new(b, (char *) url, 0, 1));
  }
  else
  {
    #ifdef TRACE
1403
      if (tl & (1u<<16)) Printf("history_fetch_backwards: Exitting through windows_create_browser and browser_inherit\n");
1404
    #endif
1405

1406 1407 1408 1409 1410 1411 1412 1413 1414
    RetError(windows_create_browser((char *) url, NULL, NULL, NULL, Windows_CreateBrowser_Normal));
    RetError(browser_inherit(b, last_browser));

    /* We didn't end up moving anywhere in b, and only stepped backwards */
    /* so that the indirectly called history_inherit could work properly */
    /* - so now make sure that b's current history position has not been */
    /* altered.                                                          */

    b->history_current = (void *) (user);
1415
  }
1416 1417

  return NULL;
1418
}
1419

1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
/*************************************************/
/* history_fetch_forwards()                      */
/*                                               */
/* When called, will fetch the next page in a    */
/* given browser's local History.                */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the History;          */
/*                                               */
/*             1 to open the URL in a new window */
/*             or 0 to open it in the window to  */
/*             which the browser_data struct is  */
/*             relevant.                         */
/*************************************************/
1434

1435 1436 1437 1438
_kernel_oserror * history_fetch_forwards(browser_data * b, int new_view)
{
  history_user * user;
  const char   * url;
1439

1440 1441 1442
  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_fetch_forwards: Called for %p\n", b);
  #endif
1443

1444
  if (!is_known_browser(b)) return NULL;
1445

1446
  /* Only proceed if we're not right at the start of the history */
1447

1448
  user = (history_user *) b->history_current;
1449

1450 1451 1452 1453 1454 1455 1456
  if (!user || !user->history_next)
  {
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_fetch_forwards: Can't go forwards any further, exitting\n");
    #endif

   return NULL;
1457 1458 1459
  }

  #ifdef TRACE
1460
    if (tl & (1u<<16)) Printf("history_fetch_forwards: Proceeding\n");
1461 1462
  #endif

1463 1464 1465 1466 1467
  /* Step forwards - even if we're going to open a new view, */
  /* when the child inherits the parent's history this needs */
  /* to have been set up to make sure the child gains the    */
  /* right position in the inherited history list. We will   */
  /* correct the parent's history position later.            */
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493

  b->history_current = (void *) (user->history_next);

  /* Get a pointer to the URL */

  url = user->history_next->parent->url->full;

  /* Flag that this will be a History based fetch */

  b->from_history = 1;

  /* Get the URL in either the same window or a new window. */

  if (!new_view)
  {
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_fetch_forwards: Exitting through fetchpage_new\n");
    #endif

    /* Fetch the URL, flagging not to record this URL in the history */

    return (fetchpage_new(b, (char *) url, 0, 1));
  }
  else
  {
    #ifdef TRACE
1494
      if (tl & (1u<<16)) Printf("history_fetch_forwards: Exitting through windows_create_browser and browser_inherit\n");
1495 1496
    #endif

1497 1498 1499 1500 1501 1502 1503 1504 1505
    RetError(windows_create_browser((char *) url, NULL, NULL, NULL, Windows_CreateBrowser_Normal));
    RetError(browser_inherit(b, last_browser));

    /* We didn't end up moving anywhere in b, and only stepped forwards  */
    /* so that the indirectly called history_inherit could work properly */
    /* - so now make sure that b's current history position has not been */
    /* altered.                                                          */

    b->history_current = (void *) (user);
1506
  }
1507 1508

  return NULL;
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
/*************************************************/
/* history_menu_popup()                          */
/*                                               */
/* Handles clicks on a history menu popup item.  */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
/*             relevant to the history to show,  */
/*             or NULL if this is for a global   */
/*             history from an OpenURL dialogue  */
/*             box;                              */
/*                                               */
/*             Object ID of the item holding the */
/*             menu gadget;                      */
/*                                               */
/*             Component ID of the item that was */
/*             clicked on;                       */
/*                                               */
/*             1 to show the global history even */
/*             if the first parameter is not     */
/*             NULL, else 0;                     */
/*                                               */
/*             1 to show the URLs, 0 to show     */
/*             page titles where available.      */
/*************************************************/

_kernel_oserror * history_menu_popup(browser_data * b, ObjectId object, ComponentId component, int global, int show_urls)
{
  _kernel_oserror         * e;
  WimpGetWindowStateBlock   state;
  BBox                      menu;

  /* If there's already a menu open, close it */
  /* (so the action is to toggle the menu).   */

  if ((menusrc == Menu_LocalHist || menusrc == Menu_GlobalHist) && menuhdl == b)
  {
    menusrc = Menu_None;
    menuhdl = NULL;

    return wimp_create_menu((void *) -1, 0, 0);
  }

  /* Get the Wimp handle for the tool bar and get the window state */

  e = window_get_wimp_handle(0, object, &state.window_handle);
  if (e) return e;

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

  /* Get the bounding box of the popup icon that was used */

  e = gadget_get_bbox(0, object, component, &menu);
  if (e) return e;

  /* Convert that to screen coords ready for opening the menu */
  /* next to it.                                              */

  coords_box_toscreen(&menu, (WimpRedrawWindowBlock *) &state);

1571
  if (component == URLBarHistoryMenuR || component == OpenHistory)
1572
  {
1573
    /* Build and show menu to right of menu icon for URLBarHistoryMenuR object */
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598

    e = (history_build_menu(b,
                            menu.xmax - 2,
                            menu.ymax,
                            global,
                            show_urls,
                            0));
    if (e) return e;
  }
  else
  {
    /* Otherwise, show it to the left of the icon */

    e = history_build_menu(b,
                           menu.xmin - 4,
                           menu.ymin + 4,
                           global,
                           show_urls,
                           1);
    if (e) return e;
  }

  return NULL;
}

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
/*************************************************/
/* history_compare_entries()                     */
/*                                               */
/* A comparisson function for qsort(); compares  */
/* the last_accessed fields of two given         */
/* history_entry structures so that an array     */
/* being sorted will have highest last_accessed  */
/* field (newest) items first.                   */
/*                                               */
/* Parameters: Pointer to the first              */
/*             history_entry struct as a void *. */
/*                                               */
/*             Pointer to the second             */
/*             history_entry struct as a void *. */
/*************************************************/

static int history_compare_entries(const void * first, const void * second)
{
  history_entry * f = *((history_entry **) first);
  history_entry * s = *((history_entry **) second);

  if (f->last_accessed < s->last_accessed) return 1; /* We want the greatest last_accessed field to come first */
  if (f->last_accessed > s->last_accessed) return -1;

  return 0;
}

1626 1627 1628 1629 1630 1631 1632
/*************************************************/
/* history_build_menu()                          */
/*                                               */
/* Builds a history menu for the given browser,  */
/* showing it at the specified coordinates.      */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
1633 1634
/*             relevant to the menu, or NULL to  */
/*             build from the global history;    */
1635 1636 1637 1638 1639
/*                                               */
/*             x coordinate to show at;          */
/*                                               */
/*             y coordinate to show at;          */
/*                                               */
1640 1641 1642 1643
/*             1 to show the global history even */
/*             if the first parameter is not     */
/*             NULL;                             */
/*                                               */
1644 1645 1646 1647 1648 1649 1650 1651 1652
/*             Non-0 to only show URLs, 0 to     */
/*             allow titles in the menu;         */
/*                                               */
/*             Non-0 to subtract the width of    */
/*             the menu from the given show x    */
/*             coordinate (e.g. to show to the   */
/*             left of a given position) else 0. */
/*************************************************/

1653
_kernel_oserror * history_build_menu(browser_data * b, int x, int y, int global, int show_urls, int subtract)
1654
{
1655 1656 1657 1658
  _kernel_oserror * e;
  wimp_menuhdr    * mhp;
  wimp_menuitem   * mip;
  char            * menudata;
1659

1660 1661 1662 1663
  int               i;
  int               size;
  int               width, awidth, thiswidth;
  int               len;
1664

1665
  /* Clear out any existing menu-related data */
1666

1667 1668 1669
  free(history_menu); history_menu = NULL;
  free(entry_array);  entry_array  = NULL, nentries = 0;
  free(user_array);   user_array   = NULL, nusers   = 0;
1670

1671 1672 1673
  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_build_menu: Called with %p\n", (void *) b);
  #endif
1674

1675
  /* If there are no History items, flag an error. */
1676

1677
  if (!history_base) goto history_build_menu_empty_history;
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689

  /* Work out the data size required for the menu structure. */
  /* Can't just point the menu to the history list as it's a */
  /* flex block, which may shift whilst the menu is open.    */

  size   = sizeof(wimp_menuhdr);
  width  = 8;
  awidth = 0;

  /* Loop round finding the string length of the longest entry */
  /* in 'width' and the OS unit width of it in 'awidth'.       */

1690 1691
  _swix(Hourglass_On, 0);

1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
  #ifdef TRACE
    if (tl & (1u<<16))
    {
      Printf("\nhistory_build_menu: Widthing menu\n"
               "=================================\n\n");
    }
  #endif

  if (b && !global)
  {
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
    history_user  * current;

    /* Want a local (visit history).                                     */
    /*                                                                   */
    /* For this, we want to build a menu which shows where the forwards  */
    /* / backwards buttons will go, with the current position in the     */
    /* local History ticked. So we need to find the browser's current    */
    /* position, move right to the end of it, and build the menu from    */
    /* there. The build order will follow the history path by definition */
    /* so no sorting is needed afterwards.                               */
1712

1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
    current = (history_user *) b->history_current;

    if (!current) goto history_build_menu_empty_history;

    /* Track to the end of the local History */

    while (current->history_next) current = current->history_next;

    /* Now add in each entry */

    menu_entries = 0;

    while (current)
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
      history_user    ** new_array;
      const char       * used;
      const char       * url;
      const char       * title = current->parent->title;
      url_description  * url_d = current->parent->url;

      /* Rremember the item in the array */

      new_array = realloc(user_array, (++nusers) * sizeof(history_user *));

      if (!new_array) /* Zoiks! The allocation failed */
      {
        goto history_build_menu_out_of_memory;
      }

      user_array             = new_array;
      user_array[nusers - 1] = current;

      menu_entries ++;

      if (url_d) url = url_d->full;
      else       url = "";

      /* (So from the above, 'url' is never NULL) */

      if (show_urls || !title || !*title) len = strlen(url),   used = url;
      else                                len = strlen(title), used = title;
1754

1755 1756 1757
      #ifdef TRACE
        if (tl & (1u<<16))
        {
1758 1759
          Printf("Local  - URL  : '%s'\n",   url);
          Printf("Local  - Title: '%s'\n\n", title ? title : "");
1760 1761 1762
        }
      #endif

1763 1764
      /* Account for an appended space to stop e.g. 'Home' being taken */
      /* as a keyboard shortcut by the Wimp                            */
1765

1766
      len ++;
1767

1768 1769
      /* Work out the space requirement for this entry and record the */
      /* widest entry in characters in 'width'.                       */
1770

1771
      size += len + 1 + sizeof(wimp_menuitem); /* (+1 = string terminator) */
1772

1773 1774 1775 1776 1777
      if (len > width) width = len;

      /* Find the width of the entry in OS units */

      RetError(utils_text_width((char *) used, &thiswidth, 0));
1778

1779
      /* Record the widest entry in OS units in 'awidth' */
1780

1781
      if (thiswidth > awidth) awidth = thiswidth;
1782

1783 1784
      /* Go on to the next (or rather, given the order we want the */
      /* menu items in, previous!) item.                           */
1785

1786
      current = current->history_prev;
1787
    }
1788 1789 1790
  }
  else
  {
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
    history_entry   * entry = history_base;
    history_entry  ** new_array;
    const char      * used;
    const char      * url;
    const char      * title;
    url_description * url_d;

    /* Want a global history.                                        */
    /*                                                               */
    /* We need to go through all history_entry structures, recording */
    /* each on in the entry_array array so menu entry numbers can be */
    /* associated with history_entry structures.                     */
1803

1804
    menu_entries = 0;
1805

1806
    while (entry)
1807
    {
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
      new_array = realloc(entry_array, (++nentries) * sizeof(history_user *));

      if (!new_array)
      {
        goto history_build_menu_out_of_memory;
      }

      entry_array = new_array;
      entry_array[nentries - 1] = entry;

      /* Find the maximum width in chars and OS units of the URL or title strings */
1819

1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
      title = entry_array[nentries - 1]->title;
      url_d = entry_array[nentries - 1]->url;

      /* From here on it's more or less identical to the local history code above */

      if (url_d) url = url_d->full;
      else       url = NULL;

      if (show_urls || !title || !*title) len = url ? strlen(url) : 0, used = url;
      else                                len = strlen(title),         used = title;
1830

1831 1832 1833
      #ifdef TRACE
        if (tl & (1u<<16))
        {
1834 1835
          Printf("Global - URL  : '%s'\n",   url   ? url   : "");
          Printf("Global - Title: '%s'\n\n", title ? title : "");
1836 1837
        }
      #endif
1838

1839 1840
      len ++;
      size += len + 1 + sizeof(wimp_menuitem);
1841

1842
      if (len > width) width = len;
1843

1844 1845 1846 1847 1848
      RetError(utils_text_width((char *) used, &thiswidth, 0));

      if (thiswidth > awidth) awidth = thiswidth;

      menu_entries ++;
1849

1850
      /* Next item */
1851

1852
      entry = entry->next;
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

    /* Sort the entries array based on the entry datestamps - */
    /* newest (highest datestamp number) first.               */

    qsort(entry_array, nentries, sizeof(history_entry *), history_compare_entries);

    #ifdef TRACE

      if (tl & (1u<<16))
      {
        history_entry * entry;

        Printf("Post-sorting, entry array looks like:\n\n");

        for (i = 0; i < nentries; i++)
        {
          entry = entry_array[i];

          Printf("Entry %04d - URL '%s'\n", i, entry->url ? entry->url->full : "");
        }

        Printf("\n");
      }

    #endif
1879 1880 1881 1882 1883 1884 1885 1886 1887
  }

  size += 4;

  /* Deallocate any existing menu data and allocate the new required size. */

  #ifdef TRACE
    if (tl & (1u<<16))
    {
1888 1889
      if (history_menu) Printf("history_build_menu: Freeing existing store\n");
      else              Printf("history_build_menu: There is no existing store\n");
1890 1891 1892
    }
  #endif

1893 1894
  free(history_menu);
  history_menu = NULL;
1895 1896 1897 1898 1899

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_build_menu: Attempting to malloc %d bytes\n",size);
  #endif

1900 1901
  history_menu = calloc(1, size);
  if (!history_menu) goto history_build_menu_out_of_memory;
1902 1903 1904 1905

  /* Point mhp to the start of the menu header, and mip  */
  /* to the first menu item (straight after the header). */

1906
  mhp = (wimp_menuhdr  *) history_menu;
1907 1908 1909 1910
  mip = (wimp_menuitem *) (((int) mhp) + sizeof(wimp_menuhdr));

  /* Fill in the header. */

1911
  strncpy(mhp->title, lookup_token("HistMenT:History",0,0), 12);
1912 1913 1914 1915 1916 1917 1918 1919 1920

  mhp->tit_fcol  = 7;
  mhp->tit_bcol  = 2;
  mhp->work_fcol = 7;
  mhp->work_bcol = 0;
  mhp->width     = awidth;
  mhp->height    = 44;
  mhp->gap       = 0;

1921 1922 1923 1924
  /* Pointer arithmetic - mip + menu_entries adds menu_entries */
  /* lots of sizeof(mip) to menudata, since the cast to char * */
  /* is the last thing that happens. So menudata points past   */
  /* all the menu structure stuff to the data area.            */
1925

1926 1927
  menudata = (char *) (mip + menu_entries);

1928 1929
  /* Fill in each menu item. */

1930 1931 1932 1933 1934 1935 1936 1937
  #ifdef TRACE
    if (tl & (1u<<16))
    {
      Printf("\nhistory_build_menu: Building menu\n"
               "=================================\n\n");
    }
  #endif

1938
  for (i = 0; i < menu_entries; i++)
1939
  {
1940 1941 1942 1943 1944 1945
    url_description * url_d;
    char            * url;
    char            * title;

    /* Find the URL or title string for this entry */

1946 1947
    if (b && !global)
    {
1948 1949 1950 1951 1952 1953
      history_user * user = user_array[i];

      url_d = user->parent->url;
      title = user->parent->title;

      url = url_d ? url_d->full : "";
1954

1955 1956 1957
      #ifdef TRACE
        if (tl & (1u<<16))
        {
1958 1959
          Printf("Local  - URL  : '%s'\n",   url);
          Printf("Local  - Title: '%s'\n\n", title ? title : "");
1960 1961 1962 1963 1964
        }
      #endif
    }
    else
    {
1965 1966 1967 1968
      history_entry * entry = entry_array[i];

      url_d = entry->url;
      title = entry->title;
1969

1970
      url = url_d ? url_d->full : "";
1971 1972 1973 1974

      #ifdef TRACE
        if (tl & (1u<<16))
        {
1975 1976
          Printf("Global - URL  : '%s'\n",   url);
          Printf("Global - Title: '%s'\n\n", title ? title : "");
1977 1978 1979 1980
        }
      #endif
    }

1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
    /* Fill in the entry header */

    mip->flags     = (
                       (i == menu_entries - 1)
                       ?
                       wimp_MLAST
                       :
                       0
                     )
                     |
                     (
                       (
                         b       &&
                         !global &&
                         user_array[i] == (history_user *) b->history_current
                       )
                       ?
                       wimp_MTICK
                       :
                       0
                     );
2002

2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
    mip->submenu   = (wimp_menuptr) -1;
    mip->iconflags = wimp_ITEXT    |
                     wimp_IFILLED  |
                     wimp_INDIRECT |
                     (7<<24);

    mip->data.indirecttext.validstring = NULL;
    mip->data.indirecttext.bufflen     = 0;
    mip->data.indirecttext.buffer      = menudata;

2013
    /* Use the URL if we're told to, or the title is NULL / a null string */
2014

2015
    if (show_urls || !title || !*title)
2016
    {
2017
      /* Use the URL */
2018

2019 2020
      strcpy(menudata, url);
      strcat(menudata, " "); /* To stop e.g. 'Home' at the end of an item being taken as a keyboard shortcut by the Wimp */
2021

2022
      len = strlen(menudata);
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038

      /* Advance the data pointer, possibly removing any */
      /* CGI information if HIDE_CGI is defined inside   */
      /* the compiler.                                   */

      #ifdef HIDE_CGI

        toolbars_hide_cgi(menudata);

      #else

        /* If not hiding all CGI information, still don't want to  */
        /* put all the CGI stuff in the menu or it can get far too */
        /* wide. So leave an indicator to show there was CGI info. */

        toolbars_hide_cgi(menudata);
2039

2040 2041 2042 2043 2044 2045 2046
        if      (len > strlen(menudata) + 7) strcat(menudata, " (+CGI)");
        else if (len > strlen(menudata) + 4) strcat(menudata, "?...");

      #endif
    }
    else
    {
2047
      /* Use the title */
2048 2049

      strcpy(menudata, title);
2050
      strcat(menudata, " "); /* To stop e.g. 'Home' at the end of an item being taken as a keyboard shortcut by the Wimp */
2051

2052
      len = strlen(menudata);
2053 2054
    }

2055 2056 2057
    /* If we've gone over the width limit on this entry,  */
    /* show the right hand portion of the item with '...' */
    /* before it.                                         */
2058

2059
    if (len + 4 > Limits_HistoryMenuItemSize) /* '+4' to account for the '...' we'll put in front plus terminator */
2060
    {
2061 2062 2063
      memmove(menudata + 3, menudata + len - (Limits_HistoryMenuItemSize - 3), Limits_HistoryMenuItemSize - 3);
      strncpy(menudata, "...", 3);
      menudata[Limits_HistoryMenuItemSize - 1] = '\0';
2064 2065
    }

2066 2067 2068 2069 2070
    menudata += strlen(menudata) + 1;

    /* Next item... */

    mip ++;
2071 2072 2073
  }

  #ifdef TRACE
2074
    if (menudata > ((char *) history_menu) + size)
2075 2076
    {
      erb.errnum = 0;
2077
      sprintf(erb.errmess,"Fatal error inside history_build_menu: Overran menu buffer! Allocated %d bytes, then used %d.",size,(int) menudata - (int) history_menu);
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
      show_error(&erb);
    }
  #endif

  /* Finally, open the menu */

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_build_menu: Exitting through wimp_create_menu\n");
  #endif

  menuhdl = (void *) b;
2089 2090 2091

  if (global) menusrc = Menu_GlobalHist;
  else        menusrc = Menu_LocalHist;
2092

2093 2094 2095 2096 2097
  e = wimp_create_menu(history_menu, x - (subtract ? (mhp->width + 64) : 0), y);

  _swix(Hourglass_Off, 0);

  return e;
2098 2099 2100 2101 2102

  /* Forced exits... */

history_build_menu_out_of_memory:

2103 2104
  _swix(Hourglass_Off, 0);

2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
  free(history_menu); history_menu = NULL;
  free(entry_array);  entry_array  = NULL, nentries = 0;
  free(user_array);   user_array   = NULL, nusers   = 0;

  /* Out of memory */

  erb.errnum = Utils_Error_Custom_Normal;

  StrNCpy0(erb.errmess,
           lookup_token("NoMemLHi:There is not enough free memory to open the history menu.",
                        0,
                        0));

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_build_menu: Exitting (out of memory)\n");
  #endif

  return &erb;

history_build_menu_empty_history:

2126 2127
  _swix(Hourglass_Off, 0);

2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
  free(history_menu); history_menu = NULL;
  free(entry_array);  entry_array  = NULL, nentries = 0;
  free(user_array);   user_array   = NULL, nusers   = 0;

  /* Empty history (nothing at all, nothing for a given */
  /* browser, or whatever)                              */

  erb.errnum = Utils_Error_Custom_Message;

  StrNCpy0(erb.errmess,
           lookup_token("EmptyHistE:The history list is empty.",
                        0,
                        0));

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_build_menu: Exitting (history is empty)\n");
  #endif

  return &erb;
2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
}

/*************************************************/
/* history_menu_selection()                      */
/*                                               */
/* Jumps to a URL according to the item selected */
/* in a history menu.                            */
/*                                               */
/* If Adjust is used the menu is not reopened as */
/* the fetch will occur in a new window (as with */
/* following page links) - it doesn't make sense */
/* to reopen the menu in this case.              */
/*                                               */
/* Parameters: Pointer to a browser_data struct  */
2161 2162 2163 2164 2165 2166
/*             relevant to the history, or NULL  */
/*             for the global history - in this  */
/*             case it is assumed that the menu  */
/*             opened from an Open URL dialogue  */
/*             and appropriate alternative       */
/*             functions will be called;         */
2167
/*                                               */
2168 2169 2170 2171 2172 2173 2174
/*             Pointer to a WimpPollBlock struct */
/*             from which the menu item that was */
/*             selected may be determined.       */
/*************************************************/

_kernel_oserror * history_menu_selection(browser_data * b, WimpPollBlock * block)
{
2175 2176 2177
  int          item, adj;
  int          global;
  const char * url = NULL;
2178 2179 2180 2181 2182 2183

  /* What type of menu was it? */

  if (menusrc == Menu_GlobalHist || !b) global = 1;
  else                                  global = 0;

2184 2185 2186 2187 2188
  /* Flag that there is no known menu source anymore */
  /* and fetch the new URL.                          */

  menusrc = Menu_None;

2189
  /* What item was clicked on? */
2190 2191 2192 2193 2194 2195

  item = block->menu_selection[0];

  /* If the menu selection appears to be out of range, */
  /* exit quietly.                                     */

2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
  if (
       item < 0             ||
       item >= menu_entries ||
       (
         global           &&
         item >= nentries
       )
       ||
       (
         !global        &&
         item >= nusers
       )
     )
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
  {
    #ifdef TRACE
      if (tl & (1u<<16)) Printf("history_menu_selection: Warning, menu selection out of range\n");
    #endif

    return NULL;
  }

  /* Otherwise find out the button that was used. */

2219
  adj = controls.ignore_adjust ? 0 : adjust();
2220 2221 2222 2223 2224 2225

  /* If a new window isn't going to be opened, */
  /* need to remember that we've just dived    */
  /* into the History list so that forwards /  */
  /* backwards work correctly.                 */

2226
  if (!adj && b && !global)
2227
  {
2228
    history_user * user = user_array[item];
2229

2230
    b->history_current = (void *) user;
2231 2232
  }

2233
  /* Point to the required URL */
2234

2235 2236
  if (!global)
  {
2237
    history_user * user = user_array[item];
2238

2239
    if (user->parent && user->parent->url) url = user->parent->url->full;
2240 2241
  }
  else
2242
  {
2243
    history_entry * entry = entry_array[item];
2244

2245
    if (entry->url) url = entry->url->full;
2246 2247
  }

2248 2249 2250 2251 2252 2253 2254 2255 2256
  /* If b is set, this is from a browser toolbar */

  if (b)
  {
    /* Somewhat non-standard behaviour to have an adjust-click  */
    /* open a new window instead of leaving the menu up, but    */
    /* this is more consistent with the rest of the browser UI. */

    if (!adj) return fetchpage_new(b,
2257
                                   url,
2258 2259 2260
                                   0,
                                   1);

2261
    else return windows_create_browser((char *) url,
2262 2263 2264
                                       NULL,
                                       NULL,
                                       NULL,
2265
                                       Windows_CreateBrowser_Normal);
2266 2267 2268 2269 2270 2271
  }

  /* Otherwise, if b is NULL, it's from an Open URL dialogue */

  else
  {
2272
    return openurl_fill_in_url((char *) url);
2273 2274 2275 2276 2277 2278 2279 2280 2281
  }

  return NULL;
}

/*************************************************/
/* history_load()                                */
/*                                               */
/* Loads the global history from the given path. */
2282 2283 2284 2285 2286 2287
/* Will raise errors (usually, due to RISC OS    */
/* C's file I/O, the wrong ones...) if there is  */
/* a failure during loading, but not if the file */
/* refuses to open or the number of items cannot */
/* be read from it (i.e. a missing or zero       */
/* length History file).                         */
2288 2289 2290 2291 2292 2293 2294
/*                                               */
/* Parameters: Pointer to the full pathname for  */
/*             the history file.                 */
/*************************************************/

_kernel_oserror * history_load(char * pathname)
{
2295 2296 2297 2298 2299 2300 2301 2302
  FILE        * file;
  char        * title      = NULL;
  char        * url        = NULL;
  static char * local_path = NULL;
  int           result;
  int           last_accessed, title_len, url_len;
  int           items, item;
  int           cc, ch;
2303

2304
  if (!pathname || !*pathname) return NULL;
2305

2306 2307
  local_path = malloc(strlen(pathname) + 1);
  if (!local_path) return NULL;
2308

2309
  strcpy(local_path, pathname);
2310

2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_load: Called\n");
  #endif

  file = fopen(local_path, "rb");

  if (!file)
  {
    free(local_path);
    return NULL; /* Fail silently - there may be no History file; this is OK */
  }

  /* Read how many items there are - again file silently, the */
  /* file may just be zero bytes long.                        */

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_load: File opened OK\n");
  #endif

  result = fscanf(file, "%d\n", &items);
2331

2332 2333 2334 2335
  if (result == EOF)
  {
    fclose(file);
    free(local_path);
2336

2337 2338
    return NULL;
  }
2339

2340 2341 2342 2343 2344 2345 2346
  #ifdef TRACE
    if (tl & (1u<<16))
    {
      if (items > 1) Printf("history_load: There are %d items\n",items);
      else           Printf("history_load: There is 1 item\n");
    }
  #endif
2347

2348 2349
  _swix(Hourglass_On, 0);

2350
  for (item = 0; item < items; item++)
2351
  {
2352 2353 2354 2355 2356
    _swix(Hourglass_Percentage,
          _IN(0),

          (100 * item) / items);

2357 2358 2359
    /* Read the last accessed time and required string lengths */

    result = fscanf(file, "%d,%d,%d\n", &last_accessed, &title_len, &url_len);
2360
    if (result == EOF) goto history_load_exit;
2361 2362 2363 2364 2365 2366 2367 2368

    /* Allocate buffers for the strings */

    free(title);
    title = malloc(title_len + 1);

    if (!title)
    {
2369 2370
      fclose(file);

2371 2372
      _swix(Hourglass_Off,0);

2373
      free(local_path);
2374

2375 2376 2377 2378 2379 2380 2381 2382
      return make_no_memory_error(27);
    }

    free(url);
    url = malloc(url_len + 1);

    if (!url)
    {
2383 2384
      fclose(file);

2385 2386
      _swix(Hourglass_Off,0);

2387 2388
      free(title);
      free(local_path);
2389

2390 2391 2392 2393 2394 2395 2396 2397 2398
      return make_no_memory_error(27);
    }

    /* Read the title */

    for (cc = 0; cc < title_len; cc++)
    {
      int ch = fgetc(file);

2399
      if (ch == EOF) goto history_load_exit;
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410

      title[cc] = (char) ch;
    }

    title[title_len] = 0;

    /* Hmm, should not be needed? But it seems fscanf reads one \n extra */
    /* when there is a NULL title string. It probably thinks the line    */
    /* ending type is '\n\n' or something.                               */

    if (title_len)
2411
    {
2412 2413 2414
      /* Skip the '\n' */

      ch = fgetc(file);
2415
      if (ch == EOF) goto history_load_exit;
2416 2417 2418
    }

    /* Read the URL */
2419

2420 2421 2422
    for (cc = 0; cc < url_len; cc++)
    {
      int ch = fgetc(file);
2423

2424
      if (ch == EOF) goto history_load_exit;
2425

2426
      url[cc] = (char) ch;
2427 2428
    }

2429 2430 2431 2432 2433
    url[url_len] = 0;

    /* Skip the '\n' */

    ch = fgetc(file);
2434
    if (ch == EOF) goto history_load_exit;
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457

    #ifdef TRACE
      if (tl & (1u<<16))
      {
        Printf("history_load: %04d Title = \0213'%s'\0217\n", item, title);
        Printf("                     URL = \0216'%s'\0217\n", url);
      }
    #endif

    /* Now make the entry */

    if (url_len)
    {
      history_entry * found = malloc(sizeof(history_entry));

      if (!found)
      {
        #ifdef TRACE
          if (tl & (1u<<16)) Printf("history_load: Couldn't allocate space for entry\n");
        #endif

        fclose(file);

2458 2459
        _swix(Hourglass_Off,0);

2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
        free(url);
        free(title);
        free(local_path);

        return make_no_memory_error(25);
      }

      found->url = urlutils_return_description(url);

      /* We've now finished with the temporary URL string */

      free(url);
      url = NULL;

      if (!found->url)
      {
        free(found);

        #ifdef TRACE
          if (tl & (1u<<16)) Printf("history_load: Couldn't allocate space for URL description\n");
        #endif

        fclose(file);
2483

2484 2485
        _swix(Hourglass_Off,0);

2486 2487 2488
        free(url);
        free(title);
        free(local_path);
2489

2490
        history_remove_entry(NULL, found);
2491

2492 2493
        return make_no_memory_error(25);
      }
2494 2495 2496 2497 2498 2499
      else
      {
        /* Create a hash number for the string */

        found->hash = utils_return_hash(found->url->full);
      }
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523

      /* Link in the structure */

      found->prev = NULL;
      found->next = history_base;

      if (history_base) history_base->prev = found;

      history_base = found;

      /* Fill in some other fields */

      found->title         = title; /* Use the title string directly */
      found->users         = NULL;
      found->last_accessed = last_accessed;

      title = NULL;

      #ifdef TRACE
        if (tl & (1u<<16)) Printf("history_load: OK, have entry %p with description block %p\n",found,found->url);
      #endif
    }

  /* (Closure of 'for' loop) */
2524 2525
  }

2526 2527 2528 2529 2530 2531
  fclose(file);

  #ifdef TRACE
    if (tl & (1u<<16)) Printf("history_load: Successful, exitting via. expiry functions\n");
  #endif

2532 2533
  _swix(Hourglass_Off,0);

2534 2535 2536 2537 2538 2539 2540 2541
  free(url);
  free(title);
  free(local_path);

  if (choices.expiry_age) RetError(history_expire(NULL, time(NULL) - choices.expiry_age));

  if (choices.max_size) return history_limit(choices.max_size);
  else return NULL;
2542 2543 2544 2545 2546

  /* Error condition exit routine */

history_load_exit:

2547 2548 2549
  if (file) fclose(file);

  _swix(Hourglass_Off, 0);
2550 2551 2552 2553 2554 2555

  free(url);
  free(title);
  free(local_path);

  RetLastE;
2556 2557 2558
}

/*************************************************/
2559
/* history_save()                                */
2560 2561 2562 2563 2564 2565 2566 2567 2568
/*                                               */
/* Saves the global history to the given path.   */
/*                                               */
/* Parameters: Pointer to the full pathname for  */
/*             the history file.                 */
/*************************************************/

_kernel_oserror * history_save(char * pathname)
{
2569 2570 2571 2572 2573 2574 2575
  history_entry * entry      = history_base;
  FILE          * file;
  static char   * local_path = NULL;
  int             wrote;
  int             items = 0;

  if (!pathname || !*pathname) return NULL;
2576

2577
  /* Canonicalise the path */
2578

2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
  RetError(utils_canonicalise_path(pathname, &local_path));

  /* Ensure it is present */

  {
    _kernel_oserror * e = utils_build_tree(local_path);

    if (e)
    {
      free(local_path);
      return e;
    }
  }
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601

  /* How many items are there? */

  while (entry)
  {
    items ++;
    entry = entry->next;
  }

  entry = history_base;
2602 2603 2604

  /* Create the file */

2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
  file = fopen(local_path, "wb");

  if (!file)
  {
    free(local_path);

    RetLastE;
  }

  /* Write the number of items */

  wrote = fprintf(file, "%d\n", items);

  if (wrote <= 0)
  {
    fclose(file);
    free(local_path);

    RetLastE;
  }

  /* Write the item contents */

  while (entry)
  {
    if (entry->url)
    {
      wrote = fprintf(file,

                      "%d,%d,%d\n%s\n%s\n",

                      entry->last_accessed,

                      entry->title     ? strlen(entry->title)     : 0,
                      entry->url->full ? strlen(entry->url->full) : 0,

                      entry->title     ? entry->title     : "",
                      entry->url->full ? entry->url->full : "");

      if (wrote <= 0)
      {
        fclose(file);
        free(local_path);
2648

2649 2650 2651
        RetLastE;
      }
    }
2652

2653 2654
    entry = entry->next;
  }
2655 2656

  /* Close the file and exit */
2657

2658
  fclose(file);
2659
  free(local_path);
2660 2661 2662

  return NULL;
}
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694

/*************************************************/
/* history_save_as_html()                        */
/*                                               */
/* This function saves the History as an HTML    */
/* file.                                         */
/*                                               */
/* Parameters: Pointer to the filename to save   */
/*             to (null terminated);             */
/*                                               */
/*             Pointer to a browser_data struct  */
/*             to save the History for if you    */
/*             want a local history, else NULL   */
/*             for the global history.           */
/*************************************************/

_kernel_oserror * history_save_as_html(char * pathname, browser_data * b)
{
  _kernel_oserror * e;
  static char     * local_path = NULL;
  history_entry   * entry      = history_base;
  history_user    * user;
  FILE            * fileptr;
  int               written;

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

  local_path = malloc(strlen(pathname) + 1);
  if (!local_path) return NULL;

  strcpy(local_path, pathname);

2695 2696 2697 2698
  /* Could take a while... */

  _swix(Hourglass_On, 0);

2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
  /* Open the file for writng */

  fileptr = fopen(local_path, "wb");

  /* Complain if it fails */

  if (fileptr == NULL)
  {
    free(local_path);

    RetLastE;
  }

  /* Write the file header */

  HistoryWrite(fprintf(fileptr, "<html>\n"
                                "<head>\n"
                                CHARSET_SPECIFIER
                                "<title>"));

  HistoryWrite(fprintf(fileptr, lookup_token("HistoryHTMLTitle:History",0,0)));

  HistoryWrite(fprintf(fileptr, "</title>\n"
                                "</head>\n"
                                "<body>\n"
                                "<ul>\n"));

  /* Fill in the body for global histories */

  if (!b)
  {
    while (entry)
    {
      if (entry->url && entry->url->full)
      {
        HistoryWrite(fprintf(fileptr, "<li><a href=\"%s\">%s</a>\n",
                                      entry->url->full,
2736
                                      (entry->title && *entry->title) ? entry->title : entry->url->full));
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
      }

      entry = entry->next;
    }
  }

  /* Fill in the body for local histories */

  else
  {
    user = (history_user *) b->history_current;

    while (user && user->history_next) user = user->history_next;

    while (user)
    {
      entry = user->parent;

      if (entry && entry->url && entry->url->full)
      {
        HistoryWrite(fprintf(fileptr, "<li><a href=\"%s\">%s</a>\n",
                                      entry->url->full,
2759
                                      (entry->title && *entry->title) ? entry->title : ""));
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
      }

      user = user->history_prev;
    }
  }

  /* Write the footer and close the file */

  HistoryWrite(fprintf(fileptr, "</ul>\n"));
  HistoryWrite(fprintf(fileptr, "</body>\n"));
  HistoryWrite(fprintf(fileptr, "</html>\n"));

  fclose(fileptr);

2774 2775
  _swix(Hourglass_Off, 0);

2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
  /* Set the filetype to HTML (0xfaf) */

  e = _swix(OS_File,
            _INR(0,2),

            18,
            local_path,
            FileType_HTML);

  free(local_path);

  return e;

  /* Error condition exit */

history_save_error:

2793 2794 2795 2796 2797 2798
  if (fileptr)
  {
    fclose(fileptr);

    _swix(Hourglass_Off, 0);
  }
2799 2800 2801 2802 2803

  free(local_path);

  RetLastE;
}
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972

/*************************************************/
/* history_find_match()                          */
/*                                               */
/* Takes a string from the given buffer and sees */
/* if there's something in the global History    */
/* that matches it in some way.                  */
/*                                               */
/* If it finds something, it writes it back to   */
/* the buffer and returns 1.                     */
/*                                               */
/* Parameters: Pointer to the buffer holding the */
/*             string to try and match;          */
/*                                               */
/*             Size of the buffer in bytes.      */
/*                                               */
/* Returns:    1 if the buffer is updated with a */
/*             match string, else 0 (buffer      */
/*             contents will be unaltered).      */
/*************************************************/

int history_find_match(char * buffer, int buffer_size)
{
  history_entry * entry         = history_base;
  history_entry * lowest_entry  = NULL;
  const char    * found         = NULL;
  int             lowest_offset = -1;
  int             lowest_diff   = 0;
  int             this_offset   = 0;
  int             got_one;

  if (!buffer || !*buffer) return 0;

  while (entry)
  {
    if (entry->url && entry->url->full)
    {
      got_one = 0;

      /* Match in the host, if present */

      if (entry->url->host)
      {
        /* See if we can find the string */

        found = strstr(entry->url->host, buffer);

        if (found)
        {
          /* If so, record the offset into the string where  */
          /* the match was found and mark we've got a match. */

          this_offset = found - entry->url->host;
          got_one     = 1;
        }
      }

      /* Match in the path, if nothing found in the host */

      if (!got_one && entry->url->path)
      {
        found = strstr(entry->url->path, buffer);

        if (found)
        {
          this_offset = found - entry->url->path;
          got_one     = 1;
        }
      }

      /* Match in the full URL, if all else fails */

      if (!got_one)
      {
        found = strstr(entry->url->full, buffer);

        if (found)
        {
          this_offset = found - entry->url->full;
          got_one     = 1;
        }
      }

      /* Match in the title, out of desperation! */

      if (!got_one && entry->title)
      {
        found = strstr(entry->title, buffer);

        if (found)
        {
          this_offset = found - entry->title;
          got_one     = 1;
        }
      }

      /* If found, have we not recorded an offset before, or is this offset  */
      /* lower than any previously recorded? If so, remember the entry. This */
      /* way, 'digital' will match 'www.digital.com' rather than             */
      /* 'www.altavista.digital.com' regardless of where the entry is in the */
      /* History. Matching the first one we come to would obviously rely on  */
      /* the order of appearance in the list.                                */

      if (got_one)
      {
        if (lowest_offset < 0 || this_offset <= lowest_offset)
        {
          int this_diff = strlen(entry->url->full) - strlen(buffer);

          lowest_offset = this_offset;

          /* Having found an entry that matches in the lowest part of the string */
          /* so far, we also want to choose one which has the smallest string    */
          /* length difference between itself and the given match string, which  */
          /* is non-zero. This ensures we would go 'www.acorn.com/acorn/',       */
          /* 'www.acorn.com/acorn/news/', 'www.acorn.com/acorn/news/releases/'   */
          /* again regardless of the relative position of the entries in the     */
          /* History list.                                                       */
          /*                                                                     */
          /* Of course, the whole thing is still fairly undetermined - whatever  */
          /* the next directory is after you've found a match on the root of a   */
          /* site (say) which happens to be the shortest will be the tree you    */
          /* always end up fetching. But it's a reasonable start on this anyway, */
          /* and the mists of time may well reveal that further enhancements are */
          /* not necessary in practice.                                          */

          if (this_offset < lowest_offset)
          {
            /* First thing, we've found a new lowest offset; so forget any previous */
            /* string length differences.                                           */

            lowest_diff = 0;
          }

          /* If we've not got a lowest difference yet, or we have a current difference */
          /* and it's lower than the recorded lowest, then remember the difference and */
          /* the entry that generated it.                                              */

          if (!lowest_diff || (this_diff && this_diff < lowest_diff))
          {
            lowest_diff  = this_diff;
            lowest_entry = entry;
          }
        }
      }
    }

    /* Try the next item */

    entry = entry->next;
  }

  /* Did we end up finding anything? */

  if (lowest_entry && lowest_offset >= 0)
  {
    /* Yes - copy the full URL into the buffer and return, saying */
    /* we updated the buffer contents.                            */

    strncpy(buffer, lowest_entry->url->full, buffer_size);
    buffer[buffer_size - 1] = 0;

    return 1;
  }

  /* No - exit, saying we didn't touch the buffer contents. */

  return 0;
}