# NhExt: A protocol for NetHack plug-in window ports

This document describes NhExt 1.0.2, a protocol to be used when NetHack calls a function located inside a plug-in window port and for when that window port function in turn calls a function located inside NetHack (a call back). The protocol specifies no limit to the depth of recursion which may occur.

NhExt requires a two-way, single duplex, connection between the game and the window-port. How that connection is set up is outside the scope of the protocol.

NhExt has provision for more than one sub-protocol, to allow for future backwards compatibility. Initially, both the game and the window port should be in sub-protocol 0. Sub-protocols 0 and 1 must be supported by games; sub-protocol 2 is optional (this is to maintain compatibility with NhExt 1.0).

# Sub-protocol 0

Sub-protocol 0 is line based. Each line consists of a series of characters terminated with one end-of-line character. The game will always use the ASCII NL character (code 0x0A) for this, but it will accept either ASCII NL or CR (codes 0x0A and 0x0D) - but not both.

The game will always start by writing a line consisting of the five characters "NhExt" which will be followed by a number of tags and values.

Tags are sequences of up to 64 alpha-numeric characters, plus "_".

Values are sequences of up to 64 printable ASCII characters (space to "~"), enclosed in double quote marks. Characters may be escaped with backslash. If every character was escaped, and including the two enclosing quotes, a 64 character sequence could take 130 bytes to transmit.

Tags need not be in any order within the line.

Tags and values are seperated from each other (and from the "NhExt" command) by one space character.

The following tags will always be present:

- standard. The NhExt standard to which the game complies. NhExt standards are always of the form major.minor where major and minor are non-negative decimal numbers. Micro revisions (eg., 1.0.1) are fully compatible with each other and are therefore not important. Games complying to a later standard will be compatible with window ports complying with an earlier standard in the same series (having the same major number). Window ports should refuse to connect to a game with a major number greater than the standard to which they comply; they should connect with full functionality to a game with the same major number and with a minor number no lower than the standard to which they comply. Window ports may connect to games complying to earlier revisions of the standard if they are able to modify their functionality to comply with the earlier standard.
- game. This value can be used to distinguish vanilla NetHack (which uses the value "NetHack") from its variants (eg., Slash'EM uses the value "SlashEM").
- version. This is the value of `VERSION_STRING`.
- protocols. This is a comma seperated list of protocols that this game supports. There should be no whitespace in the list. Sub-protocol zero is not listed.

The following tag may also be present:

- authmethods. This is a comma seperated list of authentication methods that this game allows. There should be no whitespace in the list. If this tag is not present, its value should be taken as "0".

Window ports should ignore tags they do not recognize.

Example:

    NhExt standard "1.0" game "NetHack" version "3.3.2" protocols "1" junk "foo \" bar"

The window-port should reply with either an error or an acknowledgment response.

An error response consists of the five characters "Error" followed by a "mesg" tag and a value. As a special case, this value may be up to 200 characters in length.

Example:

    Error mesg "X11: Can't open display (Permission denied)"

There may also be other tags present, which will be ignored.

The game will respond to an error response by displaying the error message to the user and then terminating.

An acknowledgment response consists of the three characters "Ack" followed by a number of tags and values.

The following tags must always be present:

- windowtype. The name of the window-port.
- protocol. The sub-protocol to use.

The following tags may be present:

- authmethod. The authentication method used. If this tag is not present, its value should be taken as "0".
- username. The user name for authentication.
- password. The password for authentication.

The game will ignore tags it does not recognize.

Example:

    Ack windowtype "Gtk" protocol "1"

On receipt of an acknowledgment response, the game will immediately start the requested sub-protocol. The window-port should enter listening mode.

## Authentication

There is currently just one method of authentication defined (in addition to method 0). This is a simple password authenticaion scheme which transmits the password in clear text. A future version of this standard may define a more secure authentication method, perhaps along the same lines as RFC 2195.

Game servers that wish to take advantage of authentication should declare that they allow authentication by method 1 and optionally also via method 0 if they wish to allow non-authenticated users. On receipt of an acknowledgment response, the game should check that the authenticaion method employed is allowed and, in the case of method 1, that the user name and password are acceptable. The game should then remember whether the remote interface is authenticated or not. Note that a compliant game may not refuse to enter the requested sub-protocol even if authentication fails.

If authentication fails then the game should issue an error and exit after the error is displayed and acknowledged by the user (eg., by using display_nhwindow with blocking set to TRUE). Games may fail all callbacks received during this period (while still sending replies where required).

Example:

    NhExt standard "1.0" game "SlashEM" version "0.0.7E6F2" protocols "1,2" authmethods "1"
    Ack windowtype "Gtk" protocol "2" authmethod "1" username "fred" password "secret"

# Sub-protocol 1

This sub-protocol is heavily based on Sun Microsystem's XDR protocol, documented in RFC 1014. In addition, I use their XDR language to describe the structure of request and reply encodings. It should be possible to use their rpcgen program (supplied with Solaris) to generate routines to encode and decode data compatible with sub-protocol 1. There is, however, no need to use rpcgen.

I have also plagiarised window.doc mercilessly.

Sub-protocol 1 is fully synchronous. That is, at any time either the game is waiting for input and the window-port is either writing data or is not yet ready to write data, or the reverse is true.

## Window Types and Terminology

There are 5 basic window types, used to call create_nhwindow:

NHW_MESSAGE | (top line)
NHW_STATUS | (bottom lines)
NHW_MAP | (main dungeon)
NHW_MENU | (inventory or other "corner" windows)
NHW_TEXT | (help/text, full screen paged window)

The tty window-port also uses NHW_BASE (the base display) internally.

NHW_MENU windows can be used for either menu or text display. Their basic feature is that for the tty-port, if the window is small enough, it appears in the corner of the tty display instead of overwriting the whole screen. The first call to add information to the window will decide if it is going to be used to display a menu or text. If start_menu() is called, then it will be used as a menu. If putstr() is called, it will be used as text. Once decided, there is no turning back. For the tty-port, if the data is too large for a single screen then the data is paged (with --more--) between pages. Only NHW_MENU type windows can be used for menus.

NHW_TEXT windows are used to display a large amount of textual data. This is the type of window one would use for displaying a help file, for example. In the tty window-port, windows of type NHW_TEXT can page using the DEF_PAGER, if DEF_PAGER is defined. There exists an assumption that the font for text windows is monospaced. The help files are all formatted accordingly.

"window" is always of type int. The proxy module will convert to and from winids if it ever needs to. There are a few fixed window names that are known throughout the code:

WIN_MESSAGE | (top line)
WIN_STATUS | (bottom lines)
WIN_MAP | (main dungeon)
WIN_INVEN | (inventory)

Other windows are created and destroyed as needed.

"Port" in this document refers to a CPU/OS/hardware platform (UNIX, MSDOS TOS, etc.) "window-port" refers to the windowing platform. This is orthogonal (e.g. UNIX might use either a tty window-port or an X11 window-port).

## Standard window port procedures

These procedures must be supported by all plug-in window ports (although for many procedures they need not actually do anything). Depending on the setting of the configuration variables, the game may never call some of these. Such configuration variables have no effect on the values of the IDs.

Procedure | ID
--- | ---
init | 0x01
init_nhwindows | 0x02
player_selection | 0x03
askname | 0x04
get_nh_event | 0x05
exit_nhwindows | 0x06
suspend_nhwindows | 0x07
resume_nhwindows | 0x08
create_nhwindow | 0x09
clear_nhwindow | 0x0A
display_nhwindow | 0x0B
destroy_nhwindow | 0x0C
curs | 0x0D
putstr | 0x0E
display_file | 0x0F
start_menu | 0x10
add_menu | 0x11
end_menu | 0x12
select_menu | 0x13
message_menu | 0x14
update_inventory | 0x15
mark_sync | 0x16
wait_sync | 0x17
cliparound | 0x18
update_positionbar | 0x19
print_glyph | 0x1A
raw_print | 0x1B
raw_print_bold | 0x1C
nhgetch | 0x1D
nh_poskey | 0x1E
nhbell | 0x1F
doprev_message | 0x20
yn_function | 0x21
getlin | 0x22
get_ext_cmd | 0x23
number_pad | 0x24
delay_output | 0x25
change_color | 0x26
change_background | 0x27
set_font_name | 0x28
get_color_string | 0x29
start_screen | 0x2A
end_screen | 0x2B
outrip | 0x2C
preference_update | 0x2D
status | 0x2E
print_glyph_layered | 0x2F
send_config_file | 0x30

Plug-in window ports may define non-standard procedures with IDs of 0x8000 and above. In response to all other IDs, the window port should return a reply packet with no results.

The proxy module will initiate a procedure by writing an unsigned integer (according to RFC1014) whose value is as follows:

    	value = (ID << 16) | (length >> 2);

where `length` is the length of the following data (not including `value`) in bytes. It will then write the relevant request structure (if a procedure takes no arguments then length will be zero and no request structure will be written).

The proxy module will then read back an unsigned integer from the plug-in window-port and decode it as follows:

    	ID = value >> 16;
    	length = (value & 0xffff) << 2;

If `ID` is non-zero, this is a callback.

If `ID` is zero, this is a reply to the active procedure. The proxy module will read that many bytes from the plug-in window-port and process the reply.

### init

init takes no arguments and returns no results.

This procedure will be called once before all other procedures.

### init_nhwindows

    typedef string argument<>;
    typedef string wincap<>;

    struct init_nhwindows_req {
    	argument argv<>;
    };

    struct init_nhwindows_res {
    	bool inited;
    	argument argv<>;
    	wincap capabilities<>;
    };

- Initialize the windows used by NetHack. This can also create the standard windows listed at the top, but does not display them.
- Any commandline arguments relevant to the windowport should be interpreted, argv should be changed to remove those arguments and returned.
- When the message window is created, inited needs to be returned as `TRUE`. Otherwise all `plines()` will be done via raw_print.
- ALI: Would a window-port ever want to leave `iflags.window_inited FALSE`?
- The capabilities list should be filled in with the relevant values. The proxy module will ignore capabilities that it does not recognize. The following capabilities are currently understood:
  - align_message
  - align_status
  - ascii_map
  - color
  - eight_bit_tty
  - font_map
  - font_menu
  - font_message
  - font_size_map
  - font_size_menu
  - font_size_message
  - font_size_status
  - font_size_text
  - font_status
  - font_text
  - hilite_pet
  - map_mode
  - mouse_support
  - perm_invent
  - player_selection
  - popup_dialog
  - preload_tiles
  - scroll_amount
  - scroll_margin
  - splash_screen
  - tiled_map
  - tile_file
  - tile_height
  - tile_width
  - use_inverse
  - var_msgcount
  - windowcolors

### player_selection

    struct player_selection_req {
    	int initrole;
    	int initrace;
    	int initgend;
    	int initalign;
    };

    struct player_selection_res {
    	int role;
    	int race;
    	int gend;
    	int align;
    	bool quit;
    };

Do a window-port specific player type selection. If player_selection offers a Quit option, it should return `TRUE` in quit if this is selected.

### askname

askname takes no arguments.

    struct askname_res {
    	string plname<>;
    };

Ask the user for a player name and return it.

### get_nh_event

get_nh_event takes no arguments and returns no results.

Does window event processing (e.g. exposure events). A noop for the tty and X window-ports.

### exit_nhwindows

    struct exit_nhwindows_req {
    	string str<>;
    };

exit_nhwindows returns no results.

Exits the window system. This should dismiss all windows, except the "window" used for raw_print(). str is printed if possible.

### suspend_nhwindows

    struct suspend_nhwindows_req {
    	string str<>;
    };

suspend_nhwindows returns no results.

Prepare the windows to be suspended.

### resume_nhwindows

resume_nhwindows takes no arguments and returns no results.

Restore the windows after being suspended.

### create_nhwindow

    enum nhwindow_type {
        NHW_MESSAGE = 1,		/* (top line) */
        NHW_STATUS = 2,		/* (bottom lines) */
        NHW_MAP = 3,		/* (main dungeon) */
        NHW_MENU = 4,		/* (inventory or other "corner" windows) */
        NHW_TEXT = 5		/* (help/text, full screen paged window) */
    };

    struct create_nhwindow_req {
        enum nhwindow_type type;
    };

    struct create_nhwindow_res {
        int window;
    };

Create a window of type type.

### clear_nhwindow

    struct clear_nhwindow_req {
        int window;
        int rows;
        int cols;
        int layers;
    };

clear_nhwindow returns no results.

Clear the given window, when appropriate.

For windows of type NHW_MAP, the rows, cols and layers fields specify the number of rows, columns and layers to be used for this window from now until the next call to clear the window. Windowing interfaces which choose not to use layered glyphs may ignore this value.

### display_nhwindow

    struct display_nhwindow_req {
        int window;
        bool blocking;
    };

display_nhwindow returns no results.

Display the window on the screen. If there is data pending for output in that window, it should be sent. If blocking is `TRUE`, display_nhwindow will not return until the data has been displayed on the screen, and acknowledged by the user where appropriate.

All calls are blocking in the tty window-port.

Calling `display_nhwindow(WIN_MESSAGE,???)` will do a `--more--`, if necessary, in the tty window-port.

### destroy_nhwindow

    struct destroy_nhwindow_req {
        int window;
    };

destroy_nhwindow returns no results.

Destroy will dismiss the window if the window has not already been dismissed.

### curs

    struct curs_req {
        int window;
        int x;
        int y;
    };

curs returns no results.

Next output to window will start at (x,y), also moves displayable cursor to (x,y). For backward compatibility, 1 <= x < cols, 0 <= y < rows, where cols and rows are the size of window.

For variable sized windows, like the status window, the behavior when curs is called outside the window's limits is unspecified. The mac port wraps to 0, with the status window being 2 lines high and 80 columns wide.

Still used by `curs_on_u()`, status updates, screen locating (identify, teleport).

`NHW_MESSAGE`, `NHW_MENU` and `NHW_TEXT` windows do not currently support curs in the tty window-port.

### putstr

    enum nhwindow_atr {
        ATR_NONE = 0,
        ATR_BOLD = 1,
        ATR_DIM = 2,
        ATR_ULINE = 4,
        ATR_BLINK = 5,
        ATR_INVERSE = 7
    };

    struct putstr_req {
        int window;
        enum nhwindow_atr attr;
        string str<>;
    };

putstr returns no results.

Print str on the window with the given attribute. Only printable ASCII characters (040-0126) must be supported. Multiple putstrs are output on separate lines. Attributes can be one of `ATR_NONE` (or 0), `ATR_ULINE`, `ATR_BOLD`, `ATR_BLINK`, `ATR_INVERSE`. If a window-port does not support all of these, it may map unsupported attributes to a supported one (e.g. map them all to `ATR_INVERSE`). putstr may compress spaces out of str, break str, or truncate str, if necessary for the display. Where putstr breaks a line, it has to clear to end-of-line.

putstr should be implemented such that if two putstrs are done consecutively the user will see the first and then the second. In the tty port, `pline()` achieves this by calling `more()` or displaying both on the same line.

### display_file

    struct display_file_req {
        int fh;
    };

display_file returns no results.

Display the file whose handle is fh.

The proxy module is responsible for opening the file to be displayed as if the dlbh_fopen callback had been called. The window-port should read the data from the file using the dlbh_fgets callback (passing it fh as the handle). When the display_file procedure returns, the proxy module will close the file again.

The proxy module is responsible for complaining (via `pline`) if the file cannot be opened (in which case this procedure will not be initiated).

### start_menu

    struct start_menu_req {
        int window;
    };

start_menu returns no results.

Start using window as a menu. You must call start_menu before add_menu. After calling start_menu you may not putstr to the window. Only windows of type `NHW_MENU` may be used for menus.

### add_menu

    struct add_menu_req {
        int window;
        int glyph;
        int identifier;
        int accelerator;
        int groupacc;
        int attr;
        string str<>;
        bool preselected;
    };

add_menu returns no results.

Add a text line str to the given menu window. If identifier is 0, then the line cannot be selected (e.g. a title). Otherwise, identifier is the value returned if the line is selected. accelerator is a keyboard key that can be used to select the line. If the accelerator of a selectable item is 0, the window system is free to select its own accelerator. It is up to the window-port to make the accelerator visible to the user (e.g. put `a -` in front of str). The value attr is the same as in putstr. glyph is an optional glyph to accompany the line. If window port cannot or does not want to display it, this is OK. If there is no glyph applicable, then this value will be -1 (converted from NO_GLYPH by the proxy module).

All accelerators should be in the range [A-Za-z].

It is expected that callers do not mix accelerator choices. Either all selectable items have an accelerator or let the window system pick them. Don't do both.

groupacc is a group accelerator. It may be any character outside of the standard accelerator (see above) or a number. If 0, the item is unaffected by any group accelerator. If this accelerator conflicts with the menu command (or their user defined alises), it loses. The menu commands and aliases take care not to interfere with the default object class symbols.

If you want this choice to be preselected when the menu is displayed, set preselected to `TRUE`.

The proxy module is responsible for converting the game's `anything` identifiers into integers (and back again in select_menu).

### end_menu

    struct end_menu_req {
        int window;
        string prompt<>;
    };

end_menu returns no results.

Stop adding entries to the menu and flushes the window to the screen (brings to front?). prompt is a prompt to give the user. If prompt is an empty string, no prompt will be printed.

> This probably shouldn't flush the window any more (if it ever did). That should be select_menu's job. -dean

### select_menu

    enum menu_pick {
        PICK_NONE = 0,  /* user picks nothing (display only) */
        PICK_ONE = 1,   /* only pick one */
        PICK_ANY = 2    /* can pick any amount */
    };

    struct select_menu_req {
        int window;
        enum menu_pick how;
    };

    struct select_menu_res_item {
        int item;       /* identifier */
        long count;     /* count */
    };

    struct select_menu_res {
        int retval;
        select_menu_res_item selected<>;
    };

Set retval to the number of items selected; 0 if none were chosen, -1 when explicitly cancelled. If items were selected, then selected is filled in with an array of `select_menu_res_item` structures, one for each selected line. The count field of selected is a user supplied count. If the user did not supply a count, then the count field is filled with -1 (meaning all). A count of zero is equivalent to not being selected and should not be in the list. If no items were selected, then selected is empty. how is the mode of the menu. Three valid values are `PICK_NONE`, `PICK_ONE`, and `PICK_ANY`, meaning: nothing is selectable, only one thing is selectable, and any number valid items may selected. If how is `PICK_NONE`, retval should never be set to anything but 0 or -1.

You may call select_menu on a window multiple times -- the menu is saved until start_menu or destroy_nhwindow is called on the window.

Note that `NHW_MENU` windows need not have select_menu called for them. There is no way of knowing whether select_menu will be called for the window at create_nhwindow time.

The proxy module is responsible for converting the integer identifiers back to the original `anything` value.

### message_menu

    struct message_menu_req {
        int let;
        int how;
        string mesg<>;
    };

    struct message_menu_res {
        int retval;
    };

tty-specific hack to allow single line context-sensitive help to behave compatibly with multi-line help menus.

This should only be called when a prompt is active; it sends mesg to the message window. For tty, it forces a `--More--` prompt and enables let as a viable keystroke for dismissing that prompt, so that the original prompt can be answered from the message line "help menu".

retval is either let, 0 (no selection was made), or 27 (explicit cancellation was requested).

Interfaces which issue prompts and messages to separate windows typically won't need this functionality, and should set retval to -1 (in which case the proxy module will arrange for the message to be output via `pline()` instead).

ALI: What does how do?

### update_inventory

update_inventory takes no arguments and returns no results.

Indicate to the window port that the inventory has been changed.

Merely calls the display_inventory callback for window-ports that leave the window up, otherwise does nothing.

### mark_sync

mark_sync takes no arguments and returns no results.

Don't go beyond this point in I/O on any channel until all channels are caught up to here. Can be an empty call for the moment

### wait_sync

wait_sync takes no arguments and returns no results.

Wait until all pending output is complete (flush() for streams goes here).

May also deal with exposure events etc., so that the display is OK when return from wait_synch.

### cliparound

    struct cliparounf_req {
        int x;
        int y;
    };

cliparound returns no values.

Make sure that the user is more-or-less centered on the screen if the playing area is larger than the screen.

### update_positionbar

    struct update_positionbar_req {
        string features<>;
    };

update_positionbar returns no values.

Provide some additional information for use in a horizontal position bar (most useful on clipped displays). features is a series of char pairs. The first char in the pair is a symbol and the second char is the column where it is currently located. A '<' is used to mark an upstairs, a '>' for a downstairs, and an '@' for the current player location.

### print_glyph

    struct print_glyph_req {
        int window;
        int x;
        int y;
        int glyph;
    };

print_glyph returns no values.

Print glyph at (x,y) on the given window. Glyphs are integers at the interface, mapped to whatever the window-port wants (symbol, font, color, attributes, ...there's a 1-1 map between glyphs and distinct things on the map).

### raw_print

    struct raw_print_req {
        string str<>;
    };

raw_print returns no values.

Print directly to a screen, or otherwise guarantee that the user sees str. raw_print appends a newline to str. It need not recognize ASCII control characters. This is used during startup (before windowing system initialization -- maybe this means only error startup messages are raw), for error messages, and maybe other "msg" uses. E.g. updating status for micros (i.e, "saving").

### raw_print_bold

    struct raw_print_bold_req {
        string str<>;
    };

raw_print_bold returns no values.

Like raw_print, but prints in bold/standout (if possible).

### nhgetch

nhgetch takes no arguments.

    struct nhgetch_res {
        int ch;
    };

Sets ch to a single character input from the user.

In the tty window-port, nhgetch assumes that `tgetch()` will be the routine the OS provides to read a character. The character returned must be non-zero.

### nh_poskey

nh_poskey takes no arguments.

    enum mouse_click {
        CLICK_1 = 1,	/* mouse click type 1 */
        CLICK_2 = 2		/* mouse click type 2 */
    };

    struct nh_poskey_res {
        int retval;
        int x;
        int y;
        enum mouse_click mod;
    };

Returns a single character input from the user or a positioning event (perhaps from a mouse). If retval is non-zero, a character was typed, else, a position in the MAP window is returned in x, y and mod.

The different click types can map to whatever the hardware supports. If no mouse is supported, this routine always sets retval to a non-zero character.

### nhbell

nhbell takes no arguments and returns no values.

Beep at user. [This will exist at least until sounds are redone, since sounds aren't attributable to windows anyway.]

### doprev_message

doprev_message takes no arguments.

    struct doprev_message_res {
        int retval;
    };

Display previous messages. Used by the ^P command.

On the tty-port this scrolls WIN_MESSAGE back one line.

ALI: What purpose does retval serve?

### yn_function

    struct yn_function_req {
        string ques<>;
        string choices<>;
        int default_response;
    };

    struct yn_function_res {
        int retval;
        int count;
    };

Print a prompt made up of ques, choices and default. Read a single character response that is contained in choices or default. If choices is empty, all possible inputs are accepted and returned. This overrides everything else. The choices are expected to be in lower case. Entering ESC always maps to 'q', or 'n', in that order, if present in choices, otherwise it maps to default. Entering any other quit character (SPACE, RETURN, NEWLINE) maps to default.

If the choices string contains ESC, then anything after it is an acceptable response, but the ESC and whatever follows is not included in the prompt.

If the choices string contains a '#' then accept a count. Place this value in count and set retval to '#'.

This uses the top line in the tty window-port, other ports might use a popup.

### getlin

    struct getlin_req {
        string ques<>;
    };

    struct getlin_res {
        string input<>;
    };

Prints ques as a prompt and reads a single line of text, up to a newline. The string entered is returned in input without the newline. ESC is used to cancel, in which case the string "\033" is returned.

getlin must call the flush_screen callback with cursor_on_u set to `TRUE` before doing anything.

This uses the top line in the tty window-port, other ports might use a popup.

### get_ext_cmd

get_ext_cmd takes no arguments.

    struct get_ext_cmd_res {
        int extcmd;
    };

Get an extended command in a window-port specific way. An index into the extended command list (readable with the get_extended_commands callback) is returned on a successful selection, -1 otherwise.

### number_pad

    enum number_pad_mode {
        NP_KEYPAD = -1,		/* activate keypad mode (escape sequences) */
        NP_NUMERIC = 1		/* activate numeric mode for keypad (digits) */
    };

    struct number_pad_req {
        enum number_pad_mode state;
    };

number_pad returns no values.

Initialize the number pad to the given state.

### delay_output

delay_output takes no arguments and returns no values.

Causes a visible delay of 50ms in the output. Conceptually, this is similar to wait_synch() followed by a nap(50ms), but allows asynchronous operation.

### change_color

    struct change_color_req {
        int color;
        int rgb;
        bool reverse;
    };

change_color returns no values.

### change_background

    struct change_background_req {
        bool white_or_black;
    };

change_background returns no values.

### set_font_name

    struct set_font_name_req {
        int window;
        string font<>;
    };

    struct set_font_name_res {
        int retval;
    };

### get_color_string

get_color_string takes no arguments.

    struct get_color_string_res {
        string retval<>;
    };

### start_screen

start_screen takes no arguments and returns no values.

Only used on Unix tty ports. Sets up the tty to work in full-screen graphics mode. Look at win/tty/termcap.c for an example.

### end_screen

end_screen takes no arguments and returns no values.

Only used on Unix tty ports. The complement of start_screen().

### outrip

    struct outrip_req {
        int window;
        string killed_by_prefix<>;
    };

    struct outrip_res {
        bool handled;
    };

The tombstone code. If you want the traditional code set handled to `FALSE` (the proxy module will then call `genl_outrip`).

ALI: I suspect we should pass rather more information to this procedure; `genl_outrip()` uses a lot of global variables.

### preference_update

    struct preference_update_req {
        string pref<>;
        string value<>;
    };

Notify the window client that the value of option pref has changed to value. The set of options of which the window client will be notified is determined by the window capabilities, set in the init_nhwindows procedure.

### status

    typedef string value<>;

    struct proxy_status_req {
        int reconfig;
        value values<>;
    };

### print_glyph_layered

    struct glyph_row {
        int start;
        int glyphs<>;
    };

    struct glyph_layer {
        int start;
        struct glyph_row rows<>;
    };

    struct print_glyph_layered_req {
        int window;
        struct glyph_layer layers<>;
    };

print_glyph_layered returns no values.

Place glyphs at the relevant places on the given window. All layers are included in the call, even if there have been no changes to the glyphs in that layer. In contrast, only a subset of the rows and the glyphs within those rows are included. The start fields specify the first row or column in the window which should be written to. Note that the start column may vary across different rows and that some rows may contain no glyphs. Window interfaces may display layered glyphs using either opacity (lowest present glyph is displayed), transparancy (each glyph is represented by an irregular shaped image. Glyphs from layers further away may be seen behind the image), translucency (glpyhs are represented by images that only partially obscure the underlying image) or some other suitable method.

Layers are numbered counting away from the viewer. Layers which have no glyph present have a value of NO_GLYPH.

Glyphs are integers at the interface, mapped to whatever the window-port wants (symbol, font, color, attributes, ...there's a 1-1 map between glyphs and distinct things on the map).

Note: This procedure will only be called if the interface flag EXT_IM_DISPLAY_LAYERS is set.

### send_config_file

    struct send_config_file_req {
        int handle;
    };

send_config_file returns no values.

Request that if the window interface has a local config file then it should be sent to the game by writing it to the specified handle using the dlbh_fwrite callback. The handle will be closed when send_config_file returns.

## Standard window port call backs

Plug-in window ports may assume that the following call backs are supported.

Call back | ID
--- | ---
display_inventory | 0x01
dlbh_fopen | 0x02
dlbh_fgets | 0x03
dlbh_fread | 0x04
dlbh_fwrite | 0x05
dlbh_fclose | 0x06
dlbh_fmd5sum | 0x07
flush_screen | 0x08
doredraw | 0x09
interface_mode | 0x0A
parse_options | 0x0B
get_option | 0x0C
get_player_choices | 0x0D
get_valid_selections | 0x0E
quit_game | 0x0F
display_score | 0x10
doset | 0x11
get_extended_commands | 0x12
map_menu_cmd | 0x13
get_standard_winid | 0x14
get_tilesets | 0x15
get_glyph_mapping | 0x16
get_extensions | 0x17
set_option_mod_status | 0x18

### display_inventory

display_inventory takes no arguments and returns no values.

Display the hero's inventory.

### dlbh_fopen

    struct dlbh_fopen_req {
        string name<>;
        string mode<>;
    };

    struct dlbh_fopen_res {
        int fh;
    };

Open a file and return a handle or -1 on error. The following names have special meanings as follows:

Name | File
--- | ---
$(RECORD) | NetHack record
$(HELP) | NetHack help
$(SHELP) | NetHack short help
$(DEBUGHELP) | NetHack wizard mode help
$(DATAFILE) | NetHack data
$(CMDHELPFILE) | NetHack command help
$(HISTORY) | NetHack history
$(LICENSE) | NetHack license
$(OPTIONFILE) | NetHack option
$(OPTIONS_USED) | NetHack options used
$(GUIDEBOOK) | NetHack guidebook

The following modes are supported: r and rb.

### dlbh_fgets

    struct dlbh_fgets_req {
        int len;
        int fh;
    };

    struct dlbh_fgets_res {
        string line<>;
    };

Read one line of a file previously opened with dlbh_fopen. At most len characters will be returned including the newline at the end of the line. If len is too short to return a whole line the first len characters will be returned (with no terminating newline) and the rest of the line will be available for reading with the next call the dlbh_fgets. An empty string will be returned on end of file or other error.

### dlbh_fread

    struct dlbh_fread_req {
        int len;
        int fh;
    };

    struct dlbh_fread_res {
        int retval;
        opaque buffer<>;
    };

Read up to len bytes of a file previously opened with dlbh_fopen. If an error occurs, retval will be non-zero. Any bytes read before the error occured will be returned in the buffer. An empty buffer will be returned on end of file.

### dlbh_fwrite

    struct dlbh_fwrite_req {
        int fh;
        opaque buffer<>;
    };

    struct dlbh_fwrite_res {
        int retval;
    };

Write buffer to a file previously opened for writing. At present, the only means of aquiring a writable handle is via the send_config_file procedure. If an error occurs, retval will be non-zero.

### dlbh_fclose

    struct dlbh_fclose_req {
        int fh;
    };

    struct dlbh_fclose_res {
        int retval;
    };

Close a file previously opened with dlbh_fclose. Return non-zero on error.

### dlbh_fmd5sum

    struct dlbh_fmd5sum_req {
        string name<>;
    };

    struct dlbh_fmd5sum_res {
        int retval;
        string digest<>;
    };

Compute a message digest for a file according to RFC 1321 (MD5). See dlbh_fopen for information on file names. Retval will be zero if the file was opened successfully and -1 if an error was encountered.

### flush_screen

flush_screen takes no arguments and returns no values.

Flush the screen.

### doredraw

doredraw takes no arguments and returns no values.

Redraw the screen.

### interface_mode

    struct interface_mode_fclose_req {
        unsigned long mode;
    };

Set or reset flags to change the behaviour of the interface as follows:

Flag | Status | Behaviour
--- | --- | ---
EXT_IM_STATUS | 0 | Report status via calls to putstr(WIN_STATUS,...)
| 1 | Report status via calls to status(...)
EXT_IM_DISPLAY_LAYERS | 0 | Use print_glyph procedure
| 1 | Use print_glyph_layered procedure |

### parse_options

    struct parse_options_req {
        string opts<>;
    };

    struct parse_options_res {
        int retval;
    };

Parse the options passed. Multiple options may be given, seperated with commas. The format for options is the save as when included with the OPTIONS keyword in NetHack defaults files. See the guidebook for details.

parse_options returns non-zero on error.

### get_option

    struct get_option_req {
        string opt<>;
    };

    struct get_option_res {
        string value<>;
    };

Get the value of an option, or the empty string if the option is not recognized. Boolean options are returned as values of "yes" or "no".

### get_player_choices

    typedef string choices<>;

    struct get_player_choices_res_role {
        string male<>;
        string female<>;
    };

    struct get_player_choices_res {
        choices aligns<>;
        choices genders<>;
        choices races<>;
        struct get_player_choices_res_role roles<>;
    };

Returns an array of the possible values for each of player alignment, gender, race and role. Note that this includes all possible values, not just the ones that are compatible with the currently set options.

The (integer) values of align, gend, race and role used by the player_selection procedure can be used as indices into these arrays.

### get_valid_selctions

    struct get_valid_selections_res {
        int no_roles;
        int no_races;
        int no_aligns;
        int no_genders;
        unsigned long masks<>;
    };

Get a packed array of masks of combinations of role, race, gender and alignment which form a valid player selection.

When unpacked, the array contains no_roles * no_races * no_aligns elements each of which is a mask of the valid genders for this combination of role, race, alignment. If there are no valid genders then this mask will be zero, otherwise it will be the bitwise-OR of `(1<<gender)` for each gender that is valid.

The array is packed by copying no_gender bits from the next mask in the unpacked array into the least significant unused bits of the current element in the packed array (the order of bits within each mask is unchanged during this process). A new element in the packed array is started when there is not enough room for a complete mask to be stored (masks are not split across array elements). The final element in the packed array may only be partially filled.

### quit_game

quit_game takes no arguments and returns no values.

User request to quit the game.

### display_score

display_score takes no arguments and returns no values.

Display the current score list.

### doset

doset takes no arguments and returns no values.

Display the current options and allow the user to modify them.

### get_extended_commands

    typedef string commands<>;

    struct get_extended_commands_res {
        commands ext_cmd_list<>;
    };

Get a list of extended commands. Note that this command list may change (for example when starting in wizard mode).

### map_menu_cmd

    struct map_menu_cmd_req {
        int ch;
    };

    struct map_menu_cmd_res {
        int retval;
    };

Map the given character to its corresponding menu command. If it doesn't match anything, just return the original.

### get_standard_winid

    struct get_standard_winid_req {
        string window<>;
    };

    struct get_standard_winid_res {
        int retval;
    };

Return the window ID of standard windows (this will be -1 if the window is not open). The following window names are currently recognized:

Name | Window
--- | ---
MESSAGE | The message window
STATUS | The status window
MAP | The map window
INVEN | The permanent inventory window or, if none, the current transitory inventory window

Unrecognized windows will return -1.

### get_tilesets

    struct get_tilesets_res_tileset {
        string name<>;
        string file<>;
        string mapfile<>;
        long flags;
    };

    struct get_tilesets_res {
        struct get_tilesets_res_tileset tilesets<>;
    };

Return a list of the currently configured tile sets.

### get_glyph_mapping

    struct get_glyph_mapping_res_symdef {
        long rgbsym;
        string description<>;
    };

    struct get_glyph_mapping_res_submapping {
        struct get_glyph_mapping_res_symdef symdef;
        struct get_glyph_mapping_res_symdef glyphs<>;
    };

    struct get_glyph_mapping_res_mapping {
        string flags<>;
        int base_mapping;
        int alt_glyph;
        struct get_glyph_mapping_res_symdef symdef;
        struct get_glyph_mapping_res_submapping submappings<>;
    };

    struct get_glyph_mapping_res {
        int no_glyph;
        long transparent;
        struct get_glyph_mapping_res_mapping mappings<>;
    };

Return a set of descriptions for each glyph so that the window port can generate a map between glyphs and tiles and/or characters for display.

The descriptions are returned in a tiered structure for efficiency. The top level contains the value of no_glyph, which is both the number of glyphs in the map and the value used by the game to indicate that no glyph is present.

The transparent field contains an arbitary RGB colour which is used within the glyph map to indicate a transparent colour. When combining glyph maps (see below) a non-transparent colour should always superceed the transparent colour. Similarly, the symbol part of the transparent field contains a value which is used to indicate a transparent symbol which is used in an equivalent way. The field (and the rgbsym field described later) is encoded with an 8-bit red value in the top 8 bits, an 8-bit green value in bits 16 to 23, an 8-bit blue value in bits 9 to 15 and an 8-bit symbol in the bottom 8 bits.

There then follows a series of mappings which form the second level. Here a comma seperated set of flags may be specified which is used to distinguish similar glyphs. Window ports should ignore flags that they do not recognize.

Where a set of glyphs is substantially the same as another set, then they will be specified as being based on another mapping with the base_mapping field. This will be -1 where no base mapping is in use. Where a base mapping is specified and the number of sub-mappings is zero then the current mapping should be taken as a duplicate of the base mapping, with different flags and alternate glyph (see below) possibly with different colour and symbol (if these are different to the transparent colour and symbol). Where a base mapping is specified with sub-mappings, then each sub-mapping specifes a number of glyphs for each of the glyphs in the base mapping. This is used, for example, with swallows which are based on the monster mapping.

Also provided for some mappings is an alternate glyph which should be used where the windowing port does not support the glyph set. If there is no alternate glyph then the alt_glyph field will contain the value of no_glyph.

Finally, each mapping has a symdef field which contains an RGB colour and symbol which may be set if all glyphs in the set share the same colour and/or symbol.

Each sub-map contains a symdef field which is used in the same way as the same field in the containing mapping structure and a set of symdefs, one for each glyph in the sub-mapping.

### get_extensions

    struct get_extensions_res_extension {
        string name<>;
        string vers<>;
        int no_procedures;
    };

    struct get_extensions_res {
        struct get_extensions_res_extension extensions<>;
    };

Return a list of the supported extensions. The first extension listed will use no_procedures IDs starting at 0x8000. Subsequent extensions will use IDs starting just after the previous extension.

### set_option_mod_status

    /*
     * Option flags
     * Each higher number includes the characteristics of the numbers
     * below it.
     */
    enum option_mod_flag {
        SET_IN_FILE = 0,	/* config file option only */
        SET_VIA_PROG = 1,	/* may be set via extern program, not seen in game */
        DISP_IN_GAME = 2,	/* may be set via extern program, displayed in game */
        SET_IN_GAME = 3	/* may be set via extern program or set in the game */
    };

    struct set_option_mod_status_req {
        string optnam<>;
        enum option_mod_flag status;
    };

# Sub-protocol 2

Sub-protocol 2 has exactly the same procedures and callbacks that are documented above for sub-protocol 1 (except init), but is no longer fully synchronous. This means that some procedures and callbacks which have no need to send a reply can be defined as asynchronous. This lets the remote end know that no reply will be generated, allowing serveral requests to be sent at the same time.

In order to cope with the asychronous nature of the protocol, the header is modified slightly from that used in sub-protocol 0 so that the serial number to which a reply relates can be sent. This means that there is one less bit available and the maximum packet size (including the header) is consequently reduced to 128Kb (sub-protocol 1 allows 256Kb).

In sub-protocol 2, the proxy module will initiate a procedure by writing an unsigned integer (according to RFC1014) whose value is as follows:

    	value = (ID << 16) | (length >> 2);

where `length` is the length of the following data (not including `value`) in bytes. It will then write the relevant request structure (if a procedure takes no arguments then length will be zero and no request structure will be written). Bit 15 will always be zero. An `ID` of 0xffff indicates a special packet.

The proxy module will then read back an unsigned integer from the plug-in window-port and decode it as follows:

    	ID = value >> 16;
    	is_reply = value & 0x8000;
    	length = (value & 0x7fff) << 2;

If `ID` is 0xffff and `is_reply` is zero, this is a special packet. Otherwise, if `is_reply` is zero, this is a callback.

If `is_reply` is non-zero, this is a reply. The ID field contains the serial number of the request to which it relates. The first request to be sent has a serial number of 1. Each subsequent request has the next serial number in sequence, wrapping to 0 after 0xffff. There is no requirement that replies must be sent in any particular order.

## Special packets

Special packets provide a kind of out-of-band communication stream which have no effect on the processing of request and reply packets. They are distingushed by a header with the top 17 bits set to 0x1fffe (which corresponds to an `ID` of 0xffff and bit 15 reset). Special packets are further decoded as follows:

    	type = (value & 0x7f00) >> 8;
    	length = (value & 0xff) << 2;

### Special packet type 0 (error packets)

Error packets are at least two words long which are decoded as follows:

    	serial = word1 >> 16;
    	id = word1 & 0xffff;
    	code = word2 & 0xff;

Other bits are reserved and should be written as zero and ignored on read. `serial` is the serial number of the request to which this error relates. `id` is the ID of that request. `code` is an error code, which is one of the following:

Code | Meaning
--- | ---
1 | The function is unsupported
2 | The function is unsupported in this state (eg., directory_update() before game started)
3 | Invalid paramameter encoding (eg., passing params to a function which takes none)
4 | Invalid parameters (eg., set_option_mod_status() for an undefined status)
5 | Resource failure (eg., add_menu() runs out of memory)

Other error codes should be treated as a generic error.

On receit of a code 1 error (unsupported function), implementations may take it that all further requests with this ID will be ignored (other than to generate errors) and drop them at source. Window interfaces that would otherwise ignore certain requests from the game should instead signal an error to reduce bandwidth. Games are not expected to cope with every combination of procedures being signalled as unsupported, but will cope with the following procedures being unsupported:

- get_nh_event
- suspend_nhwindows and resume_nhwindows (must be both or none)
- update_inventory
- mark_sync
- wait_sync
- cliparound
- update_positionbar
- nhbell
- doprev_message
- number_pad
- delay_output
- change_color
- change_background
- set_font_name
- get_color_string
- start_screen
- end_screen

Window interfaces are not required to be able to cope with any of the standard callbacks being signalled as unsupported.

### Unrecognized special packets

Special packets of a type other than those listed here should be ignored.

## Window port procedures specific to sub-protocol 2

### init

    struct init_req {
        unsigned long async_callbacks<>;
    };

    struct init_res {
        unsigned long async_procedures<>;
    };

In sub-protocol 2, the init procedure is passed a list of callbacks that will not generate a reply and returns a similar list for procedures supported by the window interface.

Lists of async callbacks and procedures are encoded as an array of bitmasks with one mask per 32 callbacks or procedures starting with IDs 1-32 and going up by 32 for each subsequent mask. Within each mask, the least significant bit represents the lowest ID within the 32 IDs encoded. Bits are set to denote an asychronous callback or procedure and reset to denote a synchronous one. Synchronous callbacks and procedures always expect a reply; asynchronous ones expect no reply. IDs beyond the end of the array are treated as synchronous.

This procedure will be called once before all other procedures. No callbacks may be invoked before the init procedure returns.

# Change history

## NhExt 1.0.1

- Added sub-protocol 2.

## NhExt 1.0.2

- Added authentication.