1/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved	by Bram Moolenaar
4 *
5 * Do ":help uganda"  in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10#include "vim.h"
11#include <string.h>
12
13/*
14 * gui_riscos.c
15 *
16 * Thomas Leonard <tal197@ecs.soton.ac.uk>
17 * Updated by Andy Wingate <andy@sparse.net>
18 */
19
20extern int time_of_last_poll;
21
22int task_handle = 0;		/* Zero means we are not yet a Wimp task */
23int child_handle = 0;		/* Task handle of our child process (zero if none). */
24int *wimp_menu = (int *) -1;	/* Pointer to a Wimp menu structure (or -1) */
25int save_window = -1;		/* Save As window handle */
26
27int *redraw_block = NULL;	/* NULL means not in a redraw loop. */
28int ro_return_early = FALSE;	/* Break out of gui_mch_wait_for_chars() */
29
30int leaf_ref = 0;		/* Wimp message number - send via Wimp$Scrap */
31char_u *leaf_name = NULL;	/* Leaf name from DataSave */
32
33int default_columns = 120;	/* These values are used if the --rows and --columns */
34int default_rows = 32;		/* options aren't used on startup. */
35
36#define DRAG_FALSE	    0
37#define DRAG_SELECTION	    1
38#define DRAG_RESIZE_WINDOW  2
39int ro_dragging = DRAG_FALSE;
40int drag_button;
41int drag_modifiers;
42int drag_x_offset;
43int drag_y_offset;
44
45int nested_wimp = FALSE;	/* Bool - can we use the new wimp? */
46
47int changed_mode = FALSE;
48int x_eigen_factor;
49int y_eigen_factor;
50
51/* If ro_current_font is non-zero then use the outline font with that handle,
52 * otherwise, if zap_redraw is TRUE then use ZapRedraw, otherwise use the
53 * system font.
54 *
55 * If zap_redraw is TRUE then zap_file[] contains valid Zap font file
56 * pointers (or NULLs).
57 */
58int ro_current_font = 0;	/* 0 is system font, or ZapRedraw */
59int font_x_offset   = 0;	/* Where to position each char in its box */
60int font_y_offset   = 0;
61
62int zap_redraw	    = FALSE;
63int double_height   = FALSE;	/* Plot each line twice? */
64
65#define grgb(r,g,b) ((b<<16) + (g<<8) + (r))
66#define UNUSED_COLOUR (gui.back_pixel)
67
68#define RO_LOAD_CLIPBOARD -2	/* Internal handle for DataSave message. */
69
70/* Changes by John Kortink, 22-23 July 1998
71 *
72 * Stuff to make redraw a lot faster. Almost all of it is right here below,
73 * elsewhere changes are marked with 'JK230798'. Apart from a small change in
74 * 'gui.c' all changes are limited to this file, 'gui_riscos.c'. The change in
75 * 'gui.c' is to make Vim stop being 'smart' not redrawing characters that are
76 * 'already there' (i.e. from the previous line, by coincidence). This caused a
77 * lot more calls to the redraw code, which we want to avoid because a few nice
78 * big strings at a time is a lot faster than a truckload of small ones. ('Dear
79 * Bram ...').
80 */
81
82/* The ZapRedraw structure */
83
84static struct
85{
86    int		r_flags;
87    int		r_minx;
88    int		r_miny;
89    int		r_maxx;
90    int		r_maxy;
91    int		r_screen;
92    int		r_bpl;
93    int		r_bpp;
94    int		r_charw;
95    int		r_charh;
96    char	*r_caddr;
97    int		r_cbpl;
98    int		r_cbpc;
99    int		r_linesp;
100    int		r_data;
101    int		r_scrollx;
102    int		r_scrolly;
103    int		*r_palette;
104    int		r_for;
105    int		r_bac;
106    char	*r_workarea;
107    int		r_magx;
108    int		r_magy;
109    int		r_xsize;
110    int		r_ysize;
111    int		r_mode;
112}
113zap_redraw_block;
114
115/* Other globals */
116
117static int	zap_redraw_initialised = FALSE;
118static int	zap_redraw_update_colours;
119static int	zap_redraw_colours[2];
120static int	zap_redraw_palette[16];
121
122/* Holds the current Zap font file(s).
123 * The font is recreated from this block on a mode change.
124 * When using zap, element ZAP_NORMAL is always valid, but
125 * the others can be NULL.
126 */
127
128#define ZAP_NORMAL  0
129#define ZAP_BOLD    1
130#define ZAP_ITALIC  2
131#define ZAP_BITALIC 3
132#define ZAP_STYLES  4
133
134/* Zap font file format data */
135static char	*zap_file[ZAP_STYLES] = {NULL, NULL, NULL, NULL};
136
137/* r_caddr format for current mode */
138static char	*zap_caddr[ZAP_STYLES] = {NULL, NULL, NULL, NULL};
139
140static void ro_remove_menu(int *menu);
141
142/*
143 * Initialise all the ZapRedraw stuff.
144 * Call this when changing font and after each mode change.
145 * zap_redraw_bitmap must contain a valid Zap font file (possibly
146 * created from the system font).
147 *
148 * Return FAIL to revert to system font (if we can't use ZapRedraw).
149 */
150    int
151ro_zap_redraw_initialise()
152{
153    int	    bytes_per_bitmap_char;
154    int	    first, last;
155    int	    i;
156
157    /* Can't have initialisers for struct members :-(, ok, this way then ... */
158    if (!zap_redraw_initialised)
159    {
160	zap_redraw_block.r_workarea = NULL;
161	zap_redraw_initialised = TRUE;
162    }
163
164    /* We redraw in DSA mode */
165    zap_redraw_block.r_flags = 0x0;
166
167    /* Let ZapRedraw get the screen address for us */
168    zap_redraw_block.r_screen = 0;
169
170    /* Read the font width and height from the font file header.
171     * Assume that all styles are the same size.
172     * ZAP_NORMAL is always present.
173     */
174    zap_redraw_block.r_charw = ((int *) zap_file[ZAP_NORMAL])[2];
175    zap_redraw_block.r_charh = ((int *) zap_file[ZAP_NORMAL])[3];
176
177    /* We have no linespacing */
178    zap_redraw_block.r_linesp = 0;
179
180    /* Fix foreground = colour 1 */
181    zap_redraw_block.r_for = 1;
182
183    /* Fix background = colour 0 */
184    zap_redraw_block.r_bac = 0;
185
186    /* Colour mask buffer */
187    zap_redraw_block.r_palette = zap_redraw_palette;
188
189    /* Allocate local workspace (for the few calls following here) */
190    if (zap_redraw_block.r_workarea != NULL)
191	free(zap_redraw_block.r_workarea);
192    zap_redraw_block.r_workarea = (char*) malloc(128);
193    if (!zap_redraw_block.r_workarea)
194	return FAIL;	/* Out of memory */
195
196    /* Fill in VDU variables */
197    if (xswi(ZapRedraw_ReadVduVars, 0, &zap_redraw_block) & v_flag)
198	return FAIL;	    /* Can't find ZapRedraw module - use VDU instead */
199
200    /* Determine cbpl and cbpc */
201    swi(ZapRedraw_CachedCharSize, zap_redraw_block.r_bpp, 0,
202	zap_redraw_block.r_charw, zap_redraw_block.r_charh);
203    zap_redraw_block.r_cbpl = r2;
204    zap_redraw_block.r_cbpc = r3;
205
206    /* Allocate general workspace (for the calls outside) */
207    if (zap_redraw_block.r_workarea != NULL)
208	free(zap_redraw_block.r_workarea);
209    zap_redraw_block.r_workarea = (char*) malloc(128 + zap_redraw_block.r_cbpl);
210    if (!zap_redraw_block.r_workarea)
211	return FAIL;	/* Out of memory */
212
213    /* Now convert the 1 bpp character data ready for the current mode */
214
215    bytes_per_bitmap_char = (zap_redraw_block.r_charw * zap_redraw_block.r_charh + 7) / 8;
216
217    /* Convert the fonts from 1bpp to a format suitable for the
218     * current mode.
219     */
220    for (i = 0; i < ZAP_STYLES; i++)
221    {
222	first = ((int *) zap_file[i])[4];
223	last  = ((int *) zap_file[i])[5];
224
225	if (last > 255)
226	    last = 255;	/* Don't convert cursors (overwrites memory!) */
227
228	/* Allocate the font cache */
229	vim_free(zap_caddr[i]);
230	if (zap_file[i])
231	    zap_caddr[i] = (char*) malloc(zap_redraw_block.r_cbpc * 256);
232	else
233	    zap_caddr[i] = NULL;    /* No file for this style */
234
235	if (zap_caddr[i])
236	{
237	    zap_redraw_block.r_caddr = zap_caddr[i];
238
239	    swi(ZapRedraw_ConvertBitmap, 0, &zap_redraw_block,
240		    first, last,		/* Range of characters to convert */
241		    zap_file[i] + 0x20	/* Addr of first char provided by font */
242		    - first * bytes_per_bitmap_char);
243	}
244    }
245
246    if (!zap_caddr[ZAP_NORMAL])
247    {
248	zap_redraw = FALSE;	/* Out of memory */
249	return FAIL;
250    }
251
252    /* Next time we need them, we have to update the colour masks */
253    zap_redraw_update_colours = TRUE;
254
255    return OK;
256}
257
258/*
259 * Redraw a string at OS coordinates <x,y> (top-left, x inclusive, y exclusive).
260 * Graphics clip window is window[0..3] as in R1+28..40 of Wimp_RedrawWindow.
261 * Returns (possibly modified) flags.
262 */
263    int
264ro_zap_redraw_draw_string(x, y, string, length, flags, clip)
265    int	    x;
266    int	    y;
267    char    *string;
268    int	    length;
269    int	    flags;	/* DRAW_TRANSP, DRAW_BOLD, DRAW_UNDERL, DRAW_ITALIC */
270    int	    *clip;
271{
272    char redraw_data[1024];
273    int clip_minx;
274    int clip_miny;
275    int clip_maxx;
276    int clip_maxy;
277    int os_xshift = zap_redraw_block.r_magx;
278    int os_yshift = zap_redraw_block.r_magy;
279
280    if (flags & DRAW_TRANSP)
281	return flags;	/* We don't do transparent plotting yet. */
282
283    if (flags & DRAW_BOLD)
284    {
285	if (flags & DRAW_ITALIC && zap_caddr[ZAP_BITALIC])
286	    zap_redraw_block.r_caddr = zap_caddr[ZAP_BITALIC];
287	else
288	    zap_redraw_block.r_caddr = zap_caddr[ZAP_BOLD];
289    }
290    else
291    {
292	if (flags & DRAW_ITALIC)
293	    zap_redraw_block.r_caddr = zap_caddr[ZAP_ITALIC];
294	else
295	    zap_redraw_block.r_caddr = zap_caddr[ZAP_NORMAL];
296    }
297    if (!zap_redraw_block.r_caddr)
298    {
299	zap_redraw_block.r_caddr = zap_caddr[ZAP_NORMAL];
300	flags |= DRAW_UNDERL;	    /* Style missing - we can always underline */
301    }
302
303    /* Set the vertical scaling flag */
304    if (double_height)
305	zap_redraw_block.r_flags = 1 << 1;
306    else
307	zap_redraw_block.r_flags = 0;
308
309    /* Update the colour masks (if needed) */
310    if (zap_redraw_update_colours)
311    {
312	swi(ZapRedraw_CreatePalette, 2,
313		&zap_redraw_block,
314		zap_redraw_colours,
315		zap_redraw_block.r_palette, 2);
316	zap_redraw_update_colours = FALSE;
317    }
318
319    /* Target rectangle in ZapRedraw rectangle coordinates (pixels, Y-min/max reversed !!!) */
320    zap_redraw_block.r_minx = x >> os_xshift;					/* inclusive */
321    zap_redraw_block.r_miny = zap_redraw_block.r_ysize - (y >> os_yshift);	/* inclusive */
322    zap_redraw_block.r_maxx = (x + length * gui.char_width) >> os_xshift;	/* exclusive */
323    zap_redraw_block.r_maxy = zap_redraw_block.r_ysize - ((y - gui.char_height) >> os_yshift);
324										/* exclusive */
325
326    /* Clip rectangle in ZapRedraw rectangle coordinates (pixels, Y-min/max reversed !!!) */
327    clip_minx = clip[0] >> os_xshift;					/* inclusive */
328    clip_miny = zap_redraw_block.r_ysize - (clip[3] >> os_yshift);	/* inclusive */
329    clip_maxx = clip[2] >> os_xshift;					/* exclusive */
330    clip_maxy = zap_redraw_block.r_ysize - (clip[1] >> os_yshift);	/* exclusive */
331
332    /* Clip target rectangle against the current graphics window */
333    if (zap_redraw_block.r_minx < clip_minx)
334    {
335	zap_redraw_block.r_scrollx = clip_minx - zap_redraw_block.r_minx;
336	zap_redraw_block.r_minx = clip_minx;
337    }
338    else
339	zap_redraw_block.r_scrollx = 0;
340    if (zap_redraw_block.r_miny < clip_miny)
341    {
342	zap_redraw_block.r_scrolly = clip_miny - zap_redraw_block.r_miny;
343	zap_redraw_block.r_miny = clip_miny;
344    }
345    else
346	zap_redraw_block.r_scrolly = 0;
347    if (zap_redraw_block.r_maxx > clip_maxx)
348	zap_redraw_block.r_maxx = clip_maxx;
349    if (zap_redraw_block.r_maxy > clip_maxy)
350	zap_redraw_block.r_maxy = clip_maxy;
351
352    /* Fill in the character data structure */
353    if (length > (sizeof(redraw_data) - 2 * 4 - 2))
354	length = sizeof(redraw_data) - 2 * 4 - 2;
355    ((int*) redraw_data)[0] = 2 * 4;
356    ((int*) redraw_data)[1] = 0;
357    strncpy(redraw_data + 2 * 4, string, length);
358    redraw_data[2 * 4 + length + 0] = '\0';
359    redraw_data[2 * 4 + length + 1] = '\x2';
360    zap_redraw_block.r_data = (int) redraw_data;
361
362    /* Perform the draw */
363    swi(ZapRedraw_RedrawArea, 0, &zap_redraw_block);
364
365    return flags;
366}
367
368/*
369 * Okay that was it from me, back to Thomas ...
370 */
371
372/*
373 * Parse the GUI related command-line arguments.  Any arguments used are
374 * deleted from argv, and *argc is decremented accordingly.  This is called
375 * when vim is started, whether or not the GUI has been started.
376 */
377    void
378gui_mch_prepare(int *argc, char **argv)
379{
380    int	    arg = 1;
381
382    while (arg < *argc - 1)
383    {
384	if (strcmp(argv[arg], "--rows") == 0 || strcmp(argv[arg], "--columns") == 0)
385	{
386	    int	    value;
387
388	    value = atoi(argv[arg + 1]);
389
390	    if (argv[arg][2] == 'r')
391		default_rows = value;
392	    else
393		default_columns = value;
394
395	    /* Delete argument from argv[]. (hope this is read/write!) */
396
397	    *argc -= 2;
398	    if (*argc > arg)
399	    mch_memmove(&argv[arg], &argv[arg + 2], (*argc - arg)
400		    * sizeof(char *));
401	}
402	else
403	    arg++;
404    }
405}
406
407/* Fatal error on initialisation - report it and die. */
408    void
409ro_die(error)
410    char_u *error;	/* RISC OS error block */
411{
412    swi(Wimp_ReportError, error, 5, "GVim");
413    exit(EXIT_FAILURE);
414}
415
416/* Find the sizes of the window tools:
417 *
418 * Create a test window.
419 * Find inner and outer sizes.
420 * Find the difference.
421 * Delete window.
422 *
423 * While we're here, find the eigen values too.
424 */
425    void
426ro_measure_tools()
427{
428    int block[10];
429    int vdu[] = { 4, 5, -1};
430    int test_window[] =
431	{
432	    -100, -100,		/* Visible area : min X,Y */
433	    -50, -50,		/*		  max X,Y */
434	    0,   0,		/* Scroll offsets */
435	    -1,			/* Window in front */
436	    0xd0800150,		/* Window flags */
437	    0xff070207,		/* Colours */
438	    0x000c0103,		/* More colours */
439	    0, -0x4000,		/* Workarea extent */
440	    0x4000, 0,		/* max X,Y */
441	    0x00000000,		/* No title */
442	    0 << 12,		/* No workarea button type */
443	    1,			/* Wimp sprite area */
444	    0x00010001,		/* Minimum width, height */
445	    0, 0, 0,		/* Title data (none) */
446	    0			/* No icons */
447	};
448    int inner_max_x, inner_min_y;
449
450    swi(Wimp_CreateWindow, 0, test_window);
451
452    block[0] = r0;
453    /* Open the window (and read state).
454     * GetWindowOutline needs it too if the wimp isn't nested.
455     */
456    swi(Wimp_OpenWindow, 0, block);
457    inner_max_x = block[3];
458    inner_min_y = block[2];
459
460    swi(Wimp_GetWindowOutline, 0, block);
461
462    gui.scrollbar_width = block[3] - inner_max_x;
463    gui.scrollbar_height = inner_min_y - block[2];
464
465    swi(Wimp_DeleteWindow, 0, block);
466
467    /* Read the size of one pixel. */
468    swi(OS_ReadVduVariables, vdu, vdu);
469    x_eigen_factor = vdu[0];
470    y_eigen_factor = vdu[1];
471}
472
473/* Load a template from the current templates file.
474 * Create the window and return its handle.
475 */
476    int
477ro_load_template(str_name, title, title_size)
478    char_u  *str_name;      /* Identifier of window in file (max 12 chars)   */
479    char_u  **title;	    /* If not NULL then return pointer to title here */
480    int     *title_size;    /* If not NULL then return the title length here */
481{
482    int     *window;
483    char    *data;
484    int     name[4];
485
486    strcpy( (char *) name, str_name);
487
488    /* Find how big we must make the buffers */
489
490    if (xswi(Wimp_LoadTemplate, 0, 0, 0, 0, -1, name, 0) & v_flag)
491	ro_die( (char *) r0);
492
493    window = malloc(r1);	/* Don't print text messages from alloc() */
494    data = malloc(r2);
495    if (window == NULL || data == NULL)
496	ro_die("\0\0\0\0Out of memory - Can't load templates");
497
498    /* Load the template into the buffers */
499
500    swi(Wimp_LoadTemplate, 0,
501				window,		/* Temp block */
502				data,		/* Icon data */
503				data + r2 + 1,	/* End of icon data */
504				-1,		/* No fonts */
505				name, 0);	/* First match */
506    if (r6 == 0)
507	ro_die("\0\0\0\0Can't find window in Templates file");
508
509    /* Create the window */
510
511    if (xswi(Wimp_CreateWindow, 0, window) & v_flag)
512	ro_die( (char *) r0);
513
514    if (title)
515	*title = (char_u *) window[18];
516    if (title_size)
517	*title_size = window[20];
518
519    free(window);	/* Free temp block */
520    return r0;		/* Return the window handle */
521}
522
523/*
524 * Check if the GUI can be started.  Called before gvimrc is sourced.
525 * Return OK or FAIL.
526 */
527    int
528gui_mch_init_check()
529{
530    return OK;		/* TODO: GUI can always be started? */
531}
532
533/*
534 * Initialise the RISC OS GUI.
535 * Create all the windows.
536 * Returns OK for success, FAIL when the GUI can't be started.
537 */
538    int
539gui_mch_init()
540{
541    int     messages[] = {
542	    1, 2, 3, 4,	/* DataSave, DataSaveAck, DataLoad, DataLoadAck */
543	    8,		/* PreQuit */
544	    0xf,	/* ClaimEntity (for clipboard) */
545	    0x10,	/* DataRequest (for clipboard) */
546	    0x400c1,	/* Mode change */
547	    0x400c3,	/* TaskCloseDown */
548	    0x400c9,	/* MenusDeleted */
549	    0x808c1,	/* TW_Output */
550	    0x808c2,    /* TW_Ego */
551	    0x808c3,	/* TW_Morio */
552	    0x808c4,	/* TW_Morite */
553	    0};		/* End-of-list. */
554
555
556    /* There may have been some errors reported in the
557     * command window before we get here. Wait if so.
558     */
559    swi(Wimp_ReadSysInfo, 3);
560    if (r0 == 0)
561	swi(Wimp_CommandWindow, 0);	/* Window opened - close with prompt */
562
563    if (xswi(Wimp_Initialise, 310, 0x4b534154, "GVim", messages) & v_flag)
564	return FAIL;
565    nested_wimp = r0 >= 397;
566    task_handle = r1;
567
568    /* Load the templates. */
569
570    if (xswi(Wimp_OpenTemplate, 0, "Vim:Templates") & v_flag)
571	ro_die( (char *) r0);
572
573    gui.window_handle = ro_load_template("editor",
574	    &gui.window_title,
575	    &gui.window_title_size);
576
577    save_window = ro_load_template("save", NULL, NULL);
578
579    swi(Wimp_CloseTemplate);
580
581    /* Set default foreground and background colours. */
582
583    gui.norm_pixel = gui.def_norm_pixel;
584    gui.back_pixel = gui.def_back_pixel;
585
586    /* Get the colours from the "Normal" and "Menu" group (set in syntax.c or
587     * in a vimrc file) */
588
589    set_normal_colors();
590
591    /*
592     * Check that none of the colors are the same as the background color
593     */
594
595    gui_check_colors();
596
597    /* Get the colours for the highlight groups (gui_check_colors() might have
598     * changed them) */
599
600    highlight_gui_started();		/* re-init colours and fonts */
601
602    /* Set geometry based on values read on initialisation. */
603
604    gui.num_cols = Columns = default_columns;
605    gui.num_rows = Rows    = default_rows;
606
607    /* Get some information about our environment. */
608
609    ro_measure_tools();
610
611    return OK;
612}
613
614/*
615 * Called when the foreground or background colour has been changed.
616 */
617    void
618gui_mch_new_colors()
619{
620}
621
622/*
623 * Open the GUI window which was created by a call to gui_mch_init().
624 */
625    int
626gui_mch_open(void)
627{
628    int block[10];
629
630    block[0] = gui.window_handle;
631    swi(Wimp_GetWindowState, 0, block);
632    block[7] = -1;		    /* Open at the top of the stack */
633    swi(Wimp_OpenWindow, 0, block);
634
635    /* Give the new window the input focus */
636    swi(Wimp_SetCaretPosition, gui.window_handle, -1, 0, 0, -1, -1);
637
638    if (gui_win_x != -1 && gui_win_y != -1)
639	gui_mch_set_winpos(gui_win_x, gui_win_y);
640
641    return OK;
642}
643
644    void
645gui_mch_exit(int rc)
646{
647    int	    block[64];
648
649    /* Close window. Stops us from getting troublesome events
650     * if we take a while to die.
651     */
652    block[0] = gui.window_handle;
653    swi(Wimp_CloseWindow, 0, block);
654
655    if (child_handle)
656    {
657	/* We still have a sub-task running - kill it */
658	block[0] = 20;
659	block[3] = 0;
660	block[4] = 0;	    /* Quit */
661	if ((xswi(Wimp_SendMessage, 17, block, child_handle) & v_flag) == 0)
662	{
663	    /* Idle until child dies. */
664	    while (child_handle)
665	    {
666		process_event(wimp_poll(1, block), block);
667	    }
668	}
669    }
670
671    exit(rc);
672}
673
674/*
675 * Get the position of the top left corner of the window.
676 */
677    int
678gui_mch_get_winpos(int *x, int *y)
679{
680    /* TODO */
681    return FAIL;
682}
683
684/*
685 * Set the position of the top left corner of the window to the given
686 * coordinates.
687 */
688    void
689gui_mch_set_winpos(int x, int y)
690{
691    /* TODO */
692}
693
694    void
695gui_mch_set_shellsize(width, height, min_width, min_height, base_width, base_height, direction)
696    int width;		/* In OS units */
697    int height;
698    int min_width;	/* Smallest permissible window size (ignored) */
699    int min_height;
700    int base_width;	/* Space for scroll bars, etc */
701    int base_height;
702    int direction;
703{
704    int s_width, s_height;
705    int block[] = {
706	gui.window_handle,
707	0,
708	-height + 1,
709	width,
710	1};
711
712    gui_mch_get_screen_dimensions(&s_width, &s_height);
713    s_width -= base_width;
714    s_height -= base_height;		    /* Underestimate - ignores titlebar */
715
716    swi(Wimp_GetWindowState, 0, block);
717    block[3]  = block[1] + width;
718    block[2]  = block[4] - height;
719    if (block[3] > s_width)
720    {
721	block[3] = s_width;
722	block[1] = block[3] - width;
723    }
724    if (block[2] < gui.scrollbar_height)
725    {
726	block[2] = gui.scrollbar_height;
727	block[4] = block[2] + height;
728    }
729    swi(Wimp_OpenWindow, 0, block);
730    swi(Wimp_ForceRedraw, gui.window_handle, 0, -height, width, 0);
731}
732
733    void
734gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
735{
736    int block[] = {4, 5, 11, 12, -1};
737
738    swi(OS_ReadVduVariables, block, block);
739    *screen_w = (block[2] + 1) << block[0];
740    *screen_h = (block[3] + 1) << block[1];
741}
742
743/* Take a font name with options and return a font handle, or
744 * zero for failure.
745 * Replace extension with 'Bold' or 'Italic' depending on modifiers.
746 */
747    int
748ro_get_font(fullname, weight)
749    char_u	*fullname;
750    int		weight;		/* Initial weights:
751				 * BIT	    MEANING
752				 * 0	    bold
753				 * 1	    italic
754				 */
755{
756    char_u	*arg;
757    char_u	font[41];
758    int		width = -1;
759    int		height = -1;
760    int		name_len;
761    int		i;
762    char_u	c;
763
764    for (i = 0; i < 39;)
765    {
766	c = fullname[i];
767	if (c == ':' || c == NUL || c == '.')
768	    break;
769	font[i++] = c;
770    }
771
772    /* find the first modifier, NULL if none */
773    arg = strchr(fullname + i, ':');
774
775    while (arg)
776    {
777	switch (*++arg)
778	{
779	    case 'h':
780		height = strtol(arg + 1, (char **) &arg, 10);
781		break;
782	    case 'w':
783		width = strtol(arg + 1, (char **) &arg, 10);
784		break;
785	    case 'b':
786		weight |= 1;
787		break;
788	    case 'i':
789		weight |= 2;
790		break;
791	    default:
792		return 0;
793	}
794	arg = strchr(arg, ':');
795    }
796
797    if ((weight & 1) && i < 35)
798    {
799	/* Bold goes instead of given suffix */
800	strncpy(font + i, ".Bold", 5);
801	i += 5;
802    }
803    else
804    {
805	/* Copy rest of name unless we are using Bold */
806	while (i < 39)
807	{
808	    c = fullname[i];
809	    if (c == ':' || c == NUL)
810		break;
811	    font[i++] = c;
812	}
813    }
814    if ((weight & 2) && i < 32)
815    {
816	strncpy(font + i, ".Oblique", 8);
817	i += 8;
818    }
819
820    font[i] = 0;
821
822    if (height < 1 && width < 1)
823	height = width = 10;	/* Default to 10pt */
824    else if (height < 1)
825	height = width;
826    else if (width < 1)
827	width = height;
828
829    if (xswi(Font_FindFont, 0, font, width << 4, height << 4, 0, 0) & v_flag)
830	return NOFONT;		/* Can't find font */
831
832    return r0;
833}
834
835/* Load a file into allocated memory and check it is valid.
836 * Return a pointer to the allocated block on success.
837 */
838    char    *
839zap_load_file(name, style)
840    char_u  *name;	    /* Name of directory containing styles */
841    char_u  *style;	    /* Name of style within directory */
842{
843    char_u  fname[256];
844    char_u  *file;
845
846    if (strlen(name) + strlen(style) > 254)
847	return NULL;	    /* Names too long */
848
849    sprintf(fname, "%s.%s", name, style);
850
851    /* Load the named font in 1bpp format. */
852    if (xswi(OS_File, 13, fname, 0, 0, "VimFonts:") & v_flag || r0 != 1)
853	return NULL;	    /* Error reading file info, or not a file */
854
855    /* Allocate enough memory to load the whole file */
856    file = (char *) alloc(r4);
857    if (!file)
858	return NULL;	/* Out of memory */
859
860    if (xswi(OS_File, 12, fname, file, 0, "VimFonts:") & v_flag)
861	return NULL;	/* Unable to load file */
862
863    if (strncmp(file, "ZapFont\015", 8) == 0)
864	return file;	/* Loaded OK! */
865
866    vim_free(file);
867    return NULL;	/* Not a valid font file */
868}
869
870/* Load and convert the named font.
871 * If name is NULL or a null string then convert the system font.
872 * Return OK on success; FAIL and we revert to using the VDU drivers.
873 *
874 * 'name' is the name of a directory.
875 * Tries to load 'name.0', 'name.B', 'name.I' and 'name.IB'.
876 */
877    int
878zap_load_font(name)
879    char_u  *name;
880{
881    int	    i;
882
883    /* Free the existing font files, if any */
884    for (i = 0; i < ZAP_STYLES; i++)
885    {
886	vim_free(zap_file[i]);
887	zap_file[i] = NULL;
888    }
889
890    if (name && *name == '!')
891    {
892	name++;
893	double_height = TRUE;
894    }
895    else
896	double_height = FALSE;
897
898    if (name && *name)
899    {
900	zap_file[ZAP_NORMAL]	= zap_load_file(name, "0");
901	if (!zap_file[ZAP_NORMAL])
902	    return FAIL;	/* Can't load the 'normal' style - error */
903
904	zap_file[ZAP_BOLD]	= zap_load_file(name, "B");
905	zap_file[ZAP_ITALIC]	= zap_load_file(name, "I");
906	zap_file[ZAP_BITALIC]	= zap_load_file(name, "IB");
907    }
908    else
909    {
910	int	*header;
911	char	workarea[16];
912	char	*old_wa;
913
914	/* Allocate memory for system font (8 x 8 x 256 bits, plus header) */
915	header = (int *) alloc(0x20 + 8 * 256);
916	if (header == NULL)
917	    return FAIL;
918	zap_file[ZAP_NORMAL] = (char *) header;
919
920	/* Store details about the system font */
921	header[2] = 8;	    /* Width */
922	header[3] = 8;	    /* Height */
923	header[4] = 0;	    /* First char */
924	header[5] = 255;    /* Last char */
925	header[6] = header[7] = 0;  /* Reserved */
926
927	/* Get system font bitmap */
928	old_wa = zap_redraw_block.r_workarea;
929	zap_redraw_block.r_workarea = workarea;
930	swi(ZapRedraw_ReadSystemChars, zap_file[ZAP_NORMAL] + 0x20, &zap_redraw_block);
931	zap_redraw_block.r_workarea = old_wa;
932    }
933
934    return ro_zap_redraw_initialise();
935}
936
937/*
938 * Initialise vim to use the font with the given name.
939 * Return FAIL if the font could not be loaded, OK otherwise.
940 */
941    int
942gui_mch_init_font(char_u *font_name, int fontset)
943{
944    int	    new_handle	= 0;	    /* Use the system font by default */
945
946    if (font_name[0] == '!')
947    {
948	/* Select a ZapRedraw font */
949	if (zap_load_font(font_name + 1))
950	    zap_redraw = TRUE;
951	else
952	{
953	    EMSG2(_("E610: Can't load Zap font '%s'"), font_name);
954	    font_name = "System";   /* Error - use system font */
955	    zap_redraw = FALSE;
956	}
957    }
958    else
959    {
960	zap_redraw = FALSE;
961
962	if (font_name)
963	{
964	    /* Extract any extra details about the font */
965	    new_handle = ro_get_font(font_name, 0);
966	    if (!new_handle)
967		return FAIL;
968	}
969	else
970	    font_name = "System";
971    }
972
973    /* Free the previous font, if any */
974    gui_mch_free_font(gui.norm_font);
975    gui.norm_font = new_handle;
976    gui.char_ascent = 0;
977
978    if (new_handle)
979    {
980	/* Read details about the chosen font */
981	swi(Font_ReadInfo, new_handle);
982
983	gui.char_width	= r3 - r1;
984	gui.char_height = r4 - r2;
985
986	font_x_offset = -r1;	/* Where to position each char in its box */
987	font_y_offset = -r4;
988
989	/* Try to load other fonts for bold, italic, and bold-italic */
990	gui_mch_free_font(gui.bold_font);
991	gui.bold_font = ro_get_font(font_name, 1);
992	gui_mch_free_font(gui.ital_font);
993	gui.ital_font = ro_get_font(font_name, 2);
994	gui_mch_free_font(gui.boldital_font);
995	gui.boldital_font = ro_get_font(font_name, 3);
996    }
997    else
998    {
999	/* Use the system font or ZapRedraw. */
1000	if (zap_redraw)
1001	{
1002	    gui.char_width	= zap_redraw_block.r_charw << zap_redraw_block.r_magx;
1003	    gui.char_height	= zap_redraw_block.r_charh << zap_redraw_block.r_magy;
1004	    if (double_height)
1005		gui.char_height <<= 1;
1006	}
1007	else
1008	{
1009	    gui.char_width	= 16;
1010	    gui.char_height	= 32;
1011	}
1012
1013	gui_mch_free_font(gui.bold_font);
1014	gui.bold_font = 0;
1015	gui_mch_free_font(gui.ital_font);
1016	gui.ital_font = 0;
1017	gui_mch_free_font(gui.boldital_font);
1018	gui.boldital_font = 0;
1019    }
1020    hl_set_font_name(font_name);
1021
1022    must_redraw = CLEAR;
1023    return OK;
1024}
1025
1026/*
1027 * Adjust gui.char_height (after 'linespace' was changed).
1028 */
1029    int
1030gui_mch_adjust_charheight()
1031{
1032    return FAIL;
1033}
1034
1035/*
1036 * Get a font structure for highlighting.
1037 */
1038    GuiFont
1039gui_mch_get_font(name, giveErrorIfMissing)
1040    char_u	*name;
1041    int		giveErrorIfMissing;
1042{
1043    int		handle;
1044
1045    if (!name)
1046	return NOFONT;		/* System font if no name */
1047
1048    handle = ro_get_font(name, 0);
1049    if (!handle)
1050    {
1051	if (giveErrorIfMissing)
1052	    EMSG2(_("E611: Can't use font %s"), name);
1053	return NOFONT;
1054    }
1055
1056    return handle;
1057}
1058
1059#if defined(FEAT_EVAL) || defined(PROTO)
1060/*
1061 * Return the name of font "font" in allocated memory.
1062 * Don't know how to get the actual name, thus use the provided name.
1063 */
1064    char_u *
1065gui_mch_get_fontname(font, name)
1066    GuiFont font;
1067    char_u  *name;
1068{
1069    if (name == NULL)
1070	return NULL;
1071    return vim_strsave(name);
1072}
1073#endif
1074
1075/*
1076 * Set the current text font.
1077 */
1078    void
1079gui_mch_set_font(GuiFont font)
1080{
1081    ro_current_font = font;
1082
1083    if (font)
1084    {
1085	/* Not the system font or ZapRedraw font - select it */
1086	swi(Font_SetFont, font);
1087    }
1088}
1089
1090/*
1091 * If a font is not going to be used, free its structure.
1092 */
1093    void
1094gui_mch_free_font(GuiFont font)
1095{
1096    if (font)
1097	swi(Font_LoseFont, font);
1098}
1099
1100/*
1101 * Return the Pixel value (colour) for the given colour name.
1102 * Return INVALCOLOR for error.
1103 * NB: I've changed Green for now, since it looked really sick
1104 */
1105    guicolor_T
1106gui_mch_get_color(char_u *name)
1107{
1108    int		i;
1109    struct colour
1110    {
1111	char_u		*name;
1112	guicolor_T	value;
1113    } colours[] =
1114    {
1115	{ "Red",		grgb(255,	0,	0)	},
1116	{ "LightRed",		grgb(255,	0,	0)	},
1117	{ "DarkRed",		grgb(139,	0,	0)	},
1118
1119	{ "Green",		grgb(50,	200,	50)	},
1120	{ "LightGreen",		grgb(144,	238,	144)	},
1121	{ "DarkGreen",		grgb(0,		100,	0)	},
1122	{ "SeaGreen",		grgb(46,	139,	87)	},
1123
1124	{ "Blue",		grgb(0,		0,	255)	},
1125	{ "LightBlue",		grgb(173,	216,	230)	},
1126	{ "DarkBlue",		grgb(0,		0,	139)	},
1127	{ "SlateBlue",		grgb(160,	90,	205)	},
1128
1129	{ "Cyan",		grgb(0,		255,	255)	},
1130	{ "LightCyan",		grgb(224,	255,	255)	},
1131	{ "DarkCyan",		grgb(0,		139,	139)	},
1132
1133	{ "Magenta",		grgb(255,	0,	255)	},
1134	{ "LightMagenta",	grgb(255,	224,	255)	},
1135	{ "DarkMagenta",	grgb(139,	0,	139)	},
1136
1137	{ "Yellow",		grgb(255,	255,	0)	},
1138	{ "LightYellow",	grgb(255,	255,	224)	},
1139	{ "DarkYellow",		grgb(139,	139,	0)	},
1140	{ "Brown",		grgb(165,	42,	42)	},
1141
1142	{ "Gray",		grgb(190,	190,	190)	},
1143	{ "Grey",		grgb(190,	190,	190)	},
1144	{ "LightGray",		grgb(211,	211,	211)	},
1145	{ "LightGrey",		grgb(211,	211,	211)	},
1146	{ "DarkGray",		grgb(169,	169,	169)	},
1147	{ "DarkGrey",		grgb(169,	169,	169)	},
1148	{ "Gray10",		grgb(26,	26,	26)	},
1149	{ "Grey10",		grgb(26,	26,	26)	},
1150	{ "Gray20",		grgb(51,	51,	51)	},
1151	{ "Grey20",		grgb(51,	51,	51)	},
1152	{ "Gray30",		grgb(77,	77,	77)	},
1153	{ "Grey30",		grgb(77,	77,	77)	},
1154	{ "Gray40",		grgb(102,	102,	102)	},
1155	{ "Grey40",		grgb(102,	102,	102)	},
1156	{ "Gray50",		grgb(127,	127,	127)	},
1157	{ "Grey50",		grgb(127,	127,	127)	},
1158	{ "Gray60",		grgb(153,	153,	153)	},
1159	{ "Grey60",		grgb(153,	153,	153)	},
1160	{ "Gray70",		grgb(179,	179,	179)	},
1161	{ "Grey70",		grgb(179,	179,	179)	},
1162	{ "Gray80",		grgb(204,	204,	204)	},
1163	{ "Grey80",		grgb(204,	204,	204)	},
1164	{ "Gray90",		grgb(229,	229,	229)	},
1165	{ "Grey90",		grgb(229,	229,	229)	},
1166
1167	{ "Black",		grgb(0,		0,	0)	},
1168	{ "White",		grgb(255,	255,	255)	},
1169
1170	{ "Orange",		grgb(255,	165,	0)	},
1171	{ "Purple",		grgb(160,	32,	240)	},
1172	{ "Violet",		grgb(238,	130,	238)	},
1173	{NULL, 0}
1174    };
1175
1176    if (name[0] == '#')
1177    {
1178	char	    *end;
1179	int	    c;
1180
1181	c = strtol(name + 1, &end, 16);
1182	return (guicolor_T) ((c >> 16) & 0xff) | (c & 0xff00) | ((c & 0xff) << 16);
1183    }
1184
1185    for (i = 0; colours[i].name != NULL; i++)
1186    {
1187	if (STRICMP(name, colours[i].name) == 0)
1188	    return colours[i].value;
1189    }
1190    if (strnicmp(name, "grey", 4) == 0 || strnicmp(name, "gray", 4) == 0)
1191    {
1192	int level = (255 * atoi(name + 4)) / 100;
1193	return (guicolor_T) grgb(level, level, level);
1194    }
1195    return INVALCOLOR;
1196}
1197
1198/*
1199 * Set the current text colours.
1200 * If we are using fonts then set the antialiasing colours too.
1201 */
1202    void
1203gui_mch_set_colors(guicolor_T fg, guicolor_T bg)
1204{
1205    zap_redraw_colours[0] = bg << 8;	/* JK230798, register new background colour */
1206    zap_redraw_colours[1] = fg << 8;	/* JK230798, register new foreground colour */
1207    zap_redraw_update_colours = TRUE;	/* JK230798, need update of colour masks */
1208
1209    swi(ColourTrans_ReturnGCOL, fg << 8);
1210    gui.fg_colour = r0;
1211    swi(ColourTrans_ReturnGCOL, bg << 8);
1212    gui.bg_colour = r0;
1213
1214    if (ro_current_font)
1215	swi(ColourTrans_SetFontColours, 0, bg << 8, fg << 8, 14);
1216}
1217
1218    void
1219ro_draw_string(x, y, s, len, flags, clip)
1220    int	    x;		/* Top-left coord to plot at (x incl, y excl) */
1221    int	    y;		/* (screen coords) */
1222    char_u  *s;		/* String to plot */
1223    int	    len;	/* Length of string */
1224    int	    flags;	/* DRAW_TRANSP, DRAW_BOLD, DRAW_UNDERL */
1225    int*    clip;	/* JK230798, added clip window */
1226{
1227    if (ro_current_font)
1228    {
1229	int	fx;
1230	int	flen = len;	/* Preserve for underline */
1231
1232	/* Use the Font manager to paint the string.
1233	 * Must do one char at a time to get monospacing.
1234	 */
1235
1236	if (flags & DRAW_ITALIC && !gui.ital_font)
1237	    flags |= DRAW_UNDERL;	/* No italic - underline instead */
1238
1239	if ((flags & DRAW_TRANSP) == 0)
1240	{
1241	    swi(ColourTrans_SetColour, gui.bg_colour, 0, 0, 0, 0);
1242	    swi(OS_Plot, 4, x, y - gui.char_height);
1243	    swi(OS_Plot, 96 + 5, x + len * gui.char_width - 1, y - 1);
1244	}
1245
1246	fx = x + font_x_offset;
1247	while (flen--)
1248	{
1249	    swi(Font_Paint, 0, s++, 0x90, fx, y + font_y_offset, 0, 0, 1);
1250	    fx += gui.char_width;
1251	}
1252    }
1253    else
1254    {
1255	if (zap_redraw)
1256	{
1257	    /* Using fast Zap redraw. */
1258	    flags = ro_zap_redraw_draw_string(x, y, s, len, flags, clip);
1259	}
1260	else
1261	{
1262	    /* Using the system font */
1263	    if (flags & DRAW_ITALIC)
1264		flags |= DRAW_UNDERL;
1265
1266	    if ((flags & DRAW_TRANSP) == 0)
1267	    {
1268		swi(ColourTrans_SetColour, gui.bg_colour, 0, 0, 0, 0);
1269		swi(OS_Plot, 4, x, y - gui.char_height);
1270		swi(OS_Plot, 96 + 5, x + len * gui.char_width - 1, y - 1);
1271	    }
1272	    swi(OS_Plot, 4,			/* Move the drawing cursor */
1273		    x,
1274		    y - 1);
1275	    swi(ColourTrans_SetColour, gui.fg_colour, 0, 0, 0, 0);
1276	    swi(OS_WriteN, s, len);
1277
1278	    if (flags & DRAW_BOLD)
1279	    {
1280		swi(OS_Plot, 4, x + (1 << x_eigen_factor), y - 1);
1281		swi(OS_WriteN, s, len);
1282	    }
1283	}
1284    }
1285
1286    if (flags & DRAW_UNDERL)
1287    {
1288	if (ro_current_font || zap_redraw)
1289	    swi(ColourTrans_SetColour, gui.fg_colour, 0, 0, 0, 0);
1290	/* Underlined is the same with all plotting methods */
1291	swi(OS_Plot, 4, x, y - gui.char_height);
1292	swi(OS_Plot, 1, gui.char_width * len, 0);
1293    }
1294}
1295
1296    void
1297gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
1298{
1299    int x, y;		/* Workarea x,y */
1300    x = col * gui.char_width;
1301    y = -row * gui.char_height;
1302
1303    if (redraw_block)
1304    {
1305	ro_draw_string(x + redraw_block[1], y + redraw_block[4],
1306			s, len, flags, &redraw_block[7]);	/* JK230798, added clip window */
1307    }
1308    else
1309    {
1310	int block[44];
1311	block[0] = gui.window_handle;
1312	block[1] = x;
1313	block[2] = y - gui.char_height;
1314	block[3] = (col + len) * gui.char_width;
1315	block[4] = y;
1316	swi(Wimp_UpdateWindow, 0, block);
1317	while (r0)
1318	{
1319	    ro_draw_string(x + block[1], y + block[4],
1320			s, len, flags, &block[7]);	/* JK230798, added clip window */
1321	    swi(Wimp_GetRectangle, 0, block);
1322	}
1323    }
1324}
1325
1326/*
1327 * Return OK if the key with the termcap name "name" is supported.
1328 */
1329    int
1330gui_mch_haskey(char_u *name)
1331{
1332    return FAIL;
1333}
1334
1335    void
1336gui_mch_beep(void)
1337{
1338    swi(OS_WriteI + 7);
1339}
1340
1341/*
1342 * Visual bell.
1343 */
1344    void
1345gui_mch_flash(int msec)
1346{
1347    /* TODO */
1348}
1349
1350
1351/*
1352 * Plot a solid rectangle using the given plot action and colour.
1353 * Coordinates are inclusive and window-relative.
1354 */
1355    void
1356plot_rectangle(plot, colour, minx, miny, maxx, maxy)
1357    int plot;		/* OS_Plot action */
1358    int colour;
1359    int minx;
1360    int miny;
1361    int maxx;
1362    int maxy;
1363{
1364    if (redraw_block)
1365    {
1366	swi(ColourTrans_SetColour, colour, 0, 0, 0, 0);
1367	swi(OS_Plot, 4, minx + redraw_block[1], miny + redraw_block[4]);
1368	swi(OS_Plot, plot, maxx + redraw_block[1], maxy + redraw_block[4]);
1369    }
1370    else
1371    {
1372	int block[44];
1373	block[0] = gui.window_handle;
1374	block[1] = minx;
1375	block[2] = miny;
1376	block[3] = maxx + 1;
1377	block[4] = maxy + 1;
1378	swi(Wimp_UpdateWindow, 0, block);
1379	while (r0)
1380	{
1381	    swi(ColourTrans_SetColour, colour, 0, 0, 0, 0);
1382	    swi(OS_Plot, 4, minx + block[1], miny + block[4]);
1383	    swi(OS_Plot, plot, maxx + block[1], maxy + block[4]);
1384	    swi(Wimp_GetRectangle, 0, block);
1385	}
1386    }
1387}
1388
1389/*
1390 * Invert a rectangle from row r, column c, for nr rows and nc columns.
1391 */
1392    void
1393gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1394{
1395    plot_rectangle(96 + 6, 0, FILL_X(c), -FILL_Y(r + nr), FILL_X(c + nc), -FILL_Y(r));
1396}
1397
1398/*
1399 * Iconify the GUI window.
1400 */
1401    void
1402gui_mch_iconify(void)
1403{
1404}
1405
1406#if defined(FEAT_EVAL) || defined(PROTO)
1407/*
1408 * Bring the Vim window to the foreground.
1409 */
1410    void
1411gui_mch_set_foreground()
1412{
1413    /* TODO */
1414}
1415#endif
1416
1417/* Draw a hollow rectangle relative to the current
1418 * graphics cursor position, with the given width
1419 * and height. Start position is top-left.
1420 */
1421    void
1422draw_hollow(w, h)
1423    int	w;
1424    int	h;
1425{
1426    swi(OS_Plot, 1, w - 1, 0);
1427    swi(OS_Plot, 1, 0, 1 - h);
1428    swi(OS_Plot, 1, 1 - w, 0);
1429    swi(OS_Plot, 1, 0, h - 1);
1430}
1431
1432/*
1433 * Draw a cursor without focus.
1434 */
1435    void
1436gui_mch_draw_hollow_cursor(guicolor_T colour)
1437{
1438    int x = FILL_X(gui.cursor_col);	/* Window relative, top-left */
1439    int y = -FILL_Y(gui.cursor_row);
1440    if (redraw_block == NULL)
1441    {
1442	int block[11];
1443
1444	block[0] = gui.window_handle;
1445	block[1] = x;
1446	block[2] = y - gui.char_height;
1447	block[3] = x + gui.char_width;
1448	block[4] = y;
1449	swi(Wimp_UpdateWindow, 0, block);
1450	while (r0)
1451	{
1452	    swi(ColourTrans_SetGCOL, colour << 8, 0, 0, 0, 0);
1453
1454	    swi(OS_Plot, 4, x + block[1], y + block[4] - 1);
1455	    draw_hollow(gui.char_width, gui.char_height);
1456
1457	    swi(Wimp_GetRectangle, 0, block);
1458	}
1459    }
1460    else
1461    {
1462	swi(ColourTrans_SetGCOL, colour << 8, 0, 0, 0, 0);
1463
1464	swi(OS_Plot, 4, x + redraw_block[1], y + redraw_block[4] - 1);
1465	draw_hollow(gui.char_width, gui.char_height);
1466    }
1467}
1468
1469/*
1470 * Draw part of a cursor, "w" pixels wide, and "h" pixels high, using
1471 * color "color".
1472 */
1473    void
1474gui_mch_draw_part_cursor(w, h, colour)
1475    int w;
1476    int h;
1477    guicolor_T colour;
1478{
1479    int x = FILL_X(gui.cursor_col);
1480    int y = -FILL_Y(gui.cursor_row);
1481    swi(ColourTrans_ReturnGCOL, colour << 8);
1482    plot_rectangle(96 + 5, r0, x, y - h, x + w - 1, y - 1);
1483}
1484
1485/*
1486 * Catch up with any queued events.  This may put keyboard input into the
1487 * input buffer, call resize call-backs, trigger timers etc.
1488 * If there is nothing in the event queue(& no timers pending), then we return
1489 * immediately (well, after a Wimp_Poll).
1490 */
1491    void
1492gui_mch_update(void)
1493{
1494    int block[64];
1495    int reason;
1496
1497    swi(OS_ReadMonotonicTime);
1498    if ((r0 - time_of_last_poll) < 50)
1499	return;			    /* Don't return too often */
1500
1501    reason = wimp_poll(0, block);
1502    if (reason)
1503	process_event(reason, block);
1504    ro_return_early = FALSE;		/* We're returning anyway. */
1505}
1506
1507    void
1508redraw_window(block)
1509    int *block;
1510{
1511    int x, y;			/* Vim workarea coords */
1512    int width, height;
1513    int blank_col;
1514
1515    swi(ColourTrans_ReturnGCOL, UNUSED_COLOUR << 8, 0, 0, 1<<7, 0);
1516    blank_col = r0;
1517
1518    swi(Wimp_RedrawWindow, 0, block);
1519    redraw_block = block;
1520    while (r0)
1521    {
1522	x = block[7] - block[1];
1523	y = block[4] - block[10];
1524	width  = block[9]  - block[7];
1525	height = block[10] - block[8];
1526
1527	if (height + y > Rows * gui.char_height)
1528	{
1529	    /* Blank everything off the bottom. */
1530	    plot_rectangle(96 + 5, blank_col,
1531				0, block[8] - block[4],
1532				block[9] - block[1], -FILL_Y(Rows) - 1);
1533	    height = Rows * gui.char_height;
1534	}
1535	if (width + x> Columns * gui.char_width)
1536	{
1537	    /* Blank everything off to the right. */
1538	    plot_rectangle(96 + 5, blank_col,
1539				FILL_X(Columns), block[8] - block[4],
1540				block[9] - block[1], 0);
1541	    width = Columns * gui.char_width;
1542	}
1543	gui_redraw(x , y, width, height);
1544	swi(Wimp_GetRectangle, 0, block);
1545    }
1546    redraw_block = NULL;
1547}
1548
1549/* Check if we have modified data.
1550 * If we do then ack the message to stop the shutdown.
1551 * Otherwise, ignore the message.
1552 */
1553    void
1554ro_prequit(block)
1555    int	    *block;
1556{
1557    if (!ro_ok_to_quit())
1558    {
1559	/* Not OK to quit - stop shutdown */
1560	block[3] = block[2];
1561	swi(Wimp_SendMessage, 19, block, block[1]);
1562    }
1563    /* Do nothing. We may get a Message_Quit later. */
1564}
1565
1566/* If there is unsaved data then ask the user if they mind losing it.
1567 * Return TRUE if we can quit without saving, FALSE to halt the
1568 * shutdown.
1569 */
1570    int
1571ro_ok_to_quit()
1572{
1573    int	    old_confirm = cmdmod.confirm;
1574
1575    cmdmod.confirm = FALSE;	    /* Use our own, single tasking, box */
1576
1577    if (check_changed_any(FALSE))
1578    {
1579	swi(Wimp_ReportError,
1580		"\0\0\0\0Vim contains unsaved data - quit anyway?",
1581		0x17,
1582		"Vim");
1583	cmdmod.confirm = old_confirm;
1584	if (r1 != 1)
1585	    return FALSE;
1586    }
1587    cmdmod.confirm = old_confirm;
1588    return TRUE;
1589}
1590
1591/* Quit without checking for unsaved data. */
1592    void
1593ro_quit()
1594{
1595    exiting = TRUE;
1596    getout(0);
1597
1598    exiting = FALSE;		    /* probably can't get here */
1599    setcursor();		    /* position cursor */
1600    out_flush();
1601}
1602
1603/* Insent the given vim special code into the input buffer */
1604    void
1605ro_press(a, b, modifier)
1606    char a;
1607    char b;
1608    int modifier;	/* %<Ctrl><Shift> 0000 0000 */
1609{
1610    char_u buf[6];
1611    int	    vim_mod;
1612    int	    key;
1613
1614
1615    /* Convert RISC OS modifier to Vim modifier. */
1616    vim_mod = ((modifier & 0x10) ? MOD_MASK_SHIFT : 0)
1617	       | ((modifier & 0x20) ? MOD_MASK_CTRL : 0);
1618    key = simplify_key(TERMCAP2KEY(a, b), &vim_mod);
1619
1620    buf[3] = CSI;
1621    buf[4] = KEY2TERMCAP0(key);
1622    buf[5] = KEY2TERMCAP1(key);
1623    if (vim_mod)
1624    {
1625	buf[0] = CSI;
1626	buf[1] = KS_MODIFIER;
1627	buf[2] = vim_mod;
1628	add_to_input_buf(buf, 6);
1629    }
1630    else
1631	add_to_input_buf(buf + 3, 3);
1632}
1633
1634/* Take a wimp key code and insert the vim equivalent
1635 * into vim's input buffer.
1636 * CTRL-C also sets got_int.
1637 */
1638    void
1639ro_insert_key(code)
1640    char_u *code;		/* Wimp_ProcessKey code (4 bytes) */
1641{
1642    char a = code[0];
1643    char b = code[1];
1644    int base, modifier;
1645
1646    if (a == 3 && ctrl_c_interrupts)
1647	got_int = TRUE;
1648
1649    /* Is it a normal key? */
1650    if (a > 31 && a < 127)
1651    {
1652	add_to_input_buf(code, 1);
1653	return;
1654    }
1655
1656    /* We should pass any unrecognised keys on, but
1657     * for now just pass on F12 combinations.
1658     */
1659    switch (b)
1660    {
1661	case 0:
1662	    /* Home and Delete are the only special cases */
1663	    switch (a)
1664	    {
1665		case 0x1e:
1666		    ro_press('k','h', 0);	/* Home */
1667		    return;
1668		case 0x7f:
1669		    ro_press('k','D', 0);	/* Delete */
1670		    return;
1671		case CSI:
1672		    {
1673			/* Turn CSI into K_CSI.  Untested! */
1674			char_u string[3] = {CSI, KS_EXTRA, KE_CSI};
1675
1676			add_to_input_buf(string, 3);
1677			return;
1678		    }
1679		default:
1680		    add_to_input_buf(code, 1);
1681		    return;
1682	    }
1683	case 1:
1684	    if ((a & 0xcf) == 0xcc)
1685	    {
1686		/* F12 pressed - pass it on (quick hack) */
1687		swi(Wimp_ProcessKey, a | 0x100);
1688		return;
1689	    }
1690	    base = a & 0xcf;
1691	    modifier = a & 0x30;
1692	    switch (base)
1693	    {
1694		case 0x8a:	/* Tab */
1695		    add_to_input_buf("\011", 1);
1696		    return;
1697		case 0x8b:	/* Copy (End) */
1698		    return ro_press('@', '7', modifier);
1699		case 0x8c:	/* Left */
1700		    return ro_press('k', 'l', modifier);
1701		case 0x8d:	/* Right */
1702		    return ro_press('k', 'r', modifier);
1703		case 0x8e:	/* Down */
1704		    if (modifier & 0x10)
1705			return ro_press('k', 'N', modifier ^ 0x10);
1706		    else
1707			return ro_press('k', 'd', modifier);
1708		case 0x8f:	/* Up */
1709		    if (modifier & 0x10)
1710			return ro_press('k', 'P', modifier ^ 0x10);
1711		    else
1712			return ro_press('k', 'u', modifier);
1713		case 0xca:	/* F10 */
1714		    return ro_press('k', ';', modifier);
1715		case 0xcb:	/* F11 */
1716		    return ro_press('F', '1', modifier);
1717		case 0xcd:	/* Insert */
1718		    return ro_press('k', 'I', modifier);
1719		default:
1720		    if (base > 0x80 && base < 0x18a)
1721		    {
1722			/* One of the other function keys */
1723			return ro_press('k', '0' + (base & 15), modifier);
1724		    }
1725	    }
1726    }
1727}
1728
1729/* Process a mouse event. */
1730    void
1731ro_mouse(block)
1732    int *block;
1733{
1734    int x, y, button, vim_button;
1735    int modifiers = 0;
1736    int min_x, min_y;		/* Visible area of editor window */
1737    int max_x, max_y;
1738
1739    if (block[3] != gui.window_handle || ro_dragging)
1740	return;			/* Not our window or ignoring clicks*/
1741
1742    x = block[0];		/* Click position - screen coords */
1743    y = block[1];
1744    button = block[2];
1745
1746    block[0] = gui.window_handle;
1747    swi(Wimp_GetWindowState, 0, block);
1748    min_x = block[1];
1749    min_y = block[2];
1750    max_x = block[3];
1751    max_y = block[4];
1752
1753    if (block[3] - x < gui.scrollbar_width)
1754    {
1755	/* Click in that blank area under the scrollbars */
1756
1757	if (button & 0x444)
1758	{
1759	    int	    front_block[10];
1760	    /* Dragging with Select - bring window to front first */
1761	    front_block[0] = gui.window_handle;
1762	    swi(Wimp_GetWindowState, 0, front_block);
1763	    front_block[7] = -1;
1764	    ro_open_main(front_block);
1765	}
1766
1767	block[0] = gui.window_handle;
1768	block[1] = 7;			/* Drag point */
1769	block[2] = block[4] = 0;	/* Coords of point. */
1770	block[3] = block[5] = 0;
1771	drag_x_offset = max_x - x;
1772	drag_y_offset = min_y - y;
1773
1774	/* Parent box. */
1775	block[6] = min_x +
1776			gui.scrollbar_width * 2 +
1777			MIN_COLUMNS * gui.char_width;
1778	block[7] = 0;
1779	gui_mch_get_screen_dimensions(&block[8], &block[9]);
1780	block[9] = max_y -
1781			4 * gui.char_height -
1782			gui.scrollbar_height;
1783
1784	swi(Wimp_DragBox, 0, block);
1785	ro_dragging = DRAG_RESIZE_WINDOW;
1786	drag_button = vim_button;
1787	drag_modifiers = modifiers;
1788	return;
1789    }
1790
1791    if (button & 0x111)
1792	vim_button = MOUSE_RIGHT;
1793    else if (button & 0x222)
1794	vim_button = MOUSE_MIDDLE;
1795    else
1796	vim_button = MOUSE_LEFT;
1797
1798    swi(OS_Byte, 121, 0x80);
1799    if (r1 == 0xff)
1800	modifiers |= MOUSE_SHIFT;
1801    swi(OS_Byte, 121, 0x81);
1802    if (r1 == 0xff)
1803	modifiers |= MOUSE_CTRL;
1804    swi(OS_Byte, 121, 0x82);
1805    if (r1 == 0xff)
1806	modifiers |= MOUSE_ALT;
1807
1808    if (button == 2)
1809    {
1810	/* Menu click:
1811	 * If shift was pressed then do the paste action.
1812	 * If not, then open the pop-up menu.
1813	 */
1814	modifiers ^= MOUSE_SHIFT;
1815	if (modifiers && MOUSE_SHIFT)
1816	{
1817	    vimmenu_T	main;
1818	    /* Shift was NOT pressed - show menu */
1819	    main.dname = (char_u *) "Vim";
1820	    main.children = root_menu;
1821	    gui_mch_show_popupmenu(&main);
1822	    return;
1823	}
1824    }
1825
1826    /* Gain the input focus */
1827    swi(Wimp_SetCaretPosition, gui.window_handle, -1, 0, 0, -1, -1);
1828
1829    if (button & 0xf0)
1830    {
1831	/* Drag operation:
1832	 *
1833	 * Tell the Wimp to start a drag.
1834	 * Monitor null events.
1835	 */
1836	block[1] = 7;			/* Drag a point. */
1837	block[2] = block[4] = x;	/* Coords of point. */
1838	block[3] = block[5] = y;
1839	block[6] = 0;			/* Coords of bounding box. */
1840	block[7] = 0;
1841	gui_mch_get_screen_dimensions(&block[8], &block[9]);
1842
1843	drag_x_offset = drag_y_offset = 0;
1844
1845	swi(Wimp_DragBox, 0, block);
1846	ro_dragging = DRAG_SELECTION;
1847	drag_button = vim_button;
1848	drag_modifiers = modifiers;
1849
1850	vim_button |= MOUSE_DRAG;
1851    }
1852
1853    gui_send_mouse_event(
1854		vim_button,
1855		x - min_x,
1856		max_y - y,
1857		button & 0xf ? TRUE : FALSE,	/* dclick */
1858		modifiers);
1859}
1860
1861    void
1862ro_continue_drag(block)
1863    int *block;			/* Just used as scrap. */
1864{
1865    int x, y;
1866
1867    /* Get screen coords of pointer. */
1868    swi(Wimp_GetPointerInfo, 0, block);
1869    x = block[0] + drag_x_offset;
1870    y = block[1] + drag_y_offset;
1871
1872    block[0] = gui.window_handle;
1873    swi(Wimp_GetWindowState, 0, block);
1874
1875    if (ro_dragging == DRAG_RESIZE_WINDOW)
1876    {
1877	/* Resizeing the main window. */
1878	block[2] = y;
1879	block[3] = x;
1880	ro_open_main(block);
1881    }
1882    else
1883    {
1884	/* Selecting some text. */
1885	gui_send_mouse_event(
1886	    drag_button | MOUSE_DRAG,	/* Always report the same button */
1887	    x - block[1],
1888	    block[4] - y,
1889	    FALSE,			/* Not a double click. */
1890	    drag_modifiers);
1891    }
1892}
1893
1894/* User has released all mouse buttons, marking the end of a drag. */
1895    void
1896ro_drag_finished(block)
1897    int *block;
1898{
1899    int x;
1900    int y;
1901    int width, height;
1902
1903    /* I don't trust the box returned by Wimp_Poll; look at the pointer
1904     * ourselves.
1905     */
1906    swi(Wimp_GetPointerInfo, 0, block);
1907    x = block[0] + drag_x_offset;
1908    y = block[1] + drag_y_offset;
1909
1910    if (ro_dragging == DRAG_RESIZE_WINDOW)
1911    {
1912	block[0] = gui.window_handle;
1913	swi(Wimp_GetWindowState, 0, block);
1914	block[2] = y;
1915	block[3] = x;
1916	ro_open_main(block);
1917
1918	width = (block[3] - block[1]);
1919	height = (block[4] - block[2]);
1920
1921	swi(Wimp_ForceRedraw, gui.window_handle, 0, -height, width, 0);
1922	gui_resize_shell(width, height);
1923    }
1924    else
1925    {
1926	block[0] = gui.window_handle;
1927	swi(Wimp_GetWindowState, 0, block);
1928	gui_send_mouse_event(
1929		MOUSE_RELEASE,
1930		x - block[1],
1931		block[4] - y,
1932		FALSE,			/* not a double click */
1933		drag_modifiers);
1934    }
1935    ro_dragging = DRAG_FALSE;
1936}
1937
1938/* Load the file/pathname given in block into a [new] buffer.
1939 *
1940 * Modifier	Action
1941 *
1942 * None		:confirm e <file>
1943 * Ctrl		:sp <file>
1944 * Shift	<file>
1945 *
1946 * Insert into typebuf, at the start.
1947 * If loading from !Scrap then use saved leafname instead, and
1948 * delete the scrap file. Also, ignore shift key.
1949 *
1950 * NB: Doesn't send DataLoadAck (other app might delete temp file?).
1951 */
1952    void
1953ro_dataload(block)
1954    int	    *block;
1955{
1956    char_u  new_path[MAXPATHL];
1957    char_u  *path = ((char_u *) block) + 44;
1958    int	    scrap = FALSE;
1959
1960    if (block[3] == leaf_ref && leaf_name)
1961	scrap = TRUE;
1962
1963    switch (get_real_state() & 0xff)
1964    {
1965	case INSERT:
1966	case CMDLINE:
1967	case CMDLINE+LANGMAP:
1968	    /* For insert mode we can only insert the pathname (currently)
1969	     * Make sure Shift is pressed.
1970	     */
1971	    swi(OS_Byte, 121, 0x80);	    /* Is Shift pressed? */
1972	    if (r1 == 0xff)
1973	    {
1974		ins_typebuf(" ", REMAP_NONE, 0, TRUE, FALSE);
1975		ins_typebuf(path, REMAP_NONE, 0, TRUE, FALSE);
1976		ro_return_early = TRUE;		    /* Return even though nothing was typed. */
1977	    }
1978	    else
1979		swi(Wimp_ReportError,
1980			"\0\0\0\0Sorry, you can only load text in normal mode", 5, "Vim");
1981	    break;
1982
1983	case NORMAL:
1984	    ro_return_early = TRUE;	    /* Return even though nothing was typed. */
1985
1986	    if (scrap)			    /* Remove <Wimp$Scrap>. Later. */
1987		ins_typebuf(":!~remove <Wimp$Scrap>\r", REMAP_NONE, 0, TRUE, FALSE);
1988
1989	    /* Insert {:sp ,:confirm e }[+f\ <leaf> ]<file><CR> */
1990	    ins_typebuf("\r", REMAP_NONE, 0, TRUE, FALSE);
1991	    ins_typebuf(path, REMAP_NONE, 0, TRUE, FALSE);
1992	    ins_typebuf(" ", REMAP_NONE, 0, TRUE, FALSE);
1993
1994	    if (scrap)
1995	    {
1996		/* Loading via !Scrap - change pathname to stored leafname */
1997		ins_typebuf(leaf_name, REMAP_NONE, 0, TRUE, FALSE);
1998		ins_typebuf(" +f\\ ", REMAP_NONE, 0, TRUE, FALSE);
1999		leaf_ref = 0;
2000		vim_free(leaf_name);
2001		leaf_name = NULL;
2002	    }
2003
2004	    swi(OS_Byte, 121, 0x81);	    /* Is Ctrl pressed? */
2005	    if (r1 == 0xff)
2006		/* Yes, split window */
2007		ins_typebuf(":sp", REMAP_NONE, 0, TRUE, FALSE);
2008	    else
2009		ins_typebuf(":confirm e", REMAP_NONE, 0, TRUE, FALSE);
2010	    break;
2011
2012	default:
2013	    swi(Wimp_ReportError, "\0\0\0\0You can only load text in normal mode.", 5, "Vim");
2014    }
2015    /* Send DataSaveAck so other program doesn't think we died
2016     * and delete <Wimp$Scrap>.
2017     */
2018    block[3] = block[2];
2019    block[4] = 4;
2020    swi(Wimp_SendMessage, 17, block, block[1]);
2021}
2022
2023    void
2024ro_datasave(block)
2025    int	    *block;
2026{
2027    char_u *path = ((char_u *) block) + 44;
2028
2029    /* Preserve the name given so we can use it, not <Wimp$Scrap> */
2030    if (leaf_name)
2031	vim_free(leaf_name);
2032    leaf_name = vim_strsave(path);
2033
2034    block[9] = -1;	    /* File is unsafe. */
2035    strcpy(path, "<Wimp$Scrap>");
2036    block[0] = 60;
2037    block[3] = block[2];
2038    block[4] = 2;
2039    swi(Wimp_SendMessage, 17, block, block[1]);
2040
2041    leaf_ref = block[2];
2042}
2043
2044    void
2045ro_message(block)
2046    int *block;
2047{
2048    char_u	*buffer;
2049    long_u	len;
2050
2051    if (block[1] == task_handle)
2052	return;			    /* Don't talk to ourself! */
2053    switch (block[4])
2054    {
2055	case 0:		/* Quit. */
2056	    if (block[4] == 0)
2057		ro_quit();
2058	    break;
2059	case 1:	/* DataSave */
2060	    ro_datasave(block);
2061	    break;
2062	case 2:		/* DataSaveAck. */
2063	    if (clip_convert_selection(&buffer, &len, &clip_star) == -1)
2064		return;
2065
2066	    /* Save the clipboard contents to a file. */
2067	    swi(OS_File, 10, ((char_u *) block) + 44, 0xfff, 0, buffer, buffer + len);
2068
2069	    /* Ack with DataLoad message. */
2070	    block[3] = block[2];
2071	    block[4] = 3;
2072	    block[9] = len;
2073	    swi(Wimp_SendMessage, 17, block, block[1]);
2074
2075	    vim_free(buffer);
2076	    break;
2077	case 3:		/* DataLoad */
2078	    ro_dataload(block);
2079	    break;
2080	case 8:		/* PreQuit */
2081	    ro_prequit(block);
2082	    break;
2083	case 0xf:	/* Lose clipboard. */
2084	    if (block[5] & 4)
2085	    {
2086		clip_free_selection(&clip_star);
2087		clip_star.owned = FALSE;
2088	    }
2089	    break;
2090	case 0x10:	/* DataRequest (clip_star) */
2091	    if (clip_star.owned)
2092	    {
2093		int rows;
2094
2095		/* Tell other program that we have the clipboard. */
2096		block[0] = 52;
2097		block[3] = block[2];	    /* Copy myref to yourref. */
2098		block[4] = 1;		    /* DataSave message. */
2099		/* Create an estimate for the size (larger or same as true
2100		 * value) */
2101		rows = clip_star.end.lnum - clip_star.start.lnum;
2102		if (rows < 0)
2103		    rows = -rows;
2104		block[9] = (rows + 1) * Columns + 1; /* Add one for possible
2105							final newline. */
2106		block[10] = 0xfff;	    /* Clipboard is text. */
2107		strcpy( ((char_u *) block) + 44, "VimClip");
2108		swi(Wimp_SendMessage, 17, block, block[1]);
2109	    }
2110	    break;
2111	case 0x400c1:	/* Mode change */
2112	    changed_mode = TRUE;		/* Flag - update on next OpenWindow */
2113	    if (zap_redraw)
2114	    {
2115		/* JK230798, re-initialise ZapRedraw stuff */
2116		if (ro_zap_redraw_initialise() == FAIL)
2117		    zap_redraw = FALSE;
2118	    }
2119	    break;
2120	case 0x400c3:	/* TaskCloseDown */
2121	    if (block[1] == child_handle)
2122		child_handle = 0;
2123	    break;
2124    }
2125}
2126
2127/*
2128 * Converts a scrollbar's window handle into a scrollbar pointer.
2129 * NULL on failure.
2130 */
2131    scrollbar_T *
2132ro_find_sbar(id)
2133    int		id;
2134{
2135    win_T	*wp;
2136
2137    if (gui.bottom_sbar.id == id)
2138	return &gui.bottom_sbar;
2139    FOR_ALL_WINDOWS(wp)
2140    {
2141	if (wp->w_scrollbars[SBAR_LEFT].id == id)
2142	    return &wp->w_scrollbars[SBAR_LEFT];
2143	if (wp->w_scrollbars[SBAR_RIGHT].id == id)
2144	    return &wp->w_scrollbars[SBAR_RIGHT];
2145    }
2146    return NULL;
2147}
2148
2149    void
2150scroll_to(line, sb)
2151    int sb;	/* Scrollbar number */
2152    int line;
2153{
2154    char_u code[8];
2155
2156    /* Don't put events in the input queue now. */
2157    if (hold_gui_events)
2158	return;
2159
2160    /* Send a scroll event:
2161     *
2162     * A scrollbar event is CSI (NOT K_SPECIAL), KS_VER_SCROLLBAR,
2163     * KE_FILLER followed by:
2164     * one byte representing the scrollbar number, and then four bytes
2165     * representing a long_u which is the new value of the scrollbar.
2166     */
2167    code[0] = CSI;
2168    code[1] = KS_VER_SCROLLBAR;
2169    code[2] = KE_FILLER;
2170    code[3] = sb;
2171    code[4] = line >> 24;
2172    code[5] = line >> 16;
2173    code[6] = line >> 8;
2174    code[7] = line;
2175    add_to_input_buf(code, 8);
2176}
2177
2178    void
2179h_scroll_to(col)
2180    int col;
2181{
2182    char_u code[8];
2183
2184    /* Don't put events in the input queue now. */
2185    if (hold_gui_events)
2186	return;
2187
2188    /* Send a scroll event:
2189     *
2190     * A scrollbar event is CSI (NOT K_SPECIAL)
2191     *
2192     * A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR,
2193     * KE_FILLER followed by four bytes representing a long_u which is the
2194     * new value of the scrollbar.
2195     */
2196    code[0] = CSI;
2197    code[1] = KS_HOR_SCROLLBAR;
2198    code[2] = KE_FILLER;
2199    code[4] = col >> 24;
2200    code[5] = col >> 16;
2201    code[6] = col >> 8;
2202    code[7] = col;
2203    add_to_input_buf(code, 8);
2204}
2205
2206    void
2207ro_scroll(block)
2208    int		*block;
2209{
2210    scrollbar_T	*sb;
2211    int		offset;
2212    win_T	*wp;
2213
2214    /* Block is ready for Wimp_OpenWindow, and also contains:
2215     *
2216     * +32 = scroll X direction (-2 .. +2)
2217     * +36 = scroll Y direction (-2 .. +2)
2218     */
2219
2220    sb = ro_find_sbar(block[0]);
2221    if (!sb)
2222	return;		/* Window not found (error). */
2223
2224    wp = sb-> wp;
2225
2226    if (wp == NULL)
2227    {
2228	/* Horizontal bar. */
2229	offset = block[8];
2230	if (offset == -2)
2231	    offset = (block[1] - block[3]) / gui.char_width;
2232	else if (offset == 2)
2233	    offset = (block[3] - block[1]) / gui.char_width;
2234
2235	block[5] += offset * gui.char_width;
2236
2237	gui_drag_scrollbar(sb, block[5] / gui.char_width, FALSE);
2238
2239	swi(Wimp_OpenWindow, 0, block);
2240    }
2241    else
2242    {
2243	offset = -block[9];
2244	if (offset == -2)
2245	    offset = -(wp -> w_height - 1);
2246	else if (offset == 2)
2247	    offset = wp -> w_height - 1;
2248
2249	/* Possibly we should reposition the scrollbar?
2250	 * Vim seems to update the bar anyway...
2251	 */
2252	gui_drag_scrollbar(sb, offset - (block[6] / gui.char_height), FALSE);
2253    }
2254}
2255
2256/* Move a window by a given offset. Used to simulate the function of the
2257 * nested wimp.
2258 */
2259    void
2260ro_move_child(window, x, y, pos_wanted, pos_got)
2261    int	window;
2262    int x,y;		/* offset to move by */
2263    int	pos_wanted, pos_got;
2264{
2265    int	block[10];
2266
2267    block[0] = window;
2268    swi(Wimp_GetWindowState, 0, block);
2269    block[1] += x;
2270    block[2] += y;
2271    block[3] += x;
2272    block[4] += y;
2273    if (pos_wanted == -1)
2274	block[7] = -1;
2275    else if (pos_wanted == -2)
2276	block[7] = pos_got;
2277    swi(Wimp_OpenWindow, 0, block);
2278}
2279
2280/* Open the main window. Also updates scrollbars if we are not
2281 * using the nested Wimp.
2282 * If we have just changed mode then re-read all values.
2283 */
2284    void
2285ro_open_main(block)
2286    int	    *block;
2287{
2288    int	    toggle_size;
2289
2290    /* Find out if the user clicked on the toggle size icon. */
2291    block[20] = block[0];
2292    swi(Wimp_GetWindowState, 0, block + 20);
2293    toggle_size = block[28] & (1 << 19);
2294
2295    if (nested_wimp)
2296    {
2297	swi(Wimp_OpenWindow, 0, block);
2298    }
2299    else
2300    {
2301	int	old[10];
2302	int	x_offset, y_offset;	    /* Move children same as parent. */
2303	int	pos_wanted, pos_got;
2304	int	left_bar  = gui.which_scrollbars[SBAR_LEFT];
2305	int	right_bar = gui.which_scrollbars[SBAR_RIGHT];
2306	win_T	*wp;
2307
2308	/* Three cases to think about:
2309	 * 1) Move to top. Open each window at the top.
2310	 * 2) Same stack position. Open each with same position.
2311	 * 3) Open at bottom. Open children with parent's new position.
2312	 */
2313
2314	old[0] = block[0];
2315	swi(Wimp_GetWindowState, 0, old);
2316	pos_wanted = block[7];
2317	swi(Wimp_OpenWindow, 0, block);
2318	/* Block updated by OpenWindow? I don't think so! */
2319	swi(Wimp_GetWindowState, 0, block);
2320	pos_got = block[7];
2321
2322	x_offset = block[1] - old[1];
2323	y_offset = block[4] - old[4];
2324	if (x_offset || y_offset || pos_wanted == -1 || pos_wanted == -2)
2325	{
2326	    /* If parent has moved, re-open all the child windows. */
2327	    FOR_ALL_WINDOWS(wp)
2328	    {
2329		/* Reopen scrollbars for this window. */
2330		if (left_bar)
2331		    ro_move_child(wp -> w_scrollbars[SBAR_LEFT].id,
2332				x_offset, y_offset,
2333				pos_wanted, pos_got);
2334		if (right_bar)
2335		    ro_move_child(wp -> w_scrollbars[SBAR_RIGHT].id,
2336				x_offset, y_offset,
2337				pos_wanted, pos_got);
2338	    }
2339	}
2340    }
2341    if (changed_mode || toggle_size)
2342    {
2343	int	width, height;
2344
2345	if (changed_mode)
2346	    ro_measure_tools();
2347	block[0] = gui.window_handle;
2348	swi(Wimp_GetWindowState, 0, block);
2349
2350	width = block[3] - block[1];
2351	height = block[4] - block[2];
2352	swi(Wimp_ForceRedraw, gui.window_handle, 0, -height, width, 0);
2353	gui_resize_shell(width, height);
2354	changed_mode = FALSE;
2355    }
2356}
2357
2358    void
2359ro_open_window(block)
2360    int		*block;
2361{
2362    int		pos;
2363    scrollbar_T *sb;
2364
2365    if (block[0] == gui.window_handle)
2366	ro_open_main(block);
2367    else
2368    {
2369	swi(Wimp_OpenWindow, 0, block);
2370	if (block[0] != gui.window_handle)
2371	{
2372	    sb = ro_find_sbar(block[0]);
2373	    if (sb)
2374	    {
2375		if (sb-> wp != NULL)
2376		    gui_drag_scrollbar(sb, -block[6] / gui.char_height, FALSE);
2377		else
2378		    gui_drag_scrollbar(sb, block[5] / gui.char_width, FALSE);
2379	    }
2380	}
2381    }
2382}
2383
2384    void
2385ro_menu_selection(block)
2386    int		*block;
2387{
2388    int		*item = wimp_menu + 7;
2389    vimmenu_T	*menu;
2390    /* wimp_menu points to a wimp menu structure */
2391
2392    for (;;)
2393    {
2394	while (block[0]--)
2395	    item += 6;
2396	if (block[1] == -1)
2397	    break;
2398	item = ((int *) item[1]) + 7;
2399	block++;
2400    }
2401    /* item points to the wimp menu item structure chosen */
2402    menu = (vimmenu_T *) item[5];
2403
2404    swi(Wimp_GetPointerInfo, 0, block);
2405    if (block[2] == 1)
2406	/* Adjust used - keep menu open */
2407	swi(Wimp_CreateMenu, 0, wimp_menu);
2408
2409    if (menu-> cb)
2410	menu-> cb(menu);
2411}
2412
2413    void
2414ro_open_parent()
2415{
2416    int head;
2417    char_u *i = curbuf-> b_ffname;
2418    char_u  buffer[256];
2419
2420    head = 0;
2421    for (; *i; i++)
2422    {
2423	if (*i == '.')
2424	    head = i - curbuf-> b_ffname;
2425    }
2426
2427    /* Append head chars to buffer */
2428    if (head < 240 && curbuf-> b_ffname && head)
2429    {
2430	strcpy(buffer, "%filer_opendir ");
2431	strncpy(buffer + 15, curbuf-> b_ffname, head);
2432	buffer[15 + head] = '\0';
2433	swi(OS_CLI, buffer);
2434    }
2435}
2436
2437    void
2438process_event(event, block)
2439    int event;
2440    int *block;
2441{
2442    switch (event)
2443    {
2444	case 0:		/* Nothing - update drag state. */
2445	    if (ro_dragging)
2446		ro_continue_drag(block);
2447	    break;
2448	case 1:		/* Redraw window. */
2449	    redraw_window(block);
2450	    break;
2451	case 2:		/* Open window. */
2452	    ro_open_window(block);
2453	    break;
2454	case 3:		/* Close window. */
2455	    swi(Wimp_GetPointerInfo, 0, block + 1);
2456	    if (block[3] == 1)
2457		ro_open_parent();
2458	    else
2459		if (ro_ok_to_quit())
2460		    ro_quit();
2461	    break;
2462	case 6:		/* Mouse click. */
2463	    ro_mouse(block);
2464	    break;
2465	case 7:		/* Finished drag. */
2466	    ro_drag_finished(block);
2467	    break;
2468	case 8:		/* Key pressed. */
2469	    ro_insert_key((char_u *) &block[6]);
2470	    break;
2471	case 9:
2472	    ro_menu_selection(block);
2473	    break;
2474	case 10:	/* Scroll request. */
2475	    ro_scroll(block);
2476	    break;
2477	case 11:	/* Lose caret. */
2478	    if (block[0] == gui.window_handle)
2479		gui_focus_change(FALSE);
2480	    break;
2481	case 12:	/* Gain caret. */
2482	    if (block[0] == gui.window_handle)
2483		gui_focus_change(TRUE);
2484	    break;
2485	case 17:	/* User message. */
2486	case 18:	/* User message recorded. */
2487	    ro_message(block);
2488	    break;
2489    }
2490}
2491
2492/*
2493 * GUI input routine called by gui_wait_for_chars().  Waits for a character
2494 * from the keyboard.
2495 *  wtime == -1	    Wait forever.
2496 *  wtime == 0	    This should never happen.
2497 *  wtime > 0	    Wait wtime milliseconds for a character.
2498 * Returns OK if a character was found to be available within the given time,
2499 * or FAIL otherwise.
2500 */
2501    int
2502gui_mch_wait_for_chars(long wtime)
2503{
2504    int block[64];
2505    int	reason;
2506    int start_time = -1;
2507    int ctime = wtime / 10;	/* delay in cs */
2508
2509    if (wtime != -1)
2510    {
2511	swi(OS_ReadMonotonicTime);
2512	start_time = r0;
2513    }
2514
2515    for (;;)
2516    {
2517	if (ro_dragging)
2518	    reason = wimp_poll(0, block);	/* Always return immediately */
2519	else if (wtime == -1)
2520	    reason = wimp_poll(1, block);
2521	else
2522	    reason = wimp_pollidle(0, block, start_time + ctime);
2523
2524	process_event(reason, block);
2525
2526	if (input_available() || ro_return_early)
2527	{
2528	    ro_return_early = FALSE;
2529	    return OK;	    /* There is something to process (key / menu event) */
2530	}
2531
2532	if (wtime != -1)
2533	{
2534	    swi(OS_ReadMonotonicTime);
2535	    if (r0 - start_time > ctime)
2536		return FAIL;	/* We've been waiting too long - return failure */
2537	}
2538    }
2539}
2540
2541/* Flush any output to the screen */
2542    void
2543gui_mch_flush(void)
2544{
2545}
2546
2547/*
2548 * Clear a rectangular region of the screen from text pos(row1, col1) to
2549 * (row2, col2) inclusive.
2550 */
2551    void
2552gui_mch_clear_block(int row1, int col1, int row2, int col2)
2553{
2554    swi(ColourTrans_ReturnGCOL, gui.back_pixel << 8, 0, 0, 1<<7, 0);
2555    plot_rectangle(96 + 5, r0,
2556			FILL_X(col1), -FILL_Y(row2 + 1),
2557			FILL_X(col2 + 1), -FILL_Y(row1));
2558}
2559
2560    void
2561gui_mch_clear_all(void)
2562{
2563    if (redraw_block)
2564    {
2565	swi(ColourTrans_SetGCOL, gui.back_pixel << 8, 0, 0, 1<<7, 0);
2566	swi(OS_WriteI + 16);
2567    }
2568    else
2569    {
2570	int block[44];
2571	block[0] = gui.window_handle;
2572	block[1] = 0;
2573	block[2] = -gui.num_rows * gui.char_height;
2574	block[3] = gui.num_cols * gui.char_width;
2575	block[4] = 0;
2576	swi(Wimp_UpdateWindow, 0, block);
2577	while (r0)
2578	{
2579	    swi(ColourTrans_SetGCOL, gui.back_pixel << 8, 0, 0, 1<<7, 0);
2580	    swi(OS_WriteI + 16);
2581	    swi(Wimp_GetRectangle, 0, block);
2582	}
2583    }
2584}
2585
2586/*
2587 * Delete the given number of lines from the given row, scrolling up any
2588 * text further down within the scroll region.
2589 */
2590    void
2591gui_mch_delete_lines(int row, int num_lines)
2592{
2593    int top_from = -row - num_lines;
2594    int bot_from = -gui.scroll_region_bot - 1;
2595    int bot_to   = bot_from + num_lines;
2596
2597    swi(ColourTrans_SetGCOL, gui.back_pixel << 8, 0, 0, 0x80, 0);
2598
2599    /* Changed without checking! */
2600    swi(Wimp_BlockCopy, gui.window_handle,
2601			    gui.scroll_region_left * gui.char_width,
2602			    bot_from * gui.char_height,
2603			    (gui.scroll_region_right - gui.scroll_region_left
2604							+ 1) * gui.char_width,
2605			    top_from * gui.char_height,
2606
2607			    gui.scroll_region_left * gui.char_width,
2608			    bot_to * gui.char_height);
2609
2610    gui_clear_block(gui.scroll_region_bot - num_lines + 1,
2611						       gui.scroll_region_left,
2612	gui.scroll_region_bot, gui.scroll_region_right);
2613}
2614
2615/*
2616 * Insert the given number of lines before the given row, scrolling down any
2617 * following text within the scroll region.
2618 */
2619    void
2620gui_mch_insert_lines(int row, int num_lines)
2621{
2622    int top_from = -row;
2623    int bot_to   = -gui.scroll_region_bot - 1;
2624    int bot_from = bot_to + num_lines;
2625
2626    swi(ColourTrans_SetGCOL, gui.back_pixel << 8, 0, 0, 0x80, 0);
2627
2628    swi(Wimp_BlockCopy, gui.window_handle,
2629			    gui.scroll_region_left * gui.char_width,
2630			    bot_from * gui.char_height,
2631			    (gui.scroll_region_right - gui.scroll_region_left
2632							+ 1) * gui.char_width,
2633			    top_from * gui.char_height,
2634
2635			    gui.scroll_region_left * gui.char_width,
2636			    bot_to * gui.char_height);
2637
2638    gui_clear_block(row, gui.scroll_region_left,
2639				row + num_lines - 1, gui.scroll_region_right);
2640}
2641
2642/* Put selection in clipboard buffer.
2643 * Should we become the new owner?
2644 */
2645    void
2646clip_mch_request_selection(VimClipboard *cbd)
2647{
2648    int		block[64];	/* Will be used in Wimp_Poll. */
2649    int		reason;
2650    char_u	*buffer;
2651    long_u	length;
2652
2653    block[0] = 48;			/* Size of block. */
2654    block[3] = 0;			/* Orinial message. */
2655    block[4] = 0x10;			/* Data request. */
2656    block[5] = gui.window_handle;
2657    block[6] = RO_LOAD_CLIPBOARD;	/* Internal handle. */
2658    block[7] = block[8] = 0;		/* (x,y) not used. */
2659    block[9] = 4;
2660    block[10] = 0xfff;	    /* We want text files if possible, I think. */
2661    block[11] = -1;	    /* End of list. */
2662    swi(Wimp_SendMessage, 17, block, 0);    /* Broadcast request. */
2663
2664    /* OK, we've sent the request. Poll until we get a null poll (failure) or
2665     * we load the clipboard.
2666     * If we receive a DataSave event with icon handle = -2 then put it on the
2667     * clipboard. RISC OS should ensure that key events will not be delivered
2668     * until the clipboard operation completes (unless the owner starts idling
2669     * - we can't wait forever!).
2670     */
2671    for (;;)
2672    {
2673	reason = wimp_poll(0, block);
2674	if (reason == 0)
2675	    return;	    /* Failed to get clipboard. */
2676	if ((reason == 17 || reason == 18) &&
2677		block[4] == 1 && block[6] == RO_LOAD_CLIPBOARD)
2678	    break;	    /* Got it - stop waiting. */
2679	process_event(reason, block);
2680	if (ro_return_early)
2681	    return;
2682    }
2683    /* Tell owner to save data in <Wimp$Scrap>. */
2684    block[0] = 60;
2685    block[3] = block[2];   /* Copy myref -> yourref */
2686    block[4] = 2;	    /* DataSaveAck. */
2687    block[9] = -1;	    /* Data is unsafe. */
2688    strcpy( ((char_u *) block) + 44, "<Wimp$Scrap>");
2689    swi(Wimp_SendMessage, 17, block, block[1]);
2690
2691    /* Wait again for reply. */
2692    for (;;)
2693    {
2694	reason = wimp_poll(0, block);
2695	if (reason == 0)
2696	    return;	/* Other program has given up! */
2697	if ((reason == 17 || reason == 18) && block[4] == 3 && block[6] == RO_LOAD_CLIPBOARD)
2698	    break;	/* Clipboard data saved to <Wimp$Scrap> */
2699	process_event(reason, block);
2700	if (ro_return_early)
2701	    return;
2702    }
2703
2704    /* <Wimp$Scrap> contains clipboard - load it. */
2705    if (xswi(OS_File, 17, "<Wimp$Scrap>") & v_flag)
2706	return;		/* Error! */
2707    if (r0 != 1 && r0 != 3)
2708	return;
2709    length = r4;
2710
2711    buffer = lalloc(length, TRUE);  /* Claim memory (and report errors). */
2712    if (buffer == NULL)
2713	return;
2714
2715    if (xswi(OS_File, 16, "<Wimp$Scrap>", buffer, 0) & v_flag)
2716	return;
2717
2718    clip_yank_selection(MCHAR, buffer, length, cbd);
2719
2720    vim_free(buffer);
2721
2722    swi(OS_FSControl, 27, "<Wimp$Scrap>", 0, 0);    /* Delete temp file. */
2723
2724    block[4] = 4;		    /* Send DataLoadAck. */
2725    block[3] = block[2];	    /* Copy myref -> yourref. */
2726    swi(Wimp_SendMessage, 17, block, block[1]);
2727}
2728
2729/* Not sure what this means under RISC OS. */
2730    void
2731clip_mch_lose_selection(VimClipboard *cbd)
2732{
2733}
2734
2735/* Tell everyone that we now own the clipboard.
2736 * Return OK if our claim is accepted (always, under RISC OS)
2737 */
2738    int
2739clip_mch_own_selection(VimClipboard *cbd)
2740{
2741    int block[6];
2742    block[0] = 24;	/* Length of block.  */
2743    block[3] = 0;	/* Original message. */
2744    block[4] = 0xf;	/* ClaimEntity. */
2745    block[5] = 0x4;	/* Claim clipboard only. */
2746    swi(Wimp_SendMessage, 17, block, 0);
2747    return OK;
2748}
2749
2750/*
2751 * Send the current selection to the clipboard.  Do nothing for X because we
2752 * will fill in the selection only when requested by another app. Sounds good
2753 * for RISC OS too.
2754 */
2755    void
2756clip_mch_set_selection(VimClipboard *cbd)
2757{
2758    clip_get_selection(cbd);
2759}
2760
2761/*
2762 * Make a menu either grey or not grey.
2763 */
2764    void
2765gui_mch_menu_grey(vimmenu_T *menu, int grey)
2766{
2767    menu-> greyed_out = grey;
2768}
2769
2770/*
2771 * Make menu item hidden or not hidden
2772 */
2773    void
2774gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
2775{
2776    menu-> hidden = hidden;
2777}
2778
2779/*
2780 * This is called after setting all the menus to grey/hidden or not.
2781 */
2782    void
2783gui_mch_draw_menubar(void)
2784{
2785    swi(Wimp_CreateMenu, 0, -1);
2786    if (wimp_menu != (int *) -1)
2787    {
2788	ro_remove_menu(wimp_menu);
2789	wimp_menu = (int *) -1;
2790    }
2791}
2792
2793/* Add or remove a scrollbar. Note that this is only called when
2794 * the scrollbar state is changing.
2795 * The scroll bar window has already been created.
2796 * We can't do anything except remove the scroll bar
2797 * until we know what size to use.
2798 */
2799    void
2800gui_mch_enable_scrollbar(sb, flag)
2801    scrollbar_T	*sb;
2802    int		flag;
2803{
2804    if (!flag)
2805	swi(Wimp_CloseWindow, 0, & (sb->id) );
2806    return;
2807}
2808
2809    void
2810gui_mch_set_blinking(long waittime, long on, long off)
2811{
2812}
2813
2814/*
2815 * Stop the cursor blinking.  Show the cursor if it wasn't shown.
2816 */
2817    void
2818gui_mch_stop_blink(void)
2819{
2820}
2821
2822/*
2823 * Start the cursor blinking.  If it was already blinking, this restarts the
2824 * waiting time and shows the cursor.
2825 */
2826    void
2827gui_mch_start_blink(void)
2828{
2829}
2830
2831/*
2832 * Return the RGB value of a pixel as a long.
2833 */
2834    long_u
2835gui_mch_get_rgb(guicolor_T pixel)
2836{
2837    return (long_u)pixel;
2838}
2839
2840    void
2841gui_mch_set_text_area_pos(int x, int y, int w, int h)
2842{
2843}
2844
2845    void
2846gui_mch_enable_menu(int flag)
2847{
2848}
2849
2850    void
2851gui_mch_set_menu_pos(int x, int y, int w, int h)
2852{
2853}
2854
2855    void
2856gui_mch_add_menu(vimmenu_T *menu, int idx)
2857{
2858}
2859
2860    void
2861gui_mch_add_menu_item(vimmenu_T *menu, int idx)
2862{
2863}
2864
2865    void
2866gui_mch_new_menu_colors(void)
2867{
2868}
2869
2870    void
2871gui_mch_destroy_menu(vimmenu_T *menu)
2872{
2873}
2874
2875/* Size of buffer has changed.
2876 * Add one to max since gui.c subtracts one more than it should!
2877 */
2878    void
2879gui_mch_set_scrollbar_thumb(sb, val, size, max)
2880    scrollbar_T	*sb;
2881    long	val;
2882    long	size;
2883    long	max;
2884{
2885    int		block[10], width, height;
2886
2887    width = (max + 1) * gui.char_width;
2888    height = (max + 1 + W_STATUS_HEIGHT(sb->wp)) * gui.char_height;
2889
2890    block[0] = block[3] = 0;
2891    block[1] = -height + (1 << y_eigen_factor);
2892    block[2] = width;
2893
2894    swi(Wimp_SetExtent, sb -> id, block);
2895
2896    block[0] = sb -> id;
2897    swi(Wimp_GetWindowState, 0, block);
2898    block[5] = val * gui.char_width;
2899    block[6] = -val * gui.char_height;
2900    swi(Wimp_OpenWindow, 0, block, 0x4b534154,
2901			gui.window_handle,	/* Parent window handle. */
2902			(CHILD_FIX_TO_RIGHT  << CHILD_LEFT  )   |
2903			(CHILD_FIX_TO_RIGHT  << CHILD_RIGHT )   |
2904			(CHILD_FIX_TO_BOTTOM << CHILD_TOP   )   |
2905			(CHILD_FIX_TO_BOTTOM << CHILD_BOTTOM)   |
2906			(CHILD_SELF_SCROLL   << CHILD_SCROLL_X) |
2907			(CHILD_SELF_SCROLL   << CHILD_SCROLL_Y)
2908			);
2909}
2910
2911/* Set the position of the scrollbar within the editor
2912 * window. Note that, for vertical scrollbars, x and w
2913 * are ignored. For horizontal bars y and h are ignored.
2914 */
2915    void
2916gui_mch_set_scrollbar_pos(sb, x, y, w, h)
2917    scrollbar_T *sb;
2918    int		x;		/* Horizontal sb position */
2919    int		y;		/* Top of scroll bar */
2920    int		w;		/* Width */
2921    int		h;		/* Height */
2922{
2923    int		block[24];
2924    int		px1, py1;	/* Parent window min coords */
2925    int		px2, py2;	/* Parent window max coords */
2926
2927    /* Find where the parent window is. */
2928    block[0] = gui.window_handle;
2929    swi(Wimp_GetWindowState, 0, block);
2930    px1 = block[1];
2931    py1 = block[2];
2932    px2 = block[3];
2933    py2 = block[4];
2934
2935    block[0] = sb -> id;
2936
2937    /* Find out how big the scroll window is at the moment. */
2938    swi(Wimp_GetWindowInfo, 0, ((char_u *)block) + 1);
2939
2940    if (block[13] < w || block[12] > -h)
2941    {
2942	/* Current window is too small! */
2943	if (block[12] > -h)
2944	    block[12] = -h;
2945	if (block[13] < w)
2946	    block[13] = w;
2947	swi(Wimp_SetExtent, block[0], block + 11);
2948    }
2949
2950    /* This works better on the nested_wimp. */
2951    if (sb-> wp)
2952    {
2953	/* This is a vertical scrollbar. */
2954	block[1] = block[3] = px2 - gui.scrollbar_width + (1 << x_eigen_factor);
2955	block[2] = 1 + py2 - (y + h) + (1 << y_eigen_factor);
2956	block[4] = 1 + py2 - y;
2957    }
2958    else
2959    {
2960	/* This is a horizontal scrollbar. */
2961	block[2] = block[4] = py1 + gui.scrollbar_height;
2962	block[1] = px1;
2963	block[3] = px2 - gui.scrollbar_width;
2964    }
2965
2966    block[5] = 0;
2967    block[6] = 0;
2968    block[7] = -1;
2969
2970    swi(Wimp_OpenWindow, 0, block, 0x4b534154,
2971	    gui.window_handle,	/* Parent window handle. */
2972	    (CHILD_FIX_TO_RIGHT  << CHILD_LEFT  )   |
2973	    (CHILD_FIX_TO_RIGHT  << CHILD_RIGHT )   |
2974	    (CHILD_FIX_TO_BOTTOM << CHILD_TOP   )   |
2975	    (CHILD_FIX_TO_BOTTOM << CHILD_BOTTOM)   |
2976	    (CHILD_SELF_SCROLL   << CHILD_SCROLL_X) |
2977	    (CHILD_SELF_SCROLL   << CHILD_SCROLL_Y)
2978       );
2979}
2980
2981/* Create a window with no workarea to place inside editor window.
2982 * (what happens without the nested wimp?)
2983 * Data for scrollbar is invalid.
2984 */
2985    void
2986gui_mch_create_scrollbar(sb, orient)
2987    scrollbar_T *sb;
2988    int		orient;	/* orient is SBAR_HORIZ or SBAR_VERT */
2989{
2990    int bar[] =
2991	{
2992	    0,   0,		/* Visible area : min X,Y */
2993	    100, 100,		/*		  max X,Y */
2994	    0,   0,		/* Scroll offsets */
2995	    -1,			/* Window in front */
2996	    0x80800150 | (orient == SBAR_HORIZ ? (1 << 30) : (1 << 28)),
2997	    0xff070207,		/* Colours */
2998	    0x000c0103,		/* More colours */
2999	    0, -0x4000,		/* Workarea extent */
3000	    0x4000, 0,		/* max X,Y */
3001	    0x00000000,		/* No title */
3002	    0 << 12,		/* No workarea button type */
3003	    1,			/* Wimp sprite area */
3004	    0x00010001,		/* Minimum width, height */
3005	    0, 0, 0,		/* Title data (none) */
3006	    0			/* No icons */
3007	};
3008    swi(Wimp_CreateWindow, 0, bar);
3009    sb -> id = r0;
3010}
3011
3012#if defined(FEAT_WINDOWS) || defined(PROTO)
3013    void
3014gui_mch_destroy_scrollbar(scrollbar_T *sb)
3015{
3016    swi(Wimp_DeleteWindow, 0, & (sb->id));
3017    sb -> id = -1;
3018}
3019#endif
3020
3021    void
3022gui_mch_set_scrollbar_colors(scrollbar_T *sb)
3023{
3024    /* Always use default RO colour scheme. */
3025}
3026
3027/*
3028 * Get current mouse coordinates in text window.
3029 * Note: (0,0) is the bottom left corner, positive y is UP.
3030 */
3031    void
3032gui_mch_getmouse(x, y)
3033    int *x;
3034    int *y;
3035{
3036    int left;
3037    int top;
3038    int block[10];
3039
3040    block[0] = gui.window_handle;
3041    swi(Wimp_GetWindowState, 0, block);
3042    left = block[1];
3043    top = block[4];
3044
3045    swi(Wimp_GetPointerInfo, 0, block);
3046    *x = block[0] - left;
3047    *y = top - block[1];
3048}
3049
3050/* MouseTo(x, y) */
3051    void
3052gui_mch_setmouse(x, y)
3053    int		x;
3054    int		y;
3055{
3056}
3057
3058    void
3059gui_mch_toggle_tearoffs(enable)
3060    int		enable;
3061{
3062    /* no tearoff menus */
3063}
3064
3065/* Redraw a window's title.
3066 * For the nested wimp we use the new 'redraw-title-bar' reason code.
3067 * For older wimps we mark the area of the screen where the title bar
3068 * is as invalid.
3069 */
3070    void
3071ro_redraw_title(window)
3072    int window;
3073{
3074    if (nested_wimp)
3075    {
3076	swi(Wimp_ForceRedraw, window, 0x4b534154, 3);
3077    }
3078    else
3079    {
3080	int block[10];
3081	int miny;
3082
3083	block[0] = window;
3084	swi(Wimp_GetWindowState, 0, block);
3085	miny = block[4];
3086	swi(Wimp_GetWindowOutline, 0, block);
3087	swi(Wimp_ForceRedraw, -1,
3088			block[1], miny,
3089			block[3], block[4]);
3090    }
3091}
3092
3093/* Turn a vimmenu_T structure into a wimp menu structure.
3094 * -1 if resulting menu is empty.
3095 * Only the children and dname items in the root menu are used.
3096 */
3097    int *
3098ro_build_menu(menu)
3099    vimmenu_T	*menu;
3100{
3101    int		*wimp_menu;
3102    int		width = 4;
3103    int		w;
3104    int		size = 28;
3105    vimmenu_T	*item;
3106    int		*wimp_item;
3107
3108    /* Find out how big the menu is so we can allocate memory for it */
3109    for (item = menu-> children; item; item = item-> next)
3110    {
3111	if (item-> hidden == FALSE && !menu_is_separator(item->name))
3112	    size += 24;
3113    }
3114
3115    if (size <= 28)
3116	return (int *) -1;		/* No children - shouldn't happen */
3117
3118    wimp_menu = (int *) alloc(size);
3119
3120    wimp_menu[0] = (int) menu-> dname;
3121    wimp_menu[1] = -1;
3122    wimp_menu[2] = 0;
3123    wimp_menu[3] = 0x00070207;
3124    wimp_menu[5] = 44;
3125    wimp_menu[6] = 0;
3126
3127    wimp_item = wimp_menu + 7;
3128
3129    for (item = menu-> children; item; item = item-> next)
3130    {
3131	if (menu_is_separator(item-> name))
3132	{
3133	    /* This menu entry is actually a separator. If it is not the first
3134	     * menu entry then mark the previous menu item as needing a dotted
3135	     * line after it.
3136	     */
3137	    if (wimp_item > wimp_menu + 7)
3138		wimp_item[-6] |= 0x2;
3139	}
3140	else if (item-> hidden == FALSE)
3141	{
3142	    wimp_item[0] = 0;
3143	    wimp_item[1] = item-> children ? (int) ro_build_menu(item) : -1;
3144	    wimp_item[2] = 0x07009131 | (item-> greyed_out << 22);
3145	    wimp_item[3] = (int) item-> dname;
3146	    wimp_item[4] = -1;
3147	    wimp_item[5] = (int) item;  /* Stuff the menu address in this unused space */
3148
3149	    w = strlen(item-> dname) + 1;
3150	    if (w > width)
3151		width = w;
3152	    wimp_item += 6;
3153	}
3154    }
3155
3156    wimp_menu[4] = (width + 2) * 16;
3157    wimp_menu[7]  |= 0x100;	    /* Menu title is indirected */
3158    wimp_item[-6] |= 0x080;	    /* Last entry in menu */
3159    return wimp_menu;
3160}
3161
3162    static void
3163ro_remove_menu(menu)
3164    int	    *menu;
3165{
3166    int	    *item = menu + 7;
3167
3168    if (menu == NULL || menu == (int *) -1)
3169	return;
3170
3171    for (;;)
3172    {
3173	if (item[1] != -1)
3174	    ro_remove_menu((int *) item[1]);	/* Remove sub-menu */
3175	if (item[0] & 0x80)
3176	    break;			/* This was the last entry */
3177	item += 6;
3178    }
3179    vim_free(menu);
3180}
3181
3182    void
3183gui_mch_show_popupmenu(menu)
3184    vimmenu_T	*menu;
3185{
3186    int		block[10];
3187
3188    /* Remove the existing menu, if any */
3189    if (wimp_menu != (int *) -1)
3190    {
3191	swi(Wimp_CreateMenu, 0, -1);
3192	ro_remove_menu(wimp_menu);
3193	wimp_menu = (int *) -1;
3194    }
3195
3196    wimp_menu = ro_build_menu(menu);
3197    if (wimp_menu != (int *) -1)
3198    {
3199	swi(Wimp_GetPointerInfo, 0, block);
3200	swi(Wimp_CreateMenu, 0, wimp_menu, block[0] - 64, block[1] + 64);
3201    }
3202}
3203
3204/* Run a command using the TaskWindow module.
3205 * If SHELL_FILTER is set then output is not echoed to the screen,
3206 * If it is not set, then \r is not sent to the output file.
3207 */
3208    int
3209gui_mch_call_shell(cmd, options)
3210    char_u  *cmd;
3211    int	    options;	/* SHELL_FILTER if called by do_filter() */
3212			/* SHELL_COOKED if term needs cooked mode */
3213{
3214    char_u  task_cmd[256];	/* Contains *TaskWindow command. */
3215    int	    block[64];
3216    int	    reason;
3217    char_u  *out;
3218    char_u  c;
3219    int	    old_msg_col;
3220    char_u  *out_redir;
3221    int	    length;
3222    FILE    *out_file = NULL;
3223
3224    out_redir = strstr(cmd, " > ");
3225    if (out_redir == NULL)
3226	length = strlen(cmd);	/* No redirection. */
3227    else
3228    {
3229	length = out_redir - cmd;
3230	out_file = fopen(out_redir + 3, "wb");
3231	if (out_file == NULL)
3232	    smsg("WARNING : Can't open file %s for writing\n", out_redir + 3);
3233    }
3234
3235    if (length > 180)
3236    {
3237	if (out_file)
3238	    fclose(out_file);
3239	return FAIL;		/* Command too long. */
3240    }
3241
3242    strcpy(task_cmd, "TaskWindow \"");
3243    strncpy(task_cmd + 12, cmd, length);
3244    sprintf(task_cmd + 12 + length,
3245	    "\" -task &%08x -ctrl -quit -name \"Vim command\"",
3246	    task_handle);
3247
3248    if (options & SHELL_COOKED)
3249	settmode(TMODE_COOK);
3250
3251    if (xswi(Wimp_StartTask, task_cmd) & v_flag)
3252    {
3253	/* Failed to even start a new task (out of memory?) */
3254	settmode(TMODE_RAW);
3255	if (out_file)
3256	    fclose(out_file);
3257	return FAIL;
3258    }
3259
3260    /* Wait for the child process to initialise. */
3261    child_handle = 0;
3262    while (!child_handle)
3263    {
3264	reason = wimp_poll(0, block);
3265	if ((reason == 17 || reason == 18) && block[4] == 0x808c2)
3266	    child_handle = block[1];
3267	else
3268	    process_event(reason, block);
3269    }
3270
3271    /* Block until finished */
3272    while (child_handle)
3273    {
3274	reason = wimp_poll(1, block);
3275	if (reason == 3 || (reason == 8 && block[6] == 3))
3276	{
3277	    /* Close window request or CTRL-C - kill child task. */
3278	    block[0] = 20;
3279	    block[3] = 0;
3280	    block[4] = 0x808c4;	    /* Morite */
3281	    swi(Wimp_SendMessage, 17, block, child_handle);
3282	    MSG_PUTS(_("\nSending message to terminate child process.\n"));
3283	    continue;
3284	}
3285	else if (reason == 8)
3286	{
3287	    block[0] = 28;
3288	    block[3] = 0;
3289	    block[4] = 0x808c0;	    /* Input */
3290	    block[5] = 1;
3291	    /* Block[6] is OK as it is! */
3292	    swi(Wimp_SendMessage, 17, block, child_handle);
3293	    continue;
3294	}
3295	else if (reason == 17 || reason == 18)
3296	{
3297	    if (block[4] == 0x808c1)
3298	    {
3299		/* Ack message. */
3300		block[3] = block[2];
3301		swi(Wimp_SendMessage, 19, block, block[1]);
3302		out = (char_u *)block + 24;
3303		old_msg_col = msg_col;
3304		while (block[5]--)
3305		{
3306		    c = *out++;
3307		    if (out_file && (c != '\r' || (options & SHELL_FILTER)))
3308			fputc(c, out_file);
3309		    if ((options & SHELL_FILTER) == 0)
3310		    {
3311			if (c == 127)
3312			    msg_puts("\b \b");
3313			else if (c > 31)
3314			    msg_putchar(c);
3315			else if (c == 10)
3316			{
3317			    lines_left = 8;	/* Don't do More prompt! */
3318			    msg_putchar(10);
3319			}
3320		    }
3321		}
3322		/* Flush output to the screen. */
3323		windgoto(msg_row, msg_col);
3324		out_flush();
3325		continue;
3326	    }
3327	}
3328	process_event(reason, block);
3329    }
3330    msg_putchar('\n');
3331    settmode(TMODE_RAW);
3332    if (out_file)
3333	fclose(out_file);
3334    return OK;
3335}
3336
3337/* Like strsave(), but stops at any control char */
3338    char_u *
3339wimp_strsave(str)
3340    char    *str;
3341{
3342    int	    strlen = 0;
3343    char_u  *retval;
3344    while (str[strlen] > 31)
3345	strlen++;
3346    retval = alloc(strlen + 1);
3347    if (retval)
3348    {
3349	memcpy(retval, str, strlen);
3350	retval[strlen] = '\0';
3351    }
3352    return retval;
3353}
3354
3355/* If we are saving then pop up a standard RISC OS save box.
3356 * Otherwise, open a directory viewer on the given directory (and return NULL)
3357 * The string we return will be freed later.
3358 */
3359    char_u *
3360gui_mch_browse(saving, title, dflt, ext, initdir, filter)
3361    int		saving;		/* write action */
3362    char_u	*title;		/* title for the window */
3363    char_u	*dflt;		/* default file name */
3364    char_u	*ext;		/* extension added */
3365    char_u	*initdir;	/* initial directory, NULL for current dir */
3366    char_u	*filter;	/* file name filter */
3367{
3368    char command[256];
3369    int length;
3370
3371    if (saving)
3372    {
3373	int	block[64];
3374	int	reason;
3375	int	done_save = FALSE;
3376	char_u	*retval = NULL;
3377	char_u  *sprname;
3378	char_u	*fname;
3379	int	dragging_icon = FALSE;
3380	int	filetype;
3381
3382	if (!dflt)
3383	    dflt = "TextFile";
3384
3385	block[0] = save_window;
3386	block[1] = 0;
3387	swi(Wimp_GetIconState, 0, block);
3388	sprname = ((char_u *) block[7]);
3389	block[1] = 1;
3390	swi(Wimp_GetIconState, 0, block);
3391	fname = ((char *) block[7]);
3392	strncpy(fname, dflt, 255);
3393
3394	if (xswi(OS_FSControl, 31, curbuf->b_p_oft) & v_flag)
3395	{
3396	    filetype = 0xfff;
3397	    strcpy(sprname + 5, "xxx");
3398	}
3399	else
3400	{
3401	    filetype = r2;
3402	    sprintf(sprname + 5, "%03x", filetype);
3403	}
3404
3405	/* Open the save box */
3406
3407	swi(Wimp_GetPointerInfo, 0, block);
3408	swi(Wimp_CreateMenu, 0, save_window, block[0] - 64, block[1] + 64);
3409	swi(Wimp_SetCaretPosition, save_window, 1, 0, 0, -1, -1);
3410
3411	while (!done_save)
3412	{
3413	    reason = wimp_poll(1, block);
3414	    switch (reason)
3415	    {
3416		case 1:
3417		    redraw_window(block);
3418		    break;
3419		case 2:
3420		    if (block[0] == save_window)
3421			swi(Wimp_OpenWindow, 0, block);
3422		    else
3423			ro_open_window(block);
3424		    break;
3425		case 3:
3426		    done_save = TRUE;
3427		    break;
3428		case 6:
3429		    if (block[3] != save_window)
3430			done_save = TRUE;
3431		    else
3432		    {
3433			int drag_box[4];
3434			int min_x, max_y;
3435
3436			switch (block[4])
3437			{
3438			    case    0: /* Start drag */
3439				block[0] = save_window;
3440				swi(Wimp_GetWindowState, 0, block);
3441				min_x = block[1];
3442				max_y = block[4];
3443				block[1] = 0;
3444				swi(Wimp_GetIconState, 0, block);
3445				drag_box[0] = block[2] + min_x;
3446				drag_box[1] = block[3] + max_y;
3447				drag_box[2] = block[4] + min_x;
3448				drag_box[3] = block[5] + max_y;
3449
3450				swi(DragASprite_Start,
3451					0x45,
3452					1,
3453					sprname,
3454					drag_box);
3455				dragging_icon = TRUE;
3456				break;
3457			    case    2: /* OK */
3458				retval = wimp_strsave(fname);
3459				done_save = TRUE;
3460				break;
3461			    case    3: /* Cancel */
3462				done_save = TRUE;
3463				break;
3464			}
3465		    }
3466		    break;
3467		case 7:
3468		    if (dragging_icon)
3469		    {
3470			int len = 0;
3471
3472			dragging_icon = FALSE;
3473			swi(Wimp_GetPointerInfo, 0, block);
3474			block[5] = block[3];
3475			block[6] = block[4];
3476			block[7] = block[0];
3477			block[8] = block[1];
3478			block[9] = 0;		/* Don't know the size */
3479			block[10] = filetype;
3480
3481			while (fname[len] > 31)
3482			{
3483			    if (fname[len] == '.')
3484			    {
3485				fname += len + 1;
3486				len = 0;
3487			    }
3488			    else
3489				len++;
3490			}
3491			if (len > 211)
3492			    len = 211;
3493
3494			memcpy(((char_u *) block) + 44, fname, len);
3495			((char_u *)block)[44 + len] = '\0';
3496
3497			block[0] = (len + 48) & 0xfc;
3498			block[3] = 0;
3499			block[4] = 1;	    /* DataSave */
3500
3501			swi(Wimp_SendMessage, 17, block, block[5], block[6]);
3502		    }
3503		    else
3504			ro_drag_finished(block);
3505		    break;
3506		case 8:
3507		    if (block[6] == 13)
3508		    {
3509			retval = wimp_strsave(fname);
3510			done_save = TRUE;
3511		    }
3512		    else if (block[6] == 0x1b)
3513			done_save = TRUE;
3514		    else
3515			swi(Wimp_ProcessKey, block[6]);
3516		    break;
3517		case 17:
3518		case 18:
3519		    if (block[4] == 2 && block[9] != -1)
3520		    {
3521			/* DataSaveAck from dragging icon. */
3522			retval = wimp_strsave(((char_u *) block) + 44);
3523			done_save = TRUE;
3524		    }
3525		    else if (block[4] == 0x400c9)
3526		    {
3527			/* MenusDeleted */
3528			done_save = TRUE;
3529		    }
3530		    else
3531			ro_message(block);
3532		    break;
3533	    }
3534	}
3535	block[0] = save_window;
3536	swi(Wimp_CloseWindow, 0, block);
3537	swi(Wimp_GetCaretPosition, 0, block);
3538	if (block[0] == -1)
3539	    swi(Wimp_SetCaretPosition, gui.window_handle, -1, 0, 0, -1, -1);
3540
3541	return retval;
3542    }
3543    else if (initdir)
3544    {
3545	/* Open a directory viewer */
3546	length = strlen(initdir);
3547
3548	if (length > 240)
3549	    return NULL;	/* Path too long! */
3550
3551	length = sprintf(command, "Filer_OpenDir %s", initdir);
3552	while (command[length - 1] == '.')
3553	    length--;
3554	command[length] = '\0';
3555	swi(OS_CLI, command);
3556    }
3557    return NULL;
3558}
3559