w32inevt.c 23.6 KB
Newer Older
1
/* Input event support for Emacs on the Microsoft Windows API.
Paul Eggert's avatar
Paul Eggert committed
2
   Copyright (C) 1992-1993, 1995, 2001-2019 Free Software Foundation,
3
   Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4

5 6
This file is part of GNU Emacs.

7
GNU Emacs is free software: you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9 10
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
11 12 13 14 15 16 17

GNU Emacs 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
18
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
19

20
/*
Richard M. Stallman's avatar
Richard M. Stallman committed
21 22 23 24 25
   Drew Bliss                   01-Oct-93
     Adapted from ntkbd.c by Tim Fleehart
*/


Pavel Janík's avatar
Pavel Janík committed
26
#include <config.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
27 28 29
#include <stdio.h>
#include <windows.h>

30 31 32
#ifndef MOUSE_MOVED
#define MOUSE_MOVED   1
#endif
33 34 35
#ifndef MOUSE_HWHEELED
#define MOUSE_HWHEELED 8
#endif
36

Richard M. Stallman's avatar
Richard M. Stallman committed
37
#include "lisp.h"
38
#include "keyboard.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
39 40
#include "frame.h"
#include "blockinput.h"
41
#include "termchar.h"	/* for Mouse_HLInfo, tty_display_info */
42
#include "w32term.h"
43
#include "w32inevt.h"
44
#include "w32common.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
45

46
/* stdin, from w32console.c */
Richard M. Stallman's avatar
Richard M. Stallman committed
47 48 49 50
extern HANDLE keyboard_handle;

/* Info for last mouse motion */
static COORD movement_pos;
51
static Time movement_time;
Richard M. Stallman's avatar
Richard M. Stallman committed
52

53
/* from w32fns.c */
54 55
extern unsigned int map_keypad_keys (unsigned int, unsigned int);
extern unsigned int w32_key_to_modifier (int key);
56

Richard M. Stallman's avatar
Richard M. Stallman committed
57 58 59 60 61
/* Event queue */
#define EVENT_QUEUE_SIZE 50
static INPUT_RECORD event_queue[EVENT_QUEUE_SIZE];
static INPUT_RECORD *queue_ptr = event_queue, *queue_end = event_queue;

62 63 64
/* Temporarily store lead byte of DBCS input sequences.  */
static char dbcs_lead = 0;

65 66 67 68 69 70 71 72 73
static inline BOOL
w32_read_console_input (HANDLE h, INPUT_RECORD *rec, DWORD recsize,
			DWORD *waiting)
{
  return (w32_console_unicode_input
	  ? ReadConsoleInputW (h, rec, recsize, waiting)
	  : ReadConsoleInputA (h, rec, recsize, waiting));
}

Daniel Colascione's avatar
Daniel Colascione committed
74 75 76
/* Set by w32_console_toggle_lock_key.  */
int faked_key;

77
static int
Richard M. Stallman's avatar
Richard M. Stallman committed
78 79 80 81
fill_queue (BOOL block)
{
  BOOL rc;
  DWORD events_waiting;
82

Richard M. Stallman's avatar
Richard M. Stallman committed
83 84
  if (queue_ptr < queue_end)
    return queue_end-queue_ptr;
85

Richard M. Stallman's avatar
Richard M. Stallman committed
86 87 88 89 90 91 92 93 94
  if (!block)
    {
      /* Check to see if there are some events to read before we try
	 because we can't block.  */
      if (!GetNumberOfConsoleInputEvents (keyboard_handle, &events_waiting))
	return -1;
      if (events_waiting == 0)
	return 0;
    }
95

96 97
  rc = w32_read_console_input (keyboard_handle, event_queue, EVENT_QUEUE_SIZE,
			       &events_waiting);
Richard M. Stallman's avatar
Richard M. Stallman committed
98 99 100 101 102 103 104 105
  if (!rc)
    return -1;
  queue_ptr = event_queue;
  queue_end = event_queue + events_waiting;
  return (int) events_waiting;
}

/* In a generic, multi-frame world this should take a console handle
Dmitry Antipov's avatar
Dmitry Antipov committed
106
   and return the frame for it.
Richard M. Stallman's avatar
Richard M. Stallman committed
107 108

   Right now, there's only one frame so return it.  */
Dmitry Antipov's avatar
Dmitry Antipov committed
109
static struct frame *
Richard M. Stallman's avatar
Richard M. Stallman committed
110 111
get_frame (void)
{
112
  return SELECTED_FRAME ();
Richard M. Stallman's avatar
Richard M. Stallman committed
113 114
}

115
/* Translate console modifiers to emacs modifiers.
116 117 118
   German keyboard support (Kai Morgan Zeise 2/18/95).  */


119 120 121 122 123 124 125 126 127 128 129 130
#if 0
/* Return nonzero if the virtual key is a dead key.  */
static int
is_dead_key (int wparam)
{
  unsigned int code = MapVirtualKey (wparam, 2);

  /* Windows 95 returns 0x8000, NT returns 0x80000000.  */
  return (code & 0x80008000) ? 1 : 0;
}
#endif

131 132 133
/* The return code indicates key code size.  cpID is the codepage to
   use for translation to Unicode; -1 means use the current console
   input codepage.  */
134

Richard M. Stallman's avatar
Richard M. Stallman committed
135

136
/* return code -1 means that event_queue_ptr won't be incremented.
137
   In other word, this event makes two key codes.   (by himi)       */
138
static int
139
key_event (KEY_EVENT_RECORD *event, struct input_event *emacs_ev, int *isdead)
Richard M. Stallman's avatar
Richard M. Stallman committed
140
{
141 142
  static int mod_key_state = 0;
  int wParam;
143 144

  *isdead = 0;
145

Richard M. Stallman's avatar
Richard M. Stallman committed
146
  /* Skip key-up events.  */
147
  if (!event->bKeyDown)
Richard M. Stallman's avatar
Richard M. Stallman committed
148
    {
149 150 151
      switch (event->wVirtualKeyCode)
	{
	case VK_LWIN:
152 153
          if (!w32_kbdhook_active)
            mod_key_state &= ~LEFT_WIN_PRESSED;
154 155
	  break;
	case VK_RWIN:
156 157
          if (!w32_kbdhook_active)
            mod_key_state &= ~RIGHT_WIN_PRESSED;
158 159 160 161 162
	  break;
	case VK_APPS:
	  mod_key_state &= ~APPS_PRESSED;
	  break;
	}
Richard M. Stallman's avatar
Richard M. Stallman committed
163 164
      return 0;
    }
165

166 167
  /* Ignore keystrokes we fake ourself; see below.  */
  if (faked_key == event->wVirtualKeyCode)
Richard M. Stallman's avatar
Richard M. Stallman committed
168
    {
169
      faked_key = 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
170 171
      return 0;
    }
172 173 174

  /* To make it easier to debug this code, ignore modifier keys!  */
  switch (event->wVirtualKeyCode)
Richard M. Stallman's avatar
Richard M. Stallman committed
175
    {
176 177 178 179 180 181 182 183
    case VK_LWIN:
      if (NILP (Vw32_pass_lwindow_to_system))
	{
	  /* Prevent system from acting on keyup (which opens the Start
	     menu if no other key was pressed) by simulating a press of
	     Space which we will ignore.  */
	  if ((mod_key_state & LEFT_WIN_PRESSED) == 0)
	    {
184
	      if (FIXNUMP (Vw32_phantom_key_code))
Tom Tromey's avatar
Tom Tromey committed
185
		faked_key = XUFIXNUM (Vw32_phantom_key_code) & 255;
186 187 188
	      else
		faked_key = VK_SPACE;
	      keybd_event (faked_key, (BYTE) MapVirtualKey (faked_key, 0), 0, 0);
189 190
	    }
	}
191 192
      if (!w32_kbdhook_active)
        mod_key_state |= LEFT_WIN_PRESSED;
193
      if (!NILP (Vw32_lwindow_modifier))
194
	return 0;
195 196 197 198 199 200
      break;
    case VK_RWIN:
      if (NILP (Vw32_pass_rwindow_to_system))
	{
	  if ((mod_key_state & RIGHT_WIN_PRESSED) == 0)
	    {
201
	      if (FIXNUMP (Vw32_phantom_key_code))
Tom Tromey's avatar
Tom Tromey committed
202
		faked_key = XUFIXNUM (Vw32_phantom_key_code) & 255;
203 204 205
	      else
		faked_key = VK_SPACE;
	      keybd_event (faked_key, (BYTE) MapVirtualKey (faked_key, 0), 0, 0);
206 207
	    }
	}
208 209
      if (!w32_kbdhook_active)
        mod_key_state |= RIGHT_WIN_PRESSED;
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
      if (!NILP (Vw32_rwindow_modifier))
	return 0;
      break;
    case VK_APPS:
      mod_key_state |= APPS_PRESSED;
      if (!NILP (Vw32_apps_modifier))
	return 0;
      break;
    case VK_CAPITAL:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_enable_caps_lock))
	goto disable_lock_key;
      return 0;
    case VK_NUMLOCK:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_enable_num_lock))
	goto disable_lock_key;
      return 0;
    case VK_SCROLL:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_scroll_lock_modifier))
	goto disable_lock_key;
      return 0;
    disable_lock_key:
      /* Ensure the appropriate lock key state is off (and the
	 indicator light as well).  */
      wParam = event->wVirtualKeyCode;
      if (GetAsyncKeyState (wParam) & 0x8000)
	{
	  /* Fake another press of the relevant key.  Apparently, this
	     really is the only way to turn off the indicator.  */
	  faked_key = wParam;
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | 0, 0);
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
	}
      break;
    case VK_MENU:
    case VK_CONTROL:
    case VK_SHIFT:
      return 0;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    case VK_CANCEL:
      /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
	 which is confusing for purposes of key binding; convert
	 VK_CANCEL events into VK_PAUSE events.  */
      event->wVirtualKeyCode = VK_PAUSE;
      break;
    case VK_PAUSE:
      /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
	 for purposes of key binding; convert these back into
	 VK_NUMLOCK events, at least when we want to see NumLock key
	 presses.  (Note that there is never any possibility that
	 VK_PAUSE with Ctrl really is C-Pause as per above.)  */
      if (NILP (Vw32_enable_num_lock)
	  && (event->dwControlKeyState
	      & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0)
	event->wVirtualKeyCode = VK_NUMLOCK;
      break;
Richard M. Stallman's avatar
Richard M. Stallman committed
271
    }
272 273 274

  /* Recognize state of Windows and Apps keys.  */
  event->dwControlKeyState |= mod_key_state;
275 276 277 278 279 280 281
  if (w32_kbdhook_active)
    {
      if (check_w32_winkey_state (VK_LWIN))
        event->dwControlKeyState |= LEFT_WIN_PRESSED;
      if (check_w32_winkey_state (VK_RWIN))
        event->dwControlKeyState |= RIGHT_WIN_PRESSED;
    }
282 283 284 285 286 287 288

  /* Distinguish numeric keypad keys from extended keys.  */
  event->wVirtualKeyCode =
    map_keypad_keys (event->wVirtualKeyCode,
		     (event->dwControlKeyState & ENHANCED_KEY));

  if (lispy_function_keys[event->wVirtualKeyCode] == 0)
289
    {
290 291 292
      if (!NILP (Vw32_recognize_altgr)
	  && (event->dwControlKeyState & LEFT_CTRL_PRESSED)
	  && (event->dwControlKeyState & RIGHT_ALT_PRESSED))
293
	{
294 295
	  /* Don't try to interpret AltGr key chords; ToAscii seems not
	     to process them correctly.  */
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
      /* Handle key chords including any modifiers other than shift
         directly, in order to preserve as much modifier information as
         possible.  */
      else if (event->dwControlKeyState
	       & (  RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED
		  | RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED
		  | (!NILP (Vw32_lwindow_modifier) ? LEFT_WIN_PRESSED : 0)
		  | (!NILP (Vw32_rwindow_modifier) ? RIGHT_WIN_PRESSED : 0)
		  | (!NILP (Vw32_apps_modifier) ? APPS_PRESSED : 0)
		  | (!NILP (Vw32_scroll_lock_modifier) ? SCROLLLOCK_ON : 0)))
	{
	  /* Don't translate modified alphabetic keystrokes, so the user
	     doesn't need to constantly switch layout to type control or
	     meta keystrokes when the normal layout translates
	     alphabetic characters to non-ascii characters.  */
	  if ('A' <= event->wVirtualKeyCode && event->wVirtualKeyCode <= 'Z')
	    {
	      event->uChar.AsciiChar = event->wVirtualKeyCode;
	      if ((event->dwControlKeyState & SHIFT_PRESSED) == 0)
		event->uChar.AsciiChar += ('a' - 'A');
	    }
	  /* Try to handle unrecognized keystrokes by determining the
             base character (ie. translating the base key plus shift
             modifier).  */
	  else if (event->uChar.AsciiChar == 0)
322
	    w32_kbd_patch_key (event, -1);
323
	}
324

325
      if (event->uChar.AsciiChar == 0)
326 327 328 329
	{
	  emacs_ev->kind = NO_EVENT;
	  return 0;
	}
330
      else if (event->uChar.AsciiChar > 0)
331
	{
332
	  /* Pure ASCII characters < 128.  */
333 334 335
	  emacs_ev->kind = ASCII_KEYSTROKE_EVENT;
	  emacs_ev->code = event->uChar.AsciiChar;
	}
336 337
      else if (event->uChar.UnicodeChar > 0
	       && w32_console_unicode_input)
338
	{
339 340
	  /* Unicode codepoint; only valid if we are using Unicode
	     console input mode.  */
341 342 343 344 345
	  emacs_ev->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
	  emacs_ev->code = event->uChar.UnicodeChar;
	}
      else
	{
346 347 348 349
	  /* Fallback handling of non-ASCII characters for non-Unicode
	     versions of Windows, and for non-Unicode input on NT
	     family of Windows.  Only characters in the current
	     console codepage are supported by this fallback.  */
350 351 352 353
	  wchar_t code;
	  char dbcs[2];
          int cpId;

354 355 356 357 358 359
	  /* Get the current console input codepage to interpret this
	     key with.  Note that the system defaults for the OEM
	     codepage could have been changed by calling SetConsoleCP
	     or w32-set-console-codepage, so using GetLocaleInfo to
	     get LOCALE_IDEFAULTCODEPAGE is not TRT here.  */
          cpId = GetConsoleCP ();
360 361 362 363 364 365 366 367 368 369 370

	  dbcs[0] = dbcs_lead;
	  dbcs[1] = event->uChar.AsciiChar;
	  if (dbcs_lead)
	    {
	      dbcs_lead = 0;
	      if (!MultiByteToWideChar (cpId, 0, dbcs, 2, &code, 1))
		{
		  /* Garbage  */
		  DebPrint (("Invalid DBCS sequence: %d %d\n",
			     dbcs[0], dbcs[1]));
371
		  emacs_ev->kind = NO_EVENT;
372 373 374 375 376
		}
	    }
	  else if (IsDBCSLeadByteEx (cpId, dbcs[1]))
	    {
	      dbcs_lead = dbcs[1];
377
	      emacs_ev->kind = NO_EVENT;
378 379 380 381 382 383 384
	    }
	  else
	    {
	      if (!MultiByteToWideChar (cpId, 0, &dbcs[1], 1, &code, 1))
		{
		  /* Garbage  */
		  DebPrint (("Invalid character: %d\n", dbcs[1]));
385
		  emacs_ev->kind = NO_EVENT;
386 387 388 389 390
		}
	    }
	  emacs_ev->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
	  emacs_ev->code = code;
	}
391
    }
Richard M. Stallman's avatar
Richard M. Stallman committed
392 393
  else
    {
394
      /* Function keys and other non-character keys.  */
Pavel Janík's avatar
Pavel Janík committed
395
      emacs_ev->kind = NON_ASCII_KEYSTROKE_EVENT;
396
      emacs_ev->code = event->wVirtualKeyCode;
Richard M. Stallman's avatar
Richard M. Stallman committed
397
    }
398

399
  XSETFRAME (emacs_ev->frame_or_window, get_frame ());
400 401
  emacs_ev->modifiers = w32_kbd_mods_to_emacs (event->dwControlKeyState,
					       event->wVirtualKeyCode);
Richard M. Stallman's avatar
Richard M. Stallman committed
402 403 404 405 406
  emacs_ev->timestamp = GetTickCount ();
  return 1;
}

/* Mouse position hook.  */
407
void
Dmitry Antipov's avatar
Dmitry Antipov committed
408
w32_console_mouse_position (struct frame **f,
409 410 411 412 413
			    int insist,
			    Lisp_Object *bar_window,
			    enum scroll_bar_part *part,
			    Lisp_Object *x,
			    Lisp_Object *y,
414
			    Time *time)
Richard M. Stallman's avatar
Richard M. Stallman committed
415
{
416
  block_input ();
417

418 419
  insist = insist;

Richard M. Stallman's avatar
Richard M. Stallman committed
420 421
  *f = get_frame ();
  *bar_window = Qnil;
422
  *part = scroll_bar_above_handle;
423
  SELECTED_FRAME ()->mouse_moved = 0;
424

425 426
  XSETINT (*x, movement_pos.X);
  XSETINT (*y, movement_pos.Y);
Richard M. Stallman's avatar
Richard M. Stallman committed
427
  *time = movement_time;
428

429
  unblock_input ();
Richard M. Stallman's avatar
Richard M. Stallman committed
430 431
}

432
/* Remember mouse motion and notify emacs.  */
433
static void
Richard M. Stallman's avatar
Richard M. Stallman committed
434 435
mouse_moved_to (int x, int y)
{
436
  /* If we're in the same place, ignore it.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
437 438
  if (x != movement_pos.X || y != movement_pos.Y)
    {
439
      SELECTED_FRAME ()->mouse_moved = 1;
Richard M. Stallman's avatar
Richard M. Stallman committed
440 441 442 443 444 445 446 447 448 449 450 451
      movement_pos.X = x;
      movement_pos.Y = y;
      movement_time = GetTickCount ();
    }
}

/* Consoles return button bits in a strange order:
     least significant - Leftmost button
     next - Rightmost button
     next - Leftmost+1
     next - Leftmost+2...

452
   For the 3 standard buttons, we have:
Richard M. Stallman's avatar
Richard M. Stallman committed
453 454 455 456 457
     Left == 0
     Middle == 1
     Right == 2
   Others increase from there.  */

458
#define NUM_TRANSLATED_MOUSE_BUTTONS 5
459
static int emacs_button_translation[NUM_TRANSLATED_MOUSE_BUTTONS] =
Richard M. Stallman's avatar
Richard M. Stallman committed
460
{
461
  0, 2, 1, 3, 4
Richard M. Stallman's avatar
Richard M. Stallman committed
462 463
};

464
static int
Richard M. Stallman's avatar
Richard M. Stallman committed
465 466 467 468
do_mouse_event (MOUSE_EVENT_RECORD *event,
		struct input_event *emacs_ev)
{
  static DWORD button_state = 0;
469
  static Lisp_Object last_mouse_window;
470
  DWORD but_change, mask, flags = event->dwEventFlags;
Richard M. Stallman's avatar
Richard M. Stallman committed
471
  int i;
472

473
  switch (flags)
Richard M. Stallman's avatar
Richard M. Stallman committed
474
    {
475
    case MOUSE_MOVED:
Richard M. Stallman's avatar
Richard M. Stallman committed
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
	struct frame *f = get_frame ();
	Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
	int mx = event->dwMousePosition.X, my = event->dwMousePosition.Y;

	mouse_moved_to (mx, my);

	if (f->mouse_moved)
	  {
	    if (hlinfo->mouse_face_hidden)
	      {
		hlinfo->mouse_face_hidden = 0;
		clear_mouse_face (hlinfo);
	      }

	    /* Generate SELECT_WINDOW_EVENTs when needed.  */
	    if (!NILP (Vmouse_autoselect_window))
	      {
		Lisp_Object mouse_window = window_from_coordinates (f, mx, my,
								    0, 0);
		/* A window will be selected only when it is not
		   selected now, and the last mouse movement event was
		   not in it.  A minibuffer window will be selected iff
		   it is active.  */
		if (WINDOWP (mouse_window)
		    && !EQ (mouse_window, last_mouse_window)
		    && !EQ (mouse_window, selected_window))
		  {
		    struct input_event event;

		    EVENT_INIT (event);
		    event.kind = SELECT_WINDOW_EVENT;
		    event.frame_or_window = mouse_window;
		    event.arg = Qnil;
		    event.timestamp = movement_time;
		    kbd_buffer_store_event (&event);
		  }
		last_mouse_window = mouse_window;
	      }
	    else
	      last_mouse_window = Qnil;

	    previous_help_echo_string = help_echo_string;
	    help_echo_string = help_echo_object = help_echo_window = Qnil;
	    help_echo_pos = -1;
	    note_mouse_highlight (f, mx, my);
	    /* If the contents of the global variable help_echo has
	       changed (inside note_mouse_highlight), generate a HELP_EVENT.  */
	    if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
	      gen_help_event (help_echo_string, selected_frame,
			      help_echo_window, help_echo_object,
			      help_echo_pos);
	  }
529
	/* We already called kbd_buffer_store_event, so indicate to
530 531
	   the caller it shouldn't.  */
	return 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
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
    case MOUSE_WHEELED:
    case MOUSE_HWHEELED:
      {
	struct frame *f = get_frame ();
	int mx = event->dwMousePosition.X, my = event->dwMousePosition.Y;
	bool down_p = (event->dwButtonState & 0x10000000) != 0;

	emacs_ev->kind =
	  flags == MOUSE_HWHEELED ? HORIZ_WHEEL_EVENT : WHEEL_EVENT;
	emacs_ev->code = 0;
	emacs_ev->modifiers = down_p ? down_modifier : up_modifier;
	emacs_ev->modifiers |=
	  w32_kbd_mods_to_emacs (event->dwControlKeyState, 0);
	XSETINT (emacs_ev->x, mx);
	XSETINT (emacs_ev->y, my);
	XSETFRAME (emacs_ev->frame_or_window, f);
	emacs_ev->arg = Qnil;
	emacs_ev->timestamp = GetTickCount ();
	return 1;
      }
    case DOUBLE_CLICK:
    default:	/* mouse pressed or released */
      /* It looks like the console code sends us a button-release
	 mouse event with dwButtonState == 0 when a window is
	 activated and when the mouse is first clicked.  Ignore this
	 case.  */
      if (event->dwButtonState == button_state)
	return 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
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
      emacs_ev->kind = MOUSE_CLICK_EVENT;

      /* Find out what button has changed state since the last button
	 event.  */
      but_change = button_state ^ event->dwButtonState;
      mask = 1;
      for (i = 0; mask; i++, mask <<= 1)
	if (but_change & mask)
	  {
	    if (i < NUM_TRANSLATED_MOUSE_BUTTONS)
	      emacs_ev->code = emacs_button_translation[i];
	    else
	      emacs_ev->code = i;
	    break;
	  }

      button_state = event->dwButtonState;
      emacs_ev->modifiers =
	w32_kbd_mods_to_emacs (event->dwControlKeyState, 0)
	| ((event->dwButtonState & mask) ? down_modifier : up_modifier);

      XSETFASTINT (emacs_ev->x, event->dwMousePosition.X);
      XSETFASTINT (emacs_ev->y, event->dwMousePosition.Y);
      XSETFRAME (emacs_ev->frame_or_window, get_frame ());
      emacs_ev->arg = Qnil;
      emacs_ev->timestamp = GetTickCount ();

      return 1;
    }
Richard M. Stallman's avatar
Richard M. Stallman committed
591 592
}

593
static void
Richard M. Stallman's avatar
Richard M. Stallman committed
594 595
resize_event (WINDOW_BUFFER_SIZE_RECORD *event)
{
Dmitry Antipov's avatar
Dmitry Antipov committed
596
  struct frame *f = get_frame ();
597

598 599
  change_frame_size (f, event->dwSize.X, event->dwSize.Y
		     - FRAME_MENU_BAR_LINES (f), 0, 1, 0, 0);
Richard M. Stallman's avatar
Richard M. Stallman committed
600 601 602
  SET_FRAME_GARBAGED (f);
}

603
static void
604
maybe_generate_resize_event (void)
605 606
{
  CONSOLE_SCREEN_BUFFER_INFO info;
Dmitry Antipov's avatar
Dmitry Antipov committed
607
  struct frame *f = get_frame ();
608 609 610 611 612 613 614

  GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &info);

  /* It is okay to call this unconditionally, since it will do nothing
     if the size hasn't actually changed.  */
  change_frame_size (f,
		     1 + info.srWindow.Right - info.srWindow.Left,
615
		     1 + info.srWindow.Bottom - info.srWindow.Top
616
		     - FRAME_MENU_BAR_LINES (f), 0, 1, 0, 0);
617 618
}

619
#if HAVE_W32NOTIFY
620
int
621 622
handle_file_notifications (struct input_event *hold_quit)
{
623
  struct notifications_set *ns = NULL;
Eli Zaretskii's avatar
Eli Zaretskii committed
624
  int nevents = 0;
625
  int done = 0;
626 627 628 629 630

  /* We cannot process notification before Emacs is fully initialized,
     since we need the UTF-16LE coding-system to be set up.  */
  if (!initialized)
    {
Eli Zaretskii's avatar
Eli Zaretskii committed
631
      return nevents;
632 633
    }

634
  while (!done)
635
    {
636
      ns = NULL;
Eli Zaretskii's avatar
Eli Zaretskii committed
637

638 639 640 641 642 643 644 645 646 647 648 649 650
      /* Find out if there is a record available in the linked list of
	 notifications sets.  If so, unlink te set from the linked list.
	 Use the critical section.  */
      enter_crit ();
      if (notifications_set_head->next != notifications_set_head)
	{
	  ns = notifications_set_head->next;
	  ns->prev->next = ns->next;
	  ns->next->prev = ns->prev;
	}
      else
	done = 1;
      leave_crit();
651

652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
      if (ns)
	{
	  BYTE *p = ns->notifications;
	  FILE_NOTIFY_INFORMATION *fni = (PFILE_NOTIFY_INFORMATION)p;
	  const DWORD min_size
	    = offsetof (FILE_NOTIFY_INFORMATION, FileName) + sizeof(wchar_t);
	  struct input_event inev;
	  DWORD info_size = ns->size;
	  Lisp_Object cs = Qutf_16le;
	  Lisp_Object obj = w32_get_watch_object (ns->desc);

	  /* notifications size could be zero when the buffer of
	     notifications overflowed on the OS level, or when the
	     directory being watched was itself deleted.  Do nothing in
	     that case.  */
	  if (info_size
	      && !NILP (obj) && CONSP (obj))
669
	    {
670 671 672 673 674 675 676 677 678 679 680 681 682
	      Lisp_Object callback = XCDR (obj);

	      EVENT_INIT (inev);

	      while (info_size >= min_size)
		{
		  Lisp_Object utf_16_fn
		    = make_unibyte_string ((char *)fni->FileName,
					   fni->FileNameLength);
		  /* Note: mule-conf is preloaded, so utf-16le must
		     already be defined at this point.  */
		  Lisp_Object fname
		    = code_convert_string_norecord (utf_16_fn, cs, 0);
683
		  Lisp_Object action = w32_lispy_file_action (fni->Action);
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699

		  inev.kind = FILE_NOTIFY_EVENT;
		  inev.timestamp = GetTickCount ();
		  inev.modifiers = 0;
		  inev.frame_or_window = callback;
		  inev.arg = Fcons (action, fname);
		  inev.arg = list3 (make_pointer_integer (ns->desc),
				    action, fname);
		  kbd_buffer_store_event_hold (&inev, hold_quit);
		  nevents++;
		  if (!fni->NextEntryOffset)
		    break;
		  p += fni->NextEntryOffset;
		  fni = (PFILE_NOTIFY_INFORMATION)p;
		  info_size -= fni->NextEntryOffset;
		}
700
	    }
701 702 703
	  /* Free this notification set.  */
	  free (ns->notifications);
	  free (ns);
704 705
	}
    }
Eli Zaretskii's avatar
Eli Zaretskii committed
706
  return nevents;
707
}
708
#else  /* !HAVE_W32NOTIFY */
709
int
710 711 712 713 714
handle_file_notifications (struct input_event *hold_quit)
{
  return 0;
}
#endif	/* !HAVE_W32NOTIFY */
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
/* Here's an overview of how Emacs input works in non-GUI sessions on
   MS-Windows.  (For description of the GUI input, see the commentary
   before w32_msg_pump in w32fns.c.)

   When Emacs is idle, it loops inside wait_reading_process_output,
   calling pselect periodically to check whether any input is
   available.  On Windows, pselect is redirected to sys_select, which
   uses MsgWaitForMultipleObjects to wait for input, either from the
   keyboard or from any of the Emacs subprocesses.  In addition,
   MsgWaitForMultipleObjects wakes up when some Windows message is
   posted to the input queue of the Emacs's main thread (which is the
   thread in which sys_select runs).

   When the Emacs's console window has focus, Windows sends input
   events that originate from the keyboard or the mouse; these events
   wake up MsgWaitForMultipleObjects, which reports that input is
   available.  Emacs then calls w32_console_read_socket, below, to
   read the input.  w32_console_read_socket uses
   GetNumberOfConsoleInputEvents and ReadConsoleInput to peek at and
   read the console input events.

   One type of non-keyboard input event that gets reported as input
   available is due to the Emacs's console window receiving focus.
   When that happens, Emacs gets the FOCUS_EVENT event and sys_select
   reports some input; however, w32_console_read_socket ignores such
   events when called to read them.

   Note that any other Windows message sent to the main thread will
   also wake up MsgWaitForMultipleObjects.  These messages get
   immediately dispatched to their destinations by calling
   drain_message_queue.  */

748
int
749 750
w32_console_read_socket (struct terminal *terminal,
                         struct input_event *hold_quit)
Richard M. Stallman's avatar
Richard M. Stallman committed
751
{
752
  int nev, add;
753 754
  int isdead;

755
  block_input ();
756

Richard M. Stallman's avatar
Richard M. Stallman committed
757 758
  for (;;)
    {
Eli Zaretskii's avatar
Eli Zaretskii committed
759 760
      int nfnotify = handle_file_notifications (hold_quit);

761
      nev = fill_queue (0);
Richard M. Stallman's avatar
Richard M. Stallman committed
762 763 764
      if (nev <= 0)
        {
	  /* If nev == -1, there was some kind of error
Eli Zaretskii's avatar
Eli Zaretskii committed
765
	     If nev == 0 then no events were available
Richard M. Stallman's avatar
Richard M. Stallman committed
766
	     so return.  */
Eli Zaretskii's avatar
Eli Zaretskii committed
767 768
	  if (nfnotify)
	    nev = 0;
769
	  break;
Richard M. Stallman's avatar
Richard M. Stallman committed
770 771
        }

772
      while (nev > 0)
Richard M. Stallman's avatar
Richard M. Stallman committed
773
        {
774
	  struct input_event inev;
775 776 777 778 779
	  /* Having a separate variable with this value makes
	     debugging easier, as otherwise the compiler might
	     rearrange the switch below in a way that makes it hard to
	     track the event type.  */
	  unsigned evtype = queue_ptr->EventType;
780 781 782 783 784

	  EVENT_INIT (inev);
	  inev.kind = NO_EVENT;
	  inev.arg = Qnil;

785
	  switch (evtype)
Richard M. Stallman's avatar
Richard M. Stallman committed
786 787
            {
            case KEY_EVENT:
788
	      add = key_event (&queue_ptr->Event.KeyEvent, &inev, &isdead);
789
	      if (add == -1) /* 95.7.25 by himi */
790
		{
791 792 793
		  queue_ptr--;
		  add = 1;
		}
794 795
	      if (add)
		kbd_buffer_store_event_hold (&inev, hold_quit);
Richard M. Stallman's avatar
Richard M. Stallman committed
796 797 798
	      break;

            case MOUSE_EVENT:
799 800 801
	      add = do_mouse_event (&queue_ptr->Event.MouseEvent, &inev);
	      if (add)
		kbd_buffer_store_event_hold (&inev, hold_quit);
Richard M. Stallman's avatar
Richard M. Stallman committed
802 803 804
	      break;

            case WINDOW_BUFFER_SIZE_EVENT:
805 806
	      if (w32_use_full_screen_buffer)
		resize_event (&queue_ptr->Event.WindowBufferSizeEvent);
Richard M. Stallman's avatar
Richard M. Stallman committed
807
	      break;
808

Richard M. Stallman's avatar
Richard M. Stallman committed
809 810 811 812 813
            case MENU_EVENT:
            case FOCUS_EVENT:
	      /* Internal event types, ignored. */
	      break;
            }
814

Richard M. Stallman's avatar
Richard M. Stallman committed
815 816 817 818
	  queue_ptr++;
	  nev--;
        }
    }
819 820 821 822

  /* We don't get told about changes in the window size (only the buffer
     size, which we no longer care about), so we have to check it
     periodically.  */
823 824
  if (!w32_use_full_screen_buffer)
    maybe_generate_resize_event ();
825

826
  unblock_input ();
827
  return nev;
Richard M. Stallman's avatar
Richard M. Stallman committed
828
}