Implement cygw32
[bpt/emacs.git] / src / w32select.c
CommitLineData
b46a6a83 1/* Selection processing for Emacs on the Microsoft Windows API.
e9bffc61 2
acaf905b 3Copyright (C) 1993-1994, 2001-2012 Free Software Foundation, Inc.
41a48e45 4
3b7ad313
EN
5This file is part of GNU Emacs.
6
9ec0b715 7GNU Emacs is free software: you can redistribute it and/or modify
3b7ad313 8it under the terms of the GNU General Public License as published by
9ec0b715
GM
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
3b7ad313
EN
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
9ec0b715 18along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
ee78dc32 19
52c7f9ee
JR
20/* Written by Kevin Gallo, Benjamin Riefenstahl */
21
22
23/*
24 * Notes on usage of selection-coding-system and
25 * next-selection-coding-system on MS Windows:
26 *
27 * The selection coding system variables apply only to the version of
28 * the clipboard data that is closest in type, i.e. when a 16-bit
29 * Unicode coding system is given, they apply to he Unicode clipboard
30 * (CF_UNICODETEXT), when a well-known console codepage is given, they
31 * apply to the console version of the clipboard data (CF_OEMTEXT),
32 * else they apply to the normal 8-bit text clipboard (CF_TEXT).
b56ceb92 33 *
52c7f9ee
JR
34 * When pasting (getting data from the OS), the clipboard format that
35 * matches the {next-}selection-coding-system is retrieved. If
36 * Unicode is requested, but not available, 8-bit text (CF_TEXT) is
37 * used. In all other cases the OS will transparently convert
38 * formats, so no other fallback is needed.
39 *
40 * When copying or cutting (sending data to the OS), the data is
41 * announced and stored internally, but only actually rendered on
fa463103 42 * request. The requestor determines the format provided. The
52c7f9ee
JR
43 * {next-}selection-coding-system is only used, when its corresponding
44 * clipboard type matches the type requested.
45 *
46 * Scenarios to use the facilities for customizing the selection
47 * coding system are:
b56ceb92 48 *
52c7f9ee
JR
49 * ;; Generally use KOI8-R instead of the russian MS codepage for
50 * ;; the 8-bit clipboard.
51 * (set-selection-coding-system 'koi8-r-dos)
b56ceb92 52 *
52c7f9ee 53 * Or
b56ceb92 54 *
52c7f9ee
JR
55 * ;; Create a special clipboard copy function that uses codepage
56 * ;; 1253 (Greek) to copy Greek text to a specific non-Unicode
57 * ;; application.
58 * (defun greek-copy (beg end)
59 * (interactive "r")
60 * (set-next-selection-coding-system 'cp1253-dos)
61 * (copy-region-as-kill beg end))
62 * (global-set-key "\C-c\C-c" 'greek-copy)
63 */
64
65/*
66 * Ideas for further directions:
67 *
68 * The encoding and decoding routines could be moved to Lisp code
69 * similar to how xselect.c does it (using well-known routine names
70 * for the delayed rendering). If the definition of which clipboard
71 * types should be supported is also moved to Lisp, functionality
72 * could be expanded to CF_HTML, CF_RTF and maybe other types.
73 */
b56ceb92 74
ee78dc32 75#include <config.h>
d7306fe6 76#include <setjmp.h>
ee78dc32 77#include "lisp.h"
fbd6baed 78#include "w32term.h" /* for all of the w32 includes */
52c7f9ee 79#include "w32heap.h" /* os_subtype */
ee78dc32 80#include "blockinput.h"
bbb059f3
AI
81#include "charset.h"
82#include "coding.h"
f7d05dc4 83#include "composite.h"
ee78dc32 84
0fda9b75
DC
85#ifdef CYGWIN
86#include <string.h>
87#include <stdio.h>
88#define _memccpy memccpy
89#endif
52c7f9ee
JR
90
91static HGLOBAL convert_to_handle_as_ascii (void);
92static HGLOBAL convert_to_handle_as_coded (Lisp_Object coding_system);
93static Lisp_Object render (Lisp_Object oformat);
94static Lisp_Object render_locale (void);
b56ceb92
JB
95static Lisp_Object render_all (Lisp_Object ignore);
96static void run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg);
52c7f9ee
JR
97static Lisp_Object lisp_error_handler (Lisp_Object error);
98static LRESULT CALLBACK owner_callback (HWND win, UINT msg,
99 WPARAM wp, LPARAM lp);
100static HWND create_owner (void);
101
102static void setup_config (void);
103static BOOL WINAPI enum_locale_callback (/*const*/ char* loc_string);
104static UINT cp_from_locale (LCID lcid, UINT format);
105static Lisp_Object coding_from_cp (UINT codepage);
9a38f8d5
KH
106static Lisp_Object validate_coding_system (Lisp_Object coding_system);
107static void setup_windows_coding_system (Lisp_Object coding_system,
108 struct coding_system * coding);
52c7f9ee
JR
109
110
111/* A remnant from X11: Symbol for the CLIPBORD selection type. Other
112 selections are not used on Windows, so we don't need symbols for
113 PRIMARY and SECONDARY. */
9aa94bd5
KH
114Lisp_Object QCLIPBOARD;
115
52c7f9ee
JR
116/* Internal pseudo-constants, initialized in globals_of_w32select()
117 based on current system parameters. */
118static LCID DEFAULT_LCID;
119static UINT ANSICP, OEMCP;
120static Lisp_Object QUNICODE, QANSICP, QOEMCP;
121
122/* A hidden window just for the clipboard management. */
123static HWND clipboard_owner;
124/* A flag to tell WM_DESTROYCLIPBOARD who is to blame this time (just
125 checking GetClipboardOwner() doesn't work, sadly). */
126static int modifying_clipboard = 0;
127
128/* Configured transfer parameters, based on the last inspection of
129 selection-coding-system. */
130static Lisp_Object cfg_coding_system;
131static UINT cfg_codepage;
132static LCID cfg_lcid;
133static UINT cfg_clipboard_type;
134
135/* The current state for delayed rendering. */
136static Lisp_Object current_text;
137static Lisp_Object current_coding_system;
138static int current_requires_encoding, current_num_nls;
139static UINT current_clipboard_type;
140static LCID current_lcid;
141
142#if TRACE
143#define ONTRACE(stmt) stmt
144#else
145#define ONTRACE(stmt) /*stmt*/
146#endif
147
148
149/* This function assumes that there is no multibyte character in
150 current_text, so we can short-cut encoding. */
151
152static HGLOBAL
153convert_to_handle_as_ascii (void)
ee78dc32 154{
52c7f9ee
JR
155 HGLOBAL htext = NULL;
156 int nbytes;
157 int truelen;
158 unsigned char *src;
159 unsigned char *dst;
41a48e45 160
52c7f9ee 161 ONTRACE (fprintf (stderr, "convert_to_handle_as_ascii\n"));
41a48e45 162
52c7f9ee
JR
163 nbytes = SBYTES (current_text) + 1;
164 src = SDATA (current_text);
41a48e45 165
52c7f9ee
JR
166 /* We need to add to the size the number of LF chars where we have
167 to insert CR chars (the standard CF_TEXT clipboard format uses
168 CRLF line endings, while Emacs uses just LF internally). */
41a48e45 169
52c7f9ee
JR
170 truelen = nbytes + current_num_nls;
171
172 if ((htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, truelen)) == NULL)
173 return NULL;
41a48e45 174
52c7f9ee
JR
175 if ((dst = (unsigned char *) GlobalLock (htext)) == NULL)
176 {
177 GlobalFree (htext);
178 return NULL;
179 }
180
181 /* convert to CRLF line endings expected by clipboard */
182 while (1)
183 {
184 unsigned char *next;
185 /* copy next line or remaining bytes including '\0' */
186 next = _memccpy (dst, src, '\n', nbytes);
187 if (next)
188 {
189 /* copied one line ending with '\n' */
190 int copied = next - dst;
191 nbytes -= copied;
192 src += copied;
193 /* insert '\r' before '\n' */
194 next[-1] = '\r';
195 next[0] = '\n';
196 dst = next + 1;
197 }
198 else
199 /* copied remaining partial line -> now finished */
200 break;
201 }
202
203 GlobalUnlock (htext);
204
205 return htext;
ee78dc32
GV
206}
207
52c7f9ee
JR
208/* This function assumes that there are multibyte or NUL characters in
209 current_text, or that we need to construct Unicode. It runs the
210 text through the encoding machinery. */
211
212static HGLOBAL
213convert_to_handle_as_coded (Lisp_Object coding_system)
ee78dc32 214{
9a38f8d5 215 HGLOBAL htext;
52c7f9ee 216 unsigned char *dst = NULL;
52c7f9ee 217 struct coding_system coding;
52c7f9ee 218
b56ceb92 219 ONTRACE (fprintf (stderr, "convert_to_handle_as_coded: %s\n",
52c7f9ee
JR
220 SDATA (SYMBOL_NAME (coding_system))));
221
9a38f8d5 222 setup_windows_coding_system (coding_system, &coding);
ed3751c8 223 coding.dst_bytes = SBYTES (current_text) * 2;
23f86fce 224 coding.destination = xmalloc (coding.dst_bytes);
9a38f8d5
KH
225 encode_coding_object (&coding, current_text, 0, 0,
226 SCHARS (current_text), SBYTES (current_text), Qnil);
41a48e45 227
9a38f8d5 228 htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, coding.produced +2);
41a48e45 229
52c7f9ee
JR
230 if (htext != NULL)
231 dst = (unsigned char *) GlobalLock (htext);
41a48e45 232
52c7f9ee
JR
233 if (dst != NULL)
234 {
9a38f8d5 235 memcpy (dst, coding.destination, coding.produced);
52c7f9ee
JR
236 /* Add the string terminator. Add two NULs in case we are
237 producing Unicode here. */
238 dst[coding.produced] = dst[coding.produced+1] = '\0';
52c7f9ee 239
9a38f8d5 240 GlobalUnlock (htext);
52c7f9ee
JR
241 }
242
9a38f8d5
KH
243 xfree (coding.destination);
244
52c7f9ee 245 return htext;
ee78dc32
GV
246}
247
52c7f9ee
JR
248static Lisp_Object
249render (Lisp_Object oformat)
ee78dc32 250{
52c7f9ee
JR
251 HGLOBAL htext = NULL;
252 UINT format = XFASTINT (oformat);
253
254 ONTRACE (fprintf (stderr, "render\n"));
255
256 if (NILP (current_text))
257 return Qnil;
258
259 if (current_requires_encoding || format == CF_UNICODETEXT)
260 {
261 if (format == current_clipboard_type)
262 htext = convert_to_handle_as_coded (current_coding_system);
263 else
264 switch (format)
265 {
266 case CF_UNICODETEXT:
267 htext = convert_to_handle_as_coded (QUNICODE);
268 break;
269 case CF_TEXT:
270 case CF_OEMTEXT:
271 {
272 Lisp_Object cs;
273 cs = coding_from_cp (cp_from_locale (current_lcid, format));
274 htext = convert_to_handle_as_coded (cs);
275 break;
276 }
277 }
278 }
279 else
280 htext = convert_to_handle_as_ascii ();
281
282 ONTRACE (fprintf (stderr, "render: htext = 0x%08X\n", (unsigned) htext));
283
284 if (htext == NULL)
285 return Qnil;
286
287 if (SetClipboardData (format, htext) == NULL)
288 {
ed3751c8 289 GlobalFree (htext);
52c7f9ee
JR
290 return Qnil;
291 }
292
293 return Qt;
ee78dc32
GV
294}
295
52c7f9ee
JR
296static Lisp_Object
297render_locale (void)
ee78dc32 298{
52c7f9ee
JR
299 HANDLE hlocale = NULL;
300 LCID * lcid_ptr;
301
302 ONTRACE (fprintf (stderr, "render_locale\n"));
303
304 if (current_lcid == LOCALE_NEUTRAL || current_lcid == DEFAULT_LCID)
305 return Qt;
306
307 hlocale = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, sizeof (current_lcid));
308 if (hlocale == NULL)
309 return Qnil;
310
311 if ((lcid_ptr = (LCID *) GlobalLock (hlocale)) == NULL)
312 {
ed3751c8 313 GlobalFree (hlocale);
52c7f9ee
JR
314 return Qnil;
315 }
316
317 *lcid_ptr = current_lcid;
318 GlobalUnlock (hlocale);
319
320 if (SetClipboardData (CF_LOCALE, hlocale) == NULL)
321 {
ed3751c8 322 GlobalFree (hlocale);
52c7f9ee
JR
323 return Qnil;
324 }
325
326 return Qt;
327}
328
329/* At the end of the program, we want to ensure that our clipboard
330 data survives us. This code will do that. */
331
332static Lisp_Object
b56ceb92 333render_all (Lisp_Object ignore)
52c7f9ee
JR
334{
335 ONTRACE (fprintf (stderr, "render_all\n"));
336
337 /* According to the docs we should not call OpenClipboard() here,
338 but testing on W2K and working code in other projects shows that
339 it is actually necessary. */
340
341 OpenClipboard (NULL);
342
fa463103 343 /* There is no useful means to report errors here, there are none
52c7f9ee
JR
344 expected anyway, and even if there were errors, they wouldn't do
345 any harm. So we just go ahead and do what has to be done without
346 bothering with error handling. */
347
348 ++modifying_clipboard;
349 EmptyClipboard ();
350 --modifying_clipboard;
351
352 /* For text formats that we don't render here, the OS can use its
353 own translation rules instead, so we don't really need to offer
354 everything. To minimize memory consumption we cover three
355 possible situations based on our primary format as detected from
356 selection-coding-system (see setup_config()):
357
358 - Post CF_TEXT only. Let the OS convert to CF_OEMTEXT and the OS
359 (on NT) or the application (on 9x/Me) convert to
360 CF_UNICODETEXT.
361
362 - Post CF_OEMTEXT only. Similar automatic conversions happen as
363 for CF_TEXT.
364
365 - Post CF_UNICODETEXT + CF_TEXT. 9x itself ignores
366 CF_UNICODETEXT, even though some applications can still handle
367 it.
368
369 Note 1: We render the less capable CF_TEXT *before* the more
370 capable CF_UNICODETEXT, to prevent clobbering through automatic
371 conversions, just in case.
372
373 Note 2: We could check os_subtype here and only render the
374 additional CF_TEXT on 9x/Me. But OTOH with
375 current_clipboard_type == CF_UNICODETEXT we don't involve the
376 automatic conversions anywhere else, so to get consistent
377 results, we probably don't want to rely on it here either. */
378
ed3751c8 379 render_locale ();
52c7f9ee
JR
380
381 if (current_clipboard_type == CF_UNICODETEXT)
382 render (make_number (CF_TEXT));
383 render (make_number (current_clipboard_type));
384
385 CloseClipboard ();
386
387 return Qnil;
388}
389
390static void
b56ceb92 391run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg)
52c7f9ee
JR
392{
393 /* FIXME: This works but it doesn't feel right. Too much fiddling
394 with global variables and calling strange looking functions. Is
395 this really the right way to run Lisp callbacks? */
396
7684e57b 397 extern int waiting_for_input; /* from keyboard.c */
52c7f9ee 398 int owfi;
41a48e45 399
ee78dc32 400 BLOCK_INPUT;
41a48e45 401
52c7f9ee
JR
402 /* Fsignal calls abort() if it sees that waiting_for_input is
403 set. */
404 owfi = waiting_for_input;
405 waiting_for_input = 0;
406
407 internal_condition_case_1 (code, arg, Qt, lisp_error_handler);
408
409 waiting_for_input = owfi;
41a48e45 410
ee78dc32 411 UNBLOCK_INPUT;
52c7f9ee 412}
41a48e45 413
52c7f9ee
JR
414static Lisp_Object
415lisp_error_handler (Lisp_Object error)
416{
417 Vsignaling_function = Qnil;
418 cmd_error_internal (error, "Error in delayed clipboard rendering: ");
419 Vinhibit_quit = Qt;
420 return Qt;
ee78dc32
GV
421}
422
ee78dc32 423
52c7f9ee
JR
424static LRESULT CALLBACK
425owner_callback (HWND win, UINT msg, WPARAM wp, LPARAM lp)
ee78dc32 426{
52c7f9ee
JR
427 switch (msg)
428 {
429 case WM_RENDERFORMAT:
430 ONTRACE (fprintf (stderr, "WM_RENDERFORMAT\n"));
431 run_protected (render, make_number (wp));
432 return 0;
433
434 case WM_RENDERALLFORMATS:
435 ONTRACE (fprintf (stderr, "WM_RENDERALLFORMATS\n"));
436 run_protected (render_all, Qnil);
437 return 0;
438
439 case WM_DESTROYCLIPBOARD:
440 if (!modifying_clipboard)
441 {
442 ONTRACE (fprintf (stderr, "WM_DESTROYCLIPBOARD (other)\n"));
443 current_text = Qnil;
444 current_coding_system = Qnil;
445 }
446 else
447 {
448 ONTRACE (fprintf (stderr, "WM_DESTROYCLIPBOARD (self)\n"));
449 }
450 return 0;
0ece9ef6 451
52c7f9ee
JR
452 case WM_DESTROY:
453 if (win == clipboard_owner)
454 clipboard_owner = NULL;
455 break;
456 }
41a48e45 457
52c7f9ee
JR
458 return DefWindowProc (win, msg, wp, lp);
459}
41a48e45 460
52c7f9ee
JR
461static HWND
462create_owner (void)
463{
464 static const char CLASSNAME[] = "Emacs Clipboard";
465 WNDCLASS wc;
69cddef0 466
52c7f9ee
JR
467 memset (&wc, 0, sizeof (wc));
468 wc.lpszClassName = CLASSNAME;
469 wc.lpfnWndProc = owner_callback;
470 RegisterClass (&wc);
471
472 return CreateWindow (CLASSNAME, CLASSNAME, 0, 0, 0, 0, 0, NULL, NULL,
473 NULL, NULL);
474}
475
476/* Called on exit by term_ntproc() in w32.c */
477
478void
479term_w32select (void)
480{
481 /* This is needed to trigger WM_RENDERALLFORMATS. */
482 if (clipboard_owner != NULL)
483 DestroyWindow (clipboard_owner);
484}
0ece9ef6 485
52c7f9ee
JR
486static void
487setup_config (void)
488{
489 const char *coding_name;
490 const char *cp;
491 char *end;
492 int slen;
9a38f8d5
KH
493 Lisp_Object coding_system;
494 Lisp_Object dos_coding_system;
52c7f9ee
JR
495
496 CHECK_SYMBOL (Vselection_coding_system);
497
9a38f8d5 498 coding_system = NILP (Vnext_selection_coding_system) ?
52c7f9ee 499 Vselection_coding_system : Vnext_selection_coding_system;
9a38f8d5
KH
500
501 dos_coding_system = validate_coding_system (coding_system);
502 if (NILP (dos_coding_system))
503 Fsignal (Qerror,
504 list2 (build_string ("Coding system is invalid or doesn't have "
505 "an eol variant for dos line ends"),
506 coding_system));
507
508 /* Check if we have it cached */
52c7f9ee 509 if (!NILP (cfg_coding_system)
9a38f8d5 510 && EQ (cfg_coding_system, dos_coding_system))
52c7f9ee 511 return;
9a38f8d5 512 cfg_coding_system = dos_coding_system;
b56ceb92 513
52c7f9ee
JR
514 /* Set some sensible fallbacks */
515 cfg_codepage = ANSICP;
516 cfg_lcid = LOCALE_NEUTRAL;
517 cfg_clipboard_type = CF_TEXT;
518
519 /* Interpret the coding system symbol name */
520 coding_name = SDATA (SYMBOL_NAME (cfg_coding_system));
521
522 /* "(.*-)?utf-16.*" -> CF_UNICODETEXT */
523 cp = strstr (coding_name, "utf-16");
524 if (cp != NULL && (cp == coding_name || cp[-1] == '-'))
0ece9ef6 525 {
52c7f9ee
JR
526 cfg_clipboard_type = CF_UNICODETEXT;
527 return;
0ece9ef6 528 }
69cddef0 529
52c7f9ee
JR
530 /* "cp[0-9]+.*" or "windows-[0-9]+.*" -> CF_TEXT or CF_OEMTEXT */
531 slen = strlen (coding_name);
532 if (slen >= 4 && coding_name[0] == 'c' && coding_name[1] == 'p')
533 cp = coding_name + 2;
534 else if (slen >= 10 && memcmp (coding_name, "windows-", 8) == 0)
535 cp = coding_name + 8;
536 else
537 return;
538
539 end = (char*)cp;
540 cfg_codepage = strtol (cp, &end, 10);
541
542 /* Error return from strtol() or number of digits < 2 -> Restore the
543 default and drop it. */
544 if (cfg_codepage == 0 || (end-cp) < 2 )
545 {
546 cfg_codepage = ANSICP;
547 return;
548 }
bbb059f3 549
52c7f9ee
JR
550 /* Is it the currently active system default? */
551 if (cfg_codepage == ANSICP)
552 {
553 /* cfg_clipboard_type = CF_TEXT; */
554 return;
555 }
556 if (cfg_codepage == OEMCP)
557 {
558 cfg_clipboard_type = CF_OEMTEXT;
559 return;
560 }
69cddef0 561
52c7f9ee
JR
562 /* Else determine a suitable locale the hard way. */
563 EnumSystemLocales (enum_locale_callback, LCID_INSTALLED);
564}
69cddef0 565
52c7f9ee
JR
566static BOOL WINAPI
567enum_locale_callback (/*const*/ char* loc_string)
568{
569 LCID lcid;
570 UINT codepage;
69cddef0 571
52c7f9ee 572 lcid = strtoul (loc_string, NULL, 16);
bbb059f3 573
52c7f9ee
JR
574 /* Is the wanted codepage the "ANSI" codepage for this locale? */
575 codepage = cp_from_locale (lcid, CF_TEXT);
576 if (codepage == cfg_codepage)
577 {
578 cfg_lcid = lcid;
579 cfg_clipboard_type = CF_TEXT;
580 return FALSE; /* Stop enumeration */
581 }
b56ceb92 582
52c7f9ee
JR
583 /* Is the wanted codepage the OEM codepage for this locale? */
584 codepage = cp_from_locale (lcid, CF_OEMTEXT);
585 if (codepage == cfg_codepage)
586 {
587 cfg_lcid = lcid;
588 cfg_clipboard_type = CF_OEMTEXT;
589 return FALSE; /* Stop enumeration */
590 }
41a48e45 591
52c7f9ee
JR
592 return TRUE; /* Continue enumeration */
593}
41a48e45 594
52c7f9ee
JR
595static UINT
596cp_from_locale (LCID lcid, UINT format)
597{
598 char buffer[20] = "";
599 UINT variant, cp;
0108f679 600
52c7f9ee
JR
601 variant =
602 format == CF_TEXT ? LOCALE_IDEFAULTANSICODEPAGE : LOCALE_IDEFAULTCODEPAGE;
bbb059f3 603
52c7f9ee
JR
604 GetLocaleInfo (lcid, variant, buffer, sizeof (buffer));
605 cp = strtoul (buffer, NULL, 10);
bf2133d7 606
52c7f9ee
JR
607 if (cp == CP_ACP)
608 return ANSICP;
609 else if (cp == CP_OEMCP)
610 return OEMCP;
611 else
612 return cp;
613}
bf2133d7 614
52c7f9ee
JR
615static Lisp_Object
616coding_from_cp (UINT codepage)
617{
618 char buffer[30];
619 sprintf (buffer, "cp%d-dos", (int) codepage);
620 return intern (buffer);
9a38f8d5
KH
621 /* We don't need to check that this coding system actually exists
622 right here, because that is done later for all coding systems
623 used, regardless of where they originate. */
ee78dc32 624}
06466d9a 625
9a38f8d5
KH
626static Lisp_Object
627validate_coding_system (Lisp_Object coding_system)
628{
629 Lisp_Object eol_type;
630
631 /* Make sure the input is valid. */
632 if (NILP (Fcoding_system_p (coding_system)))
633 return Qnil;
634
635 /* Make sure we use a DOS coding system as mandated by the system
636 specs. */
637 eol_type = Fcoding_system_eol_type (coding_system);
638
639 /* Already a DOS coding system? */
640 if (EQ (eol_type, make_number (1)))
641 return coding_system;
642
643 /* Get EOL_TYPE vector of the base of CODING_SYSTEM. */
644 if (!VECTORP (eol_type))
645 {
646 eol_type = Fcoding_system_eol_type (Fcoding_system_base (coding_system));
647 if (!VECTORP (eol_type))
648 return Qnil;
649 }
650
651 return AREF (eol_type, 1);
652}
653
654static void
655setup_windows_coding_system (Lisp_Object coding_system,
656 struct coding_system * coding)
657{
658 memset (coding, 0, sizeof (*coding));
659 setup_coding_system (coding_system, coding);
660
661 /* Unset CODING_ANNOTATE_COMPOSITION_MASK. Previous code had
662 comments about crashes in encode_coding_iso2022 trying to
663 dereference a null pointer when composition was on. Selection
664 data should not contain any composition sequence on Windows.
665
666 CODING_ANNOTATION_MASK also includes
667 CODING_ANNOTATE_DIRECTION_MASK and CODING_ANNOTATE_CHARSET_MASK,
668 which both apply to ISO6429 only. We don't know if these really
669 need to be unset on Windows, but it probably doesn't hurt
670 either. */
671 coding->mode &= ~CODING_ANNOTATION_MASK;
672 coding->mode |= CODING_MODE_LAST_BLOCK | CODING_MODE_SAFE_ENCODING;
673}
674
675
06466d9a 676
33f09670
JR
677DEFUN ("w32-set-clipboard-data", Fw32_set_clipboard_data,
678 Sw32_set_clipboard_data, 1, 2, 0,
679 doc: /* This sets the clipboard data to the given text. */)
5842a27b 680 (Lisp_Object string, Lisp_Object ignored)
ee78dc32
GV
681{
682 BOOL ok = TRUE;
69cddef0 683 int nbytes;
69cddef0
GV
684 unsigned char *src;
685 unsigned char *dst;
52c7f9ee 686 unsigned char *end;
06466d9a 687
52c7f9ee
JR
688 /* This parameter used to be the current frame, but we don't use
689 that any more. */
690 (void) ignored;
41a48e45 691
b7826503 692 CHECK_STRING (string);
41a48e45 693
52c7f9ee 694 setup_config ();
41a48e45 695
52c7f9ee
JR
696 current_text = string;
697 current_coding_system = cfg_coding_system;
698 current_clipboard_type = cfg_clipboard_type;
699 current_lcid = cfg_lcid;
700 current_num_nls = 0;
701 current_requires_encoding = 0;
b56ceb92 702
ee78dc32 703 BLOCK_INPUT;
69cddef0 704
52c7f9ee
JR
705 /* Check for non-ASCII characters. While we are at it, count the
706 number of LFs, so we know how many CRs we will have to add later
707 (just in the case where we can use our internal ASCII rendering,
708 see code and comment in convert_to_handle_as_ascii() above). */
709 nbytes = SBYTES (string);
d5db4077 710 src = SDATA (string);
0ece9ef6 711
52c7f9ee 712 for (dst = src, end = src+nbytes; dst < end; dst++)
0ece9ef6 713 {
52c7f9ee
JR
714 if (*dst == '\n')
715 current_num_nls++;
716 else if (*dst >= 0x80 || *dst == 0)
717 {
718 current_requires_encoding = 1;
719 break;
720 }
0ece9ef6 721 }
69cddef0 722
52c7f9ee
JR
723 if (!current_requires_encoding)
724 {
725 /* If all we have is ASCII we don't need to pretend we offer
726 anything fancy. */
727 current_coding_system = Qraw_text;
728 current_clipboard_type = CF_TEXT;
729 current_lcid = LOCALE_NEUTRAL;
730 }
0108f679 731
52c7f9ee 732 if (!OpenClipboard (clipboard_owner))
ee78dc32 733 goto error;
06466d9a 734
52c7f9ee
JR
735 ++modifying_clipboard;
736 ok = EmptyClipboard ();
737 --modifying_clipboard;
06466d9a 738
52c7f9ee
JR
739 /* If we have something non-ASCII we may want to set a locale. We
740 do that directly (non-delayed), as it's just a small bit. */
741 if (ok)
ed3751c8 742 ok = !NILP (render_locale ());
06466d9a 743
52c7f9ee
JR
744 if (ok)
745 {
746 if (clipboard_owner == NULL)
747 {
748 /* If for some reason we don't have a clipboard_owner, we
749 just set the text format as chosen by the configuration
750 and than forget about the whole thing. */
ed3751c8 751 ok = !NILP (render (make_number (current_clipboard_type)));
52c7f9ee
JR
752 current_text = Qnil;
753 current_coding_system = Qnil;
754 }
755 else
756 {
757 /* Advertise all supported formats so that whatever the
fa463103 758 requestor chooses, only one encoding step needs to be
52c7f9ee
JR
759 made. This is intentionally different from what we do in
760 the handler for WM_RENDERALLFORMATS. */
761 SetClipboardData (CF_UNICODETEXT, NULL);
762 SetClipboardData (CF_TEXT, NULL);
763 SetClipboardData (CF_OEMTEXT, NULL);
764 }
765 }
41a48e45 766
6383ca22
JR
767 CloseClipboard ();
768
52c7f9ee
JR
769 /* With delayed rendering we haven't really "used" this coding
770 system yet, and it's even unclear if we ever will. But this is a
771 way to tell the upper level what we *would* use under ideal
772 circumstances.
41a48e45 773
52c7f9ee
JR
774 We don't signal the actually used coding-system later when we
775 finally render, because that can happen at any time and we don't
776 want to disturb the "foreground" action. */
777 if (ok)
778 Vlast_coding_system_used = current_coding_system;
6383ca22 779
52c7f9ee 780 Vnext_selection_coding_system = Qnil;
ee79d1aa 781
ee78dc32
GV
782 if (ok) goto done;
783
784 error:
41a48e45 785
ee78dc32 786 ok = FALSE;
52c7f9ee
JR
787 current_text = Qnil;
788 current_coding_system = Qnil;
ee79d1aa 789
ee78dc32
GV
790 done:
791 UNBLOCK_INPUT;
41a48e45 792
ee78dc32
GV
793 return (ok ? string : Qnil);
794}
795
52c7f9ee 796
33f09670
JR
797DEFUN ("w32-get-clipboard-data", Fw32_get_clipboard_data,
798 Sw32_get_clipboard_data, 0, 1, 0,
799 doc: /* This gets the clipboard data in text format. */)
5842a27b 800 (Lisp_Object ignored)
ee78dc32 801{
52c7f9ee 802 HGLOBAL htext;
ee78dc32 803 Lisp_Object ret = Qnil;
52c7f9ee
JR
804 UINT actual_clipboard_type;
805 int use_configured_coding_system = 1;
806
807 /* This parameter used to be the current frame, but we don't use
808 that any more. */
809 (void) ignored;
41a48e45 810
52c7f9ee
JR
811 /* Don't pass our own text from the clipboard (which might be
812 troublesome if the killed text includes null characters). */
813 if (!NILP (current_text))
814 return ret;
815
816 setup_config ();
817 actual_clipboard_type = cfg_clipboard_type;
41a48e45 818
ee78dc32 819 BLOCK_INPUT;
41a48e45 820
52c7f9ee 821 if (!OpenClipboard (clipboard_owner))
ee78dc32 822 goto done;
41a48e45 823
52c7f9ee
JR
824 if ((htext = GetClipboardData (actual_clipboard_type)) == NULL)
825 {
826 /* If we want CF_UNICODETEXT but can't get it, the current
827 coding system is useless. OTOH we can still try and decode
828 CF_TEXT based on the locale that the system gives us and that
829 we get down below. */
830 if (actual_clipboard_type == CF_UNICODETEXT)
831 {
832 htext = GetClipboardData (CF_TEXT);
833 if (htext != NULL)
834 {
835 actual_clipboard_type = CF_TEXT;
836 use_configured_coding_system = 0;
837 }
838 }
839 }
840 if (htext == NULL)
ee78dc32
GV
841 goto closeclip;
842
ee78dc32 843 {
69cddef0
GV
844 unsigned char *src;
845 unsigned char *dst;
ee78dc32 846 int nbytes;
69cddef0 847 int truelen;
c0ca703b 848 int require_decoding = 0;
41a48e45 849
69cddef0 850 if ((src = (unsigned char *) GlobalLock (htext)) == NULL)
ee78dc32 851 goto closeclip;
41a48e45 852
52c7f9ee
JR
853 /* If the clipboard data contains any non-ascii code, we need to
854 decode it with a coding system. */
855 if (actual_clipboard_type == CF_UNICODETEXT)
856 {
857 nbytes = lstrlenW ((WCHAR *)src) * 2;
858 require_decoding = 1;
859 }
860 else
861 {
862 int i;
06466d9a 863
52c7f9ee 864 nbytes = strlen (src);
aab7e392 865
52c7f9ee
JR
866 for (i = 0; i < nbytes; i++)
867 {
868 if (src[i] >= 0x80)
869 {
870 require_decoding = 1;
871 break;
872 }
873 }
874 }
93cbf229 875
c0ca703b 876 if (require_decoding)
69cddef0 877 {
bbb059f3 878 struct coding_system coding;
52c7f9ee 879 Lisp_Object coding_system = Qnil;
9a38f8d5 880 Lisp_Object dos_coding_system;
b56ceb92 881
52c7f9ee
JR
882 /* `next-selection-coding-system' should override everything,
883 even when the locale passed by the system disagrees. The
884 only exception is when `next-selection-coding-system'
885 requested CF_UNICODETEXT and we couldn't get that. */
886 if (use_configured_coding_system
887 && !NILP (Vnext_selection_coding_system))
888 coding_system = Vnext_selection_coding_system;
889
890 /* If we have CF_TEXT or CF_OEMTEXT, we want to check out
891 CF_LOCALE, too. */
892 else if (actual_clipboard_type != CF_UNICODETEXT)
893 {
894 HGLOBAL hlocale;
895 LCID lcid = DEFAULT_LCID;
896 UINT cp;
897
898 /* Documentation says that the OS always generates
899 CF_LOCALE info automatically, so the locale handle
900 should always be present. Fact is that this is not
901 always true on 9x ;-(. */
902 hlocale = GetClipboardData (CF_LOCALE);
903 if (hlocale != NULL)
904 {
905 const LCID * lcid_ptr;
906 lcid_ptr = (const LCID *) GlobalLock (hlocale);
907 if (lcid_ptr != NULL)
908 {
909 lcid = *lcid_ptr;
910 GlobalUnlock (hlocale);
911 }
912
913 /* 9x has garbage as the sort order (to be exact there
914 is another instance of the language id in the upper
915 word). We don't care about sort order anyway, so
916 we just filter out the unneeded mis-information to
917 avoid irritations. */
918 lcid = MAKELCID (LANGIDFROMLCID (lcid), SORT_DEFAULT);
919 }
920
921 /* If we are using fallback from CF_UNICODETEXT, we can't
922 use the configured coding system. Also we don't want
923 to use it, if the system has supplied us with a locale
924 and it is not just the system default. */
925 if (!use_configured_coding_system || lcid != DEFAULT_LCID)
926 {
927 cp = cp_from_locale (lcid, actual_clipboard_type);
928 /* If it's just our current standard setting anyway,
929 use the coding system that the user has selected.
930 Otherwise create a new spec to match the locale
931 that was specified by the other side or the
932 system. */
933 if (!use_configured_coding_system || cp != cfg_codepage)
934 coding_system = coding_from_cp (cp);
935 }
936 }
937
938 if (NILP (coding_system))
939 coding_system = Vselection_coding_system;
940 Vnext_selection_coding_system = Qnil;
bbb059f3 941
9a38f8d5
KH
942 dos_coding_system = validate_coding_system (coding_system);
943 if (!NILP (dos_coding_system))
944 {
945 setup_windows_coding_system (dos_coding_system, &coding);
946 coding.source = src;
947 decode_coding_object (&coding, Qnil, 0, 0, nbytes, nbytes, Qt);
948 ret = coding.dst_object;
949
950 Vlast_coding_system_used = CODING_ID_NAME (coding.id);
951 }
69cddef0 952 }
bbb059f3
AI
953 else
954 {
52c7f9ee
JR
955 /* FIXME: We may want to repeat the code in this branch for
956 the Unicode case. */
957
958 /* Need to know final size after CR chars are removed because
959 we can't change the string size manually, and doing an
960 extra copy is silly. We only remove CR when it appears as
961 part of CRLF. */
bbb059f3
AI
962
963 truelen = nbytes;
964 dst = src;
965 /* avoid using strchr because it recomputes the length everytime */
966 while ((dst = memchr (dst, '\r', nbytes - (dst - src))) != NULL)
967 {
c0ca703b
GV
968 if (dst[1] == '\n') /* safe because of trailing '\0' */
969 truelen--;
bbb059f3
AI
970 dst++;
971 }
69cddef0 972
bbb059f3 973 ret = make_uninit_string (truelen);
69cddef0 974
c0ca703b
GV
975 /* Convert CRLF line endings (the standard CF_TEXT clipboard
976 format) to LF endings as used internally by Emacs. */
69cddef0 977
d5db4077 978 dst = SDATA (ret);
bbb059f3 979 while (1)
69cddef0 980 {
bbb059f3
AI
981 unsigned char *next;
982 /* copy next line or remaining bytes excluding '\0' */
983 next = _memccpy (dst, src, '\r', nbytes);
984 if (next)
985 {
986 /* copied one line ending with '\r' */
987 int copied = next - dst;
988 nbytes -= copied;
c0ca703b 989 dst += copied;
bbb059f3 990 src += copied;
c0ca703b
GV
991 if (*src == '\n')
992 dst--; /* overwrite '\r' with '\n' */
993 }
bbb059f3
AI
994 else
995 /* copied remaining partial line -> now finished */
996 break;
997 }
0108f679
AI
998
999 Vlast_coding_system_used = Qraw_text;
69cddef0
GV
1000 }
1001
ee78dc32
GV
1002 GlobalUnlock (htext);
1003 }
1004
1005 closeclip:
1006 CloseClipboard ();
41a48e45 1007
ee78dc32
GV
1008 done:
1009 UNBLOCK_INPUT;
41a48e45 1010
ee78dc32
GV
1011 return (ret);
1012}
1013
9aa94bd5
KH
1014/* Support checking for a clipboard selection. */
1015
1016DEFUN ("x-selection-exists-p", Fx_selection_exists_p, Sx_selection_exists_p,
1c0ca0b7
EZ
1017 0, 2, 0,
1018 doc: /* Whether there is an owner for the given X selection.
1019SELECTION should be the name of the selection in question, typically
1020one of the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'. (X expects
1021these literal upper-case names.) The symbol nil is the same as
1022`PRIMARY', and t is the same as `SECONDARY'.
1023
1024TERMINAL should be a terminal object or a frame specifying the X
1025server to query. If omitted or nil, that stands for the selected
1026frame's display, or the first available X display. */)
1027 (Lisp_Object selection, Lisp_Object terminal)
9aa94bd5 1028{
b7826503 1029 CHECK_SYMBOL (selection);
9aa94bd5
KH
1030
1031 /* Return nil for PRIMARY and SECONDARY selections; for CLIPBOARD, check
1032 if the clipboard currently has valid text format contents. */
1033
1034 if (EQ (selection, QCLIPBOARD))
1035 {
1036 Lisp_Object val = Qnil;
1037
9a38f8d5
KH
1038 setup_config ();
1039
9aa94bd5
KH
1040 if (OpenClipboard (NULL))
1041 {
52c7f9ee 1042 UINT format = 0;
52c7f9ee
JR
1043 while ((format = EnumClipboardFormats (format)))
1044 /* Check CF_TEXT in addition to cfg_clipboard_type,
1045 because we can fall back on that if CF_UNICODETEXT is
1046 not available. Actually a check for CF_TEXT only
1047 should be enough. */
1048 if (format == cfg_clipboard_type || format == CF_TEXT)
9aa94bd5
KH
1049 {
1050 val = Qt;
1051 break;
1052 }
1053 CloseClipboard ();
1054 }
1055 return val;
1056 }
1057 return Qnil;
1058}
1059
52c7f9ee
JR
1060/* One-time init. Called in the un-dumped Emacs, but not in the
1061 dumped version. */
1062
41a48e45 1063void
b56ceb92 1064syms_of_w32select (void)
ee78dc32 1065{
fbd6baed
GV
1066 defsubr (&Sw32_set_clipboard_data);
1067 defsubr (&Sw32_get_clipboard_data);
9aa94bd5
KH
1068 defsubr (&Sx_selection_exists_p);
1069
29208e82 1070 DEFVAR_LISP ("selection-coding-system", Vselection_coding_system,
33f09670 1071 doc: /* Coding system for communicating with other programs.
f5f25615
GM
1072
1073For MS-Windows and MS-DOS:
1074When sending or receiving text via selection and clipboard, the text
1075is encoded or decoded by this coding system. The default value is
1076the current system default encoding on 9x/Me, `utf-16le-dos'
1077\(Unicode) on NT/W2K/XP, and `iso-latin-1-dos' on MS-DOS.
1078
1079For X Windows:
1080When sending text via selection and clipboard, if the target
1081data-type matches with the type of this coding system, it is used
1082for encoding the text. Otherwise (including the case that this
1083variable is nil), a proper coding system is used as below:
1084
1085data-type coding system
1086--------- -------------
1087UTF8_STRING utf-8
1088COMPOUND_TEXT compound-text-with-extensions
1089STRING iso-latin-1
1090C_STRING no-conversion
1091
1092When receiving text, if this coding system is non-nil, it is used
1093for decoding regardless of the data-type. If this is nil, a
1094proper coding system is used according to the data-type as above.
1095
1096See also the documentation of the variable `x-select-request-type' how
1097to control which data-type to request for receiving text.
1098
1099The default value is nil. */);
52c7f9ee
JR
1100 /* The actual value is set dynamically in the dumped Emacs, see
1101 below. */
1102 Vselection_coding_system = Qnil;
bbb059f3 1103
29208e82 1104 DEFVAR_LISP ("next-selection-coding-system", Vnext_selection_coding_system,
33f09670
JR
1105 doc: /* Coding system for the next communication with other programs.
1106Usually, `selection-coding-system' is used for communicating with
3646b86d
GM
1107other programs (X Windows clients or MS Windows programs). But, if this
1108variable is set, it is used for the next communication only.
1109After the communication, this variable is set to nil. */);
93cbf229
GV
1110 Vnext_selection_coding_system = Qnil;
1111
9c9d6d8b 1112 DEFSYM (QCLIPBOARD, "CLIPBOARD");
52c7f9ee
JR
1113
1114 cfg_coding_system = Qnil; staticpro (&cfg_coding_system);
1115 current_text = Qnil; staticpro (&current_text);
1116 current_coding_system = Qnil; staticpro (&current_coding_system);
1117
9c9d6d8b 1118 DEFSYM (QUNICODE, "utf-16le-dos");
52c7f9ee
JR
1119 QANSICP = Qnil; staticpro (&QANSICP);
1120 QOEMCP = Qnil; staticpro (&QOEMCP);
1121}
1122
1123/* One-time init. Called in the dumped Emacs, but not in the
1124 un-dumped version. */
1125
1126void
b56ceb92 1127globals_of_w32select (void)
52c7f9ee
JR
1128{
1129 DEFAULT_LCID = GetUserDefaultLCID ();
1130 /* Drop the sort order from the LCID, so we can compare this with
1131 CF_LOCALE objects that have the same fix on 9x. */
1132 DEFAULT_LCID = MAKELCID (LANGIDFROMLCID (DEFAULT_LCID), SORT_DEFAULT);
1133
1134 ANSICP = GetACP ();
1135 OEMCP = GetOEMCP ();
1136
1137 QANSICP = coding_from_cp (ANSICP);
1138 QOEMCP = coding_from_cp (OEMCP);
1139
1140 if (os_subtype == OS_NT)
1141 Vselection_coding_system = QUNICODE;
1142 else if (inhibit_window_system)
1143 Vselection_coding_system = QOEMCP;
1144 else
1145 Vselection_coding_system = QANSICP;
1146
1147 clipboard_owner = create_owner ();
ee78dc32 1148}