1 /*
2 * window.c - the PuTTY(tel) main program, which runs a PuTTY terminal
3 * emulator and backend in a window.
4 */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <ctype.h>
9 #include <time.h>
10 #include <limits.h>
11 #include <assert.h>
12
13 #ifdef __WINE__
14 #define NO_MULTIMON /* winelib doesn't have this */
15 #endif
16
17 #ifndef NO_MULTIMON
18 #define COMPILE_MULTIMON_STUBS
19 #endif
20
21 #include "putty.h"
22 #include "terminal.h"
23 #include "storage.h"
24 #include "win_res.h"
25 #include "winsecur.h"
26 #include "winseat.h"
27 #include "tree234.h"
28
29 #ifndef NO_MULTIMON
30 #include <multimon.h>
31 #endif
32
33 #include <imm.h>
34 #include <commctrl.h>
35 #include <richedit.h>
36 #include <mmsystem.h>
37
38 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
39 * wParam are used by Windows, and should be masked off, so we shouldn't
40 * attempt to store information in them. Hence all these identifiers have
41 * the low 4 bits clear. Also, identifiers should < 0xF000. */
42
43 #define IDM_SHOWLOG 0x0010
44 #define IDM_NEWSESS 0x0020
45 #define IDM_DUPSESS 0x0030
46 #define IDM_RESTART 0x0040
47 #define IDM_RECONF 0x0050
48 #define IDM_CLRSB 0x0060
49 #define IDM_RESET 0x0070
50 #define IDM_HELP 0x0140
51 #define IDM_ABOUT 0x0150
52 #define IDM_SAVEDSESS 0x0160
53 #define IDM_COPYALL 0x0170
54 #define IDM_FULLSCREEN 0x0180
55 #define IDM_COPY 0x0190
56 #define IDM_PASTE 0x01A0
57 #define IDM_SPECIALSEP 0x0200
58
59 #define IDM_SPECIAL_MIN 0x0400
60 #define IDM_SPECIAL_MAX 0x0800
61
62 #define IDM_SAVED_MIN 0x1000
63 #define IDM_SAVED_MAX 0x5000
64 #define MENU_SAVED_STEP 16
65 /* Maximum number of sessions on saved-session submenu */
66 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
67
68 #define WM_IGNORE_CLIP (WM_APP + 2)
69 #define WM_FULLSCR_ON_MAX (WM_APP + 3)
70 #define WM_GOT_CLIPDATA (WM_APP + 4)
71
72 /* Needed for Chinese support and apparently not always defined. */
73 #ifndef VK_PROCESSKEY
74 #define VK_PROCESSKEY 0xE5
75 #endif
76
77 /* Mouse wheel support. */
78 #ifndef WM_MOUSEWHEEL
79 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
80 #endif
81 #ifndef WHEEL_DELTA
82 #define WHEEL_DELTA 120
83 #endif
84
85 /* DPI awareness support */
86 #ifndef WM_DPICHANGED
87 #define WM_DPICHANGED 0x02E0
88 #define WM_DPICHANGED_BEFOREPARENT 0x02E2
89 #define WM_DPICHANGED_AFTERPARENT 0x02E3
90 #define WM_GETDPISCALEDSIZE 0x02E4
91 #endif
92
93 /* VK_PACKET, used to send Unicode characters in WM_KEYDOWNs */
94 #ifndef VK_PACKET
95 #define VK_PACKET 0xE7
96 #endif
97
98 static Mouse_Button translate_button(Mouse_Button button);
99 static void show_mouseptr(bool show);
100 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
101 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
102 unsigned char *output);
103 static void init_palette(void);
104 static void init_fonts(int, int);
105 static void init_dpi_info(void);
106 static void another_font(int);
107 static void deinit_fonts(void);
108 static void set_input_locale(HKL);
109 static void update_savedsess_menu(void);
110 static void init_winfuncs(void);
111
112 static bool is_full_screen(void);
113 static void make_full_screen(void);
114 static void clear_full_screen(void);
115 static void flip_full_screen(void);
116 static void process_clipdata(HGLOBAL clipdata, bool unicode);
117 static void setup_clipboards(Terminal *, Conf *);
118
119 /* Window layout information */
120 static void reset_window(int);
121 static int extra_width, extra_height;
122 static int font_width, font_height;
123 static bool font_dualwidth, font_varpitch;
124 static int offset_width, offset_height;
125 static bool was_zoomed = false;
126 static int prev_rows, prev_cols;
127
128 static void flash_window(int mode);
129 static void sys_cursor_update(void);
130 static bool get_fullscreen_rect(RECT * ss);
131
132 static int caret_x = -1, caret_y = -1;
133
134 static int kbd_codepage;
135
136 static Ldisc *ldisc;
137 static Backend *backend;
138
139 static struct unicode_data ucsdata;
140 static bool session_closed;
141 static bool reconfiguring = false;
142
143 static const SessionSpecial *specials = NULL;
144 static HMENU specials_menu = NULL;
145 static int n_specials = 0;
146
147 #define TIMING_TIMER_ID 1234
148 static long timing_next_time;
149
150 static struct {
151 HMENU menu;
152 } popup_menus[2];
153 enum { SYSMENU, CTXMENU };
154 static HMENU savedsess_menu;
155
156 static Conf *conf;
157 static LogContext *logctx;
158 static Terminal *term;
159
160 struct wm_netevent_params {
161 /* Used to pass data to wm_netevent_callback */
162 WPARAM wParam;
163 LPARAM lParam;
164 };
165
166 static void conf_cache_data(void);
167 static int cursor_type;
168 static int vtmode;
169
170 static struct sesslist sesslist; /* for saved-session menu */
171
172 #define FONT_NORMAL 0
173 #define FONT_BOLD 1
174 #define FONT_UNDERLINE 2
175 #define FONT_BOLDUND 3
176 #define FONT_WIDE 0x04
177 #define FONT_HIGH 0x08
178 #define FONT_NARROW 0x10
179
180 #define FONT_OEM 0x20
181 #define FONT_OEMBOLD 0x21
182 #define FONT_OEMUND 0x22
183 #define FONT_OEMBOLDUND 0x23
184
185 #define FONT_MAXNO 0x40
186 #define FONT_SHIFT 5
187 static HFONT fonts[FONT_MAXNO];
188 static LOGFONT lfont;
189 static bool fontflag[FONT_MAXNO];
190 static enum {
191 BOLD_NONE, BOLD_SHADOW, BOLD_FONT
192 } bold_font_mode;
193 static bool bold_colours;
194 static enum {
195 UND_LINE, UND_FONT
196 } und_mode;
197 static int descent, font_strikethrough_y;
198
199 static COLORREF colours[OSC4_NCOLOURS];
200 static HPALETTE pal;
201 static LPLOGPALETTE logpal;
202 bool tried_pal = false;
203 COLORREF colorref_modifier = 0;
204
205 enum MONITOR_DPI_TYPE { MDT_EFFECTIVE_DPI, MDT_ANGULAR_DPI, MDT_RAW_DPI, MDT_DEFAULT };
206 DECL_WINDOWS_FUNCTION(static, HRESULT, GetDpiForMonitor, (HMONITOR hmonitor, enum MONITOR_DPI_TYPE dpiType, UINT *dpiX, UINT *dpiY));
207 DECL_WINDOWS_FUNCTION(static, HRESULT, GetSystemMetricsForDpi, (int nIndex, UINT dpi));
208 DECL_WINDOWS_FUNCTION(static, HRESULT, AdjustWindowRectExForDpi, (LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle, UINT dpi));
209
210 static struct _dpi_info {
211 POINT cur_dpi;
212 RECT new_wnd_rect;
213 } dpi_info;
214
215 static HBITMAP caretbm;
216
217 static int dbltime, lasttime, lastact;
218 static Mouse_Button lastbtn;
219
220 /* this allows xterm-style mouse handling. */
221 static bool send_raw_mouse = false;
222 static int wheel_accumulator = 0;
223
224 static bool pointer_indicates_raw_mouse = false;
225
226 static BusyStatus busy_status = BUSY_NOT;
227
228 static char *window_name, *icon_name;
229
230 static int compose_state = 0;
231
232 static UINT wm_mousewheel = WM_MOUSEWHEEL;
233
234 #define IS_HIGH_VARSEL(wch1, wch2) \
235 ((wch1) == 0xDB40 && ((wch2) >= 0xDD00 && (wch2) <= 0xDDEF))
236 #define IS_LOW_VARSEL(wch) \
237 (((wch) >= 0x180B && (wch) <= 0x180D) || /* MONGOLIAN FREE VARIATION SELECTOR */ \
238 ((wch) >= 0xFE00 && (wch) <= 0xFE0F)) /* VARIATION SELECTOR 1-16 */
239
240 static bool wintw_setup_draw_ctx(TermWin *);
241 static void wintw_draw_text(TermWin *, int x, int y, wchar_t *text, int len,
242 unsigned long attrs, int lattrs, truecolour tc);
243 static void wintw_draw_cursor(TermWin *, int x, int y, wchar_t *text, int len,
244 unsigned long attrs, int lattrs, truecolour tc);
245 static void wintw_draw_trust_sigil(TermWin *, int x, int y);
246 static int wintw_char_width(TermWin *, int uc);
247 static void wintw_free_draw_ctx(TermWin *);
248 static void wintw_set_cursor_pos(TermWin *, int x, int y);
249 static void wintw_set_raw_mouse_mode(TermWin *, bool enable);
250 static void wintw_set_raw_mouse_mode_pointer(TermWin *, bool enable);
251 static void wintw_set_scrollbar(TermWin *, int total, int start, int page);
252 static void wintw_bell(TermWin *, int mode);
253 static void wintw_clip_write(
254 TermWin *, int clipboard, wchar_t *text, int *attrs,
255 truecolour *colours, int len, bool must_deselect);
256 static void wintw_clip_request_paste(TermWin *, int clipboard);
257 static void wintw_refresh(TermWin *);
258 static void wintw_request_resize(TermWin *, int w, int h);
259 static void wintw_set_title(TermWin *, const char *title);
260 static void wintw_set_icon_title(TermWin *, const char *icontitle);
261 static void wintw_set_minimised(TermWin *, bool minimised);
262 static void wintw_set_maximised(TermWin *, bool maximised);
263 static void wintw_move(TermWin *, int x, int y);
264 static void wintw_set_zorder(TermWin *, bool top);
265 static void wintw_palette_set(TermWin *, unsigned, unsigned, const rgb *);
266 static void wintw_palette_get_overrides(TermWin *, Terminal *);
267
268 static const TermWinVtable windows_termwin_vt = {
269 .setup_draw_ctx = wintw_setup_draw_ctx,
270 .draw_text = wintw_draw_text,
271 .draw_cursor = wintw_draw_cursor,
272 .draw_trust_sigil = wintw_draw_trust_sigil,
273 .char_width = wintw_char_width,
274 .free_draw_ctx = wintw_free_draw_ctx,
275 .set_cursor_pos = wintw_set_cursor_pos,
276 .set_raw_mouse_mode = wintw_set_raw_mouse_mode,
277 .set_raw_mouse_mode_pointer = wintw_set_raw_mouse_mode_pointer,
278 .set_scrollbar = wintw_set_scrollbar,
279 .bell = wintw_bell,
280 .clip_write = wintw_clip_write,
281 .clip_request_paste = wintw_clip_request_paste,
282 .refresh = wintw_refresh,
283 .request_resize = wintw_request_resize,
284 .set_title = wintw_set_title,
285 .set_icon_title = wintw_set_icon_title,
286 .set_minimised = wintw_set_minimised,
287 .set_maximised = wintw_set_maximised,
288 .move = wintw_move,
289 .set_zorder = wintw_set_zorder,
290 .palette_set = wintw_palette_set,
291 .palette_get_overrides = wintw_palette_get_overrides,
292 };
293
294 static TermWin wintw[1];
295 static HDC wintw_hdc;
296
297 static HICON trust_icon = INVALID_HANDLE_VALUE;
298
299 const bool share_can_be_downstream = true;
300 const bool share_can_be_upstream = true;
301
is_utf8(void)302 static bool is_utf8(void)
303 {
304 return ucsdata.line_codepage == CP_UTF8;
305 }
306
win_seat_is_utf8(Seat * seat)307 static bool win_seat_is_utf8(Seat *seat)
308 {
309 return is_utf8();
310 }
311
win_seat_get_ttymode(Seat * seat,const char * mode)312 static char *win_seat_get_ttymode(Seat *seat, const char *mode)
313 {
314 return term_get_ttymode(term, mode);
315 }
316
win_seat_stripctrl_new(Seat * seat,BinarySink * bs_out,SeatInteractionContext sic)317 static StripCtrlChars *win_seat_stripctrl_new(
318 Seat *seat, BinarySink *bs_out, SeatInteractionContext sic)
319 {
320 return stripctrl_new_term(bs_out, false, 0, term);
321 }
322
323 static size_t win_seat_output(
324 Seat *seat, bool is_stderr, const void *, size_t);
325 static bool win_seat_eof(Seat *seat);
326 static int win_seat_get_userpass_input(
327 Seat *seat, prompts_t *p, bufchain *input);
328 static void win_seat_notify_remote_exit(Seat *seat);
329 static void win_seat_connection_fatal(Seat *seat, const char *msg);
330 static void win_seat_update_specials_menu(Seat *seat);
331 static void win_seat_set_busy_status(Seat *seat, BusyStatus status);
332 static bool win_seat_set_trust_status(Seat *seat, bool trusted);
333 static bool win_seat_get_cursor_position(Seat *seat, int *x, int *y);
334 static bool win_seat_get_window_pixel_size(Seat *seat, int *x, int *y);
335
336 static const SeatVtable win_seat_vt = {
337 .output = win_seat_output,
338 .eof = win_seat_eof,
339 .get_userpass_input = win_seat_get_userpass_input,
340 .notify_remote_exit = win_seat_notify_remote_exit,
341 .connection_fatal = win_seat_connection_fatal,
342 .update_specials_menu = win_seat_update_specials_menu,
343 .get_ttymode = win_seat_get_ttymode,
344 .set_busy_status = win_seat_set_busy_status,
345 .verify_ssh_host_key = win_seat_verify_ssh_host_key,
346 .confirm_weak_crypto_primitive = win_seat_confirm_weak_crypto_primitive,
347 .confirm_weak_cached_hostkey = win_seat_confirm_weak_cached_hostkey,
348 .is_utf8 = win_seat_is_utf8,
349 .echoedit_update = nullseat_echoedit_update,
350 .get_x_display = nullseat_get_x_display,
351 .get_windowid = nullseat_get_windowid,
352 .get_window_pixel_size = win_seat_get_window_pixel_size,
353 .stripctrl_new = win_seat_stripctrl_new,
354 .set_trust_status = win_seat_set_trust_status,
355 .verbose = nullseat_verbose_yes,
356 .interactive = nullseat_interactive_yes,
357 .get_cursor_position = win_seat_get_cursor_position,
358 };
359 static WinGuiSeat wgs = { .seat.vt = &win_seat_vt,
360 .logpolicy.vt = &win_gui_logpolicy_vt };
361
start_backend(void)362 static void start_backend(void)
363 {
364 const struct BackendVtable *vt;
365 char *error, *realhost;
366 int i;
367
368 /*
369 * Select protocol. This is farmed out into a table in a
370 * separate file to enable an ssh-free variant.
371 */
372 vt = backend_vt_from_proto(conf_get_int(conf, CONF_protocol));
373 if (!vt) {
374 char *str = dupprintf("%s Internal Error", appname);
375 MessageBox(NULL, "Unsupported protocol number found",
376 str, MB_OK | MB_ICONEXCLAMATION);
377 sfree(str);
378 cleanup_exit(1);
379 }
380
381 seat_set_trust_status(&wgs.seat, true);
382 error = backend_init(vt, &wgs.seat, &backend, logctx, conf,
383 conf_get_str(conf, CONF_host),
384 conf_get_int(conf, CONF_port),
385 &realhost,
386 conf_get_bool(conf, CONF_tcp_nodelay),
387 conf_get_bool(conf, CONF_tcp_keepalives));
388 if (error) {
389 char *str = dupprintf("%s Error", appname);
390 char *msg = dupprintf("Unable to open connection to\n%s\n%s",
391 conf_dest(conf), error);
392 sfree(error);
393 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
394 sfree(str);
395 sfree(msg);
396 exit(0);
397 }
398 term_setup_window_titles(term, realhost);
399 sfree(realhost);
400
401 /*
402 * Connect the terminal to the backend for resize purposes.
403 */
404 term_provide_backend(term, backend);
405
406 /*
407 * Set up a line discipline.
408 */
409 ldisc = ldisc_create(conf, term, backend, &wgs.seat);
410
411 /*
412 * Destroy the Restart Session menu item. (This will return
413 * failure if it's already absent, as it will be the very first
414 * time we call this function. We ignore that, because as long
415 * as the menu item ends up not being there, we don't care
416 * whether it was us who removed it or not!)
417 */
418 for (i = 0; i < lenof(popup_menus); i++) {
419 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
420 }
421
422 session_closed = false;
423 }
424
close_session(void * ignored_context)425 static void close_session(void *ignored_context)
426 {
427 char *newtitle;
428 int i;
429
430 session_closed = true;
431 newtitle = dupprintf("%s (inactive)", appname);
432 win_set_icon_title(wintw, newtitle);
433 win_set_title(wintw, newtitle);
434 sfree(newtitle);
435
436 if (ldisc) {
437 ldisc_free(ldisc);
438 ldisc = NULL;
439 }
440 if (backend) {
441 backend_free(backend);
442 backend = NULL;
443 term_provide_backend(term, NULL);
444 seat_update_specials_menu(&wgs.seat);
445 }
446
447 /*
448 * Show the Restart Session menu item. Do a precautionary
449 * delete first to ensure we never end up with more than one.
450 */
451 for (i = 0; i < lenof(popup_menus); i++) {
452 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
453 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
454 IDM_RESTART, "&Restart Session");
455 }
456 }
457
458 const unsigned cmdline_tooltype =
459 TOOLTYPE_HOST_ARG |
460 TOOLTYPE_PORT_ARG |
461 TOOLTYPE_NO_VERBOSE_OPTION;
462
463 HINSTANCE hinst;
464
WinMain(HINSTANCE inst,HINSTANCE prev,LPSTR cmdline,int show)465 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
466 {
467 MSG msg;
468 HRESULT hr;
469 int guess_width, guess_height;
470
471 dll_hijacking_protection();
472
473 hinst = inst;
474
475 sk_init();
476
477 init_common_controls();
478
479 /* Set Explicit App User Model Id so that jump lists don't cause
480 PuTTY to hang on to removable media. */
481
482 set_explicit_app_user_model_id();
483
484 /* Ensure a Maximize setting in Explorer doesn't maximise the
485 * config box. */
486 defuse_showwindow();
487
488 init_winver();
489
490 /*
491 * If we're running a version of Windows that doesn't support
492 * WM_MOUSEWHEEL, find out what message number we should be
493 * using instead.
494 */
495 if (osMajorVersion < 4 ||
496 (osMajorVersion == 4 && osPlatformId != VER_PLATFORM_WIN32_NT))
497 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
498
499 init_help();
500
501 init_winfuncs();
502
503 conf = conf_new();
504
505 /*
506 * Initialize COM.
507 */
508 hr = CoInitialize(NULL);
509 if (hr != S_OK && hr != S_FALSE) {
510 char *str = dupprintf("%s Fatal Error", appname);
511 MessageBox(NULL, "Failed to initialize COM subsystem",
512 str, MB_OK | MB_ICONEXCLAMATION);
513 sfree(str);
514 return 1;
515 }
516
517 /*
518 * Process the command line.
519 */
520 {
521 char *p;
522 bool special_launchable_argument = false;
523
524 settings_set_default_protocol(be_default_protocol);
525 /* Find the appropriate default port. */
526 {
527 const struct BackendVtable *vt =
528 backend_vt_from_proto(be_default_protocol);
529 settings_set_default_port(0); /* illegal */
530 if (vt)
531 settings_set_default_port(vt->default_port);
532 }
533 conf_set_int(conf, CONF_logtype, LGTYP_NONE);
534
535 do_defaults(NULL, conf);
536
537 p = cmdline;
538
539 /*
540 * Process a couple of command-line options which are more
541 * easily dealt with before the line is broken up into words.
542 * These are the old-fashioned but convenient @sessionname and
543 * the internal-use-only &sharedmemoryhandle, plus the &R
544 * prefix for -restrict-acl, all of which are used by PuTTYs
545 * auto-launching each other via System-menu options.
546 */
547 while (*p && isspace(*p))
548 p++;
549 if (*p == '&' && p[1] == 'R' &&
550 (!p[2] || p[2] == '@' || p[2] == '&')) {
551 /* &R restrict-acl prefix */
552 restrict_process_acl();
553 p += 2;
554 }
555
556 if (*p == '@') {
557 /*
558 * An initial @ means that the whole of the rest of the
559 * command line should be treated as the name of a saved
560 * session, with _no quoting or escaping_. This makes it a
561 * very convenient means of automated saved-session
562 * launching, via IDM_SAVEDSESS or Windows 7 jump lists.
563 */
564 int i = strlen(p);
565 while (i > 1 && isspace(p[i - 1]))
566 i--;
567 p[i] = '\0';
568 do_defaults(p + 1, conf);
569 if (!conf_launchable(conf) && !do_config(conf)) {
570 cleanup_exit(0);
571 }
572 special_launchable_argument = true;
573 } else if (*p == '&') {
574 /*
575 * An initial & means we've been given a command line
576 * containing the hex value of a HANDLE for a file
577 * mapping object, which we must then interpret as a
578 * serialised Conf.
579 */
580 HANDLE filemap;
581 void *cp;
582 unsigned cpsize;
583 if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 &&
584 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
585 0, 0, cpsize)) != NULL) {
586 BinarySource src[1];
587 BinarySource_BARE_INIT(src, cp, cpsize);
588 if (!conf_deserialise(conf, src))
589 modalfatalbox("Serialised configuration data was invalid");
590 UnmapViewOfFile(cp);
591 CloseHandle(filemap);
592 } else if (!do_config(conf)) {
593 cleanup_exit(0);
594 }
595 special_launchable_argument = true;
596 } else if (!*p) {
597 /* Do-nothing case for an empty command line - or rather,
598 * for a command line that's empty _after_ we strip off
599 * the &R prefix. */
600 } else {
601 /*
602 * Otherwise, break up the command line and deal with
603 * it sensibly.
604 */
605 int argc, i;
606 char **argv;
607
608 split_into_argv(cmdline, &argc, &argv, NULL);
609
610 for (i = 0; i < argc; i++) {
611 char *p = argv[i];
612 int ret;
613
614 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
615 1, conf);
616 if (ret == -2) {
617 cmdline_error("option \"%s\" requires an argument", p);
618 } else if (ret == 2) {
619 i++; /* skip next argument */
620 } else if (ret == 1) {
621 continue; /* nothing further needs doing */
622 } else if (!strcmp(p, "-cleanup")) {
623 /*
624 * `putty -cleanup'. Remove all registry
625 * entries associated with PuTTY, and also find
626 * and delete the random seed file.
627 */
628 char *s1, *s2;
629 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
630 "associated with %s, and will also remove\n"
631 "the random seed file. (This only affects the\n"
632 "currently logged-in user.)\n"
633 "\n"
634 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
635 "Are you really sure you want to continue?",
636 appname);
637 s2 = dupprintf("%s Warning", appname);
638 if (message_box(NULL, s1, s2,
639 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
640 HELPCTXID(option_cleanup)) == IDYES) {
641 cleanup_all();
642 }
643 sfree(s1);
644 sfree(s2);
645 exit(0);
646 } else if (!strcmp(p, "-pgpfp")) {
647 pgp_fingerprints_msgbox(NULL);
648 exit(1);
649 } else if (*p != '-') {
650 cmdline_error("unexpected argument \"%s\"", p);
651 } else {
652 cmdline_error("unknown option \"%s\"", p);
653 }
654 }
655 }
656
657 cmdline_run_saved(conf);
658
659 /*
660 * Bring up the config dialog if the command line hasn't
661 * (explicitly) specified a launchable configuration.
662 */
663 if (!(special_launchable_argument || cmdline_host_ok(conf))) {
664 if (!do_config(conf))
665 cleanup_exit(0);
666 }
667
668 prepare_session(conf);
669 }
670
671 if (!prev) {
672 WNDCLASSW wndclass;
673
674 wndclass.style = 0;
675 wndclass.lpfnWndProc = WndProc;
676 wndclass.cbClsExtra = 0;
677 wndclass.cbWndExtra = 0;
678 wndclass.hInstance = inst;
679 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
680 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
681 wndclass.hbrBackground = NULL;
682 wndclass.lpszMenuName = NULL;
683 wndclass.lpszClassName = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
684
685 RegisterClassW(&wndclass);
686 }
687
688 memset(&ucsdata, 0, sizeof(ucsdata));
689
690 conf_cache_data();
691
692 /*
693 * Guess some defaults for the window size. This all gets
694 * updated later, so we don't really care too much. However, we
695 * do want the font width/height guesses to correspond to a
696 * large font rather than a small one...
697 */
698
699 font_width = 10;
700 font_height = 20;
701 extra_width = 25;
702 extra_height = 28;
703 guess_width = extra_width + font_width * conf_get_int(conf, CONF_width);
704 guess_height = extra_height + font_height*conf_get_int(conf, CONF_height);
705 {
706 RECT r;
707 get_fullscreen_rect(&r);
708 if (guess_width > r.right - r.left)
709 guess_width = r.right - r.left;
710 if (guess_height > r.bottom - r.top)
711 guess_height = r.bottom - r.top;
712 }
713
714 {
715 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
716 int exwinmode = 0;
717 const struct BackendVtable *vt =
718 backend_vt_from_proto(be_default_protocol);
719 bool resize_forbidden = false;
720 if (vt && vt->flags & BACKEND_RESIZE_FORBIDDEN)
721 resize_forbidden = true;
722 wchar_t *uappname = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
723 if (!conf_get_bool(conf, CONF_scrollbar))
724 winmode &= ~(WS_VSCROLL);
725 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED ||
726 resize_forbidden)
727 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
728 if (conf_get_bool(conf, CONF_alwaysontop))
729 exwinmode |= WS_EX_TOPMOST;
730 if (conf_get_bool(conf, CONF_sunken_edge))
731 exwinmode |= WS_EX_CLIENTEDGE;
732 wgs.term_hwnd = CreateWindowExW(
733 exwinmode, uappname, uappname, winmode, CW_USEDEFAULT,
734 CW_USEDEFAULT, guess_width, guess_height, NULL, NULL, inst, NULL);
735 memset(&dpi_info, 0, sizeof(struct _dpi_info));
736 init_dpi_info();
737 sfree(uappname);
738 }
739
740 /*
741 * Initialise the fonts, simultaneously correcting the guesses
742 * for font_{width,height}.
743 */
744 init_fonts(0,0);
745
746 /*
747 * Prepare a logical palette.
748 */
749 init_palette();
750
751 /*
752 * Initialise the terminal. (We have to do this _after_
753 * creating the window, since the terminal is the first thing
754 * which will call schedule_timer(), which will in turn call
755 * timer_change_notify() which will expect hwnd to exist.)
756 */
757 wintw->vt = &windows_termwin_vt;
758 term = term_init(conf, &ucsdata, wintw);
759 setup_clipboards(term, conf);
760 logctx = log_init(&wgs.logpolicy, conf);
761 term_provide_logctx(term, logctx);
762 term_size(term, conf_get_int(conf, CONF_height),
763 conf_get_int(conf, CONF_width),
764 conf_get_int(conf, CONF_savelines));
765
766 /*
767 * Correct the guesses for extra_{width,height}.
768 */
769 {
770 RECT cr, wr;
771 GetWindowRect(wgs.term_hwnd, &wr);
772 GetClientRect(wgs.term_hwnd, &cr);
773 offset_width = offset_height = conf_get_int(conf, CONF_window_border);
774 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
775 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
776 }
777
778 /*
779 * Resize the window, now we know what size we _really_ want it
780 * to be.
781 */
782 guess_width = extra_width + font_width * term->cols;
783 guess_height = extra_height + font_height * term->rows;
784 SetWindowPos(wgs.term_hwnd, NULL, 0, 0, guess_width, guess_height,
785 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
786
787 /*
788 * Set up a caret bitmap, with no content.
789 */
790 {
791 char *bits;
792 int size = (font_width + 15) / 16 * 2 * font_height;
793 bits = snewn(size, char);
794 memset(bits, 0, size);
795 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
796 sfree(bits);
797 }
798 CreateCaret(wgs.term_hwnd, caretbm, font_width, font_height);
799
800 /*
801 * Initialise the scroll bar.
802 */
803 {
804 SCROLLINFO si;
805
806 si.cbSize = sizeof(si);
807 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
808 si.nMin = 0;
809 si.nMax = term->rows - 1;
810 si.nPage = term->rows;
811 si.nPos = 0;
812 SetScrollInfo(wgs.term_hwnd, SB_VERT, &si, false);
813 }
814
815 /*
816 * Prepare the mouse handler.
817 */
818 lastact = MA_NOTHING;
819 lastbtn = MBT_NOTHING;
820 dbltime = GetDoubleClickTime();
821
822 /*
823 * Set up the session-control options on the system menu.
824 */
825 {
826 HMENU m;
827 int j;
828 char *str;
829
830 popup_menus[SYSMENU].menu = GetSystemMenu(wgs.term_hwnd, false);
831 popup_menus[CTXMENU].menu = CreatePopupMenu();
832 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_COPY, "&Copy");
833 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
834
835 savedsess_menu = CreateMenu();
836 get_sesslist(&sesslist, true);
837 update_savedsess_menu();
838
839 for (j = 0; j < lenof(popup_menus); j++) {
840 m = popup_menus[j].menu;
841
842 AppendMenu(m, MF_SEPARATOR, 0, 0);
843 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
844 AppendMenu(m, MF_SEPARATOR, 0, 0);
845 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
846 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
847 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT_PTR) savedsess_menu,
848 "Sa&ved Sessions");
849 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
850 AppendMenu(m, MF_SEPARATOR, 0, 0);
851 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
852 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
853 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
854 AppendMenu(m, MF_SEPARATOR, 0, 0);
855 AppendMenu(m, (conf_get_int(conf, CONF_resize_action)
856 == RESIZE_DISABLED) ? MF_GRAYED : MF_ENABLED,
857 IDM_FULLSCREEN, "&Full Screen");
858 AppendMenu(m, MF_SEPARATOR, 0, 0);
859 if (has_help())
860 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
861 str = dupprintf("&About %s", appname);
862 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
863 sfree(str);
864 }
865 }
866
867 if (restricted_acl()) {
868 lp_eventlog(&wgs.logpolicy, "Running with restricted process ACL");
869 }
870
871 winselgui_set_hwnd(wgs.term_hwnd);
872 start_backend();
873
874 /*
875 * Set up the initial input locale.
876 */
877 set_input_locale(GetKeyboardLayout(0));
878
879 /*
880 * Finally show the window!
881 */
882 ShowWindow(wgs.term_hwnd, show);
883 SetForegroundWindow(wgs.term_hwnd);
884
885 term_set_focus(term, GetForegroundWindow() == wgs.term_hwnd);
886 UpdateWindow(wgs.term_hwnd);
887
888 while (1) {
889 HANDLE *handles;
890 int nhandles, n;
891 DWORD timeout;
892
893 if (toplevel_callback_pending() ||
894 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
895 /*
896 * If we have anything we'd like to do immediately, set
897 * the timeout for MsgWaitForMultipleObjects to zero so
898 * that we'll only do a quick check of our handles and
899 * then get on with whatever that was.
900 *
901 * One such option is a pending toplevel callback. The
902 * other is a non-empty Windows message queue, which you'd
903 * think we could leave to MsgWaitForMultipleObjects to
904 * check for us along with all the handles, but in fact we
905 * can't because once PeekMessage in one iteration of this
906 * loop has removed a message from the queue, the whole
907 * queue is considered uninteresting by the next
908 * invocation of MWFMO. So we check ourselves whether the
909 * message queue is non-empty, and if so, set this timeout
910 * to zero to ensure MWFMO doesn't block.
911 */
912 timeout = 0;
913 } else {
914 timeout = INFINITE;
915 /* The messages seem unreliable; especially if we're being tricky */
916 term_set_focus(term, GetForegroundWindow() == wgs.term_hwnd);
917 }
918
919 handles = handle_get_events(&nhandles);
920
921 n = MsgWaitForMultipleObjects(nhandles, handles, false,
922 timeout, QS_ALLINPUT);
923
924 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
925 handle_got_event(handles[n - WAIT_OBJECT_0]);
926 sfree(handles);
927 } else
928 sfree(handles);
929
930 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
931 if (msg.message == WM_QUIT)
932 goto finished; /* two-level break */
933
934 HWND logbox = event_log_window();
935 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
936 DispatchMessageW(&msg);
937
938 /*
939 * WM_NETEVENT messages seem to jump ahead of others in
940 * the message queue. I'm not sure why; the docs for
941 * PeekMessage mention that messages are prioritised in
942 * some way, but I'm unclear on which priorities go where.
943 *
944 * Anyway, in practice I observe that WM_NETEVENT seems to
945 * jump to the head of the queue, which means that if we
946 * were to only process one message every time round this
947 * loop, we'd get nothing but NETEVENTs if the server
948 * flooded us with data, and stop responding to any other
949 * kind of window message. So instead, we keep on round
950 * this loop until we've consumed at least one message
951 * that _isn't_ a NETEVENT, or run out of messages
952 * completely (whichever comes first). And we don't go to
953 * run_toplevel_callbacks (which is where the netevents
954 * are actually processed, causing fresh NETEVENT messages
955 * to appear) until we've done this.
956 */
957 if (msg.message != WM_NETEVENT)
958 break;
959 }
960
961 run_toplevel_callbacks();
962 }
963
964 finished:
965 cleanup_exit(msg.wParam); /* this doesn't return... */
966 return msg.wParam; /* ... but optimiser doesn't know */
967 }
968
setup_clipboards(Terminal * term,Conf * conf)969 static void setup_clipboards(Terminal *term, Conf *conf)
970 {
971 assert(term->mouse_select_clipboards[0] == CLIP_LOCAL);
972
973 term->n_mouse_select_clipboards = 1;
974
975 if (conf_get_bool(conf, CONF_mouseautocopy)) {
976 term->mouse_select_clipboards[
977 term->n_mouse_select_clipboards++] = CLIP_SYSTEM;
978 }
979
980 switch (conf_get_int(conf, CONF_mousepaste)) {
981 case CLIPUI_IMPLICIT:
982 term->mouse_paste_clipboard = CLIP_LOCAL;
983 break;
984 case CLIPUI_EXPLICIT:
985 term->mouse_paste_clipboard = CLIP_SYSTEM;
986 break;
987 default:
988 term->mouse_paste_clipboard = CLIP_NULL;
989 break;
990 }
991 }
992
993 /*
994 * Clean up and exit.
995 */
cleanup_exit(int code)996 void cleanup_exit(int code)
997 {
998 /*
999 * Clean up.
1000 */
1001 deinit_fonts();
1002 sfree(logpal);
1003 if (pal)
1004 DeleteObject(pal);
1005 sk_cleanup();
1006
1007 if (conf_get_int(conf, CONF_protocol) == PROT_SSH) {
1008 random_save_seed();
1009 }
1010 shutdown_help();
1011
1012 /* Clean up COM. */
1013 CoUninitialize();
1014
1015 exit(code);
1016 }
1017
1018 /*
1019 * Refresh the saved-session submenu from `sesslist'.
1020 */
update_savedsess_menu(void)1021 static void update_savedsess_menu(void)
1022 {
1023 int i;
1024 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
1025 /* skip sesslist.sessions[0] == Default Settings */
1026 for (i = 1;
1027 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
1028 : MENU_SAVED_MAX+1);
1029 i++)
1030 AppendMenu(savedsess_menu, MF_ENABLED,
1031 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
1032 sesslist.sessions[i]);
1033 if (sesslist.nsessions <= 1)
1034 AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");
1035 }
1036
1037 /*
1038 * Update the Special Commands submenu.
1039 */
win_seat_update_specials_menu(Seat * seat)1040 static void win_seat_update_specials_menu(Seat *seat)
1041 {
1042 HMENU new_menu;
1043 int i, j;
1044
1045 if (backend)
1046 specials = backend_get_specials(backend);
1047 else
1048 specials = NULL;
1049
1050 if (specials) {
1051 /* We can't use Windows to provide a stack for submenus, so
1052 * here's a lame "stack" that will do for now. */
1053 HMENU saved_menu = NULL;
1054 int nesting = 1;
1055 new_menu = CreatePopupMenu();
1056 for (i = 0; nesting > 0; i++) {
1057 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
1058 switch (specials[i].code) {
1059 case SS_SEP:
1060 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
1061 break;
1062 case SS_SUBMENU:
1063 assert(nesting < 2);
1064 nesting++;
1065 saved_menu = new_menu; /* XXX lame stacking */
1066 new_menu = CreatePopupMenu();
1067 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
1068 (UINT_PTR) new_menu, specials[i].name);
1069 break;
1070 case SS_EXITMENU:
1071 nesting--;
1072 if (nesting) {
1073 new_menu = saved_menu; /* XXX lame stacking */
1074 saved_menu = NULL;
1075 }
1076 break;
1077 default:
1078 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
1079 specials[i].name);
1080 break;
1081 }
1082 }
1083 /* Squirrel the highest special. */
1084 n_specials = i - 1;
1085 } else {
1086 new_menu = NULL;
1087 n_specials = 0;
1088 }
1089
1090 for (j = 0; j < lenof(popup_menus); j++) {
1091 if (specials_menu) {
1092 /* XXX does this free up all submenus? */
1093 DeleteMenu(popup_menus[j].menu, (UINT_PTR)specials_menu,
1094 MF_BYCOMMAND);
1095 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
1096 }
1097 if (new_menu) {
1098 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1099 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
1100 (UINT_PTR) new_menu, "S&pecial Command");
1101 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1102 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
1103 }
1104 }
1105 specials_menu = new_menu;
1106 }
1107
update_mouse_pointer(void)1108 static void update_mouse_pointer(void)
1109 {
1110 LPTSTR curstype = NULL;
1111 bool force_visible = false;
1112 static bool forced_visible = false;
1113 switch (busy_status) {
1114 case BUSY_NOT:
1115 if (pointer_indicates_raw_mouse)
1116 curstype = IDC_ARROW;
1117 else
1118 curstype = IDC_IBEAM;
1119 break;
1120 case BUSY_WAITING:
1121 curstype = IDC_APPSTARTING; /* this may be an abuse */
1122 force_visible = true;
1123 break;
1124 case BUSY_CPU:
1125 curstype = IDC_WAIT;
1126 force_visible = true;
1127 break;
1128 default:
1129 unreachable("Bad busy_status");
1130 }
1131 {
1132 HCURSOR cursor = LoadCursor(NULL, curstype);
1133 SetClassLongPtr(wgs.term_hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1134 SetCursor(cursor); /* force redraw of cursor at current posn */
1135 }
1136 if (force_visible != forced_visible) {
1137 /* We want some cursor shapes to be visible always.
1138 * Along with show_mouseptr(), this manages the ShowCursor()
1139 * counter such that if we switch back to a non-force_visible
1140 * cursor, the previous visibility state is restored. */
1141 ShowCursor(force_visible);
1142 forced_visible = force_visible;
1143 }
1144 }
1145
win_seat_set_busy_status(Seat * seat,BusyStatus status)1146 static void win_seat_set_busy_status(Seat *seat, BusyStatus status)
1147 {
1148 busy_status = status;
1149 update_mouse_pointer();
1150 }
1151
wintw_set_raw_mouse_mode(TermWin * tw,bool activate)1152 static void wintw_set_raw_mouse_mode(TermWin *tw, bool activate)
1153 {
1154 send_raw_mouse = activate;
1155 }
1156
wintw_set_raw_mouse_mode_pointer(TermWin * tw,bool activate)1157 static void wintw_set_raw_mouse_mode_pointer(TermWin *tw, bool activate)
1158 {
1159 pointer_indicates_raw_mouse = activate;
1160 update_mouse_pointer();
1161 }
1162
1163 /*
1164 * Print a message box and close the connection.
1165 */
win_seat_connection_fatal(Seat * seat,const char * msg)1166 static void win_seat_connection_fatal(Seat *seat, const char *msg)
1167 {
1168 char *title = dupprintf("%s Fatal Error", appname);
1169 show_mouseptr(true);
1170 MessageBox(wgs.term_hwnd, msg, title, MB_ICONERROR | MB_OK);
1171 sfree(title);
1172
1173 if (conf_get_int(conf, CONF_close_on_exit) == FORCE_ON)
1174 PostQuitMessage(1);
1175 else {
1176 queue_toplevel_callback(close_session, NULL);
1177 }
1178 }
1179
1180 /*
1181 * Report an error at the command-line parsing stage.
1182 */
cmdline_error(const char * fmt,...)1183 void cmdline_error(const char *fmt, ...)
1184 {
1185 va_list ap;
1186 char *message, *title;
1187
1188 va_start(ap, fmt);
1189 message = dupvprintf(fmt, ap);
1190 va_end(ap);
1191 title = dupprintf("%s Command Line Error", appname);
1192 MessageBox(wgs.term_hwnd, message, title, MB_ICONERROR | MB_OK);
1193 sfree(message);
1194 sfree(title);
1195 exit(1);
1196 }
1197
1198 /*
1199 * Actually do the job requested by a WM_NETEVENT
1200 */
wm_netevent_callback(void * vctx)1201 static void wm_netevent_callback(void *vctx)
1202 {
1203 struct wm_netevent_params *params = (struct wm_netevent_params *)vctx;
1204 select_result(params->wParam, params->lParam);
1205 sfree(vctx);
1206 }
1207
rgb_from_colorref(COLORREF cr)1208 static inline rgb rgb_from_colorref(COLORREF cr)
1209 {
1210 rgb toret;
1211 toret.r = GetRValue(cr);
1212 toret.g = GetGValue(cr);
1213 toret.b = GetBValue(cr);
1214 return toret;
1215 }
1216
wintw_palette_get_overrides(TermWin * tw,Terminal * term)1217 static void wintw_palette_get_overrides(TermWin *tw, Terminal *term)
1218 {
1219 if (conf_get_bool(conf, CONF_system_colour)) {
1220 rgb rgb;
1221
1222 rgb = rgb_from_colorref(GetSysColor(COLOR_WINDOWTEXT));
1223 term_palette_override(term, OSC4_COLOUR_fg, rgb);
1224 term_palette_override(term, OSC4_COLOUR_fg_bold, rgb);
1225
1226 rgb = rgb_from_colorref(GetSysColor(COLOR_WINDOW));
1227 term_palette_override(term, OSC4_COLOUR_bg, rgb);
1228 term_palette_override(term, OSC4_COLOUR_bg_bold, rgb);
1229
1230 rgb = rgb_from_colorref(GetSysColor(COLOR_HIGHLIGHTTEXT));
1231 term_palette_override(term, OSC4_COLOUR_cursor_fg, rgb);
1232
1233 rgb = rgb_from_colorref(GetSysColor(COLOR_HIGHLIGHT));
1234 term_palette_override(term, OSC4_COLOUR_cursor_bg, rgb);
1235 }
1236 }
1237
1238 /*
1239 * This is a wrapper to ExtTextOut() to force Windows to display
1240 * the precise glyphs we give it. Otherwise it would do its own
1241 * bidi and Arabic shaping, and we would end up uncertain which
1242 * characters it had put where.
1243 */
exact_textout(HDC hdc,int x,int y,CONST RECT * lprc,unsigned short * lpString,UINT cbCount,CONST INT * lpDx,bool opaque)1244 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1245 unsigned short *lpString, UINT cbCount,
1246 CONST INT *lpDx, bool opaque)
1247 {
1248 #ifdef __LCC__
1249 /*
1250 * The LCC include files apparently don't supply the
1251 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1252 * proper: the differences aren't important to us (the only
1253 * variable-width string parameter is one we don't use anyway).
1254 */
1255 GCP_RESULTS gcpr;
1256 #else
1257 GCP_RESULTSW gcpr;
1258 #endif
1259 char *buffer = snewn(cbCount*2+2, char);
1260 char *classbuffer = snewn(cbCount, char);
1261 memset(&gcpr, 0, sizeof(gcpr));
1262 memset(buffer, 0, cbCount*2+2);
1263 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1264
1265 gcpr.lStructSize = sizeof(gcpr);
1266 gcpr.lpGlyphs = (void *)buffer;
1267 gcpr.lpClass = (void *)classbuffer;
1268 gcpr.nGlyphs = cbCount;
1269 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1270 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1271
1272 ExtTextOut(hdc, x, y,
1273 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1274 lprc, buffer, cbCount, lpDx);
1275 }
1276
1277 /*
1278 * The exact_textout() wrapper, unfortunately, destroys the useful
1279 * Windows `font linking' behaviour: automatic handling of Unicode
1280 * code points not supported in this font by falling back to a font
1281 * which does contain them. Therefore, we adopt a multi-layered
1282 * approach: for any potentially-bidi text, we use exact_textout(),
1283 * and for everything else we use a simple ExtTextOut as we did
1284 * before exact_textout() was introduced.
1285 */
general_textout(HDC hdc,int x,int y,CONST RECT * lprc,unsigned short * lpString,UINT cbCount,CONST INT * lpDx,bool opaque)1286 static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1287 unsigned short *lpString, UINT cbCount,
1288 CONST INT *lpDx, bool opaque)
1289 {
1290 int i, j, xp, xn;
1291 int bkmode = 0;
1292 bool got_bkmode = false;
1293
1294 xp = xn = x;
1295
1296 for (i = 0; i < (int)cbCount ;) {
1297 bool rtl = is_rtl(lpString[i]);
1298
1299 xn += lpDx[i];
1300
1301 for (j = i+1; j < (int)cbCount; j++) {
1302 if (rtl != is_rtl(lpString[j]))
1303 break;
1304 xn += lpDx[j];
1305 }
1306
1307 /*
1308 * Now [i,j) indicates a maximal substring of lpString
1309 * which should be displayed using the same textout
1310 * function.
1311 */
1312 if (rtl) {
1313 exact_textout(hdc, xp, y, lprc, lpString+i, j-i,
1314 font_varpitch ? NULL : lpDx+i, opaque);
1315 } else {
1316 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1317 lprc, lpString+i, j-i,
1318 font_varpitch ? NULL : lpDx+i);
1319 }
1320
1321 i = j;
1322 xp = xn;
1323
1324 bkmode = GetBkMode(hdc);
1325 got_bkmode = true;
1326 SetBkMode(hdc, TRANSPARENT);
1327 opaque = false;
1328 }
1329
1330 if (got_bkmode)
1331 SetBkMode(hdc, bkmode);
1332 }
1333
get_font_width(HDC hdc,const TEXTMETRIC * tm)1334 static int get_font_width(HDC hdc, const TEXTMETRIC *tm)
1335 {
1336 int ret;
1337 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1338 if (!(tm->tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1339 ret = tm->tmAveCharWidth;
1340 } else {
1341 #define FIRST '0'
1342 #define LAST '9'
1343 ABCFLOAT widths[LAST-FIRST + 1];
1344 int j;
1345
1346 font_varpitch = true;
1347 font_dualwidth = true;
1348 if (GetCharABCWidthsFloat(hdc, FIRST, LAST, widths)) {
1349 ret = 0;
1350 for (j = 0; j < lenof(widths); j++) {
1351 int width = (int)(0.5 + widths[j].abcfA +
1352 widths[j].abcfB + widths[j].abcfC);
1353 if (ret < width)
1354 ret = width;
1355 }
1356 } else {
1357 ret = tm->tmMaxCharWidth;
1358 }
1359 #undef FIRST
1360 #undef LAST
1361 }
1362 return ret;
1363 }
1364
init_dpi_info(void)1365 static void init_dpi_info(void)
1366 {
1367 if (dpi_info.cur_dpi.x == 0 || dpi_info.cur_dpi.y == 0) {
1368 if (p_GetDpiForMonitor) {
1369 UINT dpiX, dpiY;
1370 HMONITOR currentMonitor = MonitorFromWindow(
1371 wgs.term_hwnd, MONITOR_DEFAULTTOPRIMARY);
1372 if (p_GetDpiForMonitor(currentMonitor, MDT_EFFECTIVE_DPI,
1373 &dpiX, &dpiY) == S_OK) {
1374 dpi_info.cur_dpi.x = (int)dpiX;
1375 dpi_info.cur_dpi.y = (int)dpiY;
1376 }
1377 }
1378
1379 /* Fall back to system DPI */
1380 if (dpi_info.cur_dpi.x == 0 || dpi_info.cur_dpi.y == 0) {
1381 HDC hdc = GetDC(wgs.term_hwnd);
1382 dpi_info.cur_dpi.x = GetDeviceCaps(hdc, LOGPIXELSX);
1383 dpi_info.cur_dpi.y = GetDeviceCaps(hdc, LOGPIXELSY);
1384 ReleaseDC(wgs.term_hwnd, hdc);
1385 }
1386 }
1387 }
1388
1389 /*
1390 * Initialise all the fonts we will need initially. There may be as many as
1391 * three or as few as one. The other (potentially) twenty-one fonts are done
1392 * if/when they are needed.
1393 *
1394 * We also:
1395 *
1396 * - check the font width and height, correcting our guesses if
1397 * necessary.
1398 *
1399 * - verify that the bold font is the same width as the ordinary
1400 * one, and engage shadow bolding if not.
1401 *
1402 * - verify that the underlined font is the same width as the
1403 * ordinary one (manual underlining by means of line drawing can
1404 * be done in a pinch).
1405 *
1406 * - find a trust sigil icon that will look OK with the chosen font.
1407 */
init_fonts(int pick_width,int pick_height)1408 static void init_fonts(int pick_width, int pick_height)
1409 {
1410 TEXTMETRIC tm;
1411 OUTLINETEXTMETRIC otm;
1412 CPINFO cpinfo;
1413 FontSpec *font;
1414 int fontsize[3];
1415 int i;
1416 int quality;
1417 HDC hdc;
1418 int fw_dontcare, fw_bold;
1419
1420 for (i = 0; i < FONT_MAXNO; i++)
1421 fonts[i] = NULL;
1422
1423 bold_font_mode = conf_get_int(conf, CONF_bold_style) & 1 ?
1424 BOLD_FONT : BOLD_NONE;
1425 bold_colours = conf_get_int(conf, CONF_bold_style) & 2 ? true : false;
1426 und_mode = UND_FONT;
1427
1428 font = conf_get_fontspec(conf, CONF_font);
1429 if (font->isbold) {
1430 fw_dontcare = FW_BOLD;
1431 fw_bold = FW_HEAVY;
1432 } else {
1433 fw_dontcare = FW_DONTCARE;
1434 fw_bold = FW_BOLD;
1435 }
1436
1437 hdc = GetDC(wgs.term_hwnd);
1438
1439 if (pick_height)
1440 font_height = pick_height;
1441 else {
1442 font_height = font->height;
1443 if (font_height > 0) {
1444 font_height =
1445 -MulDiv(font_height, dpi_info.cur_dpi.y, 72);
1446 }
1447 }
1448 font_width = pick_width;
1449
1450 quality = conf_get_int(conf, CONF_font_quality);
1451 #define f(i,c,w,u) \
1452 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, false, u, false, \
1453 c, OUT_DEFAULT_PRECIS, \
1454 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \
1455 FIXED_PITCH | FF_DONTCARE, font->name)
1456
1457 f(FONT_NORMAL, font->charset, fw_dontcare, false);
1458
1459 SelectObject(hdc, fonts[FONT_NORMAL]);
1460 GetTextMetrics(hdc, &tm);
1461 if (GetOutlineTextMetrics(hdc, sizeof(otm), &otm))
1462 font_strikethrough_y = tm.tmAscent - otm.otmsStrikeoutPosition;
1463 else
1464 font_strikethrough_y = tm.tmAscent - (tm.tmAscent * 3 / 8);
1465
1466 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1467
1468 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1469 if (!(tm.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1470 font_varpitch = false;
1471 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1472 } else {
1473 font_varpitch = true;
1474 font_dualwidth = true;
1475 }
1476 if (pick_width == 0 || pick_height == 0) {
1477 font_height = tm.tmHeight;
1478 font_width = get_font_width(hdc, &tm);
1479 }
1480
1481 #ifdef RDB_DEBUG_PATCH
1482 debug("Primary font H=%d, AW=%d, MW=%d\n",
1483 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1484 #endif
1485
1486 {
1487 CHARSETINFO info;
1488 DWORD cset = tm.tmCharSet;
1489 memset(&info, 0xFF, sizeof(info));
1490
1491 /* !!! Yes the next line is right */
1492 if (cset == OEM_CHARSET)
1493 ucsdata.font_codepage = GetOEMCP();
1494 else
1495 if (TranslateCharsetInfo ((DWORD *)(ULONG_PTR)cset,
1496 &info, TCI_SRCCHARSET))
1497 ucsdata.font_codepage = info.ciACP;
1498 else
1499 ucsdata.font_codepage = -1;
1500
1501 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1502 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1503 }
1504
1505 f(FONT_UNDERLINE, font->charset, fw_dontcare, true);
1506
1507 /*
1508 * Some fonts, e.g. 9-pt Courier, draw their underlines
1509 * outside their character cell. We successfully prevent
1510 * screen corruption by clipping the text output, but then
1511 * we lose the underline completely. Here we try to work
1512 * out whether this is such a font, and if it is, we set a
1513 * flag that causes underlines to be drawn by hand.
1514 *
1515 * Having tried other more sophisticated approaches (such
1516 * as examining the TEXTMETRIC structure or requesting the
1517 * height of a string), I think we'll do this the brute
1518 * force way: we create a small bitmap, draw an underlined
1519 * space on it, and test to see whether any pixels are
1520 * foreground-coloured. (Since we expect the underline to
1521 * go all the way across the character cell, we only search
1522 * down a single column of the bitmap, half way across.)
1523 */
1524 {
1525 HDC und_dc;
1526 HBITMAP und_bm, und_oldbm;
1527 int i;
1528 bool gotit;
1529 COLORREF c;
1530
1531 und_dc = CreateCompatibleDC(hdc);
1532 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1533 und_oldbm = SelectObject(und_dc, und_bm);
1534 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1535 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1536 SetTextColor(und_dc, RGB(255, 255, 255));
1537 SetBkColor(und_dc, RGB(0, 0, 0));
1538 SetBkMode(und_dc, OPAQUE);
1539 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1540 gotit = false;
1541 for (i = 0; i < font_height; i++) {
1542 c = GetPixel(und_dc, font_width / 2, i);
1543 if (c != RGB(0, 0, 0))
1544 gotit = true;
1545 }
1546 SelectObject(und_dc, und_oldbm);
1547 DeleteObject(und_bm);
1548 DeleteDC(und_dc);
1549 if (!gotit) {
1550 und_mode = UND_LINE;
1551 DeleteObject(fonts[FONT_UNDERLINE]);
1552 fonts[FONT_UNDERLINE] = 0;
1553 }
1554 }
1555
1556 if (bold_font_mode == BOLD_FONT) {
1557 f(FONT_BOLD, font->charset, fw_bold, false);
1558 }
1559 #undef f
1560
1561 descent = tm.tmAscent + 1;
1562 if (descent >= font_height)
1563 descent = font_height - 1;
1564
1565 for (i = 0; i < 3; i++) {
1566 if (fonts[i]) {
1567 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1568 fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight;
1569 else
1570 fontsize[i] = -i;
1571 } else
1572 fontsize[i] = -i;
1573 }
1574
1575 ReleaseDC(wgs.term_hwnd, hdc);
1576
1577 if (trust_icon != INVALID_HANDLE_VALUE) {
1578 DestroyIcon(trust_icon);
1579 }
1580 trust_icon = LoadImage(hinst, MAKEINTRESOURCE(IDI_MAINICON),
1581 IMAGE_ICON, font_width*2, font_height,
1582 LR_DEFAULTCOLOR);
1583
1584 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1585 und_mode = UND_LINE;
1586 DeleteObject(fonts[FONT_UNDERLINE]);
1587 fonts[FONT_UNDERLINE] = 0;
1588 }
1589
1590 if (bold_font_mode == BOLD_FONT &&
1591 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1592 bold_font_mode = BOLD_SHADOW;
1593 DeleteObject(fonts[FONT_BOLD]);
1594 fonts[FONT_BOLD] = 0;
1595 }
1596 fontflag[0] = true;
1597 fontflag[1] = true;
1598 fontflag[2] = true;
1599
1600 init_ucs(conf, &ucsdata);
1601 }
1602
another_font(int fontno)1603 static void another_font(int fontno)
1604 {
1605 int basefont;
1606 int fw_dontcare, fw_bold, quality;
1607 int c, w, x;
1608 bool u;
1609 char *s;
1610 FontSpec *font;
1611
1612 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1613 return;
1614
1615 basefont = (fontno & ~(FONT_BOLDUND));
1616 if (basefont != fontno && !fontflag[basefont])
1617 another_font(basefont);
1618
1619 font = conf_get_fontspec(conf, CONF_font);
1620
1621 if (font->isbold) {
1622 fw_dontcare = FW_BOLD;
1623 fw_bold = FW_HEAVY;
1624 } else {
1625 fw_dontcare = FW_DONTCARE;
1626 fw_bold = FW_BOLD;
1627 }
1628
1629 c = font->charset;
1630 w = fw_dontcare;
1631 u = false;
1632 s = font->name;
1633 x = font_width;
1634
1635 if (fontno & FONT_WIDE)
1636 x *= 2;
1637 if (fontno & FONT_NARROW)
1638 x = (x+1)/2;
1639 if (fontno & FONT_OEM)
1640 c = OEM_CHARSET;
1641 if (fontno & FONT_BOLD)
1642 w = fw_bold;
1643 if (fontno & FONT_UNDERLINE)
1644 u = true;
1645
1646 quality = conf_get_int(conf, CONF_font_quality);
1647
1648 fonts[fontno] =
1649 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1650 false, u, false, c, OUT_DEFAULT_PRECIS,
1651 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality),
1652 DEFAULT_PITCH | FF_DONTCARE, s);
1653
1654 fontflag[fontno] = true;
1655 }
1656
deinit_fonts(void)1657 static void deinit_fonts(void)
1658 {
1659 int i;
1660 for (i = 0; i < FONT_MAXNO; i++) {
1661 if (fonts[i])
1662 DeleteObject(fonts[i]);
1663 fonts[i] = 0;
1664 fontflag[i] = false;
1665 }
1666
1667 if (trust_icon != INVALID_HANDLE_VALUE) {
1668 DestroyIcon(trust_icon);
1669 }
1670 trust_icon = INVALID_HANDLE_VALUE;
1671 }
1672
wintw_request_resize(TermWin * tw,int w,int h)1673 static void wintw_request_resize(TermWin *tw, int w, int h)
1674 {
1675 const struct BackendVtable *vt;
1676 int width, height;
1677
1678 /* If the window is maximized suppress resizing attempts */
1679 if (IsZoomed(wgs.term_hwnd)) {
1680 if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM)
1681 return;
1682 }
1683
1684 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) return;
1685 vt = backend_vt_from_proto(be_default_protocol);
1686 if (vt && vt->flags & BACKEND_RESIZE_FORBIDDEN)
1687 return;
1688 if (h == term->rows && w == term->cols) return;
1689
1690 /* Sanity checks ... */
1691 {
1692 static int first_time = 1;
1693 static RECT ss;
1694
1695 switch (first_time) {
1696 case 1:
1697 /* Get the size of the screen */
1698 if (get_fullscreen_rect(&ss))
1699 /* first_time = 0 */ ;
1700 else {
1701 first_time = 2;
1702 break;
1703 }
1704 case 0:
1705 /* Make sure the values are sane */
1706 width = (ss.right - ss.left - extra_width) / 4;
1707 height = (ss.bottom - ss.top - extra_height) / 6;
1708
1709 if (w > width || h > height)
1710 return;
1711 if (w < 15)
1712 w = 15;
1713 if (h < 1)
1714 h = 1;
1715 }
1716 }
1717
1718 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
1719
1720 if (conf_get_int(conf, CONF_resize_action) != RESIZE_FONT &&
1721 !IsZoomed(wgs.term_hwnd)) {
1722 width = extra_width + font_width * w;
1723 height = extra_height + font_height * h;
1724
1725 SetWindowPos(wgs.term_hwnd, NULL, 0, 0, width, height,
1726 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1727 SWP_NOMOVE | SWP_NOZORDER);
1728 } else
1729 reset_window(0);
1730
1731 InvalidateRect(wgs.term_hwnd, NULL, true);
1732 }
1733
recompute_window_offset(void)1734 static void recompute_window_offset(void)
1735 {
1736 RECT cr;
1737 GetClientRect(wgs.term_hwnd, &cr);
1738
1739 int win_width = cr.right - cr.left;
1740 int win_height = cr.bottom - cr.top;
1741
1742 int new_offset_width = (win_width-font_width*term->cols)/2;
1743 int new_offset_height = (win_height-font_height*term->rows)/2;
1744
1745 if (offset_width != new_offset_width ||
1746 offset_height != new_offset_height) {
1747 offset_width = new_offset_width;
1748 offset_height = new_offset_height;
1749 InvalidateRect(wgs.term_hwnd, NULL, true);
1750 }
1751 }
1752
reset_window(int reinit)1753 static void reset_window(int reinit) {
1754 /*
1755 * This function decides how to resize or redraw when the
1756 * user changes something.
1757 *
1758 * This function doesn't like to change the terminal size but if the
1759 * font size is locked that may be it's only soluion.
1760 */
1761 int win_width, win_height, resize_action, window_border;
1762 RECT cr, wr;
1763
1764 #ifdef RDB_DEBUG_PATCH
1765 debug("reset_window()\n");
1766 #endif
1767
1768 /* Current window sizes ... */
1769 GetWindowRect(wgs.term_hwnd, &wr);
1770 GetClientRect(wgs.term_hwnd, &cr);
1771
1772 win_width = cr.right - cr.left;
1773 win_height = cr.bottom - cr.top;
1774
1775 resize_action = conf_get_int(conf, CONF_resize_action);
1776 window_border = conf_get_int(conf, CONF_window_border);
1777
1778 if (resize_action == RESIZE_DISABLED)
1779 reinit = 2;
1780
1781 /* Are we being forced to reload the fonts ? */
1782 if (reinit>1) {
1783 #ifdef RDB_DEBUG_PATCH
1784 debug("reset_window() -- Forced deinit\n");
1785 #endif
1786 deinit_fonts();
1787 init_fonts(0,0);
1788 }
1789
1790 /* Oh, looks like we're minimised */
1791 if (win_width == 0 || win_height == 0)
1792 return;
1793
1794 /* Is the window out of position ? */
1795 if (!reinit) {
1796 recompute_window_offset();
1797 #ifdef RDB_DEBUG_PATCH
1798 debug("reset_window() -> Reposition terminal\n");
1799 #endif
1800 }
1801
1802 if (IsZoomed(wgs.term_hwnd)) {
1803 /* We're fullscreen, this means we must not change the size of
1804 * the window so it's the font size or the terminal itself.
1805 */
1806
1807 extra_width = wr.right - wr.left - cr.right + cr.left;
1808 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1809
1810 if (resize_action != RESIZE_TERM) {
1811 if (font_width != win_width/term->cols ||
1812 font_height != win_height/term->rows) {
1813 deinit_fonts();
1814 init_fonts(win_width/term->cols, win_height/term->rows);
1815 offset_width = (win_width-font_width*term->cols)/2;
1816 offset_height = (win_height-font_height*term->rows)/2;
1817 InvalidateRect(wgs.term_hwnd, NULL, true);
1818 #ifdef RDB_DEBUG_PATCH
1819 debug("reset_window() -> Z font resize to (%d, %d)\n",
1820 font_width, font_height);
1821 #endif
1822 }
1823 } else {
1824 if (font_width * term->cols != win_width ||
1825 font_height * term->rows != win_height) {
1826 /* Our only choice at this point is to change the
1827 * size of the terminal; Oh well.
1828 */
1829 term_size(term, win_height/font_height, win_width/font_width,
1830 conf_get_int(conf, CONF_savelines));
1831 offset_width = (win_width-font_width*term->cols)/2;
1832 offset_height = (win_height-font_height*term->rows)/2;
1833 InvalidateRect(wgs.term_hwnd, NULL, true);
1834 #ifdef RDB_DEBUG_PATCH
1835 debug("reset_window() -> Zoomed term_size\n");
1836 #endif
1837 }
1838 }
1839 return;
1840 }
1841
1842 /* Resize window after DPI change */
1843 if (reinit == 3 && p_GetSystemMetricsForDpi && p_AdjustWindowRectExForDpi) {
1844 RECT rect;
1845 rect.left = rect.top = 0;
1846 rect.right = (font_width * term->cols);
1847 if (conf_get_bool(conf, CONF_scrollbar))
1848 rect.right += p_GetSystemMetricsForDpi(SM_CXVSCROLL,
1849 dpi_info.cur_dpi.x);
1850 rect.bottom = (font_height * term->rows);
1851 p_AdjustWindowRectExForDpi(
1852 &rect, GetWindowLongPtr(wgs.term_hwnd, GWL_STYLE),
1853 FALSE, GetWindowLongPtr(wgs.term_hwnd, GWL_EXSTYLE),
1854 dpi_info.cur_dpi.x);
1855 rect.right += (window_border * 2);
1856 rect.bottom += (window_border * 2);
1857 OffsetRect(&dpi_info.new_wnd_rect,
1858 ((dpi_info.new_wnd_rect.right - dpi_info.new_wnd_rect.left) -
1859 (rect.right - rect.left)) / 2,
1860 ((dpi_info.new_wnd_rect.bottom - dpi_info.new_wnd_rect.top) -
1861 (rect.bottom - rect.top)) / 2);
1862 SetWindowPos(wgs.term_hwnd, NULL,
1863 dpi_info.new_wnd_rect.left, dpi_info.new_wnd_rect.top,
1864 rect.right - rect.left, rect.bottom - rect.top,
1865 SWP_NOZORDER);
1866
1867 InvalidateRect(wgs.term_hwnd, NULL, true);
1868 return;
1869 }
1870
1871 /* Hmm, a force re-init means we should ignore the current window
1872 * so we resize to the default font size.
1873 */
1874 if (reinit>0) {
1875 #ifdef RDB_DEBUG_PATCH
1876 debug("reset_window() -> Forced re-init\n");
1877 #endif
1878
1879 offset_width = offset_height = window_border;
1880 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1881 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1882
1883 if (win_width != font_width*term->cols + offset_width*2 ||
1884 win_height != font_height*term->rows + offset_height*2) {
1885
1886 /* If this is too large windows will resize it to the maximum
1887 * allowed window size, we will then be back in here and resize
1888 * the font or terminal to fit.
1889 */
1890 SetWindowPos(wgs.term_hwnd, NULL, 0, 0,
1891 font_width*term->cols + extra_width,
1892 font_height*term->rows + extra_height,
1893 SWP_NOMOVE | SWP_NOZORDER);
1894 }
1895
1896 InvalidateRect(wgs.term_hwnd, NULL, true);
1897 return;
1898 }
1899
1900 /* Okay the user doesn't want us to change the font so we try the
1901 * window. But that may be too big for the screen which forces us
1902 * to change the terminal.
1903 */
1904 if ((resize_action == RESIZE_TERM && reinit<=0) ||
1905 (resize_action == RESIZE_EITHER && reinit<0) ||
1906 reinit>0) {
1907 offset_width = offset_height = window_border;
1908 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1909 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1910
1911 if (win_width != font_width*term->cols + offset_width*2 ||
1912 win_height != font_height*term->rows + offset_height*2) {
1913
1914 static RECT ss;
1915 int width, height;
1916
1917 get_fullscreen_rect(&ss);
1918
1919 width = (ss.right - ss.left - extra_width) / font_width;
1920 height = (ss.bottom - ss.top - extra_height) / font_height;
1921
1922 /* Grrr too big */
1923 if ( term->rows > height || term->cols > width ) {
1924 if (resize_action == RESIZE_EITHER) {
1925 /* Make the font the biggest we can */
1926 if (term->cols > width)
1927 font_width = (ss.right - ss.left - extra_width)
1928 / term->cols;
1929 if (term->rows > height)
1930 font_height = (ss.bottom - ss.top - extra_height)
1931 / term->rows;
1932
1933 deinit_fonts();
1934 init_fonts(font_width, font_height);
1935
1936 width = (ss.right - ss.left - extra_width) / font_width;
1937 height = (ss.bottom - ss.top - extra_height) / font_height;
1938 } else {
1939 if ( height > term->rows ) height = term->rows;
1940 if ( width > term->cols ) width = term->cols;
1941 term_size(term, height, width,
1942 conf_get_int(conf, CONF_savelines));
1943 #ifdef RDB_DEBUG_PATCH
1944 debug("reset_window() -> term resize to (%d,%d)\n",
1945 height, width);
1946 #endif
1947 }
1948 }
1949
1950 SetWindowPos(wgs.term_hwnd, NULL, 0, 0,
1951 font_width*term->cols + extra_width,
1952 font_height*term->rows + extra_height,
1953 SWP_NOMOVE | SWP_NOZORDER);
1954
1955 InvalidateRect(wgs.term_hwnd, NULL, true);
1956 #ifdef RDB_DEBUG_PATCH
1957 debug("reset_window() -> window resize to (%d,%d)\n",
1958 font_width*term->cols + extra_width,
1959 font_height*term->rows + extra_height);
1960 #endif
1961 }
1962 return;
1963 }
1964
1965 /* We're allowed to or must change the font but do we want to ? */
1966
1967 if (font_width != (win_width-window_border*2)/term->cols ||
1968 font_height != (win_height-window_border*2)/term->rows) {
1969
1970 deinit_fonts();
1971 init_fonts((win_width-window_border*2)/term->cols,
1972 (win_height-window_border*2)/term->rows);
1973 offset_width = (win_width-font_width*term->cols)/2;
1974 offset_height = (win_height-font_height*term->rows)/2;
1975
1976 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1977 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1978
1979 InvalidateRect(wgs.term_hwnd, NULL, true);
1980 #ifdef RDB_DEBUG_PATCH
1981 debug("reset_window() -> font resize to (%d,%d)\n",
1982 font_width, font_height);
1983 #endif
1984 }
1985 }
1986
set_input_locale(HKL kl)1987 static void set_input_locale(HKL kl)
1988 {
1989 char lbuf[20];
1990
1991 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1992 lbuf, sizeof(lbuf));
1993
1994 kbd_codepage = atoi(lbuf);
1995 }
1996
click(Mouse_Button b,int x,int y,bool shift,bool ctrl,bool alt)1997 static void click(Mouse_Button b, int x, int y,
1998 bool shift, bool ctrl, bool alt)
1999 {
2000 int thistime = GetMessageTime();
2001
2002 if (send_raw_mouse &&
2003 !(shift && conf_get_bool(conf, CONF_mouse_override))) {
2004 lastbtn = MBT_NOTHING;
2005 term_mouse(term, b, translate_button(b), MA_CLICK,
2006 x, y, shift, ctrl, alt);
2007 return;
2008 }
2009
2010 if (lastbtn == b && thistime - lasttime < dbltime) {
2011 lastact = (lastact == MA_CLICK ? MA_2CLK :
2012 lastact == MA_2CLK ? MA_3CLK :
2013 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
2014 } else {
2015 lastbtn = b;
2016 lastact = MA_CLICK;
2017 }
2018 if (lastact != MA_NOTHING)
2019 term_mouse(term, b, translate_button(b), lastact,
2020 x, y, shift, ctrl, alt);
2021 lasttime = thistime;
2022 }
2023
2024 /*
2025 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
2026 * into a cooked one (SELECT, EXTEND, PASTE).
2027 */
translate_button(Mouse_Button button)2028 static Mouse_Button translate_button(Mouse_Button button)
2029 {
2030 if (button == MBT_LEFT)
2031 return MBT_SELECT;
2032 if (button == MBT_MIDDLE)
2033 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2034 MBT_PASTE : MBT_EXTEND;
2035 if (button == MBT_RIGHT)
2036 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2037 MBT_EXTEND : MBT_PASTE;
2038 return 0; /* shouldn't happen */
2039 }
2040
show_mouseptr(bool show)2041 static void show_mouseptr(bool show)
2042 {
2043 /* NB that the counter in ShowCursor() is also frobbed by
2044 * update_mouse_pointer() */
2045 static bool cursor_visible = true;
2046 if (!conf_get_bool(conf, CONF_hide_mouseptr))
2047 show = true; /* override if this feature disabled */
2048 if (cursor_visible && !show)
2049 ShowCursor(false);
2050 else if (!cursor_visible && show)
2051 ShowCursor(true);
2052 cursor_visible = show;
2053 }
2054
is_alt_pressed(void)2055 static bool is_alt_pressed(void)
2056 {
2057 BYTE keystate[256];
2058 int r = GetKeyboardState(keystate);
2059 if (!r)
2060 return false;
2061 if (keystate[VK_MENU] & 0x80)
2062 return true;
2063 if (keystate[VK_RMENU] & 0x80)
2064 return true;
2065 return false;
2066 }
2067
2068 static bool resizing;
2069
win_seat_notify_remote_exit(Seat * seat)2070 static void win_seat_notify_remote_exit(Seat *seat)
2071 {
2072 int exitcode, close_on_exit;
2073
2074 if (!session_closed &&
2075 (exitcode = backend_exitcode(backend)) >= 0) {
2076 close_on_exit = conf_get_int(conf, CONF_close_on_exit);
2077 /* Abnormal exits will already have set session_closed and taken
2078 * appropriate action. */
2079 if (close_on_exit == FORCE_ON ||
2080 (close_on_exit == AUTO && exitcode != INT_MAX)) {
2081 PostQuitMessage(0);
2082 } else {
2083 queue_toplevel_callback(close_session, NULL);
2084 session_closed = true;
2085 /* exitcode == INT_MAX indicates that the connection was closed
2086 * by a fatal error, so an error box will be coming our way and
2087 * we should not generate this informational one. */
2088 if (exitcode != INT_MAX) {
2089 show_mouseptr(true);
2090 MessageBox(wgs.term_hwnd, "Connection closed by remote host",
2091 appname, MB_OK | MB_ICONINFORMATION);
2092 }
2093 }
2094 }
2095 }
2096
timer_change_notify(unsigned long next)2097 void timer_change_notify(unsigned long next)
2098 {
2099 unsigned long now = GETTICKCOUNT();
2100 long ticks;
2101 if (now - next < INT_MAX)
2102 ticks = 0;
2103 else
2104 ticks = next - now;
2105 KillTimer(wgs.term_hwnd, TIMING_TIMER_ID);
2106 SetTimer(wgs.term_hwnd, TIMING_TIMER_ID, ticks, NULL);
2107 timing_next_time = next;
2108 }
2109
conf_cache_data(void)2110 static void conf_cache_data(void)
2111 {
2112 /* Cache some items from conf to speed lookups in very hot code */
2113 cursor_type = conf_get_int(conf, CONF_cursor_type);
2114 vtmode = conf_get_int(conf, CONF_vtmode);
2115 }
2116
2117 static const int clips_system[] = { CLIP_SYSTEM };
2118
make_hdc(void)2119 static HDC make_hdc(void)
2120 {
2121 HDC hdc;
2122
2123 if (!wgs.term_hwnd)
2124 return NULL;
2125
2126 hdc = GetDC(wgs.term_hwnd);
2127 if (!hdc)
2128 return NULL;
2129
2130 SelectPalette(hdc, pal, false);
2131 return hdc;
2132 }
2133
free_hdc(HDC hdc)2134 static void free_hdc(HDC hdc)
2135 {
2136 assert(wgs.term_hwnd);
2137 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), false);
2138 ReleaseDC(wgs.term_hwnd, hdc);
2139 }
2140
2141 static bool need_backend_resize = false;
2142
wm_size_resize_term(LPARAM lParam,bool border)2143 static void wm_size_resize_term(LPARAM lParam, bool border)
2144 {
2145 int width = LOWORD(lParam);
2146 int height = HIWORD(lParam);
2147 int border_size = border ? conf_get_int(conf, CONF_window_border) : 0;
2148
2149 int w = (width - border_size*2) / font_width;
2150 int h = (height - border_size*2) / font_height;
2151
2152 if (w < 1) w = 1;
2153 if (h < 1) h = 1;
2154
2155 if (resizing) {
2156 /*
2157 * If we're in the middle of an interactive resize, we don't
2158 * call term_size. This means that, firstly, the user can drag
2159 * the size back and forth indecisively without wiping out any
2160 * actual terminal contents, and secondly, the Terminal
2161 * doesn't call back->size in turn for each increment of the
2162 * resizing drag, so we don't spam the server with huge
2163 * numbers of resize events.
2164 */
2165 need_backend_resize = true;
2166 conf_set_int(conf, CONF_height, h);
2167 conf_set_int(conf, CONF_width, w);
2168 } else {
2169 term_size(term, h, w,
2170 conf_get_int(conf, CONF_savelines));
2171 }
2172 }
2173
WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)2174 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2175 WPARAM wParam, LPARAM lParam)
2176 {
2177 HDC hdc;
2178 static bool ignore_clip = false;
2179 static bool fullscr_on_max = false;
2180 static bool processed_resize = false;
2181 static bool in_scrollbar_loop = false;
2182 static UINT last_mousemove = 0;
2183 int resize_action;
2184
2185 switch (message) {
2186 case WM_TIMER:
2187 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
2188 unsigned long next;
2189
2190 KillTimer(hwnd, TIMING_TIMER_ID);
2191 if (run_timers(timing_next_time, &next)) {
2192 timer_change_notify(next);
2193 } else {
2194 }
2195 }
2196 return 0;
2197 case WM_CREATE:
2198 break;
2199 case WM_CLOSE: {
2200 char *title, *msg, *additional = NULL;
2201 show_mouseptr(true);
2202 title = dupprintf("%s Exit Confirmation", appname);
2203 if (backend && backend->vt->close_warn_text) {
2204 additional = backend->vt->close_warn_text(backend);
2205 }
2206 msg = dupprintf("Are you sure you want to close this session?%s%s",
2207 additional ? "\n" : "",
2208 additional ? additional : "");
2209 if (session_closed || !conf_get_bool(conf, CONF_warn_on_close) ||
2210 MessageBox(hwnd, msg, title,
2211 MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
2212 == IDOK)
2213 DestroyWindow(hwnd);
2214 sfree(title);
2215 sfree(msg);
2216 sfree(additional);
2217 return 0;
2218 }
2219 case WM_DESTROY:
2220 show_mouseptr(true);
2221 PostQuitMessage(0);
2222 return 0;
2223 case WM_INITMENUPOPUP:
2224 if ((HMENU)wParam == savedsess_menu) {
2225 /* About to pop up Saved Sessions sub-menu.
2226 * Refresh the session list. */
2227 get_sesslist(&sesslist, false); /* free */
2228 get_sesslist(&sesslist, true);
2229 update_savedsess_menu();
2230 return 0;
2231 }
2232 break;
2233 case WM_COMMAND:
2234 case WM_SYSCOMMAND:
2235 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
2236 case SC_VSCROLL:
2237 case SC_HSCROLL:
2238 if (message == WM_SYSCOMMAND) {
2239 /* As per the long comment in WM_VSCROLL handler: give
2240 * this message the default handling, which starts a
2241 * subsidiary message loop, but set a flag so that
2242 * when we're re-entered from that loop, scroll events
2243 * within an interactive scrollbar-drag can be handled
2244 * differently. */
2245 in_scrollbar_loop = true;
2246 LRESULT result = DefWindowProcW(hwnd, message, wParam, lParam);
2247 in_scrollbar_loop = false;
2248 return result;
2249 }
2250 break;
2251 case IDM_SHOWLOG:
2252 showeventlog(hwnd);
2253 break;
2254 case IDM_NEWSESS:
2255 case IDM_DUPSESS:
2256 case IDM_SAVEDSESS: {
2257 char b[2048];
2258 char *cl;
2259 const char *argprefix;
2260 bool inherit_handles;
2261 STARTUPINFO si;
2262 PROCESS_INFORMATION pi;
2263 HANDLE filemap = NULL;
2264
2265 if (restricted_acl())
2266 argprefix = "&R";
2267 else
2268 argprefix = "";
2269
2270 if (wParam == IDM_DUPSESS) {
2271 /*
2272 * Allocate a file-mapping memory chunk for the
2273 * config structure.
2274 */
2275 SECURITY_ATTRIBUTES sa;
2276 strbuf *serbuf;
2277 void *p;
2278 int size;
2279
2280 serbuf = strbuf_new();
2281 conf_serialise(BinarySink_UPCAST(serbuf), conf);
2282 size = serbuf->len;
2283
2284 sa.nLength = sizeof(sa);
2285 sa.lpSecurityDescriptor = NULL;
2286 sa.bInheritHandle = true;
2287 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
2288 &sa,
2289 PAGE_READWRITE,
2290 0, size, NULL);
2291 if (filemap && filemap != INVALID_HANDLE_VALUE) {
2292 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size);
2293 if (p) {
2294 memcpy(p, serbuf->s, size);
2295 UnmapViewOfFile(p);
2296 }
2297 }
2298
2299 strbuf_free(serbuf);
2300 inherit_handles = true;
2301 cl = dupprintf("putty %s&%p:%u", argprefix,
2302 filemap, (unsigned)size);
2303 } else if (wParam == IDM_SAVEDSESS) {
2304 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2305 / MENU_SAVED_STEP) + 1;
2306 if (sessno < (unsigned)sesslist.nsessions) {
2307 const char *session = sesslist.sessions[sessno];
2308 cl = dupprintf("putty %s@%s", argprefix, session);
2309 inherit_handles = false;
2310 } else
2311 break;
2312 } else /* IDM_NEWSESS */ {
2313 cl = dupprintf("putty%s%s",
2314 *argprefix ? " " : "",
2315 argprefix);
2316 inherit_handles = false;
2317 }
2318
2319 GetModuleFileName(NULL, b, sizeof(b) - 1);
2320 si.cb = sizeof(si);
2321 si.lpReserved = NULL;
2322 si.lpDesktop = NULL;
2323 si.lpTitle = NULL;
2324 si.dwFlags = 0;
2325 si.cbReserved2 = 0;
2326 si.lpReserved2 = NULL;
2327 CreateProcess(b, cl, NULL, NULL, inherit_handles,
2328 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
2329 CloseHandle(pi.hProcess);
2330 CloseHandle(pi.hThread);
2331
2332 if (filemap)
2333 CloseHandle(filemap);
2334 sfree(cl);
2335 break;
2336 }
2337 case IDM_RESTART:
2338 if (!backend) {
2339 lp_eventlog(&wgs.logpolicy, "----- Session restarted -----");
2340 term_pwron(term, false);
2341 start_backend();
2342 }
2343
2344 break;
2345 case IDM_RECONF: {
2346 Conf *prev_conf;
2347 int init_lvl = 1;
2348 bool reconfig_result;
2349
2350 if (reconfiguring)
2351 break;
2352 else
2353 reconfiguring = true;
2354
2355 term_pre_reconfig(term, conf);
2356 prev_conf = conf_copy(conf);
2357
2358 reconfig_result = do_reconfig(
2359 hwnd, conf, backend ? backend_cfg_info(backend) : 0);
2360 reconfiguring = false;
2361 if (!reconfig_result) {
2362 conf_free(prev_conf);
2363 break;
2364 }
2365
2366 conf_cache_data();
2367
2368 resize_action = conf_get_int(conf, CONF_resize_action);
2369 {
2370 /* Disable full-screen if resizing forbidden */
2371 int i;
2372 for (i = 0; i < lenof(popup_menus); i++)
2373 EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,
2374 MF_BYCOMMAND |
2375 (resize_action == RESIZE_DISABLED
2376 ? MF_GRAYED : MF_ENABLED));
2377 /* Gracefully unzoom if necessary */
2378 if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED))
2379 ShowWindow(hwnd, SW_RESTORE);
2380 }
2381
2382 /* Pass new config data to the logging module */
2383 log_reconfig(logctx, conf);
2384
2385 sfree(logpal);
2386 /*
2387 * Flush the line discipline's edit buffer in the
2388 * case where local editing has just been disabled.
2389 */
2390 if (ldisc) {
2391 ldisc_configure(ldisc, conf);
2392 ldisc_echoedit_update(ldisc);
2393 }
2394
2395 if (conf_get_bool(conf, CONF_system_colour) !=
2396 conf_get_bool(prev_conf, CONF_system_colour))
2397 term_notify_palette_changed(term);
2398
2399 /* Pass new config data to the terminal */
2400 term_reconfig(term, conf);
2401 setup_clipboards(term, conf);
2402
2403 /* Reinitialise the colour palette, in case the terminal
2404 * just read new settings out of Conf */
2405 if (pal)
2406 DeleteObject(pal);
2407 logpal = NULL;
2408 pal = NULL;
2409 init_palette();
2410
2411 /* Pass new config data to the back end */
2412 if (backend)
2413 backend_reconfig(backend, conf);
2414
2415 /* Screen size changed ? */
2416 if (conf_get_int(conf, CONF_height) !=
2417 conf_get_int(prev_conf, CONF_height) ||
2418 conf_get_int(conf, CONF_width) !=
2419 conf_get_int(prev_conf, CONF_width) ||
2420 conf_get_int(conf, CONF_savelines) !=
2421 conf_get_int(prev_conf, CONF_savelines) ||
2422 resize_action == RESIZE_FONT ||
2423 (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2424 resize_action == RESIZE_DISABLED)
2425 term_size(term, conf_get_int(conf, CONF_height),
2426 conf_get_int(conf, CONF_width),
2427 conf_get_int(conf, CONF_savelines));
2428
2429 /* Enable or disable the scroll bar, etc */
2430 {
2431 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2432 LONG nexflag, exflag =
2433 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2434
2435 nexflag = exflag;
2436 if (conf_get_bool(conf, CONF_alwaysontop) !=
2437 conf_get_bool(prev_conf, CONF_alwaysontop)) {
2438 if (conf_get_bool(conf, CONF_alwaysontop)) {
2439 nexflag |= WS_EX_TOPMOST;
2440 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2441 SWP_NOMOVE | SWP_NOSIZE);
2442 } else {
2443 nexflag &= ~(WS_EX_TOPMOST);
2444 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2445 SWP_NOMOVE | SWP_NOSIZE);
2446 }
2447 }
2448 if (conf_get_bool(conf, CONF_sunken_edge))
2449 nexflag |= WS_EX_CLIENTEDGE;
2450 else
2451 nexflag &= ~(WS_EX_CLIENTEDGE);
2452
2453 nflg = flag;
2454 if (conf_get_bool(conf, is_full_screen() ?
2455 CONF_scrollbar_in_fullscreen :
2456 CONF_scrollbar))
2457 nflg |= WS_VSCROLL;
2458 else
2459 nflg &= ~WS_VSCROLL;
2460
2461 if (resize_action == RESIZE_DISABLED ||
2462 is_full_screen())
2463 nflg &= ~WS_THICKFRAME;
2464 else
2465 nflg |= WS_THICKFRAME;
2466
2467 if (resize_action == RESIZE_DISABLED)
2468 nflg &= ~WS_MAXIMIZEBOX;
2469 else
2470 nflg |= WS_MAXIMIZEBOX;
2471
2472 if (nflg != flag || nexflag != exflag) {
2473 if (nflg != flag)
2474 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2475 if (nexflag != exflag)
2476 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2477
2478 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2479 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2480 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2481 SWP_FRAMECHANGED);
2482
2483 init_lvl = 2;
2484 }
2485 }
2486
2487 /* Oops */
2488 if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2489 force_normal(hwnd);
2490 init_lvl = 2;
2491 }
2492
2493 {
2494 FontSpec *font = conf_get_fontspec(conf, CONF_font);
2495 FontSpec *prev_font = conf_get_fontspec(prev_conf,
2496 CONF_font);
2497
2498 if (!strcmp(font->name, prev_font->name) ||
2499 !strcmp(conf_get_str(conf, CONF_line_codepage),
2500 conf_get_str(prev_conf, CONF_line_codepage)) ||
2501 font->isbold != prev_font->isbold ||
2502 font->height != prev_font->height ||
2503 font->charset != prev_font->charset ||
2504 conf_get_int(conf, CONF_font_quality) !=
2505 conf_get_int(prev_conf, CONF_font_quality) ||
2506 conf_get_int(conf, CONF_vtmode) !=
2507 conf_get_int(prev_conf, CONF_vtmode) ||
2508 conf_get_int(conf, CONF_bold_style) !=
2509 conf_get_int(prev_conf, CONF_bold_style) ||
2510 resize_action == RESIZE_DISABLED ||
2511 resize_action == RESIZE_EITHER ||
2512 resize_action != conf_get_int(prev_conf,
2513 CONF_resize_action))
2514 init_lvl = 2;
2515 }
2516
2517 InvalidateRect(hwnd, NULL, true);
2518 reset_window(init_lvl);
2519
2520 conf_free(prev_conf);
2521 break;
2522 }
2523 case IDM_COPYALL:
2524 term_copyall(term, clips_system, lenof(clips_system));
2525 break;
2526 case IDM_COPY:
2527 term_request_copy(term, clips_system, lenof(clips_system));
2528 break;
2529 case IDM_PASTE:
2530 term_request_paste(term, CLIP_SYSTEM);
2531 break;
2532 case IDM_CLRSB:
2533 term_clrsb(term);
2534 break;
2535 case IDM_RESET:
2536 term_pwron(term, true);
2537 if (ldisc)
2538 ldisc_echoedit_update(ldisc);
2539 break;
2540 case IDM_ABOUT:
2541 showabout(hwnd);
2542 break;
2543 case IDM_HELP:
2544 launch_help(hwnd, NULL);
2545 break;
2546 case SC_MOUSEMENU:
2547 /*
2548 * We get this if the System menu has been activated
2549 * using the mouse.
2550 */
2551 show_mouseptr(true);
2552 break;
2553 case SC_KEYMENU:
2554 /*
2555 * We get this if the System menu has been activated
2556 * using the keyboard. This might happen from within
2557 * TranslateKey, in which case it really wants to be
2558 * followed by a `space' character to actually _bring
2559 * the menu up_ rather than just sitting there in
2560 * `ready to appear' state.
2561 */
2562 show_mouseptr(true); /* make sure pointer is visible */
2563 if( lParam == 0 )
2564 PostMessage(hwnd, WM_CHAR, ' ', 0);
2565 break;
2566 case IDM_FULLSCREEN:
2567 flip_full_screen();
2568 break;
2569 default:
2570 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2571 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2572 }
2573 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2574 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2575 /*
2576 * Ensure we haven't been sent a bogus SYSCOMMAND
2577 * which would cause us to reference invalid memory
2578 * and crash. Perhaps I'm just too paranoid here.
2579 */
2580 if (i >= n_specials)
2581 break;
2582 if (backend)
2583 backend_special(
2584 backend, specials[i].code, specials[i].arg);
2585 }
2586 }
2587 break;
2588
2589 #define X_POS(l) ((int)(short)LOWORD(l))
2590 #define Y_POS(l) ((int)(short)HIWORD(l))
2591
2592 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2593 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2594 case WM_LBUTTONDOWN:
2595 case WM_MBUTTONDOWN:
2596 case WM_RBUTTONDOWN:
2597 case WM_LBUTTONUP:
2598 case WM_MBUTTONUP:
2599 case WM_RBUTTONUP:
2600 if (message == WM_RBUTTONDOWN &&
2601 ((wParam & MK_CONTROL) ||
2602 (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) {
2603 POINT cursorpos;
2604
2605 show_mouseptr(true); /* make sure pointer is visible */
2606 GetCursorPos(&cursorpos);
2607 TrackPopupMenu(popup_menus[CTXMENU].menu,
2608 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2609 cursorpos.x, cursorpos.y,
2610 0, hwnd, NULL);
2611 break;
2612 }
2613 {
2614 int button;
2615 bool press;
2616
2617 switch (message) {
2618 case WM_LBUTTONDOWN:
2619 button = MBT_LEFT;
2620 wParam |= MK_LBUTTON;
2621 press = true;
2622 break;
2623 case WM_MBUTTONDOWN:
2624 button = MBT_MIDDLE;
2625 wParam |= MK_MBUTTON;
2626 press = true;
2627 break;
2628 case WM_RBUTTONDOWN:
2629 button = MBT_RIGHT;
2630 wParam |= MK_RBUTTON;
2631 press = true;
2632 break;
2633 case WM_LBUTTONUP:
2634 button = MBT_LEFT;
2635 wParam &= ~MK_LBUTTON;
2636 press = false;
2637 break;
2638 case WM_MBUTTONUP:
2639 button = MBT_MIDDLE;
2640 wParam &= ~MK_MBUTTON;
2641 press = false;
2642 break;
2643 case WM_RBUTTONUP:
2644 button = MBT_RIGHT;
2645 wParam &= ~MK_RBUTTON;
2646 press = false;
2647 break;
2648 default: /* shouldn't happen */
2649 button = 0;
2650 press = false;
2651 }
2652 show_mouseptr(true);
2653 /*
2654 * Special case: in full-screen mode, if the left
2655 * button is clicked in the very top left corner of the
2656 * window, we put up the System menu instead of doing
2657 * selection.
2658 */
2659 {
2660 bool mouse_on_hotspot = false;
2661 POINT pt;
2662
2663 GetCursorPos(&pt);
2664 #ifndef NO_MULTIMON
2665 {
2666 HMONITOR mon;
2667 MONITORINFO mi;
2668
2669 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2670
2671 if (mon != NULL) {
2672 mi.cbSize = sizeof(MONITORINFO);
2673 GetMonitorInfo(mon, &mi);
2674
2675 if (mi.rcMonitor.left == pt.x &&
2676 mi.rcMonitor.top == pt.y) {
2677 mouse_on_hotspot = true;
2678 }
2679 }
2680 }
2681 #else
2682 if (pt.x == 0 && pt.y == 0) {
2683 mouse_on_hotspot = true;
2684 }
2685 #endif
2686 if (is_full_screen() && press &&
2687 button == MBT_LEFT && mouse_on_hotspot) {
2688 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2689 MAKELPARAM(pt.x, pt.y));
2690 return 0;
2691 }
2692 }
2693
2694 if (press) {
2695 click(button,
2696 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2697 wParam & MK_SHIFT, wParam & MK_CONTROL,
2698 is_alt_pressed());
2699 SetCapture(hwnd);
2700 } else {
2701 term_mouse(term, button, translate_button(button), MA_RELEASE,
2702 TO_CHR_X(X_POS(lParam)),
2703 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2704 wParam & MK_CONTROL, is_alt_pressed());
2705 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))
2706 ReleaseCapture();
2707 }
2708 }
2709 return 0;
2710 case WM_MOUSEMOVE: {
2711 /*
2712 * Windows seems to like to occasionally send MOUSEMOVE
2713 * events even if the mouse hasn't moved. Don't unhide
2714 * the mouse pointer in this case.
2715 */
2716 static WPARAM wp = 0;
2717 static LPARAM lp = 0;
2718 if (wParam != wp || lParam != lp ||
2719 last_mousemove != WM_MOUSEMOVE) {
2720 show_mouseptr(true);
2721 wp = wParam; lp = lParam;
2722 last_mousemove = WM_MOUSEMOVE;
2723 }
2724 /*
2725 * Add the mouse position and message time to the random
2726 * number noise.
2727 */
2728 noise_ultralight(NOISE_SOURCE_MOUSEPOS, lParam);
2729
2730 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2731 GetCapture() == hwnd) {
2732 Mouse_Button b;
2733 if (wParam & MK_LBUTTON)
2734 b = MBT_LEFT;
2735 else if (wParam & MK_MBUTTON)
2736 b = MBT_MIDDLE;
2737 else
2738 b = MBT_RIGHT;
2739 term_mouse(term, b, translate_button(b), MA_DRAG,
2740 TO_CHR_X(X_POS(lParam)),
2741 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2742 wParam & MK_CONTROL, is_alt_pressed());
2743 }
2744 return 0;
2745 }
2746 case WM_NCMOUSEMOVE: {
2747 static WPARAM wp = 0;
2748 static LPARAM lp = 0;
2749 if (wParam != wp || lParam != lp ||
2750 last_mousemove != WM_NCMOUSEMOVE) {
2751 show_mouseptr(true);
2752 wp = wParam; lp = lParam;
2753 last_mousemove = WM_NCMOUSEMOVE;
2754 }
2755 noise_ultralight(NOISE_SOURCE_MOUSEPOS, lParam);
2756 break;
2757 }
2758 case WM_IGNORE_CLIP:
2759 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2760 break;
2761 case WM_DESTROYCLIPBOARD:
2762 if (!ignore_clip)
2763 term_lost_clipboard_ownership(term, CLIP_SYSTEM);
2764 ignore_clip = false;
2765 return 0;
2766 case WM_PAINT: {
2767 PAINTSTRUCT p;
2768
2769 HideCaret(hwnd);
2770 hdc = BeginPaint(hwnd, &p);
2771 if (pal) {
2772 SelectPalette(hdc, pal, true);
2773 RealizePalette(hdc);
2774 }
2775
2776 /*
2777 * We have to be careful about term_paint(). It will
2778 * set a bunch of character cells to INVALID and then
2779 * call do_paint(), which will redraw those cells and
2780 * _then mark them as done_. This may not be accurate:
2781 * when painting in WM_PAINT context we are restricted
2782 * to the rectangle which has just been exposed - so if
2783 * that only covers _part_ of a character cell and the
2784 * rest of it was already visible, that remainder will
2785 * not be redrawn at all. Accordingly, we must not
2786 * paint any character cell in a WM_PAINT context which
2787 * already has a pending update due to terminal output.
2788 * The simplest solution to this - and many, many
2789 * thanks to Hung-Te Lin for working all this out - is
2790 * not to do any actual painting at _all_ if there's a
2791 * pending terminal update: just mark the relevant
2792 * character cells as INVALID and wait for the
2793 * scheduled full update to sort it out.
2794 *
2795 * I have a suspicion this isn't the _right_ solution.
2796 * An alternative approach would be to have terminal.c
2797 * separately track what _should_ be on the terminal
2798 * screen and what _is_ on the terminal screen, and
2799 * have two completely different types of redraw (one
2800 * for full updates, which syncs the former with the
2801 * terminal itself, and one for WM_PAINT which syncs
2802 * the latter with the former); yet another possibility
2803 * would be to have the Windows front end do what the
2804 * GTK one already does, and maintain a bitmap of the
2805 * current terminal appearance so that WM_PAINT becomes
2806 * completely trivial. However, this should do for now.
2807 */
2808 assert(!wintw_hdc);
2809 wintw_hdc = hdc;
2810 term_paint(term,
2811 (p.rcPaint.left-offset_width)/font_width,
2812 (p.rcPaint.top-offset_height)/font_height,
2813 (p.rcPaint.right-offset_width-1)/font_width,
2814 (p.rcPaint.bottom-offset_height-1)/font_height,
2815 !term->window_update_pending);
2816 wintw_hdc = NULL;
2817
2818 if (p.fErase ||
2819 p.rcPaint.left < offset_width ||
2820 p.rcPaint.top < offset_height ||
2821 p.rcPaint.right >= offset_width + font_width*term->cols ||
2822 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2823 {
2824 HBRUSH fillcolour, oldbrush;
2825 HPEN edge, oldpen;
2826 fillcolour = CreateSolidBrush (
2827 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2828 oldbrush = SelectObject(hdc, fillcolour);
2829 edge = CreatePen(PS_SOLID, 0,
2830 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2831 oldpen = SelectObject(hdc, edge);
2832
2833 /*
2834 * Jordan Russell reports that this apparently
2835 * ineffectual IntersectClipRect() call masks a
2836 * Windows NT/2K bug causing strange display
2837 * problems when the PuTTY window is taller than
2838 * the primary monitor. It seems harmless enough...
2839 */
2840 IntersectClipRect(hdc,
2841 p.rcPaint.left, p.rcPaint.top,
2842 p.rcPaint.right, p.rcPaint.bottom);
2843
2844 ExcludeClipRect(hdc,
2845 offset_width, offset_height,
2846 offset_width+font_width*term->cols,
2847 offset_height+font_height*term->rows);
2848
2849 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2850 p.rcPaint.right, p.rcPaint.bottom);
2851
2852 /* SelectClipRgn(hdc, NULL); */
2853
2854 SelectObject(hdc, oldbrush);
2855 DeleteObject(fillcolour);
2856 SelectObject(hdc, oldpen);
2857 DeleteObject(edge);
2858 }
2859 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2860 SelectObject(hdc, GetStockObject(WHITE_PEN));
2861 EndPaint(hwnd, &p);
2862 ShowCaret(hwnd);
2863 return 0;
2864 }
2865 case WM_NETEVENT: {
2866 /*
2867 * To protect against re-entrancy when Windows's recv()
2868 * immediately triggers a new WSAAsyncSelect window
2869 * message, we don't call select_result directly from this
2870 * handler but instead wait until we're back out at the
2871 * top level of the message loop.
2872 */
2873 struct wm_netevent_params *params =
2874 snew(struct wm_netevent_params);
2875 params->wParam = wParam;
2876 params->lParam = lParam;
2877 queue_toplevel_callback(wm_netevent_callback, params);
2878 return 0;
2879 }
2880 case WM_SETFOCUS:
2881 term_set_focus(term, true);
2882 CreateCaret(hwnd, caretbm, font_width, font_height);
2883 ShowCaret(hwnd);
2884 flash_window(0); /* stop */
2885 compose_state = 0;
2886 term_update(term);
2887 break;
2888 case WM_KILLFOCUS:
2889 show_mouseptr(true);
2890 term_set_focus(term, false);
2891 DestroyCaret();
2892 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2893 term_update(term);
2894 break;
2895 case WM_ENTERSIZEMOVE:
2896 #ifdef RDB_DEBUG_PATCH
2897 debug("WM_ENTERSIZEMOVE\n");
2898 #endif
2899 EnableSizeTip(true);
2900 resizing = true;
2901 need_backend_resize = false;
2902 break;
2903 case WM_EXITSIZEMOVE:
2904 EnableSizeTip(false);
2905 resizing = false;
2906 #ifdef RDB_DEBUG_PATCH
2907 debug("WM_EXITSIZEMOVE\n");
2908 #endif
2909 if (need_backend_resize) {
2910 term_size(term, conf_get_int(conf, CONF_height),
2911 conf_get_int(conf, CONF_width),
2912 conf_get_int(conf, CONF_savelines));
2913 InvalidateRect(hwnd, NULL, true);
2914 }
2915 recompute_window_offset();
2916 break;
2917 case WM_SIZING:
2918 /*
2919 * This does two jobs:
2920 * 1) Keep the sizetip uptodate
2921 * 2) Make sure the window size is _stepped_ in units of the font size.
2922 */
2923 resize_action = conf_get_int(conf, CONF_resize_action);
2924 if (resize_action == RESIZE_TERM ||
2925 (resize_action == RESIZE_EITHER && !is_alt_pressed())) {
2926 int width, height, w, h, ew, eh;
2927 LPRECT r = (LPRECT) lParam;
2928
2929 if (!need_backend_resize && resize_action == RESIZE_EITHER &&
2930 (conf_get_int(conf, CONF_height) != term->rows ||
2931 conf_get_int(conf, CONF_width) != term->cols)) {
2932 /*
2933 * Great! It seems that both the terminal size and the
2934 * font size have been changed and the user is now dragging.
2935 *
2936 * It will now be difficult to get back to the configured
2937 * font size!
2938 *
2939 * This would be easier but it seems to be too confusing.
2940 */
2941 conf_set_int(conf, CONF_height, term->rows);
2942 conf_set_int(conf, CONF_width, term->cols);
2943
2944 InvalidateRect(hwnd, NULL, true);
2945 need_backend_resize = true;
2946 }
2947
2948 width = r->right - r->left - extra_width;
2949 height = r->bottom - r->top - extra_height;
2950 w = (width + font_width / 2) / font_width;
2951 if (w < 1)
2952 w = 1;
2953 h = (height + font_height / 2) / font_height;
2954 if (h < 1)
2955 h = 1;
2956 UpdateSizeTip(hwnd, w, h);
2957 ew = width - w * font_width;
2958 eh = height - h * font_height;
2959 if (ew != 0) {
2960 if (wParam == WMSZ_LEFT ||
2961 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2962 r->left += ew;
2963 else
2964 r->right -= ew;
2965 }
2966 if (eh != 0) {
2967 if (wParam == WMSZ_TOP ||
2968 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2969 r->top += eh;
2970 else
2971 r->bottom -= eh;
2972 }
2973 if (ew || eh)
2974 return 1;
2975 else
2976 return 0;
2977 } else {
2978 int width, height, w, h, rv = 0;
2979 int window_border = conf_get_int(conf, CONF_window_border);
2980 int ex_width = extra_width + (window_border - offset_width) * 2;
2981 int ex_height = extra_height + (window_border - offset_height) * 2;
2982 LPRECT r = (LPRECT) lParam;
2983
2984 width = r->right - r->left - ex_width;
2985 height = r->bottom - r->top - ex_height;
2986
2987 w = (width + term->cols/2)/term->cols;
2988 h = (height + term->rows/2)/term->rows;
2989 if ( r->right != r->left + w*term->cols + ex_width)
2990 rv = 1;
2991
2992 if (wParam == WMSZ_LEFT ||
2993 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2994 r->left = r->right - w*term->cols - ex_width;
2995 else
2996 r->right = r->left + w*term->cols + ex_width;
2997
2998 if (r->bottom != r->top + h*term->rows + ex_height)
2999 rv = 1;
3000
3001 if (wParam == WMSZ_TOP ||
3002 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
3003 r->top = r->bottom - h*term->rows - ex_height;
3004 else
3005 r->bottom = r->top + h*term->rows + ex_height;
3006
3007 return rv;
3008 }
3009 /* break; (never reached) */
3010 case WM_FULLSCR_ON_MAX:
3011 fullscr_on_max = true;
3012 break;
3013 case WM_MOVE:
3014 term_notify_window_pos(term, LOWORD(lParam), HIWORD(lParam));
3015 sys_cursor_update();
3016 break;
3017 case WM_SIZE:
3018 resize_action = conf_get_int(conf, CONF_resize_action);
3019 #ifdef RDB_DEBUG_PATCH
3020 debug("WM_SIZE %s (%d,%d)\n",
3021 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
3022 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
3023 (wParam == SIZE_RESTORED && resizing) ? "to":
3024 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
3025 "...",
3026 LOWORD(lParam), HIWORD(lParam));
3027 #endif
3028 term_notify_minimised(term, wParam == SIZE_MINIMIZED);
3029 {
3030 /*
3031 * WM_SIZE's lParam tells us the size of the client area.
3032 * But historic PuTTY practice is that we want to tell the
3033 * terminal the size of the overall window.
3034 */
3035 RECT r;
3036 GetWindowRect(hwnd, &r);
3037 term_notify_window_size_pixels(
3038 term, r.right - r.left, r.bottom - r.top);
3039 }
3040 if (wParam == SIZE_MINIMIZED)
3041 SetWindowText(hwnd,
3042 conf_get_bool(conf, CONF_win_name_always) ?
3043 window_name : icon_name);
3044 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
3045 SetWindowText(hwnd, window_name);
3046 if (wParam == SIZE_RESTORED) {
3047 processed_resize = false;
3048 clear_full_screen();
3049 if (processed_resize) {
3050 /*
3051 * Inhibit normal processing of this WM_SIZE; a
3052 * secondary one was triggered just now by
3053 * clear_full_screen which contained the correct
3054 * client area size.
3055 */
3056 return 0;
3057 }
3058 }
3059 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
3060 fullscr_on_max = false;
3061 processed_resize = false;
3062 make_full_screen();
3063 if (processed_resize) {
3064 /*
3065 * Inhibit normal processing of this WM_SIZE; a
3066 * secondary one was triggered just now by
3067 * make_full_screen which contained the correct client
3068 * area size.
3069 */
3070 return 0;
3071 }
3072 }
3073
3074 processed_resize = true;
3075
3076 if (resize_action == RESIZE_DISABLED) {
3077 /* A resize, well it better be a minimize. */
3078 reset_window(-1);
3079 } else {
3080 if (wParam == SIZE_MAXIMIZED) {
3081 was_zoomed = true;
3082 prev_rows = term->rows;
3083 prev_cols = term->cols;
3084 if (resize_action == RESIZE_TERM)
3085 wm_size_resize_term(lParam, false);
3086 reset_window(0);
3087 } else if (wParam == SIZE_RESTORED && was_zoomed) {
3088 was_zoomed = false;
3089 if (resize_action == RESIZE_TERM) {
3090 wm_size_resize_term(lParam, true);
3091 reset_window(2);
3092 } else if (resize_action != RESIZE_FONT)
3093 reset_window(2);
3094 else
3095 reset_window(0);
3096 } else if (wParam == SIZE_MINIMIZED) {
3097 /* do nothing */
3098 } else if (resize_action == RESIZE_TERM ||
3099 (resize_action == RESIZE_EITHER &&
3100 !is_alt_pressed())) {
3101 wm_size_resize_term(lParam, true);
3102
3103 /*
3104 * Sometimes, we can get a spontaneous resize event
3105 * outside a WM_SIZING interactive drag which wants to
3106 * set us to a new specific SIZE_RESTORED size. An
3107 * example is what happens if you press Windows+Right
3108 * and then Windows+Up: the first operation fits the
3109 * window to the right-hand half of the screen, and
3110 * the second one changes that for the top right
3111 * quadrant. In that situation, if we've responded
3112 * here by resizing the terminal, we may still need to
3113 * recompute the border around the window and do a
3114 * full redraw to clear the new border.
3115 */
3116 if (!resizing)
3117 recompute_window_offset();
3118 } else {
3119 reset_window(0);
3120 }
3121 }
3122 sys_cursor_update();
3123 return 0;
3124 case WM_DPICHANGED:
3125 dpi_info.cur_dpi.x = LOWORD(wParam);
3126 dpi_info.cur_dpi.y = HIWORD(wParam);
3127 dpi_info.new_wnd_rect = *(RECT*)(lParam);
3128 reset_window(3);
3129 return 0;
3130 case WM_VSCROLL:
3131 switch (LOWORD(wParam)) {
3132 case SB_BOTTOM:
3133 term_scroll(term, -1, 0);
3134 break;
3135 case SB_TOP:
3136 term_scroll(term, +1, 0);
3137 break;
3138 case SB_LINEDOWN:
3139 term_scroll(term, 0, +1);
3140 break;
3141 case SB_LINEUP:
3142 term_scroll(term, 0, -1);
3143 break;
3144 case SB_PAGEDOWN:
3145 term_scroll(term, 0, +term->rows / 2);
3146 break;
3147 case SB_PAGEUP:
3148 term_scroll(term, 0, -term->rows / 2);
3149 break;
3150 case SB_THUMBPOSITION:
3151 case SB_THUMBTRACK: {
3152 /*
3153 * Use GetScrollInfo instead of HIWORD(wParam) to get
3154 * 32-bit scroll position.
3155 */
3156 SCROLLINFO si;
3157
3158 si.cbSize = sizeof(si);
3159 si.fMask = SIF_TRACKPOS;
3160 if (GetScrollInfo(hwnd, SB_VERT, &si) == 0)
3161 si.nTrackPos = HIWORD(wParam);
3162 term_scroll(term, 1, si.nTrackPos);
3163 break;
3164 }
3165 }
3166
3167 if (in_scrollbar_loop) {
3168 /*
3169 * Allow window updates to happen during interactive
3170 * scroll.
3171 *
3172 * When the user takes hold of our window's scrollbar and
3173 * wobbles it interactively back and forth, or presses on
3174 * one of the arrow buttons at the ends, the first thing
3175 * that happens is that this window procedure receives
3176 * WM_SYSCOMMAND / SC_VSCROLL. [1] The default handler for
3177 * that window message starts a subsidiary message loop,
3178 * which continues to run until the user lets go of the
3179 * scrollbar again. All WM_VSCROLL / SB_THUMBTRACK
3180 * messages are generated by the handlers within that
3181 * subsidiary message loop.
3182 *
3183 * So, during that time, _our_ message loop is not
3184 * running, which means toplevel callbacks and timers and
3185 * so forth are not happening, which means that when we
3186 * redraw the window and set a timer to clear the cooldown
3187 * flag 20ms later, that timer never fires, and we aren't
3188 * able to keep redrawing the window.
3189 *
3190 * The 'obvious' answer would be to seize that SYSCOMMAND
3191 * ourselves and inhibit the default handler, so that our
3192 * message loop carries on running. But that would mean
3193 * we'd have to reimplement the whole of the scrollbar
3194 * handler!
3195 *
3196 * So instead we apply a bodge: set a static variable that
3197 * indicates that we're _in_ that sub-loop, and if so,
3198 * decide it's OK to manually call term_update() proper,
3199 * bypassing the timer and cooldown and rate-limiting
3200 * systems completely, whenever we see an SB_THUMBTRACK.
3201 * This shouldn't cause a rate overload, because we're
3202 * only doing it once per UI event!
3203 *
3204 * [1] Actually, there's an extra oddity where SC_HSCROLL
3205 * and SC_VSCROLL have their documented values the wrong
3206 * way round. Many people on the Internet have noticed
3207 * this, e.g. https://stackoverflow.com/q/55528397
3208 */
3209 term_update(term);
3210 }
3211 break;
3212 case WM_PALETTECHANGED:
3213 if ((HWND) wParam != hwnd && pal != NULL) {
3214 HDC hdc = make_hdc();
3215 if (hdc) {
3216 if (RealizePalette(hdc) > 0)
3217 UpdateColors(hdc);
3218 free_hdc(hdc);
3219 }
3220 }
3221 break;
3222 case WM_QUERYNEWPALETTE:
3223 if (pal != NULL) {
3224 HDC hdc = make_hdc();
3225 if (hdc) {
3226 if (RealizePalette(hdc) > 0)
3227 UpdateColors(hdc);
3228 free_hdc(hdc);
3229 return true;
3230 }
3231 }
3232 return false;
3233 case WM_KEYDOWN:
3234 case WM_SYSKEYDOWN:
3235 case WM_KEYUP:
3236 case WM_SYSKEYUP:
3237 /*
3238 * Add the scan code and keypress timing to the random
3239 * number noise.
3240 */
3241 noise_ultralight(NOISE_SOURCE_KEY, lParam);
3242
3243 /*
3244 * We don't do TranslateMessage since it disassociates the
3245 * resulting CHAR message from the KEYDOWN that sparked it,
3246 * which we occasionally don't want. Instead, we process
3247 * KEYDOWN, and call the Win32 translator functions so that
3248 * we get the translations under _our_ control.
3249 */
3250 {
3251 unsigned char buf[20];
3252 int len;
3253
3254 if (wParam == VK_PROCESSKEY || /* IME PROCESS key */
3255 wParam == VK_PACKET) { /* 'this key is a Unicode char' */
3256 if (message == WM_KEYDOWN) {
3257 MSG m;
3258 m.hwnd = hwnd;
3259 m.message = WM_KEYDOWN;
3260 m.wParam = wParam;
3261 m.lParam = lParam & 0xdfff;
3262 TranslateMessage(&m);
3263 } else break; /* pass to Windows for default processing */
3264 } else {
3265 len = TranslateKey(message, wParam, lParam, buf);
3266 if (len == -1)
3267 return DefWindowProcW(hwnd, message, wParam, lParam);
3268
3269 if (len != 0) {
3270 /*
3271 * We need not bother about stdin backlogs
3272 * here, because in GUI PuTTY we can't do
3273 * anything about it anyway; there's no means
3274 * of asking Windows to hold off on KEYDOWN
3275 * messages. We _have_ to buffer everything
3276 * we're sent.
3277 */
3278 term_keyinput(term, -1, buf, len);
3279 show_mouseptr(false);
3280 }
3281 }
3282 }
3283 return 0;
3284 case WM_INPUTLANGCHANGE:
3285 /* wParam == Font number */
3286 /* lParam == Locale */
3287 set_input_locale((HKL)lParam);
3288 sys_cursor_update();
3289 break;
3290 case WM_IME_STARTCOMPOSITION: {
3291 HIMC hImc = ImmGetContext(hwnd);
3292 ImmSetCompositionFont(hImc, &lfont);
3293 ImmReleaseContext(hwnd, hImc);
3294 break;
3295 }
3296 case WM_IME_COMPOSITION: {
3297 HIMC hIMC;
3298 int n;
3299 char *buff;
3300
3301 if (osPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
3302 osPlatformId == VER_PLATFORM_WIN32s)
3303 break; /* no Unicode */
3304
3305 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
3306 break; /* fall back to DefWindowProc */
3307
3308 hIMC = ImmGetContext(hwnd);
3309 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3310
3311 if (n > 0) {
3312 int i;
3313 buff = snewn(n, char);
3314 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
3315 /*
3316 * Jaeyoun Chung reports that Korean character
3317 * input doesn't work correctly if we do a single
3318 * term_keyinputw covering the whole of buff. So
3319 * instead we send the characters one by one.
3320 */
3321 /* don't divide SURROGATE PAIR */
3322 if (ldisc) {
3323 for (i = 0; i < n; i += 2) {
3324 WCHAR hs = *(unsigned short *)(buff+i);
3325 if (IS_HIGH_SURROGATE(hs) && i+2 < n) {
3326 WCHAR ls = *(unsigned short *)(buff+i+2);
3327 if (IS_LOW_SURROGATE(ls)) {
3328 term_keyinputw(
3329 term, (unsigned short *)(buff+i), 2);
3330 i += 2;
3331 continue;
3332 }
3333 }
3334 term_keyinputw(
3335 term, (unsigned short *)(buff+i), 1);
3336 }
3337 }
3338 free(buff);
3339 }
3340 ImmReleaseContext(hwnd, hIMC);
3341 return 1;
3342 }
3343
3344 case WM_IME_CHAR:
3345 if (wParam & 0xFF00) {
3346 char buf[2];
3347
3348 buf[1] = wParam;
3349 buf[0] = wParam >> 8;
3350 term_keyinput(term, kbd_codepage, buf, 2);
3351 } else {
3352 char c = (unsigned char) wParam;
3353 term_seen_key_event(term);
3354 term_keyinput(term, kbd_codepage, &c, 1);
3355 }
3356 return (0);
3357 case WM_CHAR:
3358 case WM_SYSCHAR:
3359 /*
3360 * Nevertheless, we are prepared to deal with WM_CHAR
3361 * messages, should they crop up. So if someone wants to
3362 * post the things to us as part of a macro manoeuvre,
3363 * we're ready to cope.
3364 */
3365 {
3366 static wchar_t pending_surrogate = 0;
3367 wchar_t c = wParam;
3368
3369 if (IS_HIGH_SURROGATE(c)) {
3370 pending_surrogate = c;
3371 } else if (IS_SURROGATE_PAIR(pending_surrogate, c)) {
3372 wchar_t pair[2];
3373 pair[0] = pending_surrogate;
3374 pair[1] = c;
3375 term_keyinputw(term, pair, 2);
3376 } else if (!IS_SURROGATE(c)) {
3377 term_keyinputw(term, &c, 1);
3378 }
3379 }
3380 return 0;
3381 case WM_SYSCOLORCHANGE:
3382 if (conf_get_bool(conf, CONF_system_colour)) {
3383 /* Refresh palette from system colours. */
3384 term_notify_palette_changed(term);
3385 init_palette();
3386 /* Force a repaint of the terminal window. */
3387 term_invalidate(term);
3388 }
3389 break;
3390 case WM_GOT_CLIPDATA:
3391 process_clipdata((HGLOBAL)lParam, wParam);
3392 return 0;
3393 default:
3394 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
3395 bool shift_pressed = false, control_pressed = false;
3396
3397 if (message == WM_MOUSEWHEEL) {
3398 wheel_accumulator += (short)HIWORD(wParam);
3399 shift_pressed=LOWORD(wParam) & MK_SHIFT;
3400 control_pressed=LOWORD(wParam) & MK_CONTROL;
3401 } else {
3402 BYTE keys[256];
3403 wheel_accumulator += (int)wParam;
3404 if (GetKeyboardState(keys)!=0) {
3405 shift_pressed=keys[VK_SHIFT]&0x80;
3406 control_pressed=keys[VK_CONTROL]&0x80;
3407 }
3408 }
3409
3410 /* process events when the threshold is reached */
3411 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3412 int b;
3413
3414 /* reduce amount for next time */
3415 if (wheel_accumulator > 0) {
3416 b = MBT_WHEEL_UP;
3417 wheel_accumulator -= WHEEL_DELTA;
3418 } else if (wheel_accumulator < 0) {
3419 b = MBT_WHEEL_DOWN;
3420 wheel_accumulator += WHEEL_DELTA;
3421 } else
3422 break;
3423
3424 if (send_raw_mouse &&
3425 !(conf_get_bool(conf, CONF_mouse_override) &&
3426 shift_pressed)) {
3427 /* Mouse wheel position is in screen coordinates for
3428 * some reason */
3429 POINT p;
3430 p.x = X_POS(lParam); p.y = Y_POS(lParam);
3431 if (ScreenToClient(hwnd, &p)) {
3432 /* send a mouse-down followed by a mouse up */
3433 term_mouse(term, b, translate_button(b),
3434 MA_CLICK,
3435 TO_CHR_X(p.x),
3436 TO_CHR_Y(p.y), shift_pressed,
3437 control_pressed, is_alt_pressed());
3438 } /* else: not sure when this can fail */
3439 } else {
3440 /* trigger a scroll */
3441 term_scroll(term, 0,
3442 b == MBT_WHEEL_UP ?
3443 -term->rows / 2 : term->rows / 2);
3444 }
3445 }
3446 return 0;
3447 }
3448 }
3449
3450 /*
3451 * Any messages we don't process completely above are passed through to
3452 * DefWindowProc() for default processing.
3453 */
3454 return DefWindowProcW(hwnd, message, wParam, lParam);
3455 }
3456
3457 /*
3458 * Move the system caret. (We maintain one, even though it's
3459 * invisible, for the benefit of blind people: apparently some
3460 * helper software tracks the system caret, so we should arrange to
3461 * have one.)
3462 */
wintw_set_cursor_pos(TermWin * tw,int x,int y)3463 static void wintw_set_cursor_pos(TermWin *tw, int x, int y)
3464 {
3465 int cx, cy;
3466
3467 if (!term->has_focus) return;
3468
3469 /*
3470 * Avoid gratuitously re-updating the cursor position and IMM
3471 * window if there's no actual change required.
3472 */
3473 cx = x * font_width + offset_width;
3474 cy = y * font_height + offset_height;
3475 if (cx == caret_x && cy == caret_y)
3476 return;
3477 caret_x = cx;
3478 caret_y = cy;
3479
3480 sys_cursor_update();
3481 }
3482
sys_cursor_update(void)3483 static void sys_cursor_update(void)
3484 {
3485 COMPOSITIONFORM cf;
3486 HIMC hIMC;
3487
3488 if (!term->has_focus) return;
3489
3490 if (caret_x < 0 || caret_y < 0)
3491 return;
3492
3493 SetCaretPos(caret_x, caret_y);
3494
3495 /* IMM calls on Win98 and beyond only */
3496 if (osPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3497
3498 if (osPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3499 osMinorVersion == 0) return; /* 95 */
3500
3501 /* we should have the IMM functions */
3502 hIMC = ImmGetContext(wgs.term_hwnd);
3503 cf.dwStyle = CFS_POINT;
3504 cf.ptCurrentPos.x = caret_x;
3505 cf.ptCurrentPos.y = caret_y;
3506 ImmSetCompositionWindow(hIMC, &cf);
3507
3508 ImmReleaseContext(wgs.term_hwnd, hIMC);
3509 }
3510
draw_horizontal_line_on_text(int y,int lattr,RECT line_box,COLORREF colour)3511 static void draw_horizontal_line_on_text(int y, int lattr, RECT line_box,
3512 COLORREF colour)
3513 {
3514 if (lattr == LATTR_TOP || lattr == LATTR_BOT) {
3515 y *= 2;
3516 if (lattr == LATTR_BOT)
3517 y -= font_height;
3518 }
3519
3520 if (!(0 <= y && y < font_height))
3521 return;
3522
3523 HPEN oldpen = SelectObject(wintw_hdc, CreatePen(PS_SOLID, 0, colour));
3524 MoveToEx(wintw_hdc, line_box.left, line_box.top + y, NULL);
3525 LineTo(wintw_hdc, line_box.right, line_box.top + y);
3526 oldpen = SelectObject(wintw_hdc, oldpen);
3527 DeleteObject(oldpen);
3528 }
3529
3530 /*
3531 * Draw a line of text in the window, at given character
3532 * coordinates, in given attributes.
3533 *
3534 * We are allowed to fiddle with the contents of `text'.
3535 */
do_text_internal(int x,int y,wchar_t * text,int len,unsigned long attr,int lattr,truecolour truecolour)3536 static void do_text_internal(
3537 int x, int y, wchar_t *text, int len,
3538 unsigned long attr, int lattr, truecolour truecolour)
3539 {
3540 COLORREF fg, bg, t;
3541 int nfg, nbg, nfont;
3542 RECT line_box;
3543 bool force_manual_underline = false;
3544 int fnt_width, char_width;
3545 int text_adjust = 0;
3546 int xoffset = 0;
3547 int maxlen, remaining;
3548 bool opaque;
3549 bool is_cursor = false;
3550 static int *lpDx = NULL;
3551 static size_t lpDx_len = 0;
3552 int *lpDx_maybe;
3553 int len2; /* for SURROGATE PAIR */
3554
3555 lattr &= LATTR_MODE;
3556
3557 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3558
3559 if (attr & ATTR_WIDE)
3560 char_width *= 2;
3561
3562 /* Only want the left half of double width lines */
3563 if (lattr != LATTR_NORM && x*2 >= term->cols)
3564 return;
3565
3566 x *= fnt_width;
3567 y *= font_height;
3568 x += offset_width;
3569 y += offset_height;
3570
3571 if ((attr & TATTR_ACTCURS) && (cursor_type == 0 || term->big_cursor)) {
3572 truecolour.fg = truecolour.bg = optionalrgb_none;
3573 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS|ATTR_DIM);
3574 /* cursor fg and bg */
3575 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3576 is_cursor = true;
3577 }
3578
3579 nfont = 0;
3580 if (vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3581 /* Assume a poorman font is borken in other ways too. */
3582 lattr = LATTR_WIDE;
3583 } else
3584 switch (lattr) {
3585 case LATTR_NORM:
3586 break;
3587 case LATTR_WIDE:
3588 nfont |= FONT_WIDE;
3589 break;
3590 default:
3591 nfont |= FONT_WIDE + FONT_HIGH;
3592 break;
3593 }
3594 if (attr & ATTR_NARROW)
3595 nfont |= FONT_NARROW;
3596
3597 #ifdef USES_VTLINE_HACK
3598 /* Special hack for the VT100 linedraw glyphs. */
3599 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3600 switch ((unsigned char) (text[0])) {
3601 case 0xBA:
3602 text_adjust = -2 * font_height / 5;
3603 break;
3604 case 0xBB:
3605 text_adjust = -1 * font_height / 5;
3606 break;
3607 case 0xBC:
3608 text_adjust = font_height / 5;
3609 break;
3610 case 0xBD:
3611 text_adjust = 2 * font_height / 5;
3612 break;
3613 }
3614 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3615 text_adjust *= 2;
3616 text[0] = ucsdata.unitab_xterm['q'];
3617 if (attr & ATTR_UNDER) {
3618 attr &= ~ATTR_UNDER;
3619 force_manual_underline = true;
3620 }
3621 }
3622 #endif
3623
3624 /* Anything left as an original character set is unprintable. */
3625 if (DIRECT_CHAR(text[0]) &&
3626 (len < 2 || !IS_SURROGATE_PAIR(text[0], text[1]))) {
3627 int i;
3628 for (i = 0; i < len; i++)
3629 text[i] = 0xFFFD;
3630 }
3631
3632 /* OEM CP */
3633 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3634 nfont |= FONT_OEM;
3635
3636 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3637 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3638 if (bold_font_mode == BOLD_FONT && (attr & ATTR_BOLD))
3639 nfont |= FONT_BOLD;
3640 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3641 nfont |= FONT_UNDERLINE;
3642 another_font(nfont);
3643 if (!fonts[nfont]) {
3644 if (nfont & FONT_UNDERLINE)
3645 force_manual_underline = true;
3646 /* Don't do the same for manual bold, it could be bad news. */
3647
3648 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3649 }
3650 another_font(nfont);
3651 if (!fonts[nfont])
3652 nfont = FONT_NORMAL;
3653 if (attr & ATTR_REVERSE) {
3654 struct optionalrgb trgb;
3655
3656 t = nfg;
3657 nfg = nbg;
3658 nbg = t;
3659
3660 trgb = truecolour.fg;
3661 truecolour.fg = truecolour.bg;
3662 truecolour.bg = trgb;
3663 }
3664 if (bold_colours && (attr & ATTR_BOLD) && !is_cursor) {
3665 if (nfg < 16) nfg |= 8;
3666 else if (nfg >= 256) nfg |= 1;
3667 }
3668 if (bold_colours && (attr & ATTR_BLINK)) {
3669 if (nbg < 16) nbg |= 8;
3670 else if (nbg >= 256) nbg |= 1;
3671 }
3672 if (!pal && truecolour.fg.enabled)
3673 fg = RGB(truecolour.fg.r, truecolour.fg.g, truecolour.fg.b);
3674 else
3675 fg = colours[nfg];
3676
3677 if (!pal && truecolour.bg.enabled)
3678 bg = RGB(truecolour.bg.r, truecolour.bg.g, truecolour.bg.b);
3679 else
3680 bg = colours[nbg];
3681
3682 if (!pal && (attr & ATTR_DIM)) {
3683 fg = RGB(GetRValue(fg) * 2 / 3,
3684 GetGValue(fg) * 2 / 3,
3685 GetBValue(fg) * 2 / 3);
3686 }
3687
3688 SelectObject(wintw_hdc, fonts[nfont]);
3689 SetTextColor(wintw_hdc, fg);
3690 SetBkColor(wintw_hdc, bg);
3691 if (attr & TATTR_COMBINING)
3692 SetBkMode(wintw_hdc, TRANSPARENT);
3693 else
3694 SetBkMode(wintw_hdc, OPAQUE);
3695 line_box.left = x;
3696 line_box.top = y;
3697 line_box.right = x + char_width * len;
3698 line_box.bottom = y + font_height;
3699 /* adjust line_box.right for SURROGATE PAIR & VARIATION SELECTOR */
3700 {
3701 int i;
3702 int rc_width = 0;
3703 for (i = 0; i < len ; i++) {
3704 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3705 i++;
3706 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) {
3707 rc_width += char_width;
3708 i++;
3709 } else if (IS_LOW_VARSEL(text[i])) {
3710 /* do nothing */
3711 } else {
3712 rc_width += char_width;
3713 }
3714 }
3715 line_box.right = line_box.left + rc_width;
3716 }
3717
3718 /* Only want the left half of double width lines */
3719 if (line_box.right > font_width*term->cols+offset_width)
3720 line_box.right = font_width*term->cols+offset_width;
3721
3722 if (font_varpitch) {
3723 /*
3724 * If we're using a variable-pitch font, we unconditionally
3725 * draw the glyphs one at a time and centre them in their
3726 * character cells (which means in particular that we must
3727 * disable the lpDx mechanism). This gives slightly odd but
3728 * generally reasonable results.
3729 */
3730 xoffset = char_width / 2;
3731 SetTextAlign(wintw_hdc, TA_TOP | TA_CENTER | TA_NOUPDATECP);
3732 lpDx_maybe = NULL;
3733 maxlen = 1;
3734 } else {
3735 /*
3736 * In a fixed-pitch font, we draw the whole string in one go
3737 * in the normal way.
3738 */
3739 xoffset = 0;
3740 SetTextAlign(wintw_hdc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
3741 lpDx_maybe = lpDx;
3742 maxlen = len;
3743 }
3744
3745 opaque = true; /* start by erasing the rectangle */
3746 for (remaining = len; remaining > 0;
3747 text += len, remaining -= len, x += char_width * len2) {
3748 len = (maxlen < remaining ? maxlen : remaining);
3749 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3750 len2 = len;
3751 if (maxlen == 1) {
3752 if (remaining >= 1 && IS_SURROGATE_PAIR(text[0], text[1]))
3753 len++;
3754 if (remaining-len >= 1 && IS_LOW_VARSEL(text[len]))
3755 len++;
3756 else if (remaining-len >= 2 &&
3757 IS_HIGH_VARSEL(text[len], text[len+1]))
3758 len += 2;
3759 }
3760
3761 if (len > lpDx_len) {
3762 sgrowarray(lpDx, lpDx_len, len);
3763 if (lpDx_maybe) lpDx_maybe = lpDx;
3764 }
3765
3766 {
3767 int i;
3768 /* only last char has dx width in SURROGATE PAIR and
3769 * VARIATION sequence */
3770 for (i = 0; i < len; i++) {
3771 lpDx[i] = char_width;
3772 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3773 if (i > 0) lpDx[i-1] = 0;
3774 lpDx[i] = 0;
3775 i++;
3776 lpDx[i] = char_width;
3777 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i],text[i+1])) {
3778 lpDx[i] = 0;
3779 i++;
3780 lpDx[i] = char_width;
3781 } else if (IS_LOW_VARSEL(text[i])) {
3782 if (i > 0) lpDx[i-1] = 0;
3783 lpDx[i] = char_width;
3784 }
3785 }
3786 }
3787
3788 /* We're using a private area for direct to font. (512 chars.) */
3789 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3790 /* Ho Hum, dbcs fonts are a PITA! */
3791 /* To display on W9x I have to convert to UCS */
3792 static wchar_t *uni_buf = 0;
3793 static int uni_len = 0;
3794 int nlen, mptr;
3795 if (len > uni_len) {
3796 sfree(uni_buf);
3797 uni_len = len;
3798 uni_buf = snewn(uni_len, wchar_t);
3799 }
3800
3801 for(nlen = mptr = 0; mptr<len; mptr++) {
3802 uni_buf[nlen] = 0xFFFD;
3803 if (IsDBCSLeadByteEx(ucsdata.font_codepage,
3804 (BYTE) text[mptr])) {
3805 char dbcstext[2];
3806 dbcstext[0] = text[mptr] & 0xFF;
3807 dbcstext[1] = text[mptr+1] & 0xFF;
3808 lpDx[nlen] += char_width;
3809 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3810 dbcstext, 2, uni_buf+nlen, 1);
3811 mptr++;
3812 }
3813 else
3814 {
3815 char dbcstext[1];
3816 dbcstext[0] = text[mptr] & 0xFF;
3817 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3818 dbcstext, 1, uni_buf+nlen, 1);
3819 }
3820 nlen++;
3821 }
3822 if (nlen <= 0)
3823 return; /* Eeek! */
3824
3825 ExtTextOutW(wintw_hdc, x + xoffset,
3826 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3827 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3828 &line_box, uni_buf, nlen,
3829 lpDx_maybe);
3830 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3831 SetBkMode(wintw_hdc, TRANSPARENT);
3832 ExtTextOutW(wintw_hdc, x + xoffset - 1,
3833 y - font_height * (lattr ==
3834 LATTR_BOT) + text_adjust,
3835 ETO_CLIPPED, &line_box, uni_buf, nlen, lpDx_maybe);
3836 }
3837
3838 lpDx[0] = -1;
3839 } else if (DIRECT_FONT(text[0])) {
3840 static char *directbuf = NULL;
3841 static size_t directlen = 0;
3842
3843 sgrowarray(directbuf, directlen, len);
3844 for (size_t i = 0; i < len; i++)
3845 directbuf[i] = text[i] & 0xFF;
3846
3847 ExtTextOut(wintw_hdc, x + xoffset,
3848 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3849 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3850 &line_box, directbuf, len, lpDx_maybe);
3851 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3852 SetBkMode(wintw_hdc, TRANSPARENT);
3853
3854 /* GRR: This draws the character outside its box and
3855 * can leave 'droppings' even with the clip box! I
3856 * suppose I could loop it one character at a time ...
3857 * yuk.
3858 *
3859 * Or ... I could do a test print with "W", and use +1
3860 * or -1 for this shift depending on if the leftmost
3861 * column is blank...
3862 */
3863 ExtTextOut(wintw_hdc, x + xoffset - 1,
3864 y - font_height * (lattr ==
3865 LATTR_BOT) + text_adjust,
3866 ETO_CLIPPED, &line_box, directbuf, len, lpDx_maybe);
3867 }
3868 } else {
3869 /* And 'normal' unicode characters */
3870 static WCHAR *wbuf = NULL;
3871 static int wlen = 0;
3872 int i;
3873
3874 if (wlen < len) {
3875 sfree(wbuf);
3876 wlen = len;
3877 wbuf = snewn(wlen, WCHAR);
3878 }
3879
3880 for (i = 0; i < len; i++)
3881 wbuf[i] = text[i];
3882
3883 /* print Glyphs as they are, without Windows' Shaping*/
3884 general_textout(wintw_hdc, x + xoffset,
3885 y - font_height * (lattr==LATTR_BOT) + text_adjust,
3886 &line_box, wbuf, len, lpDx,
3887 opaque && !(attr & TATTR_COMBINING));
3888
3889 /* And the shadow bold hack. */
3890 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3891 SetBkMode(wintw_hdc, TRANSPARENT);
3892 ExtTextOutW(wintw_hdc, x + xoffset - 1,
3893 y - font_height * (lattr ==
3894 LATTR_BOT) + text_adjust,
3895 ETO_CLIPPED, &line_box, wbuf, len, lpDx_maybe);
3896 }
3897 }
3898
3899 /*
3900 * If we're looping round again, stop erasing the background
3901 * rectangle.
3902 */
3903 SetBkMode(wintw_hdc, TRANSPARENT);
3904 opaque = false;
3905 }
3906
3907 if (lattr != LATTR_TOP && (force_manual_underline ||
3908 (und_mode == UND_LINE && (attr & ATTR_UNDER))))
3909 draw_horizontal_line_on_text(descent, lattr, line_box, fg);
3910
3911 if (attr & ATTR_STRIKE)
3912 draw_horizontal_line_on_text(font_strikethrough_y, lattr, line_box, fg);
3913 }
3914
3915 /*
3916 * Wrapper that handles combining characters.
3917 */
wintw_draw_text(TermWin * tw,int x,int y,wchar_t * text,int len,unsigned long attr,int lattr,truecolour truecolour)3918 static void wintw_draw_text(
3919 TermWin *tw, int x, int y, wchar_t *text, int len,
3920 unsigned long attr, int lattr, truecolour truecolour)
3921 {
3922 if (attr & TATTR_COMBINING) {
3923 unsigned long a = 0;
3924 int len0 = 1;
3925 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3926 if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1]))
3927 len0 = 2;
3928 if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) {
3929 attr &= ~TATTR_COMBINING;
3930 do_text_internal(x, y, text, len0+1, attr, lattr, truecolour);
3931 text += len0+1;
3932 len -= len0+1;
3933 a = TATTR_COMBINING;
3934 } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) {
3935 attr &= ~TATTR_COMBINING;
3936 do_text_internal(x, y, text, len0+2, attr, lattr, truecolour);
3937 text += len0+2;
3938 len -= len0+2;
3939 a = TATTR_COMBINING;
3940 } else {
3941 attr &= ~TATTR_COMBINING;
3942 }
3943
3944 while (len--) {
3945 if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) {
3946 do_text_internal(x, y, text, 2, attr | a, lattr, truecolour);
3947 len--;
3948 text++;
3949 } else
3950 do_text_internal(x, y, text, 1, attr | a, lattr, truecolour);
3951
3952 text++;
3953 a = TATTR_COMBINING;
3954 }
3955 } else
3956 do_text_internal(x, y, text, len, attr, lattr, truecolour);
3957 }
3958
wintw_draw_cursor(TermWin * tw,int x,int y,wchar_t * text,int len,unsigned long attr,int lattr,truecolour truecolour)3959 static void wintw_draw_cursor(
3960 TermWin *tw, int x, int y, wchar_t *text, int len,
3961 unsigned long attr, int lattr, truecolour truecolour)
3962 {
3963 int fnt_width;
3964 int char_width;
3965 int ctype = cursor_type;
3966
3967 lattr &= LATTR_MODE;
3968
3969 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3970 if (*text != UCSWIDE) {
3971 win_draw_text(tw, x, y, text, len, attr, lattr, truecolour);
3972 return;
3973 }
3974 ctype = 2;
3975 attr |= TATTR_RIGHTCURS;
3976 }
3977
3978 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3979 if (attr & ATTR_WIDE)
3980 char_width *= 2;
3981 x *= fnt_width;
3982 y *= font_height;
3983 x += offset_width;
3984 y += offset_height;
3985
3986 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3987 POINT pts[5];
3988 HPEN oldpen;
3989 pts[0].x = pts[1].x = pts[4].x = x;
3990 pts[2].x = pts[3].x = x + char_width - 1;
3991 pts[0].y = pts[3].y = pts[4].y = y;
3992 pts[1].y = pts[2].y = y + font_height - 1;
3993 oldpen = SelectObject(wintw_hdc, CreatePen(PS_SOLID, 0, colours[261]));
3994 Polyline(wintw_hdc, pts, 5);
3995 oldpen = SelectObject(wintw_hdc, oldpen);
3996 DeleteObject(oldpen);
3997 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3998 int startx, starty, dx, dy, length, i;
3999 if (ctype == 1) {
4000 startx = x;
4001 starty = y + descent;
4002 dx = 1;
4003 dy = 0;
4004 length = char_width;
4005 } else {
4006 int xadjust = 0;
4007 if (attr & TATTR_RIGHTCURS)
4008 xadjust = char_width - 1;
4009 startx = x + xadjust;
4010 starty = y;
4011 dx = 0;
4012 dy = 1;
4013 length = font_height;
4014 }
4015 if (attr & TATTR_ACTCURS) {
4016 HPEN oldpen;
4017 oldpen =
4018 SelectObject(wintw_hdc, CreatePen(PS_SOLID, 0, colours[261]));
4019 MoveToEx(wintw_hdc, startx, starty, NULL);
4020 LineTo(wintw_hdc, startx + dx * length, starty + dy * length);
4021 oldpen = SelectObject(wintw_hdc, oldpen);
4022 DeleteObject(oldpen);
4023 } else {
4024 for (i = 0; i < length; i++) {
4025 if (i % 2 == 0) {
4026 SetPixel(wintw_hdc, startx, starty, colours[261]);
4027 }
4028 startx += dx;
4029 starty += dy;
4030 }
4031 }
4032 }
4033 }
4034
wintw_draw_trust_sigil(TermWin * tw,int x,int y)4035 static void wintw_draw_trust_sigil(TermWin *tw, int x, int y)
4036 {
4037 x *= font_width;
4038 y *= font_height;
4039 x += offset_width;
4040 y += offset_height;
4041
4042 DrawIconEx(wintw_hdc, x, y, trust_icon, font_width * 2, font_height,
4043 0, NULL, DI_NORMAL);
4044 }
4045
4046 /* This function gets the actual width of a character in the normal font.
4047 */
wintw_char_width(TermWin * tw,int uc)4048 static int wintw_char_width(TermWin *tw, int uc)
4049 {
4050 int ibuf = 0;
4051
4052 /* If the font max is the same as the font ave width then this
4053 * function is a no-op.
4054 */
4055 if (!font_dualwidth) return 1;
4056
4057 switch (uc & CSET_MASK) {
4058 case CSET_ASCII:
4059 uc = ucsdata.unitab_line[uc & 0xFF];
4060 break;
4061 case CSET_LINEDRW:
4062 uc = ucsdata.unitab_xterm[uc & 0xFF];
4063 break;
4064 case CSET_SCOACS:
4065 uc = ucsdata.unitab_scoacs[uc & 0xFF];
4066 break;
4067 }
4068 if (DIRECT_FONT(uc)) {
4069 if (ucsdata.dbcs_screenfont) return 1;
4070
4071 /* Speedup, I know of no font where ascii is the wrong width */
4072 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
4073 return 1;
4074
4075 if ( (uc & CSET_MASK) == CSET_ACP ) {
4076 SelectObject(wintw_hdc, fonts[FONT_NORMAL]);
4077 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
4078 another_font(FONT_OEM);
4079 if (!fonts[FONT_OEM]) return 0;
4080
4081 SelectObject(wintw_hdc, fonts[FONT_OEM]);
4082 } else
4083 return 0;
4084
4085 if (GetCharWidth32(wintw_hdc, uc & ~CSET_MASK,
4086 uc & ~CSET_MASK, &ibuf) != 1 &&
4087 GetCharWidth(wintw_hdc, uc & ~CSET_MASK,
4088 uc & ~CSET_MASK, &ibuf) != 1)
4089 return 0;
4090 } else {
4091 /* Speedup, I know of no font where ascii is the wrong width */
4092 if (uc >= ' ' && uc <= '~') return 1;
4093
4094 SelectObject(wintw_hdc, fonts[FONT_NORMAL]);
4095 if (GetCharWidth32W(wintw_hdc, uc, uc, &ibuf) == 1)
4096 /* Okay that one worked */ ;
4097 else if (GetCharWidthW(wintw_hdc, uc, uc, &ibuf) == 1)
4098 /* This should work on 9x too, but it's "less accurate" */ ;
4099 else
4100 return 0;
4101 }
4102
4103 ibuf += font_width / 2 -1;
4104 ibuf /= font_width;
4105
4106 return ibuf;
4107 }
4108
4109 DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));
4110 DECL_WINDOWS_FUNCTION(static, BOOL, ToUnicodeEx,
4111 (UINT, UINT, const BYTE *, LPWSTR, int, UINT, HKL));
4112 DECL_WINDOWS_FUNCTION(static, BOOL, PlaySound, (LPCTSTR, HMODULE, DWORD));
4113
init_winfuncs(void)4114 static void init_winfuncs(void)
4115 {
4116 HMODULE user32_module = load_system32_dll("user32.dll");
4117 HMODULE winmm_module = load_system32_dll("winmm.dll");
4118 HMODULE shcore_module = load_system32_dll("shcore.dll");
4119 GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);
4120 GET_WINDOWS_FUNCTION(user32_module, ToUnicodeEx);
4121 GET_WINDOWS_FUNCTION_PP(winmm_module, PlaySound);
4122 GET_WINDOWS_FUNCTION_NO_TYPECHECK(shcore_module, GetDpiForMonitor);
4123 GET_WINDOWS_FUNCTION_NO_TYPECHECK(user32_module, GetSystemMetricsForDpi);
4124 GET_WINDOWS_FUNCTION_NO_TYPECHECK(user32_module, AdjustWindowRectExForDpi);
4125 }
4126
4127 /*
4128 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
4129 * codes. Returns number of bytes used, zero to drop the message,
4130 * -1 to forward the message to Windows, or another negative number
4131 * to indicate a NUL-terminated "special" string.
4132 */
TranslateKey(UINT message,WPARAM wParam,LPARAM lParam,unsigned char * output)4133 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
4134 unsigned char *output)
4135 {
4136 BYTE keystate[256];
4137 int scan, shift_state;
4138 bool left_alt = false, key_down;
4139 int r, i;
4140 unsigned char *p = output;
4141 static int alt_sum = 0;
4142 int funky_type = conf_get_int(conf, CONF_funky_type);
4143 bool no_applic_k = conf_get_bool(conf, CONF_no_applic_k);
4144 bool ctrlaltkeys = conf_get_bool(conf, CONF_ctrlaltkeys);
4145 bool nethack_keypad = conf_get_bool(conf, CONF_nethack_keypad);
4146 char keypad_key = '\0';
4147
4148 HKL kbd_layout = GetKeyboardLayout(0);
4149
4150 static wchar_t keys_unicode[3];
4151 static int compose_char = 0;
4152 static WPARAM compose_keycode = 0;
4153
4154 r = GetKeyboardState(keystate);
4155 if (!r)
4156 memset(keystate, 0, sizeof(keystate));
4157 else {
4158 #if 0
4159 #define SHOW_TOASCII_RESULT
4160 { /* Tell us all about key events */
4161 static BYTE oldstate[256];
4162 static int first = 1;
4163 static int scan;
4164 int ch;
4165 if (first)
4166 memcpy(oldstate, keystate, sizeof(oldstate));
4167 first = 0;
4168
4169 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
4170 debug("+");
4171 } else if ((HIWORD(lParam) & KF_UP)
4172 && scan == (HIWORD(lParam) & 0xFF)) {
4173 debug(". U");
4174 } else {
4175 debug(".\n");
4176 if (wParam >= VK_F1 && wParam <= VK_F20)
4177 debug("K_F%d", wParam + 1 - VK_F1);
4178 else
4179 switch (wParam) {
4180 case VK_SHIFT:
4181 debug("SHIFT");
4182 break;
4183 case VK_CONTROL:
4184 debug("CTRL");
4185 break;
4186 case VK_MENU:
4187 debug("ALT");
4188 break;
4189 default:
4190 debug("VK_%02x", wParam);
4191 }
4192 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
4193 debug("*");
4194 debug(", S%02x", scan = (HIWORD(lParam) & 0xFF));
4195
4196 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
4197 if (ch >= ' ' && ch <= '~')
4198 debug(", '%c'", ch);
4199 else if (ch)
4200 debug(", $%02x", ch);
4201
4202 if (keys_unicode[0])
4203 debug(", KB0=%04x", keys_unicode[0]);
4204 if (keys_unicode[1])
4205 debug(", KB1=%04x", keys_unicode[1]);
4206 if (keys_unicode[2])
4207 debug(", KB2=%04x", keys_unicode[2]);
4208
4209 if ((keystate[VK_SHIFT] & 0x80) != 0)
4210 debug(", S");
4211 if ((keystate[VK_CONTROL] & 0x80) != 0)
4212 debug(", C");
4213 if ((HIWORD(lParam) & KF_EXTENDED))
4214 debug(", E");
4215 if ((HIWORD(lParam) & KF_UP))
4216 debug(", U");
4217 }
4218
4219 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
4220 else if ((HIWORD(lParam) & KF_UP))
4221 oldstate[wParam & 0xFF] ^= 0x80;
4222 else
4223 oldstate[wParam & 0xFF] ^= 0x81;
4224
4225 for (ch = 0; ch < 256; ch++)
4226 if (oldstate[ch] != keystate[ch])
4227 debug(", M%02x=%02x", ch, keystate[ch]);
4228
4229 memcpy(oldstate, keystate, sizeof(oldstate));
4230 }
4231 #endif
4232
4233 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
4234 keystate[VK_RMENU] = keystate[VK_MENU];
4235 }
4236
4237
4238 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
4239 if ((funky_type == FUNKY_VT400 ||
4240 (funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
4241 !no_applic_k))
4242 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
4243
4244 wParam = VK_EXECUTE;
4245
4246 /* UnToggle NUMLock */
4247 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
4248 keystate[VK_NUMLOCK] ^= 1;
4249 }
4250
4251 /* And write back the 'adjusted' state */
4252 SetKeyboardState(keystate);
4253 }
4254
4255 /* Disable Auto repeat if required */
4256 if (term->repeat_off &&
4257 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
4258 return 0;
4259
4260 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
4261 left_alt = true;
4262
4263 key_down = ((HIWORD(lParam) & KF_UP) == 0);
4264
4265 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
4266 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
4267 if (ctrlaltkeys)
4268 keystate[VK_MENU] = 0;
4269 else {
4270 keystate[VK_RMENU] = 0x80;
4271 left_alt = false;
4272 }
4273 }
4274
4275 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
4276 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
4277 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
4278
4279 /* Note if AltGr was pressed and if it was used as a compose key */
4280 if (!compose_state) {
4281 compose_keycode = 0x100;
4282 if (conf_get_bool(conf, CONF_compose_key)) {
4283 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
4284 compose_keycode = wParam;
4285 }
4286 if (wParam == VK_APPS)
4287 compose_keycode = wParam;
4288 }
4289
4290 if (wParam == compose_keycode) {
4291 if (compose_state == 0
4292 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
4293 1;
4294 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
4295 compose_state = 2;
4296 else
4297 compose_state = 0;
4298 } else if (compose_state == 1 && wParam != VK_CONTROL)
4299 compose_state = 0;
4300
4301 if (compose_state > 1 && left_alt)
4302 compose_state = 0;
4303
4304 /* Sanitize the number pad if not using a PC NumPad */
4305 if (left_alt || (term->app_keypad_keys && !no_applic_k
4306 && funky_type != FUNKY_XTERM)
4307 || funky_type == FUNKY_VT400 || nethack_keypad || compose_state) {
4308 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
4309 int nParam = 0;
4310 switch (wParam) {
4311 case VK_INSERT:
4312 nParam = VK_NUMPAD0;
4313 break;
4314 case VK_END:
4315 nParam = VK_NUMPAD1;
4316 break;
4317 case VK_DOWN:
4318 nParam = VK_NUMPAD2;
4319 break;
4320 case VK_NEXT:
4321 nParam = VK_NUMPAD3;
4322 break;
4323 case VK_LEFT:
4324 nParam = VK_NUMPAD4;
4325 break;
4326 case VK_CLEAR:
4327 nParam = VK_NUMPAD5;
4328 break;
4329 case VK_RIGHT:
4330 nParam = VK_NUMPAD6;
4331 break;
4332 case VK_HOME:
4333 nParam = VK_NUMPAD7;
4334 break;
4335 case VK_UP:
4336 nParam = VK_NUMPAD8;
4337 break;
4338 case VK_PRIOR:
4339 nParam = VK_NUMPAD9;
4340 break;
4341 case VK_DELETE:
4342 nParam = VK_DECIMAL;
4343 break;
4344 }
4345 if (nParam) {
4346 if (keystate[VK_NUMLOCK] & 1)
4347 shift_state |= 1;
4348 wParam = nParam;
4349 }
4350 }
4351 }
4352
4353 /* If a key is pressed and AltGr is not active */
4354 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
4355 /* Okay, prepare for most alts then ... */
4356 if (left_alt)
4357 *p++ = '\033';
4358
4359 /* Lets see if it's a pattern we know all about ... */
4360 if (wParam == VK_PRIOR && shift_state == 1) {
4361 SendMessage(wgs.term_hwnd, WM_VSCROLL, SB_PAGEUP, 0);
4362 return 0;
4363 }
4364 if (wParam == VK_PRIOR && shift_state == 3) { /* ctrl-shift-pageup */
4365 SendMessage(wgs.term_hwnd, WM_VSCROLL, SB_TOP, 0);
4366 return 0;
4367 }
4368 if (wParam == VK_NEXT && shift_state == 3) { /* ctrl-shift-pagedown */
4369 SendMessage(wgs.term_hwnd, WM_VSCROLL, SB_BOTTOM, 0);
4370 return 0;
4371 }
4372
4373 if (wParam == VK_PRIOR && shift_state == 2) {
4374 SendMessage(wgs.term_hwnd, WM_VSCROLL, SB_LINEUP, 0);
4375 return 0;
4376 }
4377 if (wParam == VK_NEXT && shift_state == 1) {
4378 SendMessage(wgs.term_hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
4379 return 0;
4380 }
4381 if (wParam == VK_NEXT && shift_state == 2) {
4382 SendMessage(wgs.term_hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
4383 return 0;
4384 }
4385 if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {
4386 term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));
4387 return 0;
4388 }
4389 if (wParam == VK_INSERT && shift_state == 2) {
4390 switch (conf_get_int(conf, CONF_ctrlshiftins)) {
4391 case CLIPUI_IMPLICIT:
4392 break; /* no need to re-copy to CLIP_LOCAL */
4393 case CLIPUI_EXPLICIT:
4394 term_request_copy(term, clips_system, lenof(clips_system));
4395 break;
4396 default:
4397 break;
4398 }
4399 return 0;
4400 }
4401 if (wParam == VK_INSERT && shift_state == 1) {
4402 switch (conf_get_int(conf, CONF_ctrlshiftins)) {
4403 case CLIPUI_IMPLICIT:
4404 term_request_paste(term, CLIP_LOCAL);
4405 break;
4406 case CLIPUI_EXPLICIT:
4407 term_request_paste(term, CLIP_SYSTEM);
4408 break;
4409 default:
4410 break;
4411 }
4412 return 0;
4413 }
4414 if (wParam == 'C' && shift_state == 3) {
4415 switch (conf_get_int(conf, CONF_ctrlshiftcv)) {
4416 case CLIPUI_IMPLICIT:
4417 break; /* no need to re-copy to CLIP_LOCAL */
4418 case CLIPUI_EXPLICIT:
4419 term_request_copy(term, clips_system, lenof(clips_system));
4420 break;
4421 default:
4422 break;
4423 }
4424 return 0;
4425 }
4426 if (wParam == 'V' && shift_state == 3) {
4427 switch (conf_get_int(conf, CONF_ctrlshiftcv)) {
4428 case CLIPUI_IMPLICIT:
4429 term_request_paste(term, CLIP_LOCAL);
4430 break;
4431 case CLIPUI_EXPLICIT:
4432 term_request_paste(term, CLIP_SYSTEM);
4433 break;
4434 default:
4435 break;
4436 }
4437 return 0;
4438 }
4439 if (left_alt && wParam == VK_F4 && conf_get_bool(conf, CONF_alt_f4)) {
4440 return -1;
4441 }
4442 if (left_alt && wParam == VK_SPACE && conf_get_bool(conf,
4443 CONF_alt_space)) {
4444 SendMessage(wgs.term_hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
4445 return -1;
4446 }
4447 if (left_alt && wParam == VK_RETURN &&
4448 conf_get_bool(conf, CONF_fullscreenonaltenter) &&
4449 (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) {
4450 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
4451 flip_full_screen();
4452 return -1;
4453 }
4454 /* Control-Numlock for app-keypad mode switch */
4455 if (wParam == VK_PAUSE && shift_state == 2) {
4456 term->app_keypad_keys = !term->app_keypad_keys;
4457 return 0;
4458 }
4459
4460 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
4461 *p++ = (conf_get_bool(conf, CONF_bksp_is_delete) ? 0x7F : 0x08);
4462 *p++ = 0;
4463 return -2;
4464 }
4465 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
4466 /* We do the opposite of what is configured */
4467 *p++ = (conf_get_bool(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F);
4468 *p++ = 0;
4469 return -2;
4470 }
4471 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
4472 *p++ = 0x1B;
4473 *p++ = '[';
4474 *p++ = 'Z';
4475 return p - output;
4476 }
4477 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
4478 *p++ = 0;
4479 return p - output;
4480 }
4481 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
4482 *p++ = 160;
4483 return p - output;
4484 }
4485 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
4486 if (backend)
4487 backend_special(backend, SS_BRK, 0);
4488 return 0;
4489 }
4490 if (wParam == VK_PAUSE) { /* Break/Pause */
4491 *p++ = 26;
4492 *p++ = 0;
4493 return -2;
4494 }
4495 /* Control-2 to Control-8 are special */
4496 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
4497 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
4498 return p - output;
4499 }
4500 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
4501 *p++ = 0x1F;
4502 return p - output;
4503 }
4504 if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {
4505 *p++ = 0x1C;
4506 return p - output;
4507 }
4508 if (shift_state == 3 && wParam == 0xDE) {
4509 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
4510 return p - output;
4511 }
4512
4513 switch (wParam) {
4514 case VK_NUMPAD0: keypad_key = '0'; goto numeric_keypad;
4515 case VK_NUMPAD1: keypad_key = '1'; goto numeric_keypad;
4516 case VK_NUMPAD2: keypad_key = '2'; goto numeric_keypad;
4517 case VK_NUMPAD3: keypad_key = '3'; goto numeric_keypad;
4518 case VK_NUMPAD4: keypad_key = '4'; goto numeric_keypad;
4519 case VK_NUMPAD5: keypad_key = '5'; goto numeric_keypad;
4520 case VK_NUMPAD6: keypad_key = '6'; goto numeric_keypad;
4521 case VK_NUMPAD7: keypad_key = '7'; goto numeric_keypad;
4522 case VK_NUMPAD8: keypad_key = '8'; goto numeric_keypad;
4523 case VK_NUMPAD9: keypad_key = '9'; goto numeric_keypad;
4524 case VK_DECIMAL: keypad_key = '.'; goto numeric_keypad;
4525 case VK_ADD: keypad_key = '+'; goto numeric_keypad;
4526 case VK_SUBTRACT: keypad_key = '-'; goto numeric_keypad;
4527 case VK_MULTIPLY: keypad_key = '*'; goto numeric_keypad;
4528 case VK_DIVIDE: keypad_key = '/'; goto numeric_keypad;
4529 case VK_EXECUTE: keypad_key = 'G'; goto numeric_keypad;
4530 /* also the case for VK_RETURN below can sometimes come here */
4531 numeric_keypad:
4532 /* Left Alt overrides all numeric keypad usage to act as
4533 * numeric character code input */
4534 if (left_alt) {
4535 if (keypad_key >= '0' && keypad_key <= '9')
4536 alt_sum = alt_sum * 10 + keypad_key - '0';
4537 else
4538 alt_sum = 0;
4539 break;
4540 }
4541
4542 {
4543 int nchars = format_numeric_keypad_key(
4544 (char *)p, term, keypad_key,
4545 shift_state & 1, shift_state & 2);
4546 if (!nchars) {
4547 /*
4548 * If we didn't get an escape sequence out of the
4549 * numeric keypad key, then that must be because
4550 * we're in Num Lock mode without application
4551 * keypad enabled. In that situation we leave this
4552 * keypress to the ToUnicode/ToAsciiEx handler
4553 * below, which will translate it according to the
4554 * appropriate keypad layout (e.g. so that what a
4555 * Brit thinks of as keypad '.' can become ',' in
4556 * the German layout).
4557 *
4558 * An exception is the keypad Return key: if we
4559 * didn't get an escape sequence for that, we
4560 * treat it like ordinary Return, taking into
4561 * account Telnet special new line codes and
4562 * config options.
4563 */
4564 if (keypad_key == '\r')
4565 goto ordinary_return_key;
4566 break;
4567 }
4568
4569 p += nchars;
4570 return p - output;
4571 }
4572
4573 int fkey_number;
4574 case VK_F1: fkey_number = 1; goto numbered_function_key;
4575 case VK_F2: fkey_number = 2; goto numbered_function_key;
4576 case VK_F3: fkey_number = 3; goto numbered_function_key;
4577 case VK_F4: fkey_number = 4; goto numbered_function_key;
4578 case VK_F5: fkey_number = 5; goto numbered_function_key;
4579 case VK_F6: fkey_number = 6; goto numbered_function_key;
4580 case VK_F7: fkey_number = 7; goto numbered_function_key;
4581 case VK_F8: fkey_number = 8; goto numbered_function_key;
4582 case VK_F9: fkey_number = 9; goto numbered_function_key;
4583 case VK_F10: fkey_number = 10; goto numbered_function_key;
4584 case VK_F11: fkey_number = 11; goto numbered_function_key;
4585 case VK_F12: fkey_number = 12; goto numbered_function_key;
4586 case VK_F13: fkey_number = 13; goto numbered_function_key;
4587 case VK_F14: fkey_number = 14; goto numbered_function_key;
4588 case VK_F15: fkey_number = 15; goto numbered_function_key;
4589 case VK_F16: fkey_number = 16; goto numbered_function_key;
4590 case VK_F17: fkey_number = 17; goto numbered_function_key;
4591 case VK_F18: fkey_number = 18; goto numbered_function_key;
4592 case VK_F19: fkey_number = 19; goto numbered_function_key;
4593 case VK_F20: fkey_number = 20; goto numbered_function_key;
4594 numbered_function_key:
4595 p += format_function_key((char *)p, term, fkey_number,
4596 shift_state & 1, shift_state & 2);
4597 return p - output;
4598
4599 SmallKeypadKey sk_key;
4600 case VK_HOME: sk_key = SKK_HOME; goto small_keypad_key;
4601 case VK_END: sk_key = SKK_END; goto small_keypad_key;
4602 case VK_INSERT: sk_key = SKK_INSERT; goto small_keypad_key;
4603 case VK_DELETE: sk_key = SKK_DELETE; goto small_keypad_key;
4604 case VK_PRIOR: sk_key = SKK_PGUP; goto small_keypad_key;
4605 case VK_NEXT: sk_key = SKK_PGDN; goto small_keypad_key;
4606 small_keypad_key:
4607 /* These keys don't generate terminal input with Ctrl */
4608 if (shift_state & 2)
4609 break;
4610
4611 p += format_small_keypad_key((char *)p, term, sk_key);
4612 return p - output;
4613
4614 char xkey;
4615 case VK_UP: xkey = 'A'; goto arrow_key;
4616 case VK_DOWN: xkey = 'B'; goto arrow_key;
4617 case VK_RIGHT: xkey = 'C'; goto arrow_key;
4618 case VK_LEFT: xkey = 'D'; goto arrow_key;
4619 case VK_CLEAR: xkey = 'G'; goto arrow_key; /* close enough */
4620 arrow_key:
4621 p += format_arrow_key((char *)p, term, xkey, shift_state & 2);
4622 return p - output;
4623
4624 case VK_RETURN:
4625 if (HIWORD(lParam) & KF_EXTENDED) {
4626 keypad_key = '\r';
4627 goto numeric_keypad;
4628 }
4629 ordinary_return_key:
4630 if (shift_state == 0 && term->cr_lf_return) {
4631 *p++ = '\r';
4632 *p++ = '\n';
4633 return p - output;
4634 } else {
4635 *p++ = 0x0D;
4636 *p++ = 0;
4637 return -2;
4638 }
4639 }
4640 }
4641
4642 /* Okay we've done everything interesting; let windows deal with
4643 * the boring stuff */
4644 {
4645 bool capsOn = false;
4646
4647 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4648 if(keystate[VK_CAPITAL] != 0 &&
4649 conf_get_bool(conf, CONF_xlat_capslockcyr)) {
4650 capsOn= !left_alt;
4651 keystate[VK_CAPITAL] = 0;
4652 }
4653
4654 /* XXX how do we know what the max size of the keys array should
4655 * be is? There's indication on MS' website of an Inquire/InquireEx
4656 * functioning returning a KBINFO structure which tells us. */
4657 if (osPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) {
4658 r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode,
4659 lenof(keys_unicode), 0, kbd_layout);
4660 } else {
4661 /* XXX 'keys' parameter is declared in MSDN documentation as
4662 * 'LPWORD lpChar'.
4663 * The experience of a French user indicates that on
4664 * Win98, WORD[] should be passed in, but on Win2K, it should
4665 * be BYTE[]. German WinXP and my Win2K with "US International"
4666 * driver corroborate this.
4667 * Experimentally I've conditionalised the behaviour on the
4668 * Win9x/NT split, but I suspect it's worse than that.
4669 * See wishlist item `win-dead-keys' for more horrible detail
4670 * and speculations. */
4671 int i;
4672 static WORD keys[3];
4673 static BYTE keysb[3];
4674 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4675 if (r > 0) {
4676 for (i = 0; i < r; i++) {
4677 keysb[i] = (BYTE)keys[i];
4678 }
4679 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r,
4680 keys_unicode, lenof(keys_unicode));
4681 }
4682 }
4683 #ifdef SHOW_TOASCII_RESULT
4684 if (r == 1 && !key_down) {
4685 if (alt_sum) {
4686 if (in_utf(term) || ucsdata.dbcs_screenfont)
4687 debug(", (U+%04x)", alt_sum);
4688 else
4689 debug(", LCH(%d)", alt_sum);
4690 } else {
4691 debug(", ACH(%d)", keys_unicode[0]);
4692 }
4693 } else if (r > 0) {
4694 int r1;
4695 debug(", ASC(");
4696 for (r1 = 0; r1 < r; r1++) {
4697 debug("%s%d", r1 ? "," : "", keys_unicode[r1]);
4698 }
4699 debug(")");
4700 }
4701 #endif
4702 if (r > 0) {
4703 WCHAR keybuf;
4704
4705 p = output;
4706 for (i = 0; i < r; i++) {
4707 wchar_t wch = keys_unicode[i];
4708
4709 if (compose_state == 2 && wch >= ' ' && wch < 0x80) {
4710 compose_char = wch;
4711 compose_state++;
4712 continue;
4713 }
4714 if (compose_state == 3 && wch >= ' ' && wch < 0x80) {
4715 int nc;
4716 compose_state = 0;
4717
4718 if ((nc = check_compose(compose_char, wch)) == -1) {
4719 MessageBeep(MB_ICONHAND);
4720 return 0;
4721 }
4722 keybuf = nc;
4723 term_keyinputw(term, &keybuf, 1);
4724 continue;
4725 }
4726
4727 compose_state = 0;
4728
4729 if (!key_down) {
4730 if (alt_sum) {
4731 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4732 keybuf = alt_sum;
4733 term_keyinputw(term, &keybuf, 1);
4734 } else {
4735 char ch = (char) alt_sum;
4736 /*
4737 * We need not bother about stdin
4738 * backlogs here, because in GUI PuTTY
4739 * we can't do anything about it
4740 * anyway; there's no means of asking
4741 * Windows to hold off on KEYDOWN
4742 * messages. We _have_ to buffer
4743 * everything we're sent.
4744 */
4745 term_keyinput(term, -1, &ch, 1);
4746 }
4747 alt_sum = 0;
4748 } else {
4749 term_keyinputw(term, &wch, 1);
4750 }
4751 } else {
4752 if(capsOn && wch < 0x80) {
4753 WCHAR cbuf[2];
4754 cbuf[0] = 27;
4755 cbuf[1] = xlat_uskbd2cyrllic(wch);
4756 term_keyinputw(term, cbuf+!left_alt, 1+!!left_alt);
4757 } else {
4758 WCHAR cbuf[2];
4759 cbuf[0] = '\033';
4760 cbuf[1] = wch;
4761 term_keyinputw(term, cbuf +!left_alt, 1+!!left_alt);
4762 }
4763 }
4764 show_mouseptr(false);
4765 }
4766
4767 /* This is so the ALT-Numpad and dead keys work correctly. */
4768 keys_unicode[0] = 0;
4769
4770 return p - output;
4771 }
4772 /* If we're definitely not building up an ALT-54321 then clear it */
4773 if (!left_alt)
4774 keys_unicode[0] = 0;
4775 /* If we will be using alt_sum fix the 256s */
4776 else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4777 keys_unicode[0] = 10;
4778 }
4779
4780 /*
4781 * ALT alone may or may not want to bring up the System menu.
4782 * If it's not meant to, we return 0 on presses or releases of
4783 * ALT, to show that we've swallowed the keystroke. Otherwise
4784 * we return -1, which means Windows will give the keystroke
4785 * its default handling (i.e. bring up the System menu).
4786 */
4787 if (wParam == VK_MENU && !conf_get_bool(conf, CONF_alt_only))
4788 return 0;
4789
4790 return -1;
4791 }
4792
wintw_set_title(TermWin * tw,const char * title)4793 static void wintw_set_title(TermWin *tw, const char *title)
4794 {
4795 sfree(window_name);
4796 window_name = dupstr(title);
4797 if (conf_get_bool(conf, CONF_win_name_always) || !IsIconic(wgs.term_hwnd))
4798 SetWindowText(wgs.term_hwnd, title);
4799 }
4800
wintw_set_icon_title(TermWin * tw,const char * title)4801 static void wintw_set_icon_title(TermWin *tw, const char *title)
4802 {
4803 sfree(icon_name);
4804 icon_name = dupstr(title);
4805 if (!conf_get_bool(conf, CONF_win_name_always) && IsIconic(wgs.term_hwnd))
4806 SetWindowText(wgs.term_hwnd, title);
4807 }
4808
wintw_set_scrollbar(TermWin * tw,int total,int start,int page)4809 static void wintw_set_scrollbar(TermWin *tw, int total, int start, int page)
4810 {
4811 SCROLLINFO si;
4812
4813 if (!conf_get_bool(conf, is_full_screen() ?
4814 CONF_scrollbar_in_fullscreen : CONF_scrollbar))
4815 return;
4816
4817 si.cbSize = sizeof(si);
4818 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4819 si.nMin = 0;
4820 si.nMax = total - 1;
4821 si.nPage = page;
4822 si.nPos = start;
4823 if (wgs.term_hwnd)
4824 SetScrollInfo(wgs.term_hwnd, SB_VERT, &si, true);
4825 }
4826
wintw_setup_draw_ctx(TermWin * tw)4827 static bool wintw_setup_draw_ctx(TermWin *tw)
4828 {
4829 assert(!wintw_hdc);
4830 wintw_hdc = make_hdc();
4831 return wintw_hdc != NULL;
4832 }
4833
wintw_free_draw_ctx(TermWin * tw)4834 static void wintw_free_draw_ctx(TermWin *tw)
4835 {
4836 assert(wintw_hdc);
4837 free_hdc(wintw_hdc);
4838 wintw_hdc = NULL;
4839 }
4840
4841 /*
4842 * Set up the colour palette.
4843 */
init_palette(void)4844 static void init_palette(void)
4845 {
4846 pal = NULL;
4847 logpal = snew_plus(LOGPALETTE, (OSC4_NCOLOURS - 1) * sizeof(PALETTEENTRY));
4848 logpal->palVersion = 0x300;
4849 logpal->palNumEntries = OSC4_NCOLOURS;
4850 for (unsigned i = 0; i < OSC4_NCOLOURS; i++)
4851 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
4852 }
4853
wintw_palette_set(TermWin * win,unsigned start,unsigned ncolours,const rgb * colours_in)4854 static void wintw_palette_set(TermWin *win, unsigned start,
4855 unsigned ncolours, const rgb *colours_in)
4856 {
4857 assert(start <= OSC4_NCOLOURS);
4858 assert(ncolours <= OSC4_NCOLOURS - start);
4859
4860 for (unsigned i = 0; i < ncolours; i++) {
4861 const rgb *in = &colours_in[i];
4862 PALETTEENTRY *out = &logpal->palPalEntry[i + start];
4863 out->peRed = in->r;
4864 out->peGreen = in->g;
4865 out->peBlue = in->b;
4866 colours[i + start] = RGB(in->r, in->g, in->b) ^ colorref_modifier;
4867 }
4868
4869 bool got_new_palette = false;
4870
4871 if (!tried_pal && conf_get_bool(conf, CONF_try_palette)) {
4872 HDC hdc = GetDC(wgs.term_hwnd);
4873 if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
4874 pal = CreatePalette(logpal);
4875 if (pal) {
4876 SelectPalette(hdc, pal, false);
4877 RealizePalette(hdc);
4878 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), false);
4879
4880 /* Convert all RGB() values in colours[] into PALETTERGB(),
4881 * and ensure we stick to that later */
4882 colorref_modifier = PALETTERGB(0, 0, 0) ^ RGB(0, 0, 0);
4883 for (unsigned i = 0; i < OSC4_NCOLOURS; i++)
4884 colours[i] ^= colorref_modifier;
4885
4886 /* Inhibit the SetPaletteEntries call below */
4887 got_new_palette = true;
4888 }
4889 }
4890 ReleaseDC(wgs.term_hwnd, hdc);
4891 tried_pal = true;
4892 }
4893
4894 if (pal && !got_new_palette) {
4895 /* We already had a palette, so replace the changed colours in the
4896 * existing one. */
4897 SetPaletteEntries(pal, start, ncolours, logpal->palPalEntry + start);
4898
4899 HDC hdc = make_hdc();
4900 UnrealizeObject(pal);
4901 RealizePalette(hdc);
4902 free_hdc(hdc);
4903 }
4904
4905 if (start <= OSC4_COLOUR_bg && OSC4_COLOUR_bg < start + ncolours) {
4906 /* If Default Background changes, we need to ensure any space between
4907 * the text area and the window border is redrawn. */
4908 InvalidateRect(wgs.term_hwnd, NULL, true);
4909 }
4910 }
4911
write_aclip(int clipboard,char * data,int len,bool must_deselect)4912 void write_aclip(int clipboard, char *data, int len, bool must_deselect)
4913 {
4914 HGLOBAL clipdata;
4915 void *lock;
4916
4917 if (clipboard != CLIP_SYSTEM)
4918 return;
4919
4920 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4921 if (!clipdata)
4922 return;
4923 lock = GlobalLock(clipdata);
4924 if (!lock)
4925 return;
4926 memcpy(lock, data, len);
4927 ((unsigned char *) lock)[len] = 0;
4928 GlobalUnlock(clipdata);
4929
4930 if (!must_deselect)
4931 SendMessage(wgs.term_hwnd, WM_IGNORE_CLIP, true, 0);
4932
4933 if (OpenClipboard(wgs.term_hwnd)) {
4934 EmptyClipboard();
4935 SetClipboardData(CF_TEXT, clipdata);
4936 CloseClipboard();
4937 } else
4938 GlobalFree(clipdata);
4939
4940 if (!must_deselect)
4941 SendMessage(wgs.term_hwnd, WM_IGNORE_CLIP, false, 0);
4942 }
4943
4944 typedef struct _rgbindex {
4945 int index;
4946 COLORREF ref;
4947 } rgbindex;
4948
cmpCOLORREF(void * va,void * vb)4949 int cmpCOLORREF(void *va, void *vb)
4950 {
4951 COLORREF a = ((rgbindex *)va)->ref;
4952 COLORREF b = ((rgbindex *)vb)->ref;
4953 return (a < b) ? -1 : (a > b) ? +1 : 0;
4954 }
4955
4956 /*
4957 * Note: unlike write_aclip() this will not append a nul.
4958 */
wintw_clip_write(TermWin * tw,int clipboard,wchar_t * data,int * attr,truecolour * truecolour,int len,bool must_deselect)4959 static void wintw_clip_write(
4960 TermWin *tw, int clipboard, wchar_t *data, int *attr,
4961 truecolour *truecolour, int len, bool must_deselect)
4962 {
4963 HGLOBAL clipdata, clipdata2, clipdata3;
4964 int len2;
4965 void *lock, *lock2, *lock3;
4966
4967 if (clipboard != CLIP_SYSTEM)
4968 return;
4969
4970 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4971
4972 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4973 len * sizeof(wchar_t));
4974 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4975
4976 if (!clipdata || !clipdata2) {
4977 if (clipdata)
4978 GlobalFree(clipdata);
4979 if (clipdata2)
4980 GlobalFree(clipdata2);
4981 return;
4982 }
4983 if (!(lock = GlobalLock(clipdata))) {
4984 GlobalFree(clipdata);
4985 GlobalFree(clipdata2);
4986 return;
4987 }
4988 if (!(lock2 = GlobalLock(clipdata2))) {
4989 GlobalUnlock(clipdata);
4990 GlobalFree(clipdata);
4991 GlobalFree(clipdata2);
4992 return;
4993 }
4994
4995 memcpy(lock, data, len * sizeof(wchar_t));
4996 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4997
4998 if (conf_get_bool(conf, CONF_rtf_paste)) {
4999 wchar_t unitab[256];
5000 strbuf *rtf = strbuf_new();
5001 unsigned char *tdata = (unsigned char *)lock2;
5002 wchar_t *udata = (wchar_t *)lock;
5003 int uindex = 0, tindex = 0;
5004 int multilen, blen, alen, totallen, i;
5005 char before[16], after[4];
5006 int fgcolour, lastfgcolour = -1;
5007 int bgcolour, lastbgcolour = -1;
5008 COLORREF fg, lastfg = -1;
5009 COLORREF bg, lastbg = -1;
5010 int attrBold, lastAttrBold = 0;
5011 int attrUnder, lastAttrUnder = 0;
5012 int palette[OSC4_NCOLOURS];
5013 int numcolours;
5014 tree234 *rgbtree = NULL;
5015 FontSpec *font = conf_get_fontspec(conf, CONF_font);
5016
5017 get_unitab(CP_ACP, unitab, 0);
5018
5019 strbuf_catf(
5020 rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
5021 font->name, font->height*2);
5022
5023 /*
5024 * Add colour palette
5025 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
5026 */
5027
5028 /*
5029 * First - Determine all colours in use
5030 * o Foregound and background colours share the same palette
5031 */
5032 if (attr) {
5033 memset(palette, 0, sizeof(palette));
5034 for (i = 0; i < (len-1); i++) {
5035 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5036 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5037
5038 if (attr[i] & ATTR_REVERSE) {
5039 int tmpcolour = fgcolour; /* Swap foreground and background */
5040 fgcolour = bgcolour;
5041 bgcolour = tmpcolour;
5042 }
5043
5044 if (bold_colours && (attr[i] & ATTR_BOLD)) {
5045 if (fgcolour < 8) /* ANSI colours */
5046 fgcolour += 8;
5047 else if (fgcolour >= 256) /* Default colours */
5048 fgcolour ++;
5049 }
5050
5051 if ((attr[i] & ATTR_BLINK)) {
5052 if (bgcolour < 8) /* ANSI colours */
5053 bgcolour += 8;
5054 else if (bgcolour >= 256) /* Default colours */
5055 bgcolour ++;
5056 }
5057
5058 palette[fgcolour]++;
5059 palette[bgcolour]++;
5060 }
5061
5062 if (truecolour) {
5063 rgbtree = newtree234(cmpCOLORREF);
5064 for (i = 0; i < (len-1); i++) {
5065 if (truecolour[i].fg.enabled) {
5066 rgbindex *rgbp = snew(rgbindex);
5067 rgbp->ref = RGB(truecolour[i].fg.r,
5068 truecolour[i].fg.g,
5069 truecolour[i].fg.b);
5070 if (add234(rgbtree, rgbp) != rgbp)
5071 sfree(rgbp);
5072 }
5073 if (truecolour[i].bg.enabled) {
5074 rgbindex *rgbp = snew(rgbindex);
5075 rgbp->ref = RGB(truecolour[i].bg.r,
5076 truecolour[i].bg.g,
5077 truecolour[i].bg.b);
5078 if (add234(rgbtree, rgbp) != rgbp)
5079 sfree(rgbp);
5080 }
5081 }
5082 }
5083
5084 /*
5085 * Next - Create a reduced palette
5086 */
5087 numcolours = 0;
5088 for (i = 0; i < OSC4_NCOLOURS; i++) {
5089 if (palette[i] != 0)
5090 palette[i] = ++numcolours;
5091 }
5092
5093 if (rgbtree) {
5094 rgbindex *rgbp;
5095 for (i = 0; (rgbp = index234(rgbtree, i)) != NULL; i++)
5096 rgbp->index = ++numcolours;
5097 }
5098
5099 /*
5100 * Finally - Write the colour table
5101 */
5102 put_datapl(rtf, PTRLEN_LITERAL("{\\colortbl ;"));
5103
5104 for (i = 0; i < OSC4_NCOLOURS; i++) {
5105 if (palette[i] != 0) {
5106 const PALETTEENTRY *pe = &logpal->palPalEntry[i];
5107 strbuf_catf(rtf, "\\red%d\\green%d\\blue%d;",
5108 pe->peRed, pe->peGreen, pe->peBlue);
5109 }
5110 }
5111 if (rgbtree) {
5112 rgbindex *rgbp;
5113 for (i = 0; (rgbp = index234(rgbtree, i)) != NULL; i++)
5114 strbuf_catf(rtf, "\\red%d\\green%d\\blue%d;",
5115 GetRValue(rgbp->ref), GetGValue(rgbp->ref),
5116 GetBValue(rgbp->ref));
5117 }
5118 put_datapl(rtf, PTRLEN_LITERAL("}"));
5119 }
5120
5121 /*
5122 * We want to construct a piece of RTF that specifies the
5123 * same Unicode text. To do this we will read back in
5124 * parallel from the Unicode data in `udata' and the
5125 * non-Unicode data in `tdata'. For each character in
5126 * `tdata' which becomes the right thing in `udata' when
5127 * looked up in `unitab', we just copy straight over from
5128 * tdata. For each one that doesn't, we must WCToMB it
5129 * individually and produce a \u escape sequence.
5130 *
5131 * It would probably be more robust to just bite the bullet
5132 * and WCToMB each individual Unicode character one by one,
5133 * then MBToWC each one back to see if it was an accurate
5134 * translation; but that strikes me as a horrifying number
5135 * of Windows API calls so I want to see if this faster way
5136 * will work. If it screws up badly we can always revert to
5137 * the simple and slow way.
5138 */
5139 while (tindex < len2 && uindex < len &&
5140 tdata[tindex] && udata[uindex]) {
5141 if (tindex + 1 < len2 &&
5142 tdata[tindex] == '\r' &&
5143 tdata[tindex+1] == '\n') {
5144 tindex++;
5145 uindex++;
5146 }
5147
5148 /*
5149 * Set text attributes
5150 */
5151 if (attr) {
5152 /*
5153 * Determine foreground and background colours
5154 */
5155 if (truecolour && truecolour[tindex].fg.enabled) {
5156 fgcolour = -1;
5157 fg = RGB(truecolour[tindex].fg.r,
5158 truecolour[tindex].fg.g,
5159 truecolour[tindex].fg.b);
5160 } else {
5161 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5162 fg = -1;
5163 }
5164
5165 if (truecolour && truecolour[tindex].bg.enabled) {
5166 bgcolour = -1;
5167 bg = RGB(truecolour[tindex].bg.r,
5168 truecolour[tindex].bg.g,
5169 truecolour[tindex].bg.b);
5170 } else {
5171 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5172 bg = -1;
5173 }
5174
5175 if (attr[tindex] & ATTR_REVERSE) {
5176 int tmpcolour = fgcolour; /* Swap foreground and background */
5177 fgcolour = bgcolour;
5178 bgcolour = tmpcolour;
5179
5180 COLORREF tmpref = fg;
5181 fg = bg;
5182 bg = tmpref;
5183 }
5184
5185 if (bold_colours && (attr[tindex] & ATTR_BOLD) && (fgcolour >= 0)) {
5186 if (fgcolour < 8) /* ANSI colours */
5187 fgcolour += 8;
5188 else if (fgcolour >= 256) /* Default colours */
5189 fgcolour ++;
5190 }
5191
5192 if ((attr[tindex] & ATTR_BLINK) && (bgcolour >= 0)) {
5193 if (bgcolour < 8) /* ANSI colours */
5194 bgcolour += 8;
5195 else if (bgcolour >= 256) /* Default colours */
5196 bgcolour ++;
5197 }
5198
5199 /*
5200 * Collect other attributes
5201 */
5202 if (bold_font_mode != BOLD_NONE)
5203 attrBold = attr[tindex] & ATTR_BOLD;
5204 else
5205 attrBold = 0;
5206
5207 attrUnder = attr[tindex] & ATTR_UNDER;
5208
5209 /*
5210 * Reverse video
5211 * o If video isn't reversed, ignore colour attributes for default foregound
5212 * or background.
5213 * o Special case where bolded text is displayed using the default foregound
5214 * and background colours - force to bolded RTF.
5215 */
5216 if (!(attr[tindex] & ATTR_REVERSE)) {
5217 if (bgcolour >= 256) /* Default color */
5218 bgcolour = -1; /* No coloring */
5219
5220 if (fgcolour >= 256) { /* Default colour */
5221 if (bold_colours && (fgcolour & 1) && bgcolour == -1)
5222 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
5223
5224 fgcolour = -1; /* No coloring */
5225 }
5226 }
5227
5228 /*
5229 * Write RTF text attributes
5230 */
5231 if ((lastfgcolour != fgcolour) || (lastfg != fg)) {
5232 lastfgcolour = fgcolour;
5233 lastfg = fg;
5234 if (fg == -1) {
5235 strbuf_catf(rtf, "\\cf%d ",
5236 (fgcolour >= 0) ? palette[fgcolour] : 0);
5237 } else {
5238 rgbindex rgb, *rgbp;
5239 rgb.ref = fg;
5240 if ((rgbp = find234(rgbtree, &rgb, NULL)) != NULL)
5241 strbuf_catf(rtf, "\\cf%d ", rgbp->index);
5242 }
5243 }
5244
5245 if ((lastbgcolour != bgcolour) || (lastbg != bg)) {
5246 lastbgcolour = bgcolour;
5247 lastbg = bg;
5248 if (bg == -1)
5249 strbuf_catf(rtf, "\\highlight%d ",
5250 (bgcolour >= 0) ? palette[bgcolour] : 0);
5251 else {
5252 rgbindex rgb, *rgbp;
5253 rgb.ref = bg;
5254 if ((rgbp = find234(rgbtree, &rgb, NULL)) != NULL)
5255 strbuf_catf(rtf, "\\highlight%d ", rgbp->index);
5256 }
5257 }
5258
5259 if (lastAttrBold != attrBold) {
5260 lastAttrBold = attrBold;
5261 put_datapl(rtf, attrBold ?
5262 PTRLEN_LITERAL("\\b ") :
5263 PTRLEN_LITERAL("\\b0 "));
5264 }
5265
5266 if (lastAttrUnder != attrUnder) {
5267 lastAttrUnder = attrUnder;
5268 put_datapl(rtf, attrUnder ?
5269 PTRLEN_LITERAL("\\ul ") :
5270 PTRLEN_LITERAL("\\ulnone "));
5271 }
5272 }
5273
5274 if (unitab[tdata[tindex]] == udata[uindex]) {
5275 multilen = 1;
5276 before[0] = '\0';
5277 after[0] = '\0';
5278 blen = alen = 0;
5279 } else {
5280 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
5281 NULL, 0, NULL, NULL);
5282 if (multilen != 1) {
5283 blen = sprintf(before, "{\\uc%d\\u%d", (int)multilen,
5284 (int)udata[uindex]);
5285 alen = 1; strcpy(after, "}");
5286 } else {
5287 blen = sprintf(before, "\\u%d", (int)udata[uindex]);
5288 alen = 0; after[0] = '\0';
5289 }
5290 }
5291 assert(tindex + multilen <= len2);
5292 totallen = blen + alen;
5293 for (i = 0; i < multilen; i++) {
5294 if (tdata[tindex+i] == '\\' ||
5295 tdata[tindex+i] == '{' ||
5296 tdata[tindex+i] == '}')
5297 totallen += 2;
5298 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
5299 totallen += 6; /* \par\r\n */
5300 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
5301 totallen += 4;
5302 else
5303 totallen++;
5304 }
5305
5306 put_data(rtf, before, blen);
5307 for (i = 0; i < multilen; i++) {
5308 if (tdata[tindex+i] == '\\' ||
5309 tdata[tindex+i] == '{' ||
5310 tdata[tindex+i] == '}') {
5311 put_byte(rtf, '\\');
5312 put_byte(rtf, tdata[tindex+i]);
5313 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
5314 put_datapl(rtf, PTRLEN_LITERAL("\\par\r\n"));
5315 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
5316 strbuf_catf(rtf, "\\'%02x", tdata[tindex+i]);
5317 } else {
5318 put_byte(rtf, tdata[tindex+i]);
5319 }
5320 }
5321 put_data(rtf, after, alen);
5322
5323 tindex += multilen;
5324 uindex++;
5325 }
5326
5327 put_datapl(rtf, PTRLEN_LITERAL("}\0\0")); /* Terminate RTF stream */
5328
5329 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtf->len);
5330 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
5331 memcpy(lock3, rtf->u, rtf->len);
5332 GlobalUnlock(clipdata3);
5333 }
5334 strbuf_free(rtf);
5335
5336 if (rgbtree) {
5337 rgbindex *rgbp;
5338 while ((rgbp = delpos234(rgbtree, 0)) != NULL)
5339 sfree(rgbp);
5340 freetree234(rgbtree);
5341 }
5342 } else
5343 clipdata3 = NULL;
5344
5345 GlobalUnlock(clipdata);
5346 GlobalUnlock(clipdata2);
5347
5348 if (!must_deselect)
5349 SendMessage(wgs.term_hwnd, WM_IGNORE_CLIP, true, 0);
5350
5351 if (OpenClipboard(wgs.term_hwnd)) {
5352 EmptyClipboard();
5353 SetClipboardData(CF_UNICODETEXT, clipdata);
5354 SetClipboardData(CF_TEXT, clipdata2);
5355 if (clipdata3)
5356 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
5357 CloseClipboard();
5358 } else {
5359 GlobalFree(clipdata);
5360 GlobalFree(clipdata2);
5361 }
5362
5363 if (!must_deselect)
5364 SendMessage(wgs.term_hwnd, WM_IGNORE_CLIP, false, 0);
5365 }
5366
clipboard_read_threadfunc(void * param)5367 static DWORD WINAPI clipboard_read_threadfunc(void *param)
5368 {
5369 HWND hwnd = (HWND)param;
5370 HGLOBAL clipdata;
5371
5372 if (OpenClipboard(NULL)) {
5373 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
5374 SendMessage(hwnd, WM_GOT_CLIPDATA,
5375 (WPARAM)true, (LPARAM)clipdata);
5376 } else if ((clipdata = GetClipboardData(CF_TEXT))) {
5377 SendMessage(hwnd, WM_GOT_CLIPDATA,
5378 (WPARAM)false, (LPARAM)clipdata);
5379 }
5380 CloseClipboard();
5381 }
5382
5383 return 0;
5384 }
5385
process_clipdata(HGLOBAL clipdata,bool unicode)5386 static void process_clipdata(HGLOBAL clipdata, bool unicode)
5387 {
5388 wchar_t *clipboard_contents = NULL;
5389 size_t clipboard_length = 0;
5390
5391 if (unicode) {
5392 wchar_t *p = GlobalLock(clipdata);
5393 wchar_t *p2;
5394
5395 if (p) {
5396 /* Unwilling to rely on Windows having wcslen() */
5397 for (p2 = p; *p2; p2++);
5398 clipboard_length = p2 - p;
5399 clipboard_contents = snewn(clipboard_length + 1, wchar_t);
5400 memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));
5401 clipboard_contents[clipboard_length] = L'\0';
5402 term_do_paste(term, clipboard_contents, clipboard_length);
5403 }
5404 } else {
5405 char *s = GlobalLock(clipdata);
5406 int i;
5407
5408 if (s) {
5409 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
5410 clipboard_contents = snewn(i, wchar_t);
5411 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,
5412 clipboard_contents, i);
5413 clipboard_length = i - 1;
5414 clipboard_contents[clipboard_length] = L'\0';
5415 term_do_paste(term, clipboard_contents, clipboard_length);
5416 }
5417 }
5418
5419 sfree(clipboard_contents);
5420 }
5421
wintw_clip_request_paste(TermWin * tw,int clipboard)5422 static void wintw_clip_request_paste(TermWin *tw, int clipboard)
5423 {
5424 assert(clipboard == CLIP_SYSTEM);
5425
5426 /*
5427 * I always thought pasting was synchronous in Windows; the
5428 * clipboard access functions certainly _look_ synchronous,
5429 * unlike the X ones. But in fact it seems that in some
5430 * situations the contents of the clipboard might not be
5431 * immediately available, and the clipboard-reading functions
5432 * may block. This leads to trouble if the application
5433 * delivering the clipboard data has to get hold of it by -
5434 * for example - talking over a network connection which is
5435 * forwarded through this very PuTTY.
5436 *
5437 * Hence, we spawn a subthread to read the clipboard, and do
5438 * our paste when it's finished. The thread will send a
5439 * message back to our main window when it terminates, and
5440 * that tells us it's OK to paste.
5441 */
5442 DWORD in_threadid; /* required for Win9x */
5443 HANDLE hThread = CreateThread(NULL, 0, clipboard_read_threadfunc,
5444 wgs.term_hwnd, 0, &in_threadid);
5445 if (hThread)
5446 CloseHandle(hThread); /* we don't need the thread handle */
5447 }
5448
5449 /*
5450 * Print a modal (Really Bad) message box and perform a fatal exit.
5451 */
modalfatalbox(const char * fmt,...)5452 void modalfatalbox(const char *fmt, ...)
5453 {
5454 va_list ap;
5455 char *message, *title;
5456
5457 va_start(ap, fmt);
5458 message = dupvprintf(fmt, ap);
5459 va_end(ap);
5460 show_mouseptr(true);
5461 title = dupprintf("%s Fatal Error", appname);
5462 MessageBox(wgs.term_hwnd, message, title,
5463 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
5464 sfree(message);
5465 sfree(title);
5466 cleanup_exit(1);
5467 }
5468
5469 /*
5470 * Print a message box and don't close the connection.
5471 */
nonfatal(const char * fmt,...)5472 void nonfatal(const char *fmt, ...)
5473 {
5474 va_list ap;
5475 char *message, *title;
5476
5477 va_start(ap, fmt);
5478 message = dupvprintf(fmt, ap);
5479 va_end(ap);
5480 show_mouseptr(true);
5481 title = dupprintf("%s Error", appname);
5482 MessageBox(wgs.term_hwnd, message, title, MB_ICONERROR | MB_OK);
5483 sfree(message);
5484 sfree(title);
5485 }
5486
flash_window_ex(DWORD dwFlags,UINT uCount,DWORD dwTimeout)5487 static bool flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)
5488 {
5489 if (p_FlashWindowEx) {
5490 FLASHWINFO fi;
5491 fi.cbSize = sizeof(fi);
5492 fi.hwnd = wgs.term_hwnd;
5493 fi.dwFlags = dwFlags;
5494 fi.uCount = uCount;
5495 fi.dwTimeout = dwTimeout;
5496 return (*p_FlashWindowEx)(&fi);
5497 }
5498 else
5499 return false; /* shrug */
5500 }
5501
5502 static void flash_window(int mode);
5503 static long next_flash;
5504 static bool flashing = false;
5505
5506 /*
5507 * Timer for platforms where we must maintain window flashing manually
5508 * (e.g., Win95).
5509 */
flash_window_timer(void * ctx,unsigned long now)5510 static void flash_window_timer(void *ctx, unsigned long now)
5511 {
5512 if (flashing && now == next_flash) {
5513 flash_window(1);
5514 }
5515 }
5516
5517 /*
5518 * Manage window caption / taskbar flashing, if enabled.
5519 * 0 = stop, 1 = maintain, 2 = start
5520 */
flash_window(int mode)5521 static void flash_window(int mode)
5522 {
5523 int beep_ind = conf_get_int(conf, CONF_beep_ind);
5524 if ((mode == 0) || (beep_ind == B_IND_DISABLED)) {
5525 /* stop */
5526 if (flashing) {
5527 flashing = false;
5528 if (p_FlashWindowEx)
5529 flash_window_ex(FLASHW_STOP, 0, 0);
5530 else
5531 FlashWindow(wgs.term_hwnd, false);
5532 }
5533
5534 } else if (mode == 2) {
5535 /* start */
5536 if (!flashing) {
5537 flashing = true;
5538 if (p_FlashWindowEx) {
5539 /* For so-called "steady" mode, we use uCount=2, which
5540 * seems to be the traditional number of flashes used
5541 * by user notifications (e.g., by Explorer).
5542 * uCount=0 appears to enable continuous flashing, per
5543 * "flashing" mode, although I haven't seen this
5544 * documented. */
5545 flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
5546 (beep_ind == B_IND_FLASH ? 0 : 2),
5547 0 /* system cursor blink rate */);
5548 /* No need to schedule timer */
5549 } else {
5550 FlashWindow(wgs.term_hwnd, true);
5551 next_flash = schedule_timer(450, flash_window_timer,
5552 wgs.term_hwnd);
5553 }
5554 }
5555
5556 } else if ((mode == 1) && (beep_ind == B_IND_FLASH)) {
5557 /* maintain */
5558 if (flashing && !p_FlashWindowEx) {
5559 FlashWindow(wgs.term_hwnd, true); /* toggle */
5560 next_flash = schedule_timer(450, flash_window_timer,
5561 wgs.term_hwnd);
5562 }
5563 }
5564 }
5565
5566 /*
5567 * Beep.
5568 */
wintw_bell(TermWin * tw,int mode)5569 static void wintw_bell(TermWin *tw, int mode)
5570 {
5571 if (mode == BELL_DEFAULT) {
5572 /*
5573 * For MessageBeep style bells, we want to be careful of
5574 * timing, because they don't have the nice property of
5575 * PlaySound bells that each one cancels the previous
5576 * active one. So we limit the rate to one per 50ms or so.
5577 */
5578 static long lastbeep = 0;
5579 long beepdiff;
5580
5581 beepdiff = GetTickCount() - lastbeep;
5582 if (beepdiff >= 0 && beepdiff < 50)
5583 return;
5584 MessageBeep(MB_OK);
5585 /*
5586 * The above MessageBeep call takes time, so we record the
5587 * time _after_ it finishes rather than before it starts.
5588 */
5589 lastbeep = GetTickCount();
5590 } else if (mode == BELL_WAVEFILE) {
5591 Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile);
5592 if (!p_PlaySound || !p_PlaySound(bell_wavefile->path, NULL,
5593 SND_ASYNC | SND_FILENAME)) {
5594 char *buf, *otherbuf;
5595 show_mouseptr(true);
5596 buf = dupprintf(
5597 "Unable to play sound file\n%s\nUsing default sound instead",
5598 bell_wavefile->path);
5599 otherbuf = dupprintf("%s Sound Error", appname);
5600 MessageBox(wgs.term_hwnd, buf, otherbuf,
5601 MB_OK | MB_ICONEXCLAMATION);
5602 sfree(buf);
5603 sfree(otherbuf);
5604 conf_set_int(conf, CONF_beep, BELL_DEFAULT);
5605 }
5606 } else if (mode == BELL_PCSPEAKER) {
5607 static long lastbeep = 0;
5608 long beepdiff;
5609
5610 beepdiff = GetTickCount() - lastbeep;
5611 if (beepdiff >= 0 && beepdiff < 50)
5612 return;
5613
5614 /*
5615 * We must beep in different ways depending on whether this
5616 * is a 95-series or NT-series OS.
5617 */
5618 if (osPlatformId == VER_PLATFORM_WIN32_NT)
5619 Beep(800, 100);
5620 else
5621 MessageBeep(-1);
5622 lastbeep = GetTickCount();
5623 }
5624 /* Otherwise, either visual bell or disabled; do nothing here */
5625 if (!term->has_focus) {
5626 flash_window(2); /* start */
5627 }
5628 }
5629
5630 /*
5631 * Minimise or restore the window in response to a server-side
5632 * request.
5633 */
wintw_set_minimised(TermWin * tw,bool minimised)5634 static void wintw_set_minimised(TermWin *tw, bool minimised)
5635 {
5636 if (IsIconic(wgs.term_hwnd)) {
5637 if (!minimised)
5638 ShowWindow(wgs.term_hwnd, SW_RESTORE);
5639 } else {
5640 if (minimised)
5641 ShowWindow(wgs.term_hwnd, SW_MINIMIZE);
5642 }
5643 }
5644
5645 /*
5646 * Move the window in response to a server-side request.
5647 */
wintw_move(TermWin * tw,int x,int y)5648 static void wintw_move(TermWin *tw, int x, int y)
5649 {
5650 int resize_action = conf_get_int(conf, CONF_resize_action);
5651 if (resize_action == RESIZE_DISABLED ||
5652 resize_action == RESIZE_FONT ||
5653 IsZoomed(wgs.term_hwnd))
5654 return;
5655
5656 SetWindowPos(wgs.term_hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5657 }
5658
5659 /*
5660 * Move the window to the top or bottom of the z-order in response
5661 * to a server-side request.
5662 */
wintw_set_zorder(TermWin * tw,bool top)5663 static void wintw_set_zorder(TermWin *tw, bool top)
5664 {
5665 if (conf_get_bool(conf, CONF_alwaysontop))
5666 return; /* ignore */
5667 SetWindowPos(wgs.term_hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5668 SWP_NOMOVE | SWP_NOSIZE);
5669 }
5670
5671 /*
5672 * Refresh the window in response to a server-side request.
5673 */
wintw_refresh(TermWin * tw)5674 static void wintw_refresh(TermWin *tw)
5675 {
5676 InvalidateRect(wgs.term_hwnd, NULL, true);
5677 }
5678
5679 /*
5680 * Maximise or restore the window in response to a server-side
5681 * request.
5682 */
wintw_set_maximised(TermWin * tw,bool maximised)5683 static void wintw_set_maximised(TermWin *tw, bool maximised)
5684 {
5685 if (IsZoomed(wgs.term_hwnd)) {
5686 if (!maximised)
5687 ShowWindow(wgs.term_hwnd, SW_RESTORE);
5688 } else {
5689 if (maximised)
5690 ShowWindow(wgs.term_hwnd, SW_MAXIMIZE);
5691 }
5692 }
5693
5694 /*
5695 * See if we're in full-screen mode.
5696 */
is_full_screen()5697 static bool is_full_screen()
5698 {
5699 if (!IsZoomed(wgs.term_hwnd))
5700 return false;
5701 if (GetWindowLongPtr(wgs.term_hwnd, GWL_STYLE) & WS_CAPTION)
5702 return false;
5703 return true;
5704 }
5705
5706 /* Get the rect/size of a full screen window using the nearest available
5707 * monitor in multimon systems; default to something sensible if only
5708 * one monitor is present. */
get_fullscreen_rect(RECT * ss)5709 static bool get_fullscreen_rect(RECT * ss)
5710 {
5711 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5712 HMONITOR mon;
5713 MONITORINFO mi;
5714 mon = MonitorFromWindow(wgs.term_hwnd, MONITOR_DEFAULTTONEAREST);
5715 mi.cbSize = sizeof(mi);
5716 GetMonitorInfo(mon, &mi);
5717
5718 /* structure copy */
5719 *ss = mi.rcMonitor;
5720 return true;
5721 #else
5722 /* could also use code like this:
5723 ss->left = ss->top = 0;
5724 ss->right = GetSystemMetrics(SM_CXSCREEN);
5725 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5726 */
5727 return GetClientRect(GetDesktopWindow(), ss);
5728 #endif
5729 }
5730
5731
5732 /*
5733 * Go full-screen. This should only be called when we are already
5734 * maximised.
5735 */
make_full_screen()5736 static void make_full_screen()
5737 {
5738 DWORD style;
5739 RECT ss;
5740
5741 assert(IsZoomed(wgs.term_hwnd));
5742
5743 if (is_full_screen())
5744 return;
5745
5746 /* Remove the window furniture. */
5747 style = GetWindowLongPtr(wgs.term_hwnd, GWL_STYLE);
5748 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5749 if (conf_get_bool(conf, CONF_scrollbar_in_fullscreen))
5750 style |= WS_VSCROLL;
5751 else
5752 style &= ~WS_VSCROLL;
5753 SetWindowLongPtr(wgs.term_hwnd, GWL_STYLE, style);
5754
5755 /* Resize ourselves to exactly cover the nearest monitor. */
5756 get_fullscreen_rect(&ss);
5757 SetWindowPos(wgs.term_hwnd, HWND_TOP, ss.left, ss.top,
5758 ss.right - ss.left, ss.bottom - ss.top, SWP_FRAMECHANGED);
5759
5760 /* We may have changed size as a result */
5761
5762 reset_window(0);
5763
5764 /* Tick the menu item in the System and context menus. */
5765 {
5766 int i;
5767 for (i = 0; i < lenof(popup_menus); i++)
5768 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);
5769 }
5770 }
5771
5772 /*
5773 * Clear the full-screen attributes.
5774 */
clear_full_screen()5775 static void clear_full_screen()
5776 {
5777 DWORD oldstyle, style;
5778
5779 /* Reinstate the window furniture. */
5780 style = oldstyle = GetWindowLongPtr(wgs.term_hwnd, GWL_STYLE);
5781 style |= WS_CAPTION | WS_BORDER;
5782 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
5783 style &= ~WS_THICKFRAME;
5784 else
5785 style |= WS_THICKFRAME;
5786 if (conf_get_bool(conf, CONF_scrollbar))
5787 style |= WS_VSCROLL;
5788 else
5789 style &= ~WS_VSCROLL;
5790 if (style != oldstyle) {
5791 SetWindowLongPtr(wgs.term_hwnd, GWL_STYLE, style);
5792 SetWindowPos(wgs.term_hwnd, NULL, 0, 0, 0, 0,
5793 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5794 SWP_FRAMECHANGED);
5795 }
5796
5797 /* Untick the menu item in the System and context menus. */
5798 {
5799 int i;
5800 for (i = 0; i < lenof(popup_menus); i++)
5801 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);
5802 }
5803 }
5804
5805 /*
5806 * Toggle full-screen mode.
5807 */
flip_full_screen()5808 static void flip_full_screen()
5809 {
5810 if (is_full_screen()) {
5811 ShowWindow(wgs.term_hwnd, SW_RESTORE);
5812 } else if (IsZoomed(wgs.term_hwnd)) {
5813 make_full_screen();
5814 } else {
5815 SendMessage(wgs.term_hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5816 ShowWindow(wgs.term_hwnd, SW_MAXIMIZE);
5817 }
5818 }
5819
win_seat_output(Seat * seat,bool is_stderr,const void * data,size_t len)5820 static size_t win_seat_output(Seat *seat, bool is_stderr,
5821 const void *data, size_t len)
5822 {
5823 return term_data(term, is_stderr, data, len);
5824 }
5825
win_seat_eof(Seat * seat)5826 static bool win_seat_eof(Seat *seat)
5827 {
5828 return true; /* do respond to incoming EOF with outgoing */
5829 }
5830
win_seat_get_userpass_input(Seat * seat,prompts_t * p,bufchain * input)5831 static int win_seat_get_userpass_input(
5832 Seat *seat, prompts_t *p, bufchain *input)
5833 {
5834 int ret;
5835 ret = cmdline_get_passwd_input(p);
5836 if (ret == -1)
5837 ret = term_get_userpass_input(term, p, input);
5838 return ret;
5839 }
5840
win_seat_set_trust_status(Seat * seat,bool trusted)5841 static bool win_seat_set_trust_status(Seat *seat, bool trusted)
5842 {
5843 term_set_trust_status(term, trusted);
5844 return true;
5845 }
5846
win_seat_get_cursor_position(Seat * seat,int * x,int * y)5847 static bool win_seat_get_cursor_position(Seat *seat, int *x, int *y)
5848 {
5849 term_get_cursor_position(term, x, y);
5850 return true;
5851 }
5852
win_seat_get_window_pixel_size(Seat * seat,int * x,int * y)5853 static bool win_seat_get_window_pixel_size(Seat *seat, int *x, int *y)
5854 {
5855 RECT r;
5856 GetWindowRect(wgs.term_hwnd, &r);
5857 *x = r.right - r.left;
5858 *y = r.bottom - r.top;
5859 return true;
5860 }
5861