Implement cygw32
[bpt/emacs.git] / src / w32select.c
1 /* Selection processing for Emacs on the Microsoft Windows API.
2
3 Copyright (C) 1993-1994, 2001-2012 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
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).
33 *
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 requestor 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:
48 *
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)
52 *
53 * Or
54 *
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 */
74
75 #include <config.h>
76 #include <setjmp.h>
77 #include "lisp.h"
78 #include "w32term.h" /* for all of the w32 includes */
79 #include "w32heap.h" /* os_subtype */
80 #include "blockinput.h"
81 #include "charset.h"
82 #include "coding.h"
83 #include "composite.h"
84
85 #ifdef CYGWIN
86 #include <string.h>
87 #include <stdio.h>
88 #define _memccpy memccpy
89 #endif
90
91 static HGLOBAL convert_to_handle_as_ascii (void);
92 static HGLOBAL convert_to_handle_as_coded (Lisp_Object coding_system);
93 static Lisp_Object render (Lisp_Object oformat);
94 static Lisp_Object render_locale (void);
95 static Lisp_Object render_all (Lisp_Object ignore);
96 static void run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg);
97 static Lisp_Object lisp_error_handler (Lisp_Object error);
98 static LRESULT CALLBACK owner_callback (HWND win, UINT msg,
99 WPARAM wp, LPARAM lp);
100 static HWND create_owner (void);
101
102 static void setup_config (void);
103 static BOOL WINAPI enum_locale_callback (/*const*/ char* loc_string);
104 static UINT cp_from_locale (LCID lcid, UINT format);
105 static Lisp_Object coding_from_cp (UINT codepage);
106 static Lisp_Object validate_coding_system (Lisp_Object coding_system);
107 static void setup_windows_coding_system (Lisp_Object coding_system,
108 struct coding_system * coding);
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. */
114 Lisp_Object QCLIPBOARD;
115
116 /* Internal pseudo-constants, initialized in globals_of_w32select()
117 based on current system parameters. */
118 static LCID DEFAULT_LCID;
119 static UINT ANSICP, OEMCP;
120 static Lisp_Object QUNICODE, QANSICP, QOEMCP;
121
122 /* A hidden window just for the clipboard management. */
123 static HWND clipboard_owner;
124 /* A flag to tell WM_DESTROYCLIPBOARD who is to blame this time (just
125 checking GetClipboardOwner() doesn't work, sadly). */
126 static int modifying_clipboard = 0;
127
128 /* Configured transfer parameters, based on the last inspection of
129 selection-coding-system. */
130 static Lisp_Object cfg_coding_system;
131 static UINT cfg_codepage;
132 static LCID cfg_lcid;
133 static UINT cfg_clipboard_type;
134
135 /* The current state for delayed rendering. */
136 static Lisp_Object current_text;
137 static Lisp_Object current_coding_system;
138 static int current_requires_encoding, current_num_nls;
139 static UINT current_clipboard_type;
140 static 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
152 static HGLOBAL
153 convert_to_handle_as_ascii (void)
154 {
155 HGLOBAL htext = NULL;
156 int nbytes;
157 int truelen;
158 unsigned char *src;
159 unsigned char *dst;
160
161 ONTRACE (fprintf (stderr, "convert_to_handle_as_ascii\n"));
162
163 nbytes = SBYTES (current_text) + 1;
164 src = SDATA (current_text);
165
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). */
169
170 truelen = nbytes + current_num_nls;
171
172 if ((htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, truelen)) == NULL)
173 return NULL;
174
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;
206 }
207
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
212 static HGLOBAL
213 convert_to_handle_as_coded (Lisp_Object coding_system)
214 {
215 HGLOBAL htext;
216 unsigned char *dst = NULL;
217 struct coding_system coding;
218
219 ONTRACE (fprintf (stderr, "convert_to_handle_as_coded: %s\n",
220 SDATA (SYMBOL_NAME (coding_system))));
221
222 setup_windows_coding_system (coding_system, &coding);
223 coding.dst_bytes = SBYTES (current_text) * 2;
224 coding.destination = xmalloc (coding.dst_bytes);
225 encode_coding_object (&coding, current_text, 0, 0,
226 SCHARS (current_text), SBYTES (current_text), Qnil);
227
228 htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, coding.produced +2);
229
230 if (htext != NULL)
231 dst = (unsigned char *) GlobalLock (htext);
232
233 if (dst != NULL)
234 {
235 memcpy (dst, coding.destination, coding.produced);
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';
239
240 GlobalUnlock (htext);
241 }
242
243 xfree (coding.destination);
244
245 return htext;
246 }
247
248 static Lisp_Object
249 render (Lisp_Object oformat)
250 {
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 {
289 GlobalFree (htext);
290 return Qnil;
291 }
292
293 return Qt;
294 }
295
296 static Lisp_Object
297 render_locale (void)
298 {
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 {
313 GlobalFree (hlocale);
314 return Qnil;
315 }
316
317 *lcid_ptr = current_lcid;
318 GlobalUnlock (hlocale);
319
320 if (SetClipboardData (CF_LOCALE, hlocale) == NULL)
321 {
322 GlobalFree (hlocale);
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
332 static Lisp_Object
333 render_all (Lisp_Object ignore)
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
343 /* There is no useful means to report errors here, there are none
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
379 render_locale ();
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
390 static void
391 run_protected (Lisp_Object (*code) (Lisp_Object), Lisp_Object arg)
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
397 extern int waiting_for_input; /* from keyboard.c */
398 int owfi;
399
400 BLOCK_INPUT;
401
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;
410
411 UNBLOCK_INPUT;
412 }
413
414 static Lisp_Object
415 lisp_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;
421 }
422
423
424 static LRESULT CALLBACK
425 owner_callback (HWND win, UINT msg, WPARAM wp, LPARAM lp)
426 {
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;
451
452 case WM_DESTROY:
453 if (win == clipboard_owner)
454 clipboard_owner = NULL;
455 break;
456 }
457
458 return DefWindowProc (win, msg, wp, lp);
459 }
460
461 static HWND
462 create_owner (void)
463 {
464 static const char CLASSNAME[] = "Emacs Clipboard";
465 WNDCLASS wc;
466
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
478 void
479 term_w32select (void)
480 {
481 /* This is needed to trigger WM_RENDERALLFORMATS. */
482 if (clipboard_owner != NULL)
483 DestroyWindow (clipboard_owner);
484 }
485
486 static void
487 setup_config (void)
488 {
489 const char *coding_name;
490 const char *cp;
491 char *end;
492 int slen;
493 Lisp_Object coding_system;
494 Lisp_Object dos_coding_system;
495
496 CHECK_SYMBOL (Vselection_coding_system);
497
498 coding_system = NILP (Vnext_selection_coding_system) ?
499 Vselection_coding_system : Vnext_selection_coding_system;
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 */
509 if (!NILP (cfg_coding_system)
510 && EQ (cfg_coding_system, dos_coding_system))
511 return;
512 cfg_coding_system = dos_coding_system;
513
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] == '-'))
525 {
526 cfg_clipboard_type = CF_UNICODETEXT;
527 return;
528 }
529
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 }
549
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 }
561
562 /* Else determine a suitable locale the hard way. */
563 EnumSystemLocales (enum_locale_callback, LCID_INSTALLED);
564 }
565
566 static BOOL WINAPI
567 enum_locale_callback (/*const*/ char* loc_string)
568 {
569 LCID lcid;
570 UINT codepage;
571
572 lcid = strtoul (loc_string, NULL, 16);
573
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 }
582
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 }
591
592 return TRUE; /* Continue enumeration */
593 }
594
595 static UINT
596 cp_from_locale (LCID lcid, UINT format)
597 {
598 char buffer[20] = "";
599 UINT variant, cp;
600
601 variant =
602 format == CF_TEXT ? LOCALE_IDEFAULTANSICODEPAGE : LOCALE_IDEFAULTCODEPAGE;
603
604 GetLocaleInfo (lcid, variant, buffer, sizeof (buffer));
605 cp = strtoul (buffer, NULL, 10);
606
607 if (cp == CP_ACP)
608 return ANSICP;
609 else if (cp == CP_OEMCP)
610 return OEMCP;
611 else
612 return cp;
613 }
614
615 static Lisp_Object
616 coding_from_cp (UINT codepage)
617 {
618 char buffer[30];
619 sprintf (buffer, "cp%d-dos", (int) codepage);
620 return intern (buffer);
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. */
624 }
625
626 static Lisp_Object
627 validate_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
654 static void
655 setup_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
676
677 DEFUN ("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. */)
680 (Lisp_Object string, Lisp_Object ignored)
681 {
682 BOOL ok = TRUE;
683 int nbytes;
684 unsigned char *src;
685 unsigned char *dst;
686 unsigned char *end;
687
688 /* This parameter used to be the current frame, but we don't use
689 that any more. */
690 (void) ignored;
691
692 CHECK_STRING (string);
693
694 setup_config ();
695
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;
702
703 BLOCK_INPUT;
704
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);
710 src = SDATA (string);
711
712 for (dst = src, end = src+nbytes; dst < end; dst++)
713 {
714 if (*dst == '\n')
715 current_num_nls++;
716 else if (*dst >= 0x80 || *dst == 0)
717 {
718 current_requires_encoding = 1;
719 break;
720 }
721 }
722
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 }
731
732 if (!OpenClipboard (clipboard_owner))
733 goto error;
734
735 ++modifying_clipboard;
736 ok = EmptyClipboard ();
737 --modifying_clipboard;
738
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)
742 ok = !NILP (render_locale ());
743
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. */
751 ok = !NILP (render (make_number (current_clipboard_type)));
752 current_text = Qnil;
753 current_coding_system = Qnil;
754 }
755 else
756 {
757 /* Advertise all supported formats so that whatever the
758 requestor chooses, only one encoding step needs to be
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 }
766
767 CloseClipboard ();
768
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.
773
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;
779
780 Vnext_selection_coding_system = Qnil;
781
782 if (ok) goto done;
783
784 error:
785
786 ok = FALSE;
787 current_text = Qnil;
788 current_coding_system = Qnil;
789
790 done:
791 UNBLOCK_INPUT;
792
793 return (ok ? string : Qnil);
794 }
795
796
797 DEFUN ("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. */)
800 (Lisp_Object ignored)
801 {
802 HGLOBAL htext;
803 Lisp_Object ret = Qnil;
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;
810
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;
818
819 BLOCK_INPUT;
820
821 if (!OpenClipboard (clipboard_owner))
822 goto done;
823
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)
841 goto closeclip;
842
843 {
844 unsigned char *src;
845 unsigned char *dst;
846 int nbytes;
847 int truelen;
848 int require_decoding = 0;
849
850 if ((src = (unsigned char *) GlobalLock (htext)) == NULL)
851 goto closeclip;
852
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;
863
864 nbytes = strlen (src);
865
866 for (i = 0; i < nbytes; i++)
867 {
868 if (src[i] >= 0x80)
869 {
870 require_decoding = 1;
871 break;
872 }
873 }
874 }
875
876 if (require_decoding)
877 {
878 struct coding_system coding;
879 Lisp_Object coding_system = Qnil;
880 Lisp_Object dos_coding_system;
881
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;
941
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 }
952 }
953 else
954 {
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. */
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 {
968 if (dst[1] == '\n') /* safe because of trailing '\0' */
969 truelen--;
970 dst++;
971 }
972
973 ret = make_uninit_string (truelen);
974
975 /* Convert CRLF line endings (the standard CF_TEXT clipboard
976 format) to LF endings as used internally by Emacs. */
977
978 dst = SDATA (ret);
979 while (1)
980 {
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;
989 dst += copied;
990 src += copied;
991 if (*src == '\n')
992 dst--; /* overwrite '\r' with '\n' */
993 }
994 else
995 /* copied remaining partial line -> now finished */
996 break;
997 }
998
999 Vlast_coding_system_used = Qraw_text;
1000 }
1001
1002 GlobalUnlock (htext);
1003 }
1004
1005 closeclip:
1006 CloseClipboard ();
1007
1008 done:
1009 UNBLOCK_INPUT;
1010
1011 return (ret);
1012 }
1013
1014 /* Support checking for a clipboard selection. */
1015
1016 DEFUN ("x-selection-exists-p", Fx_selection_exists_p, Sx_selection_exists_p,
1017 0, 2, 0,
1018 doc: /* Whether there is an owner for the given X selection.
1019 SELECTION should be the name of the selection in question, typically
1020 one of the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'. (X expects
1021 these literal upper-case names.) The symbol nil is the same as
1022 `PRIMARY', and t is the same as `SECONDARY'.
1023
1024 TERMINAL should be a terminal object or a frame specifying the X
1025 server to query. If omitted or nil, that stands for the selected
1026 frame's display, or the first available X display. */)
1027 (Lisp_Object selection, Lisp_Object terminal)
1028 {
1029 CHECK_SYMBOL (selection);
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
1038 setup_config ();
1039
1040 if (OpenClipboard (NULL))
1041 {
1042 UINT format = 0;
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)
1049 {
1050 val = Qt;
1051 break;
1052 }
1053 CloseClipboard ();
1054 }
1055 return val;
1056 }
1057 return Qnil;
1058 }
1059
1060 /* One-time init. Called in the un-dumped Emacs, but not in the
1061 dumped version. */
1062
1063 void
1064 syms_of_w32select (void)
1065 {
1066 defsubr (&Sw32_set_clipboard_data);
1067 defsubr (&Sw32_get_clipboard_data);
1068 defsubr (&Sx_selection_exists_p);
1069
1070 DEFVAR_LISP ("selection-coding-system", Vselection_coding_system,
1071 doc: /* Coding system for communicating with other programs.
1072
1073 For MS-Windows and MS-DOS:
1074 When sending or receiving text via selection and clipboard, the text
1075 is encoded or decoded by this coding system. The default value is
1076 the 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
1079 For X Windows:
1080 When sending text via selection and clipboard, if the target
1081 data-type matches with the type of this coding system, it is used
1082 for encoding the text. Otherwise (including the case that this
1083 variable is nil), a proper coding system is used as below:
1084
1085 data-type coding system
1086 --------- -------------
1087 UTF8_STRING utf-8
1088 COMPOUND_TEXT compound-text-with-extensions
1089 STRING iso-latin-1
1090 C_STRING no-conversion
1091
1092 When receiving text, if this coding system is non-nil, it is used
1093 for decoding regardless of the data-type. If this is nil, a
1094 proper coding system is used according to the data-type as above.
1095
1096 See also the documentation of the variable `x-select-request-type' how
1097 to control which data-type to request for receiving text.
1098
1099 The default value is nil. */);
1100 /* The actual value is set dynamically in the dumped Emacs, see
1101 below. */
1102 Vselection_coding_system = Qnil;
1103
1104 DEFVAR_LISP ("next-selection-coding-system", Vnext_selection_coding_system,
1105 doc: /* Coding system for the next communication with other programs.
1106 Usually, `selection-coding-system' is used for communicating with
1107 other programs (X Windows clients or MS Windows programs). But, if this
1108 variable is set, it is used for the next communication only.
1109 After the communication, this variable is set to nil. */);
1110 Vnext_selection_coding_system = Qnil;
1111
1112 DEFSYM (QCLIPBOARD, "CLIPBOARD");
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
1118 DEFSYM (QUNICODE, "utf-16le-dos");
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
1126 void
1127 globals_of_w32select (void)
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 ();
1148 }