/* 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   : Global.h                               */
/*                                                 */
/* Purpose: Holds all of the browser's globals.    */
/*                                                 */
/* Author : A.D.Hodgkinson                         */
/*                                                 */
/* History: 18-Oct-96: Created.                    */
/***************************************************/

#include "stdio.h"

#include "struct.h"     /* From the HTML library */
#include "tablestruc.h" /* From the HTML library */
#include "imagetrans.h" /* Image library API */

#include "setjmp.h"
#include "window.h"

#include "Bitfields.h"
#include "Limits.h"

#ifndef SINGLE_USER
  #include "Multiuser.h"
#endif

/* For comments on what these actually are, see Global.c */

#ifdef TRACE
  extern unsigned int   tl;
  extern int            malloccount;
  extern int            flexcount;
#endif

extern jmp_buf          env;

extern int              quit;
extern int              modechanged;
extern int              printing;
extern int              printer_message_ref;
extern int              drag_in_progress;
extern int              authorising;

extern void           * dialler_pollword_address;

extern int              wimp_version;
extern int              nested_wimp;
extern int              task_handle;
extern int              sprite_block;

extern int              taskmodule_ds_registered;
extern int              uri_module_present;

extern MessagesFD       meb;
extern MessagesFD     * chb;
extern char             tokens[Limits_Message];
extern char             lasttokn[Limits_Token];

extern int              messages_list[];
extern IdBlock          idb;
extern int              event_code_list[];
extern WimpPollBlock    b;

extern char             program_name[Limits_TaskName];

extern int              null_counter;
extern int              bullets;
extern unsigned int     animation_frames;

/* Fetch status */

typedef enum bs_fetch
{
  BS_IDLE = 0,  /* Nothing happening                               */
  BS_START,     /* A fetch has just started                        */
  BS_STARTED,   /* Some data has been fetched                      */
  BS_IDENTIFY,  /* Identifying a stream                            */
  BS_FETCHING,  /* Stream identified, HTML being fetched           */
  BS_DATAFETCH, /* Stream being spooled to a file                  */
  BS_PROCESS    /* Fetched stream still being processed by fetcher */

} bs_fetch;

struct reformat_line;
struct reformat_line_chunk;

/* For tables, holds information required to format a specific table cell */

typedef struct reformat_cell
{
  struct reformat_line       * ldata;
  int                          nlines;
  struct reformat_line_chunk * cdata;
  int                          x;           /* Offsets for positioning all the rest */
  int                          y;
  int                          width;       /* Size of content of this 'subwindow' (should help more formatting or  */
  int                          height;      /* clipping); width is maxlen of lines, height from last line's y coord */
  int                          cellwidth;
  int                          cellheight;  /* Full size of subwindow               */
  int                          cellpadding; /* Cell padding                         */
  table_stream               * table;       /* Main table definition structure      */
}
reformat_cell;

/* These two structures represent lines for display in the browser */
/* window. A series of reformat_line structures exist as an array  */
/* pointed to in the browser_data structure (see below). These     */
/* each have a series of line chunks, as reformat_line_chunk       */
/* structures, which they point to. The chunks themselves are in   */
/* a separate block of memory.                                     */

typedef struct reformat_line
{
  int x;       /* x coord of left of this line, in window coords   */
  int y;       /* y coord of bottom of this line, in window coords */
  int h;       /* Height of this line in OS units                  */
  int b;       /* y offset of the font base line from the bottom   */
  int n;       /* Number of line chunks on this line               */
  int chunks;  /* Starting array offset into chunks for this line  */

} reformat_line;

typedef struct reformat_line_chunk
{
  HStream       * t; /* The token number the line represents             */
  int             o; /* Offset into the token this chunk starts at       */
  int             l; /* The number of bytes from the token in this chunk */
                     /* (0 = all the rest)                               */
  int             w; /* Width of this chunk in font coords               */

} reformat_line_chunk;

/* Bistate / tristate button types */

typedef enum bistate_type
{
  BiState_None,             /* No bistate button present */
  BiState_Cancel_Back       /* A Cancel / Back bistate   */

} bistate_type;

typedef enum tristate_type
{
  TriState_None,            /* No tristate button present   */
  TriState_Go_GoTo_Stop     /* A go / go to / stop tristate */

} tristate_type;

/* Displayed information */

typedef enum display_type
{
  Display_Fetched_Page,     /* A blank page or HTML / text file (externally fetched) is shown in the window */
  Display_External_Image,   /* An internally generated HTML file to show an external image is being shown   */
  Display_Previous_Page,    /* Return to the previous page in the history list                              */
  Display_Recovered_Page,   /* Go to the page in Browse$CurrentPage                                         */
  Display_Home_Page         /* Go to the home page                                                          */

} display_type;

/* Reformat request queueing */

typedef struct reformat_queue
{
  int                     line;  /* Start reformatting on the next line after this one        */
  int                     image; /* The image number, if it resized and prompted the reformat */
  struct reformat_queue * next;

} reformat_queue;

/* One of these is allocated for each browser window, */
/* and holds lots of essential information connected  */
/* with that window and the page it contains.         */

typedef struct browser_data
{
  struct browser_data    * previous;          /* Points to previous browser_data structure, or NULL for none.            */
  struct browser_data    * next;              /* Points to next browser_data structure, or NULL for no more.             */
  ObjectId                 self_id;           /* The object ID of the browser window the structure is associated with.   */
  int                      window_handle;     /* The Wimp window handle of the browser window.                           */
                                              /*                                                                         */
  WindowShowObjectBlock    small_size;        /* Window details when not toggled to full screen size.                    */
  int                      min_height;        /* The minimum vertical extent of the browser window.                      */
  int                      display_width;     /* Visible area width, used for reformatting etc.                          */
  int                      display_extent;    /* Visible area extent normally=width but may be forced up by reformatter. */
                                              /*                                                                         */
  bs_fetch                 fetch_status;      /* To keep track of the current fetch status (see bs_fetch definition).    */
  int                      fetch_handle;      /* The html-lib handle of the document being fetched.                      */
  int                      display_handle;    /* The html-lib handle of the displayed document.                          */
                                              /*                                                                         */
  unsigned int             current_frame;     /* The currently displayed animation frame.                                */
  int                      current_fetches;   /* For frames, counts total still active fetches (so animation continues). */
                                              /*                                                                         */
  FILE                   * save_file;         /* File handle for data saves.                                             */
  int                      save_type;         /* Filetype for data saves.                                                */
  int                      save_transferred;  /* Number of bytes done so far for in-memory transfers.                    */
  ObjectId                 save_dbox;         /* Object ID of the save dialogue being used.                              */
                                              /*                                                                         */
  int                      dialler_last;      /* Time that the dialler online time was last updated.                     */
  int                      meta_refresh_at;   /* For META tags leading to a refresh, the time to start the fetch.        */
  char                   * meta_refresh_url;  /* For META tags leading to a refresh, the URL to fetch.                   */

  /* Frames fields (though some other  */
  /* frame-related bits and pieces are */
  /* scattered around elsewhere).      */

  char                   * window_name;       /* Name of this frame / browser window.                                    */
  struct browser_data    * ancestor;          /* The base browser containing the frames (NULL for the base itself).      */
  struct browser_data    * real_parent;       /* For any frame pane, this points to the pane below.                      */
  struct browser_data    * parent;            /* If this is a nested frame in one document, this points to parent.       */
                                              /*                                                                         */
  int                      nchildren;         /* Number of children if this window / frame has other children frames.    */
  struct browser_data   ** children;          /* Pointer to array of pointers to the children's browser_data structs.    */
                                              /*                                                                         */
  HStream                * frameset;          /* For a parent with children, pointer to token that defines the frameset. */
  HStream                * frame;             /* For a child, pointer to a token that defines its characteristics.       */
  int                      nesting_level;     /* For an ancestor, this tracks nesting levels as frames are defined.      */
  int                      filling_frame;     /* For a parent, as it fills in children info it updates this counter.     */
  int                    * frame_widths;      /* The width of the frames, in OS units.                                   */
  int                    * frame_heights;     /* The height of the frames, in OS units.                                  */
  struct browser_data    * selected_frame;    /* For ancestors and keyboard control, the currently selected frame.       */
                                              /*                                                                         */
  int                      nstatus;           /* Number of entries in status_contents array.                             */
  void                   * status_contents;   /* Information maintained by toolbars_update_status about frame statuses.  */
  char                   * status_help;       /* If non-NULL, points to a string of help text for the status line.       */

  /* Memory allocation and management */

  void                   * source;            /* Pointer to the page source.                                             */
  HStream                * stream;            /* Pointer to linked HStream list, malloced and owned by the HTML library. */
                                              /*                                                                         */
  HStream                * finaltoken;        /* Address of the token last dealt with by the reformatter.                */
  HStream                * display_request;   /* Token to display at top of the window as soon as possible.              */
  int                      display_offset;    /* Offset into token data to display.                                      */
  int                      display_vscroll;   /* Last vertical scroll position when a requested token was displayed.     */
                                              /*                                                                         */
  void                   * fdata;             /* Pointer to pointer to forms data.                                       */
  void                   * extradata;         /* Pointer to pointer to extra data for forms.                             */
  int                      nforms;            /* Counter for forms.                                                      */
                                              /*                                                                         */
  reformat_cell          * cell;              /* Pointer to malloced reformat_cell holding redraw information.           */
                                              /*                                                                         */
  char                   * histdata;          /* Pointer to history list (consecutive null terminated URL strings).      */
  int                      hnum;              /* Number of entries in the history list.                                  */
  int                      hpos;              /* Position in history list (from 1 to hnum, or 0 = not in history)        */
                                              /*                                                                         */
  char                   * urlfdata;          /* URL being fetched.                                                      */
  char                   * urlddata;          /* URL being displayed.                                                    */

  /* Special states */

  tristate_type            tristate;          /* Type of a tristate button, if one is present.                           */
  int                      tristate_state;    /* Current state of the tristate button.                                   */
  bistate_type             bistate;           /* Type of a bistate button, if one is present.                            */
  int                      bistate_state;     /* Current state of the bistate button.                                    */

  /* JavaScript support */

  const char             * onload;            /* The onLoad attribute specified in the BODY start tag.                   */
  const char             * onunload;          /* The onUnload attribute specified in the BODY start tag.                 */

  /* General page display information */

  int                      backgroundcol;     /* Background colour.                                                      */
  int                      backimage;         /* The image number of the background image (0..nimages - 1, -1 = none).   */
  int                      textcol;           /* Body text default colour.                                               */
  int                      aacol;             /* Colour to anti-alias text to, -1=don't anti-alias.                      */
  int                      linkcol;           /* Unfollowed link colour.                                                 */
  int                      usedcol;           /* Followed link colour.                                                   */
  int                      follcol;           /* Following link colour.                                                  */
  int                      selecol;           /* Selected (highlighted) object colour.                                   */
                                              /*                                                                         */
  int                      refotime;          /* Records time that a pending reformat has been waiting.                  */
  int                      refoline;          /* The lowest line number pending for a reformat.                          */
                                              /*                                                                         */
  int                      leftmargin;        /* Left hand basic page margin, millipoints.                               */
  int                      rightmargin;       /* Right hand basic page margin, millipoints.                              */
  int                      quotemargin;       /* Extra page margin for blockquote chunks, millipoints.                   */
  int                      leading;           /* Line spacing, OS units.                                                 */
  int                      leftindent;        /* Multiplier on list etc. indents, millipoints.                           */
                                              /*                                                                         */
  HStream                * highlight;         /* Token address of highlighted token (e.g. a pressed button), NULL=none.  */
  HStream                * pointer_over;      /* Token address that the pointer is over, for tokens representing links.  */
  HStream                * last_token;        /* Last token for which reformatting was definitely completed.             */
  HStream                * selected;          /* Token currently selected (for keyboard navigation).                     */
  struct browser_data    * selected_owner;    /* Owner of the currently selected token (for frames control).             */
                                              /*                                                                         */
  unsigned int             lastspace;         /* Total accumulated vertical space between page elements, in OS units.    */
                                              /*                                                                         */
  display_type             displayed;         /* Type of information displayed in the window (see above).                */

  /* Font manager related information */

  bitfield_set             handles;           /* Used font handles (bit set if handle is used).                          */

  /* Flags; generally, local   */
  /* configuration information */

  unsigned                 button_bar     :1; /* Button bar flag (0 = not present, 1 = present).                         */
  unsigned                 url_bar        :1; /* URL writable bar flag (0 = not present, 1 = present).                   */
  unsigned                 status_bar     :1; /* Status bar flag (0 = not present, 1 = present).                         */
  unsigned                 all_in_top     :1; /* There is only the top toolbar available.                                */
  unsigned                 all_in_bottom  :1; /* There is only the bottom toolbar available.                             */
  unsigned                 merged_url     :1; /* If 1, the URL writable and status display are to be merged.             */
                                              /*                                                                         */
  unsigned                 anim_handler   :1; /* Set to 1 if the animation null event handler is registered.             */
  unsigned                 anim_drift     :1; /* Set to 1 if the animation drift nulll event handler is registered.      */
  unsigned                 fetch_handler  :1; /* Set to 1 if the fetch_a_page null event handler is registered.          */
  unsigned                 dialler_status :1; /* Set to 1 if the dialler status change message handler is registered.    */
  unsigned                 status_handler :1; /* Set to 1 if a handler for timeout on the status messages is registered. */
  unsigned                 watching_resize:1; /* Zero if there is null events are not being claimed to watch the size of */
                                              /* the window, or 1 if they are.                                           */
  unsigned                 dragging       :1; /* 1 if a drag on the page is in progress, else 0.                         */
                                              /*                                                                         */
  unsigned                 savelink       :1; /* 1: Save next fetch as data even if parsable, else parse it if possible. */
                                              /*                                                                         */
  unsigned                 reloading      :1; /* 1: This fetch is a reload (so don't use a proxy), else 0: it isn't.     */
  unsigned                 suspend_format :1; /* 1: Reformatting suspended due to error, else 0: Reformatting OK.        */
  unsigned                 clear_images   :1; /* 1: Images have not been garbage collected from the last fetch yet.      */
                                              /*                                                                         */
  unsigned                 underlinelks   :1; /* Underline text links (0 = no, 1 = yes).                                 */
  unsigned                 displayimages  :1; /* Display images (0  = no, 1 = yes).                                      */
  unsigned                 plainback      :1; /* 1: Don't draw background images 0: Draw them if present in document.    */
  unsigned                 sourcecolours  :1; /* 1: Use source document's colours 0: Ignore them (use default colours).  */
                                              /*                                                                         */
  unsigned                 full_screen    :1; /* 1: Browser window fills the screen, 0: window has border tools.         */
  unsigned                 full_size      :1; /* 1: Browser window toggled Full Size, 0: window is smaller.              */
                                              /*                                                                         */
  unsigned                 frame_selected :1; /* 1: Browser window is selected (for frames), else is not selected.       */
  unsigned                 frame_hscroll  :2; /* 0: No horiz scroll bar; 1: auto horiz bar; 2: bar always present.       */
  unsigned                 frame_vscroll  :2; /* As frame_hscroll but for vertical scroll bar.                           */
                                              /*                                                                         */
  unsigned                 in_image_map   :1; /* 1: Image map selected for keyboard control, else 0: can move freely.    */
  unsigned                 formflag       :1; /* 1: Fetcher is in the middle of a form, else 0: normal fetching.         */

  #ifdef ANTI_TWITTER
    unsigned               taller_redraw  :1; /* 1: Taller redraw for anti-twitter is in progress, else 0.               */
  #endif

  /* Other small data items which may */
  /* pack in under the bitfield       */

  unsigned char            lastchar;          /* Used for smart quotes and other text alteration handling.               */

} browser_data;

extern browser_data   * last_browser;
extern browser_data   * highlight_frame;

/* Global choices/preferences structure */

typedef struct global_choices
{
  int                 width;                           /* Default browser window width.                                      */
  int                 height;                          /* Default browser window height.                                     */
  int                 overridex;                       /* Possible X opening coordinate.                                     */
  int                 overridey;                       /* Possible Y opening coordinate.                                     */
                                                       /*                                                                    */
  #ifndef SINGLE_USER                                  /*                                                                    */
                                                       /*                                                                    */
    char              username[Limits_Multi_UserName]; /* User name for multiuser operation.                                 */
    char              password[Limits_Multi_Password]; /* Password name for multiuser operation.                             */
                                                       /*                                                                    */
  #endif                                               /*                                                                    */
                                                       /*                                                                    */
  unsigned int        col_back;                        /* Default background colour.                                         */
  unsigned int        col_text;                        /* Default text colour.                                               */
  unsigned int        col_link;                        /* Default link colour.                                               */
  unsigned int        col_used;                        /* Default used link colour.                                          */
  unsigned int        col_foll;                        /* Default following link colour.                                     */
  unsigned int        col_sele;                        /* Default selected (highlighted) link colour.                        */
                                                       /*                                                                    */
  int                 fontsize;                        /* Default font size, 16ths of a point.                               */
                                                       /*                                                                    */
  int                 leftmargin;                      /* Left hand basic page margin, millipoints.                          */
  int                 rightmargin;                     /* Right hand basic page margin, millipoints.                         */
  int                 quotemargin;                     /* Extra page margin for blockquote chunks, millipoints.              */
  int                 leading;                         /* Line spacing, OS units.                                            */
  int                 leftindent;                      /* Multiplier on list etc. indents, millipoints.                      */
  int                 minfrmheight;                    /* Minimum frame height, in OS units.                                 */
  int                 minfrmwidth;                     /* Minimum frame width, in OS units.                                  */
                                                       /*                                                                    */
  int                 refotime;                        /* Time to queue up reformats, in centiseconds, if 'refowait' is set. */
                                                       /*                                                                    */
  int                 maxghistory;                     /* Maximum size of global history, in K.                              */
  int                 maxvhistory;                     /* Maximum size of view history, in entries.                          */
  unsigned char       maximages;                       /* Maximum number of images to fetch simultaneously.                  */
                                                       /*                                                                    */
  unsigned            systemfont    :1;                /* 1: Use system font for everything, 0: use outline fonts.           */
  unsigned            delayimages   :1;                /* 1: Delay image loading, 0: Load them immediately.                  */
  unsigned            displaybgs    :1;                /* 1: Display background images, 0: don't.                            */
  unsigned            underlinelks  :1;                /* 1: Underline link text, 0: don't.                                  */
  unsigned            overridecols  :1;                /* 1: Ignore document specified colours (use defaults), 0: use doc's. */
  unsigned            fixedptr      :1;                /* 1: Pointer must not change shape over page, 1: it can change.      */
  unsigned            highlightlks  :1;                /* 1: Objects are highlighted as the pointer moves over them.         */
  unsigned            keyboardctl   :1;                /* 1: Keyboard control of link selection enabled, else disabled.      */
  unsigned            clearfirst    :1;                /* 1: If popping up URL writable with key, clear first; else append.  */
  unsigned            keephighlight :1;                /* 1: Frames will keep (re)highlighting as keyboard navigated.        */
                                                       /*                                                                    */
  unsigned            refowait      :1;                /* 1: Reformat requests are queued for 'refotime' centiseconds.       */
  unsigned            refohang      :1;                /* 1: Reformatter will wait to know image sizes before continuing.    */
  unsigned            brickwall     :1;                /* 1: Following links halts other fetches on page else they continue. */
                                                       /*                                                                    */
  unsigned            url_bar       :1;                /* Attach a URL bar to a window upon creation (1 = yes, 0 = no).      */
  unsigned            button_bar    :1;                /* Attach a button bar to a window upon creation (1 = yes, 0 = no).   */
  unsigned            status_bar    :1;                /* Attach a status bar to a window upon creation (1 = yes, 0 = no).   */
  unsigned            show_urls     :1;                /* 0 - show titles in History menu, else always show URLs.            */
  unsigned            save_history  :1;                /* 0 - don't save global history on exit, else always save it.        */
  unsigned            save_hotlist  :1;                /* 0 - don't save hotlist on exit (losing any changes), else save it. */
                                                       /*                                                                    */
  unsigned            move_gadgets  :2;                /* 0 - don't move, 1 - move after resize, 2 = move during resize.     */
  unsigned            anim_drift    :1;                /* 0 - stop animation as soon as idle, 1 = drift over to 1st frame.   */
  unsigned            solid_resize  :2;                /* Frame resizes; 0 - dashed, 2 - solid, 1 - check CMOS resize bit.   */
                                                       /*                                                                    */
  unsigned            full_screen   :1;                /* 0 - don't start up Full Screen, else 1.                            */
  unsigned            h_scroll      :2;                /* 0 - no hscroll in Full Screen, 1 - auto add/remove, 2 - always.    */
  unsigned            v_scroll      :2;                /* 0 - no vscroll in Full Screen, 1 - auto add/remove, 2 - always.    */
                                                       /*                                                                    */
  unsigned            use_proxy     :1;                /* 0 - don't use a proxy, 1 = use one at URL in Messages file entry.  */

} global_choices;

extern global_choices choices;

typedef struct fixed_choices
{
  int                 poll_delay;             /* Minimum number of centiseconds between being called on nulls.      */
  int                 minimum_convergence;    /* See Messages file non-user configurable options section.           */
  int                 show_dstat_for;         /* For the dialler display, show unusual status for this long (cs).   */
  int                 quantise;               /* Quantise online time display to this many seconds.                 */
                                              /*                                                                    */
  int                 ptrlnkactvx;            /* Link pointer active point X offset.                                */
  int                 ptrlnkactvy;            /* Link pointer active point Y offset.                                */
  int                 ptrmapactvx;            /* Map pointer active point X offset.                                 */
  int                 ptrmapactvy;            /* Map pointer active point Y offset.                                 */
                                              /*                                                                    */
  int                 backoffat;              /* Back off image fetches when this much memory, or less, is free.    */
                                              /*                                                                    */
  unsigned            dontgrey      :2;       /* Controls greying of buttons and the history menu pop.              */
  unsigned            swapbars      :1;       /* Swap top and bottom toolbars around.                               */
  unsigned            dboxanims     :1;       /* If set, appropriate components in dialogues will be animated.      */
                                              /*                                                                    */
  unsigned            appendstatus  :1;       /* In the absence of a byte counter append this info to status field. */
  unsigned            usebrackets   :1;       /* If appending, enclose the value in brackets.                       */
  unsigned            appendurls    :1;       /* Append the current page URL before visiting special locations.     */
                                              /*                                                                    */
  unsigned            keepcaret     :1;       /* Grab the caret if it is lost (*use with caution!*).                */
  unsigned            claimhelp     :1;       /* Claim Interactive Help messages and display text in status bar.    */
  unsigned            stopwebserv   :1;       /* Broadcast an AppControl Stop reason to WebServ when 'Stop' used.   */
  unsigned            backwindow    :1;       /* If full screen, be a Back window to stop others going behind.      */
                                              /*                                                                    */
  unsigned            ignoreadjust  :1;       /* Ignore adjust (treat as select) if it would open a second window.  */
  unsigned            locktoline    :1;       /* Lock left/right arrows to only select items on the same line.      */

} fixed_choices;

extern fixed_choices fixed;

/* Global error block to allow functions to hand back filled in */
/* custom error blocks, when necessary.                         */

extern _kernel_oserror erb;

/* For keeping track of where dynamically created menus came from */

typedef enum menu_source
{
  Menu_None,       /* No menu opened / none recorded as being opened. */
  Menu_Form,       /* The menu was from a form.                       */
  Menu_History,    /* The menu was from a History menu pop-up icon.   */
  Menu_Authorise   /* The 'menu' was an authorisation dialogue.       */

} menu_source;

extern menu_source   menusrc;
extern void        * menuhdl;