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