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