aboutsummaryrefslogtreecommitdiff
path: root/dostsr.c
blob: f281d8a7b63b2ff4e4cd58fdaeba8be506238319 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
/*
 * VBMouse - DOS mouse driver resident part
 * Copyright (C) 2022 Javier S. Pedro
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <i86.h>

#include "dlog.h"
#include "ps2.h"
#include "int10vga.h"
#include "int2fwin.h"
#include "int33.h"
#include "dostsr.h"

#define MSB_MASK 0x8000U

TSRDATA data;

static const uint16_t default_cursor_graphic[] = {
    0x3FFF, 0x1FFF, 0x0FFF, 0x07FF,
    0x03FF, 0x01FF, 0x00FF, 0x007F,
    0x003F, 0x001F, 0x01FF, 0x00FF,
    0x30FF, 0xF87F, 0xF87F, 0xFCFF,
    0x0000, 0x4000, 0x6000, 0x7000,
    0x7800, 0x7C00, 0x7E00, 0x7F00,
    0x7F80, 0x7C00, 0x6C00, 0x4600,
    0x0600, 0x0300, 0x0300, 0x0000
};

/** Constraint current mouse position to the user-set window. */
static void bound_position_to_window(void)
{
	if (data.pos.x < data.min.x) data.pos.x = data.min.x;
	if (data.pos.x > data.max.x) data.pos.x = data.max.x;
	if (data.pos.y < data.min.y) data.pos.y = data.min.y;
	if (data.pos.y > data.max.y) data.pos.y = data.max.y;
}

static void hide_text_cursor(void)
{
	// Restore the character under the old position of the cursor
	uint16_t __far *ch = get_video_char(&data.video_mode,
	                                    data.cursor_pos.x / 8, data.cursor_pos.y / 8);
	*ch = data.cursor_prev_char;
	data.cursor_visible = false;
}

static void show_text_cursor(void)
{
	uint16_t __far *ch = get_video_char(&data.video_mode,
	                                    data.pos.x / 8, data.pos.y / 8);
	data.cursor_prev_char = *ch;
	data.cursor_pos = data.pos;
	*ch = (*ch & data.cursor_text_and_mask) ^ data.cursor_text_xor_mask;
	data.cursor_visible = true;
}

/** Given the new position of the cursor, compute the both our source
 *  (i.e. the mouse cursor shape) and target clipping areas.
 *  @param cursor_pos cursor position
 *  @param start top left corner of clipping box in screen
 *  @param size size of the clipping box in screen as well as cursor shape
 *  @param offset top left corner of clipping box in mouse cursor shape */
static bool get_graphic_cursor_area(struct point __far *cursor_pos,
                                    struct point __far *start,
                                    struct point __far *size,
                                    struct point __far *offset)
{
	start->x = (cursor_pos->x / data.screen_scale.x) - data.cursor_hotspot.x;
	start->y = (cursor_pos->y / data.screen_scale.y) - data.cursor_hotspot.y;
	size->x = GRAPHIC_CURSOR_WIDTH;
	size->y = GRAPHIC_CURSOR_HEIGHT;
	offset->x = 0;
	offset->y = 0;

	// Start clipping around
	// Cursor is left/top of visible area
	if (start->x <= -size->x) {
		return false;
	} else if (start->x < 0) {
		offset->x += -start->x;
		size->x   -= -start->x;
		start->x = 0;
	}
	if (start->y <= -size->y) {
		return false;
	} else if (start->y < 0) {
		offset->y += -start->y;
		size->y   -= -start->y;
		start->y = 0;
	}
	// Cursor is right/bottom of visible area
	if (start->x > data.video_mode.pixels_width) {
		return false; // Don't render cursor
	} else if (start->x + size->x > data.video_mode.pixels_width) {
		size->x -= (start->x + size->x) - data.video_mode.pixels_width;
	}
	if (start->y > data.video_mode.pixels_height) {
		return false;
	} else if (start->y + size->y > data.video_mode.pixels_height) {
		size->y -= (start->y + size->y) - data.video_mode.pixels_height;
	}

	return true;
}

static inline uint8_t * get_prev_graphic_cursor_scanline(unsigned bytes_per_line,
                                                         unsigned num_lines,
                                                         unsigned plane,
                                                         unsigned y)
{
	return &data.cursor_prev_graphic[((plane * num_lines) + y) * bytes_per_line];
}

static inline uint16_t get_graphic_cursor_and_mask_line(unsigned y)
{
	return data.cursor_graphic[y];
}

static inline uint16_t get_graphic_cursor_xor_mask_line(unsigned y)
{
	return data.cursor_graphic[GRAPHIC_CURSOR_HEIGHT + y];
}

/** Compute the total number of bytes between start and end pixels,
 *  rounding up as necessary to cover all bytes. */
static inline unsigned get_scanline_segment_bytes(unsigned bits_per_pixel, unsigned start, unsigned size)
{
	// Get starting byte (round down)
	unsigned start_byte = (start * bits_per_pixel) / 8;
	// Get end byte (round up)
	unsigned end_byte = (((start + size) * bits_per_pixel) + (8-1)) / 8;

	return end_byte - start_byte;
}

/** Creates a bitmask that extracts the topmost N bits of a byte. */
static inline uint8_t build_pixel_mask(unsigned bits_per_pixel)
{
	if      (bits_per_pixel == 1) return 0x80;
	else if (bits_per_pixel == 2) return 0xC0;
	else if (bits_per_pixel == 4) return 0xF0;
	else                          return 0xFF;
}

/** Hides the graphical mouse cursor, by restoring the contents of
 *  data.cursor_prev_graphic (i.e. what was below the cursor before we drew it)
 *  to video memory. */
static void hide_graphic_cursor(void)
{
	struct modeinfo *info = &data.video_mode;
	struct point start, size, offset;
	unsigned cursor_bytes_per_line;
	unsigned plane, y;

	// Compute the area where the cursor is currently positioned
	if (!get_graphic_cursor_area(&data.cursor_pos, &start, &size, &offset)) {
		return;
	}

	// For each scanline, we will copy this amount of bytes
	cursor_bytes_per_line = get_scanline_segment_bytes(info->bits_per_pixel,
	                                                   start.x, size.x);

	for (plane = 0; plane < info->num_planes; plane++) {
		if (info->num_planes) vga_select_plane(plane);

		for (y = 0; y < size.y; y++) {
			uint8_t __far *line = get_video_scanline(info, start.y + y)
			                      + (start.x * info->bits_per_pixel) / 8;
			uint8_t *prev = get_prev_graphic_cursor_scanline(cursor_bytes_per_line, size.y,
			                                                 plane, y);

			// Restore this scaline from cursor_prev
			nfmemcpy(line, prev, cursor_bytes_per_line);
		}
	}

	data.cursor_visible = false;
}

/** Renders the graphical cursor.
 *  It will also backup whatever pixels are below
 *  the cursor area to cursor_prev_graphic. */
static void show_graphic_cursor(void)
{
	const struct modeinfo *info = &data.video_mode;
	struct point start, size, offset;
	unsigned cursor_bytes_per_line;
	const uint8_t msb_pixel_mask = build_pixel_mask(info->bits_per_pixel);
	unsigned plane, y;

	// Compute the area where the cursor is supposed to be drawn
	if (!get_graphic_cursor_area(&data.pos, &start, &size, &offset)) {
		return;
	}

	// For each scanline, we will copy this amount of bytes
	cursor_bytes_per_line = get_scanline_segment_bytes(info->bits_per_pixel,
	                                                   start.x, size.x);

	for (plane = 0; plane < info->num_planes; plane++) {
		if (info->num_planes) vga_select_plane(plane);

		for (y = 0; y < size.y; y++) {
			uint8_t __far *line = get_video_scanline(info, start.y + y)
			                      + (start.x * info->bits_per_pixel) / 8;
			uint8_t *prev = get_prev_graphic_cursor_scanline(cursor_bytes_per_line, size.y,
			                                                 plane, y);
			uint16_t cursor_and_mask = get_graphic_cursor_and_mask_line(offset.y + y)
			                           << offset.x;
			uint16_t cursor_xor_mask = get_graphic_cursor_xor_mask_line(offset.y + y)
			                           << offset.x;
			uint8_t pixel_mask = msb_pixel_mask;
			uint8_t pixel = *line;
			unsigned x;

			// First, backup this scanline to prev before any changes
			fnmemcpy(prev, line, cursor_bytes_per_line);

			// when start.x is not pixel aligned,
			// scaline points the previous multiple of pixels_per_byte;
			// and the initial pixel will not be at the MSB of it.
			// advance the pixel_mask accordingly
			if (info->bits_per_pixel < 8) {
				pixel_mask >>= (start.x * info->bits_per_pixel) % 8;
			}

			for (x = 0; x < size.x; x++) {
				if (!(cursor_and_mask & MSB_MASK)) {
					pixel &= ~pixel_mask;
				}
				if (cursor_xor_mask & MSB_MASK) {
					pixel ^= pixel_mask;
				}

				// Advance to the next pixel
				pixel_mask >>= info->bits_per_pixel;
				if (!pixel_mask) {
					// Time to advance to the next byte
					*line = pixel; // Save current byte first
					pixel = *(++line);
					pixel_mask = msb_pixel_mask;
				}

				// Advance to the next bit in the cursor mask
				cursor_and_mask <<= 1;
				cursor_xor_mask <<= 1;
			}

			if (pixel_mask != msb_pixel_mask) {
				// We ended up in the middle of a byte, save it
				*line = pixel;
			}
		}
	}

	data.cursor_pos = data.pos;
	data.cursor_visible = true;
}

/** Refreshes cursor position and visibility. */
static void refresh_cursor(void)
{
	bool should_show = data.visible_count >= 0;
	bool pos_changed, needs_refresh;

#if USE_INT2F
	// Windows 386 is already rendering the cursor for us.
	// Hide our own.
	if (data.w386cursor) should_show = false;
#endif

#if USE_VIRTUALBOX
	if (data.vbwantcursor) {
		// We want to use the VirtualBox host cursor.
		// See if we have to update its visibility.
		int err = 0;
		if (should_show != data.cursor_visible) {
			err = vbox_set_pointer_visible(&data.vb, should_show);
			if (err == 0 && data.vbhaveabs) {
				data.cursor_visible = should_show;
			}
		}
		if (err == 0 & data.vbhaveabs) {
			// No need to refresh the cursor; VirtualBox is already showing it for us.
			return;
		}
	}
#endif

	pos_changed = data.cursor_pos.x != data.pos.x || data.cursor_pos.y != data.pos.y;
	needs_refresh = should_show && pos_changed || should_show != data.cursor_visible;

	if (!needs_refresh) {
		// Nothing to do
		return;
	}

	if (data.video_mode.type == VIDEO_TEXT) {
		// Text video mode
		if (data.cursor_visible) {
			// Hide the cursor at the old position if any
			hide_text_cursor();
		}
		if (should_show) {
			// Show the cursor at the new position
			show_text_cursor();
		}
	} else if (data.video_mode.type != VIDEO_UNKNOWN) {
		// Graphic video modes

		bool video_planar = data.video_mode.num_planes > 1;
		struct videoregs regs;
		// If current video mode is planar,
		// we will have to play with the VGA registers
		// so let's save and restore them.
		if (video_planar) {
			save_video_registers(&regs);
		}

		if (data.cursor_visible) {
			hide_graphic_cursor();
		}
		if (should_show) {
			show_graphic_cursor();
		}

		if (video_planar) {
			restore_video_registers(&regs);
		}
	} else {
		// Unknown video mode, don't render cursor.
	}
}

/** Forcefully hides the mouse cursor if shown. */
static void hide_cursor(void)
{
#if USE_VIRTUALBOX
	if (data.vbwantcursor) {
		vbox_set_pointer_visible(&data.vb, false);
		if (data.vbhaveabs) {
			data.cursor_visible = false;
		}
	}
#endif

	if (data.cursor_visible) {
		if (data.video_mode.type == VIDEO_TEXT) {
			hide_text_cursor();
		} else if (data.video_mode.type != VIDEO_UNKNOWN) {
			hide_graphic_cursor();
		}
	}
}

/** Loads the current graphic cursor,
 *  which in this case means uploading it to the host. */
static void load_cursor(void)
{
#if USE_VIRTUALBOX
	if (data.vbwantcursor) {
		VMMDevReqMousePointer *req = (VMMDevReqMousePointer *) data.vb.buf;
		const unsigned width = GRAPHIC_CURSOR_WIDTH, height = GRAPHIC_CURSOR_HEIGHT;
		uint8_t  *output = req->pointerData;
		unsigned int y, x;

		bzero(req, sizeof(VMMDevReqMousePointer));

		req->header.size = vbox_req_mouse_pointer_size(width, height);
		req->header.version = VMMDEV_REQUEST_HEADER_VERSION;
		req->header.requestType = VMMDevReq_SetPointerShape;
		req->header.rc = -1;

		req->fFlags = VBOX_MOUSE_POINTER_SHAPE;
		req->xHot = BOUND(data.cursor_hotspot.x, 0, width);
		req->yHot = BOUND(data.cursor_hotspot.y, 0, height);
		req->width = width;
		req->height = height;

		// AND mask
		// int33 format is 1-bit per pixel packed into 16-bit LE values,
		// while VirtualBox wants 1-bit per pixel packed into 8-bit.
		// All we have to do is byteswap 16-bit values.
		for (y = 0; y < height; ++y) {
			uint16_t cursor_line = get_graphic_cursor_and_mask_line(y);
			output[0] = (cursor_line >> 8) & 0xFF;
			output[1] = cursor_line & 0xFF;
			output += GRAPHIC_CURSOR_SCANLINE_LEN;
		}

		// XOR mask
		// int33 format is again 1-bit per pixel packed into 16-bit LE values,
		// however VirtualBox wants 4-byte per pixel packed "RGBA".
		for (y = 0; y < height; ++y) {
			uint16_t cursor_line = get_graphic_cursor_xor_mask_line(y);

			for (x = 0; x < width; ++x) {
				// MSB of line is current mask bit, we shift it on each iteration
				uint8_t val = (cursor_line & MSB_MASK) ? 0xFF : 0;

				output[0] = val;
				output[1] = val;
				output[2] = val;
				output[3] = 0;

				cursor_line <<= 1;
				output += 4;
			}
		}

		dlog_puts("Loading cursor to VBox");

		vbox_send_request(data.vb.iobase, data.vb.dds.physicalAddress);

		if (req->header.rc != 0) {
			dlog_puts("Could not send cursor to VirtualBox");
		}

		// After we send this message, it looks like VirtualBox shows the cursor
		// even if we didn't actually want it to be visible at this point.
		// Mark it as visible so that refresh_cursor() will rehide it if necessary.
		data.cursor_visible = true;
		refresh_cursor();
	}
#endif
}

/** Refreshes the information about the current video mode. */
static void refresh_video_info(void)
{
	uint8_t cur_mode = bda_get_video_mode() & ~0x80;
	bool mode_change = cur_mode != data.video_mode.mode;

	if (mode_change && data.cursor_visible) {
		// Assume cursor is lost
		data.cursor_visible = false;
	}

	dlog_print("Current video mode=");
	dlog_printx(cur_mode);
	dlog_endline();

	get_current_video_mode_info(&data.video_mode);

	data.screen_max.x = data.video_mode.pixels_width - 1;
	data.screen_max.y = data.video_mode.pixels_height - 1;
	data.screen_scale.x = 1;
	data.screen_scale.y = 1;

	// The actual range of coordinates expected by int33 clients
	// is, for some reason, different than real resolution in some modes.
	// For example, 320x... modes are mapped to 640x... pixels.
	if (data.video_mode.pixels_width == 320) {
		data.screen_max.x = 640 - 1;
		data.screen_scale.x = 640 / 320;
	}
}

/** Calls the application-registered event handler. */
static void call_event_handler(void (__far *handler)(), uint16_t events,
                               uint16_t buttons, int16_t x, int16_t y,
                               int16_t delta_x, int16_t delta_y)
{
#if TRACE_EVENTS
	dlog_print("calling event handler events=");
	dlog_printx(events);
	dlog_print(" buttons=");
	dlog_printx(buttons);
	dlog_print(" x=");
	dlog_printd(x);
	dlog_print(" y=");
	dlog_printd(y);
	dlog_print(" dx=");
	dlog_printd(delta_x);
	dlog_print(" dy=");
	dlog_printd(delta_y);
	dlog_endline();
#endif

	__asm {
		mov ax, [events]
		mov bx, [buttons]
		mov cx, [x]
		mov dx, [y]
		mov si, [delta_x]
		mov di, [delta_y]

		call dword ptr [handler]
	}
}

/** Process a mouse event internally.
 *  @param buttons currently pressed buttons as a bitfield
 *  @param absolute whether mouse coordinates are an absolute value
 *  @param x y if absolute, then absolute coordinates in screen pixels
 *             if relative, then relative coordinates in mickeys
 *  @param z relative wheel mouse movement
 */
static void handle_mouse_event(uint16_t buttons, bool absolute, int x, int y, int z)
{
	uint16_t events = 0;
	int i;

#if TRACE_EVENTS
	dlog_print("handle mouse event");
	if (absolute) dlog_print(" absolute");
	dlog_print(" buttons=");
	dlog_printx(buttons);
	dlog_print(" x=");
	dlog_printd(x);
	dlog_print(" y=");
	dlog_printd(y);
	dlog_print(" z=");
	dlog_printd(z);
	dlog_endline();
#endif

	if (absolute) {
		// Absolute movement: x,y are in screen pixels units
		events |= INT33_EVENT_MASK_ABSOLUTE;

		if (x != data.pos.x || y != data.pos.y) {
			events |= INT33_EVENT_MASK_MOVEMENT;

			// Simulate a fake relative movement in mickeys
			// This is almost certainly broken.
			// Programs that expect relative movement data
			// will almost never set a mickeyPerPixel value.
			// So all we can do is guess.
			data.delta.x += (x - data.pos.x) * 8;
			data.delta.y += (y - data.pos.y) * 8;

			// Store the new absolute position
			data.pos.x = x;
			data.pos.y = y;
			data.pos_frac.x = 0;
			data.pos_frac.y = 0;
		}
	} else if (x || y) {
		// Relative movement: x,y are in mickeys
		uint16_t ticks = bda_get_tick_count_lo();
		unsigned ax = ABS(x), ay = ABS(y);

		events |= INT33_EVENT_MASK_MOVEMENT;

		// Check if around one second has passed
		if ((ticks - data.last_ticks) >= 18) {
			data.total_motion = 0;
			data.last_ticks = ticks;
		}

		// If more than the double speed threshold has been moved in the last second,
		// double the speed
		data.total_motion += ax * ax + ay * ay;
		if (data.total_motion > data.doubleSpeedThreshold * data.doubleSpeedThreshold) {
			x *= 2;
			y *= 2;
		}

		data.delta.x += x;
		data.delta.y += y;
		data.delta_frac.x = 0;
		data.delta_frac.y = 0;

		// Convert mickeys into pixels
		data.pos.x += scalei_rem(x, data.mickeysPerLine.x, 8, &data.pos_frac.x);
		data.pos.y += scalei_rem(y, data.mickeysPerLine.y, 8, &data.pos_frac.y);
	}

	bound_position_to_window();

	if (data.haswheel && z) {
		events |= INT33_EVENT_MASK_WHEEL_MOVEMENT;
		// Higher byte of buttons contains wheel movement
		buttons |= (z & 0xFF) << 8;
	}

	// Update button status
	for (i = 0; i < NUM_BUTTONS; ++i) {
		uint8_t btn = 1 << i;
		uint8_t evt = 0;
		if ((buttons & btn) && !(data.buttons & btn)) {
			// Button pressed
			evt = 1 << (1 + (i * 2)); // Press event mask
			data.button[i].pressed.count++;
			data.button[i].pressed.last.x = data.pos.x;
			data.button[i].pressed.last.y = data.pos.y;
		} else if (!(buttons & btn) && (data.buttons & btn)) {
			// Button released
			evt = 1 << (2 + (i * 2)); // Release event mask
			data.button[i].released.count++;
			data.button[i].released.last.x = data.pos.x;
			data.button[i].released.last.y = data.pos.y;
		}
		events |= evt;
	}
	data.buttons = buttons;

	refresh_cursor();

	events &= data.event_mask;
	if (data.event_handler && events) {
		call_event_handler(data.event_handler, events,
		                   buttons, data.pos.x, data.pos.y, data.delta.x, data.delta.y);
	}
}

/** PS/2 BIOS calls this routine to notify mouse events. */
static void __far ps2_mouse_callback(uint8_t status, uint8_t x, uint8_t y, uint8_t z)
{
#pragma aux (PS2_CB) ps2_mouse_callback

	int sx =   status & PS2M_STATUS_X_NEG ? 0xFF00 | x : x;
	int sy = -(status & PS2M_STATUS_Y_NEG ? 0xFF00 | y : y);
	int sz = z;
	bool abs = false;

#if TRACE_EVENTS
	dlog_print("ps2 callback status=");
	dlog_printx(status);
	dlog_print(" sx=");
	dlog_printd(sx);
	dlog_print(" sy=");
	dlog_printd(sy);
	dlog_print(" sz=");
	dlog_printd(z);
	dlog_endline();
#endif

#if USE_VIRTUALBOX
	if (data.vbavail) {
		uint16_t vbx, vby;
		if ((vbox_get_mouse(&data.vb, &abs, &vbx, &vby) == 0) && abs) {
			sx = scaleu(vbx, 0xFFFFU, MAX(data.max.x, data.screen_max.x));
			sy = scaleu(vby, 0xFFFFU, MAX(data.max.y, data.screen_max.y));
			data.vbhaveabs = true;
		} else {
			// VirtualBox does not support absolute coordinates,
			// or user has disabled them.
			data.vbhaveabs = false;
		}
	}
#endif

	// VirtualBox/Bochs BIOS does not pass wheel data to the callback,
	// so we will fetch it directly from the BIOS data segment.
	if (data.haswheel && !sz) {
		int8_t __far * mouse_packet = MK_FP(bda_get_ebda_segment(), 0x28);
		sz = mouse_packet[3];
	}

	handle_mouse_event(status & (PS2M_STATUS_BUTTON_1 | PS2M_STATUS_BUTTON_2 | PS2M_STATUS_BUTTON_3),
	                   abs, sx, sy, sz);
}

#if USE_VIRTUALBOX
static void enable_vbox_absolute(bool enable)
{
	data.vbhaveabs = false;

	if (data.vbavail) {
		int err = vbox_set_mouse(&data.vb, enable, false);
		if (enable && !err) {
			dlog_puts("VBox absolute mouse enabled");
			data.vbhaveabs = true;
		} else if (!enable) {
			dlog_puts("VBox absolute mouse disabled");
		}
	}
}
#endif

static void reset_mouse_hardware()
{
	ps2m_enable(false);

#if USE_VIRTUALBOX
	// By default, enable the integration
	enable_vbox_absolute(true);
	load_cursor();
#endif

	if (data.usewheel && ps2m_detect_wheel()) {
		// Detect wheel also reinitializes the mouse to the proper packet size
		data.haswheel = true;
	} else {
		// Otherwise do an extra reset to return back to initial state, just in case
		data.haswheel = false;
		ps2m_init(PS2M_PACKET_SIZE_PLAIN);
	}

	ps2m_set_resolution(3);     // 3 = 200 dpi, 8 counts per millimeter
	ps2m_set_sample_rate(4);    // 4 = 80 reports per second
	ps2m_set_scaling_factor(1); // 1 = 1:1 scaling

	ps2m_set_callback(ps2_mouse_callback);

	ps2m_enable(true);
}

/** Reset "software" mouse settings, i.e. those configurable by the client program. */
static void reset_mouse_settings()
{
	data.event_mask = 0;
	data.event_handler = 0;

	data.mickeysPerLine.x = 8;
	data.mickeysPerLine.y = 16;
	data.doubleSpeedThreshold = 64;
	data.min.x = 0;
	data.max.x = data.screen_max.x;
	data.min.y = 0;
	data.max.y = data.screen_max.y;
	data.visible_count = -1;
	data.cursor_text_type = 0;
	data.cursor_text_and_mask = 0xFFFFU;
	data.cursor_text_xor_mask = 0x7700U;
	data.cursor_hotspot.x = 0;
	data.cursor_hotspot.y = 0;
	nnmemcpy(data.cursor_graphic, default_cursor_graphic, sizeof(data.cursor_graphic));

	refresh_cursor(); // This will hide the cursor and update data.cursor_visible
}

/** Reset the current mouse state and throw away past events. */
static void reset_mouse_state()
{
	int i;
	data.pos.x = data.min.x;
	data.pos.y = data.min.y;
	data.pos_frac.x = 0;
	data.pos_frac.y = 0;
	data.delta.x = 0;
	data.delta.y = 0;
	data.delta_frac.x = 0;
	data.delta_frac.y = 0;
	data.buttons = 0;
	for (i = 0; i < NUM_BUTTONS; i++) {
		data.button[i].pressed.count = 0;
		data.button[i].pressed.last.x = 0;
		data.button[i].pressed.last.y = 0;
		data.button[i].released.count = 0;
		data.button[i].released.last.x = 0;
		data.button[i].released.last.y = 0;
	}
	data.wheel_delta = 0;
	data.cursor_visible = false;
	data.cursor_pos.x = 0;
	data.cursor_pos.y = 0;
	data.cursor_prev_char = 0;
	bzero(data.cursor_prev_graphic, sizeof(data.cursor_prev_graphic));
}

static void return_clear_wheel_counter(union INTPACK __far *r)
{
	r->x.cx = data.wheel_last.x;
	r->x.dx = data.wheel_last.y;
	r->x.bx = data.wheel_delta;
	data.wheel_last.x = 0;
	data.wheel_last.y = 0;
	data.wheel_delta = 0;
}

static void return_clear_button_counter(union INTPACK __far *r, struct buttoncounter *c)
{
	r->x.cx = c->last.x;
	r->x.dx = c->last.y;
	r->x.bx = c->count;
	c->last.x = 0;
	c->last.y = 0;
	c->count = 0;
}

/** Entry point for our int33 API. */
static void int33_handler(union INTPACK r)
#pragma aux int33_handler "*" parm caller [] modify [ax bx cx dx es]
{
	switch (r.x.ax) {
	case INT33_RESET_MOUSE:
		dlog_puts("Mouse reset");
		refresh_video_info();
		reset_mouse_settings();
		reset_mouse_hardware();
		reset_mouse_state();
		r.x.ax = INT33_MOUSE_FOUND;
		r.x.bx = NUM_BUTTONS;
		break;
	case INT33_SHOW_CURSOR:
		data.visible_count++;
		refresh_cursor();
		break;
	case INT33_HIDE_CURSOR:
		data.visible_count--;
		refresh_cursor();
		break;
	case INT33_GET_MOUSE_POSITION:
		r.x.cx = data.pos.x;
		r.x.dx = data.pos.y;
		r.x.bx = data.buttons;
		if (data.haswheel) {
			r.h.bh = data.wheel_delta;
			data.wheel_delta = 0;
		}
		break;
	case INT33_SET_MOUSE_POSITION:
		data.pos.x = r.x.cx;
		data.pos.y = r.x.dx;
		data.pos_frac.x = 0;
		data.pos_frac.y = 0;
		data.delta.x = 0;
		data.delta.y = 0;
		data.delta_frac.x = 0;
		data.delta_frac.y = 0;
		bound_position_to_window();
		break;
	case INT33_GET_BUTTON_PRESSED_COUNTER:
		r.x.ax = data.buttons;
		if (data.haswheel) {
			r.h.bh = data.wheel_delta;
		}
		if (data.haswheel && r.x.bx == -1) {
			// Wheel information
			return_clear_wheel_counter(&r);
		} else {
			// Regular button information
			int btn = MIN(r.x.bx, NUM_BUTTONS - 1);
			return_clear_button_counter(&r, &data.button[btn].pressed);
		}
		break;
	case INT33_GET_BUTTON_RELEASED_COUNTER:
		r.x.ax = data.buttons;
		if (data.haswheel) {
			r.h.bh = data.wheel_delta;
		}
		if (data.haswheel && r.x.bx == -1) {
			// Wheel information
			return_clear_wheel_counter(&r);
		} else {
			int btn = MIN(r.x.bx, NUM_BUTTONS - 1);
			return_clear_button_counter(&r, &data.button[btn].released);
		}
		break;
	case INT33_SET_HORIZONTAL_WINDOW:
		dlog_print("Mouse set horizontal window [");
		dlog_printd(r.x.cx);
		dlog_putc(',');
		dlog_printd(r.x.dx);
		dlog_puts("]");
		// Recheck in case someone changed the video mode
		refresh_video_info();
		data.min.x = r.x.cx;
		data.max.x = r.x.dx;
		bound_position_to_window();
		break;
	case INT33_SET_VERTICAL_WINDOW:
		dlog_print("Mouse set vertical window [");
		dlog_printd(r.x.cx);
		dlog_putc(',');
		dlog_printd(r.x.dx);
		dlog_puts("]");
		refresh_video_info();
		data.min.y = r.x.cx;
		data.max.y = r.x.dx;
		bound_position_to_window();
		break;
	case INT33_SET_GRAPHICS_CURSOR:
		dlog_puts("Mouse set graphics cursor");
		hide_cursor();
		data.cursor_hotspot.x = r.x.bx;
		data.cursor_hotspot.y = r.x.cx;
		fnmemcpy(data.cursor_graphic, MK_FP(r.x.es, r.x.dx), sizeof(data.cursor_graphic));
		load_cursor();
		refresh_cursor();
		break;
	case INT33_SET_TEXT_CURSOR:
		dlog_print("Mouse set text cursor ");
		dlog_printd(r.x.bx);
		dlog_endline();
		hide_cursor();
		data.cursor_text_type = r.x.bx;
		data.cursor_text_and_mask = r.x.cx;
		data.cursor_text_xor_mask = r.x.dx;
		refresh_cursor();
		break;
	case INT33_GET_MOUSE_MOTION:
		r.x.cx = data.delta.x;
		r.x.dx = data.delta.y;
		data.delta.x = 0;
		data.delta.y = 0;
#if USE_VIRTUALBOX
		// Likely this means we need a relative mouse, or we will get out of sync
		//if (data.vbabs) enable_vbox_absolute(false);
#endif
		break;
	case INT33_SET_EVENT_HANDLER:
		dlog_puts("Mouse set event handler");
		data.event_mask = r.x.cx;
		data.event_handler = MK_FP(r.x.es, r.x.dx);
		break;
	case INT33_SET_MOUSE_SPEED:
		dlog_print("Mouse set speed x=");
		dlog_printd(r.x.cx);
		dlog_print(" y=");
		dlog_printd(r.x.dx);
		dlog_endline();
		data.mickeysPerLine.x = r.x.cx;
		data.mickeysPerLine.y = r.x.dx;
		break;
	case INT33_SET_SPEED_DOUBLE_THRESHOLD:
		dlog_print("Mouse set speed double threshold=");
		dlog_printd(r.x.dx);
		dlog_endline();
		data.doubleSpeedThreshold = r.x.dx;
		break;
	case INT33_EXCHANGE_EVENT_HANDLER:
		dlog_puts("Mouse exchange event handler");
		data.event_mask = r.x.cx;
	    {
		    void (__far *prev_event_handler)() = data.event_handler;
			data.event_handler = MK_FP(r.x.es, r.x.dx);
			r.x.es = FP_SEG(prev_event_handler);
			r.x.dx = FP_OFF(prev_event_handler);
	    }
		break;
	case INT33_GET_MOUSE_STATUS_SIZE:
		dlog_puts("Mouse get status size");
		r.x.bx = sizeof(TSRDATA);
		break;
	case INT33_SAVE_MOUSE_STATUS:
		dlog_puts("Mouse save status");
		nfmemcpy(MK_FP(r.x.es, r.x.dx), &data, sizeof(TSRDATA));
		break;
	case INT33_LOAD_MOUSE_STATUS:
		dlog_puts("Mouse load status");
		fnmemcpy(&data, MK_FP(r.x.es, r.x.dx), sizeof(TSRDATA));
		break;
	case INT33_SET_MOUSE_SENSITIVITY:
		dlog_print("Mouse set speed x=");
		dlog_printd(r.x.bx);
		dlog_print(" y=");
		dlog_printd(r.x.cx);
		dlog_print(" threshold=");
		dlog_printd(r.x.dx);
		dlog_endline();
		data.mickeysPerLine.x = r.x.bx;
		data.mickeysPerLine.y = r.x.cx;
		data.doubleSpeedThreshold = r.x.dx;
		break;
	case INT33_GET_MOUSE_SENSITIVITY:
		r.x.bx = data.mickeysPerLine.x;
		r.x.cx = data.mickeysPerLine.y;
		r.x.dx = data.doubleSpeedThreshold;
		break;
	case INT33_RESET_SETTINGS:
		dlog_puts("Mouse reset settings");
		refresh_video_info();
		reset_mouse_settings();
		reset_mouse_state();
		r.x.ax = INT33_MOUSE_FOUND;
		r.x.bx = NUM_BUTTONS;
		break;
	case INT33_GET_LANGUAGE:
		r.x.bx = 0;
		break;
	case INT33_GET_DRIVER_INFO:
		dlog_puts("Mouse get driver info");
		r.h.bh = REPORTED_VERSION_MAJOR;
		r.h.bl = REPORTED_VERSION_MINOR;
		r.h.ch = INT33_MOUSE_TYPE_PS2;
		r.h.cl = 0;
		break;
	case INT33_GET_MAX_COORDINATES:
		r.x.cx = data.screen_max.x;
		r.x.dx = data.screen_max.y;
		break;
	case INT33_GET_WINDOW:
		r.x.ax = data.min.x;
		r.x.bx = data.min.y;
		r.x.cx = data.max.x;
		r.x.dx = data.max.y;
		break;
	case INT33_GET_CAPABILITIES:
		r.x.ax = INT33_WHEEL_API_MAGIC; // Driver supports wheel API
		r.x.bx = 0;
		r.x.cx = data.haswheel ? INT33_CAPABILITY_MOUSE_API : 0;
		break;
	case INT33_GET_TSR_DATA:
		dlog_puts("Get TSR data");
		r.x.es = FP_SEG(&data);
		r.x.di = FP_OFF(&data);
		break;
	default:
		dlog_print("Unknown mouse function ax=");
		dlog_printx(r.x.ax);
		dlog_endline();
		break;
	}
}

// Can't use __interrupt, it makes a call to GETDS on the runtime
void __declspec(naked) __far int33_isr(void)
{
	__asm {
		pusha
		push ds
		push es
		push fs
		push gs

		mov bp, sp
		push cs
		pop ds

		call int33_handler

		pop gs
		pop fs
		pop es
		pop ds
		popa
		iret
	}
}

#if USE_INT2F
/** Windows will call this function to notify events when we are inside a DOS box. */
static void windows_mouse_handler(int action, int x, int y, int buttons, int events)
#pragma aux windows_mouse_handler "*" parm [ax] [bx] [cx] [dx] [si] modify [ax bx cx dx es]
{
	switch (action) {
	case VMD_ACTION_MOUSE_EVENT:
		handle_mouse_event(buttons, true, x, y, 0);
		break;
	case VMD_ACTION_HIDE_CURSOR:
		dlog_puts("VMD_ACTION_HIDE_CURSOR");
		data.w386cursor = true;
		refresh_cursor();
		break;
	case VMD_ACTION_SHOW_CURSOR:
		dlog_puts("VMD_ACTION_SHOW_CURSOR");
		data.w386cursor = false;
		refresh_cursor();
		break;
	}
}

void __declspec(naked) __far windows_mouse_callback()
{
	__asm {
		pusha
		push ds
		push es
		push fs
		push gs

		mov bp, sp
		push cs
		pop ds

		call windows_mouse_handler

		pop gs
		pop fs
		pop es
		pop ds
		popa

		retf
	}
}

static void int2f_handler(union INTPACK r)
#pragma aux int2f_handler "*" parm caller [] modify [ax bx cx dx es]
{
	switch (r.x.ax) {
	case INT2F_NOTIFY_WIN386_STARTUP:
		dlog_print("Windows is starting, version=");
		dlog_printx(r.x.di);
		dlog_endline();
		data.w386_startup.version = 3;
		data.w386_startup.next = MK_FP(r.x.es, r.x.bx);
		data.w386_startup.device_driver = 0;
		data.w386_startup.device_driver_data = 0;
		data.w386_startup.instance_data = &data.w386_instance;
		data.w386_instance[0].ptr = &data;
		data.w386_instance[0].size = sizeof(data);
		data.w386_instance[1].ptr = 0;
		data.w386_instance[1].size = 0;
		r.x.es = FP_SEG(&data.w386_startup);
		r.x.bx = FP_OFF(&data.w386_startup);
		break;
	case INT2F_NOTIFY_DEVICE_CALLOUT:
		switch (r.x.bx) {
		case VMD_DEVICE_ID:
			switch (r.x.cx) {
			case VMD_CALLOUT_TEST:
				r.x.cx = 1; // Yes, we are here!
				break;
			case VMD_CALLOUT_GET_DOS_MOUSE_API:
				// Windows is asking our mouse driver for the hook function address
				r.x.ds = FP_SEG(windows_mouse_callback);
				r.x.si = FP_OFF(windows_mouse_callback);
				r.x.ax = 0; // Yes, we are here!
				break;
			}
			break;
		}
		break;
	}
}

void __declspec(naked) __far int2f_isr(void)
{
	__asm {
		pusha
		push ds
		push es
		push fs
		push gs

		mov bp, sp
		push cs
		pop ds

		call int2f_handler

		pop gs
		pop fs
		pop es
		pop ds
		popa

		; Jump to the next handler in the chain
		jmp dword ptr cs:[data + 4] ; wasm doesn't support structs, this is data.prev_int2f_handler
	}
}
#endif

static LPTSRDATA int33_get_tsr_data(void);
#pragma aux int33_get_tsr_data = \
	"xor ax, ax" \
	"mov es, ax" \
	"mov di, ax" \
	"mov ax, 0x7f" \
	"int 0x33"   \
	__value [es di] \
	__modify [ax]

static LPTSRDATA local_get_tsr_data(void);
#pragma aux local_get_tsr_data = \
	"mov ax, cs" \
	"mov es, ax" \
	"mov di, offset data" \
	__value [es di] \
	__modify [ax]

LPTSRDATA __far get_tsr_data(bool installed)
{
	if (installed) {
		return int33_get_tsr_data();
	} else {
		return local_get_tsr_data();
	}
}

int resident_end;